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

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

Introduction

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

Prototype

public boolean contains(final T element) 

Source Link

Document

Checks whether the specified element occurs within this range.

Usage

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

/**
 * Farm this farm/*from w w w .  java 2 s . c om*/
 *
 * @param pConfig
 *            The troops used for farming or 'null' if the needed amount of
 *            troops should be calculated
 */
public FARM_RESULT farmFarm(DSWorkbenchFarmManager.FARM_CONFIGURATION pConfig) {
    StringBuilder info = new StringBuilder();
    if (inactive) {
        lastResult = FARM_RESULT.FARM_INACTIVE;
        info.append("Farm ist inaktiv. Aktiviere die Farm, um sie wieder nutzen zu knnen.\n");
    } else {// farm is active
        if (!TroopsManager.getSingleton().hasInformation(TroopsManager.TROOP_TYPE.OWN)) {
            // we need troop information to continue....
            logger.info("No own troops imported to DS Workbench");
            lastResult = FARM_RESULT.FAILED;
            info.append("Keine Truppeninformationen aus dem Spiel nach DS Workbench importiert.\n"
                    + "Wechsel in die Truppenbersicht im Spiel, kopiere die Seite per STRG+A und kopiere sie\n"
                    + "per STRG+C in die Zwischenablage, von wo DS Workbench sie dann automatisch einlesen wird.\n");
        } else {
            ////////////// troops are imported///////////////
            ///////////////// start farming//////////////////
            final HashMap<Village, TroopAmountFixed> carriageMap = new HashMap<>();
            List<Village> villages = new LinkedList<>();

            for (Village selectedVillage : DSWorkbenchFarmManager.getSelectedFarmGroup()) {
                TroopAmountFixed units;
                units = new TroopAmountFixed();
                VillageTroopsHolder holder = TroopsManager.getSingleton().getTroopsForVillage(selectedVillage,
                        TroopsManager.TROOP_TYPE.OWN);
                if (holder == null) {
                    //troops not read
                    info.append("Truppen noch nicht eingelesen");
                    lastSendInformation = info.toString();
                    return FARM_RESULT.FAILED;
                }
                // Defines the Troops to be farmed with for A/B/C/K
                units = TroopHelper.getTroopsForCarriage(pConfig, holder, this);
                // Adds rams if check box is marked and contains already units
                if (DSWorkbenchFarmManager.getSingleton().isUseRams(pConfig) && units.hasUnits()) {
                    TroopHelper.addNeededRams(units, holder, this);
                }
                if (pConfig.equals(DSWorkbenchFarmManager.FARM_CONFIGURATION.K) && units.hasUnits()) {
                    // Ignore empty attacks
                    // Only for Farm-type K
                    TroopHelper.addNeededCatas(units, holder, this);
                }
                if (units != null && units.hasUnits()) {
                    // Add result to the farm map... if reasonable
                    // units from this village can carry all resources
                    carriageMap.put(selectedVillage, units);
                    villages.add(selectedVillage);
                }
            }
            // have village with valid amounts
            if (villages.isEmpty()) {
                info.append(
                        "Es wurden alle Drfer aufgrund der Tragekapazitt ihrer Truppen, ihrer Entfernung zum Ziel oder der erwarteten Ressourcen gelscht.\n"
                                + "Mglicherweise knnte ein erneuter Truppenimport aus dem Spiel, eine Vergrerung des Farmradius oder eine Verkleinerung der minimalen Anzahl an Einheiten\n"
                                + "hilfreich sein. berprfe auch die eingestellte Truppenreserve (R), falls vorhanden.\n");
                lastResult = FARM_RESULT.IMPOSSIBLE;
            } else {
                info.append(villages.size())
                        .append(" Dorf/Drfer verfgen ber die bentigte Tragekapazitt.\n");
                // there are villages which can carry all resources or we use scenario A/B
                // sort valid villages by speed if we are not in the case that we are
                // using farm type C without sufficient troops
                Collections.sort(villages, new Comparator<Village>() {
                    @Override
                    public int compare(Village o1, Village o2) {
                        // get speed of defined troops (A and B) or by troops for carriage (C)...
                        // ...as this ordering is not performed in case of cByMinHaul, pAllowMaxCarriage
                        // is set to 'false'
                        double speed1 = carriageMap.get(o1).getSpeed();
                        double speed2 = carriageMap.get(o2).getSpeed();

                        return new Double(DSCalculator.calculateMoveTimeInMinutes(o1, getVillage(), speed1))
                                .compareTo(DSCalculator.calculateMoveTimeInMinutes(o2, getVillage(), speed2));
                    }
                });
                // now select the "best" village for farming
                Village selection = null;
                TroopAmountFixed farmers = null;
                Range<Integer> r = DSWorkbenchFarmManager.getSingleton().getFarmRange(pConfig);
                int noTroops = 0;
                int distCheckFailed = 0;
                int minHaulCheckFailed = 0;
                double minDist = 0;
                int minHaul = DSWorkbenchFarmManager.getSingleton().getMinHaul(pConfig);
                // search feasible village
                for (Village v : villages) {
                    // take troops from carriageMap
                    TroopAmountFixed troops = carriageMap.get(v);
                    double speed = troops.getSpeed();
                    int resources = getResourcesInStorage(System.currentTimeMillis()
                            + DSCalculator.calculateMoveTimeInMillis(v, getVillage(), speed));
                    double dist = DSCalculator.calculateMoveTimeInMinutes(v, getVillage(), speed);
                    // troops are empty if they are not met the minimum troop amount
                    if (!troops.hasUnits() || (pConfig.equals(DSWorkbenchFarmManager.FARM_CONFIGURATION.C)
                            && troops.getFarmCapacity() == 0)) {
                        noTroops++;
                    } else {// enough troops
                        if (dist > 0 && r.contains((int) dist)) {
                            if (resources < minHaul) {
                                minHaulCheckFailed++;
                            } else {
                                // village and troops found...use them
                                selection = v;
                                farmers = troops;
                                break;
                            }
                        } else {
                            distCheckFailed++;
                            if (dist > 0) {
                                if (minDist == 0) {
                                    minDist = dist;
                                } else {
                                    minDist = Math.min(dist, minDist);
                                }
                            }
                        }
                    }
                }

                // check if feasible village was found
                if (selection == null || farmers == null) {
                    lastResult = FARM_RESULT.IMPOSSIBLE;
                    info.append(
                            "In der abschlieenden Prfung wurden alle Drfer entfernt.\nDie Grnde waren die Folgenden:\n- ")
                            .append(noTroops)
                            .append(" Dorf/Drfer hatten nicht ausreichend Truppen fr die erwarteten Rohstoffe\n- ")
                            .append(distCheckFailed)
                            .append(" Dorf/Drfer lagen auerhalb des eingestellten Farmradius (Min. Laufzeit: ")
                            .append((int) Math.rint(minDist)).append(" Minuten)\n- ").append(minHaulCheckFailed)
                            .append(" Dorf/Drfer wrden nicht gengend Rohstoffe vorfinden, um die minimale Beute zu erzielen");
                } else {
                    // send troops and update
                    if (BrowserInterface.sendTroops(selection, getVillage(), farmers)) {
                        // if (true) {
                        if (pConfig.equals(DSWorkbenchFarmManager.FARM_CONFIGURATION.C)) {
                            int farmCap = farmers.getFarmCapacity();

                            int pwood = getWoodInStorage(System.currentTimeMillis() + DSCalculator
                                    .calculateMoveTimeInMillis(selection, getVillage(), farmers.getSpeed()));
                            int pclay = getClayInStorage(System.currentTimeMillis() + DSCalculator
                                    .calculateMoveTimeInMillis(selection, getVillage(), farmers.getSpeed()));
                            int piron = getIronInStorage(System.currentTimeMillis() + DSCalculator
                                    .calculateMoveTimeInMillis(selection, getVillage(), farmers.getSpeed()));

                            setExtraResources(Math.max(pwood - farmCap * pwood / (pwood + pclay + piron), 0),
                                    Math.max(pclay - farmCap * pclay / (pwood + pclay + piron), 0),
                                    Math.max(piron - farmCap * piron / (pwood + pclay + piron), 0));
                        }
                        TroopHelper.sendTroops(selection, farmers);
                        if (pConfig.equals(DSWorkbenchFarmManager.FARM_CONFIGURATION.K)) {
                            siegeTroop = farmers;
                            siegeTroopArrival = System.currentTimeMillis() + DSCalculator
                                    .calculateMoveTimeInMillis(selection, getVillage(), siegeTroop.getSpeed());
                            if (siegeTroop.getAmountForUnit("catapult") > 0) {
                                if (siegeTroop.getAmountForUnit("ram") > 0) {
                                    setSiegeStatus(SIEGE_STATUS.BOTH_ON_WAY);
                                } else {
                                    setSiegeStatus(SIEGE_STATUS.CATA_ON_WAY);
                                }
                            } else {
                                if (siegeTroop.getAmountForUnit("ram") > 0) {
                                    setSiegeStatus(SIEGE_STATUS.RAM_ON_WAY);
                                } else {
                                    logger.debug("Code should not get here!");
                                }
                            }
                            lastResult = FARM_RESULT.OK;
                            info.append("Der Farmangriff konnte erfolgreich abgeschickt werden.");
                        } else {
                            farmTroop = farmers;
                            farmTroopArrive = System.currentTimeMillis() + DSCalculator
                                    .calculateMoveTimeInMillis(selection, getVillage(), farmers.getSpeed());
                            setStatus(FARM_STATUS.FARMING);
                            attackCount++;
                            lastResult = FARM_RESULT.OK;
                            info.append("Der Farmangriff konnte erfolgreich abgeschickt werden.");
                        }
                    } else {
                        farmTroop = null;
                        farmTroopArrive = -1;
                        lastResult = FARM_RESULT.FAILED;
                        info.append("Der Farmangriff konnte nicht im Browser geffnet werden.\n"
                                + "Bitte berprfe die Browsereinstellungen von DS Workbench.");
                    }
                }
            }
        }
    }
    usedConfig = pConfig;
    lastSendInformation = info.toString();
    return lastResult;
}

From source file:com.rockhoppertech.music.midi.js.MIDITrack.java

/**
 * Return the notes that have a start beat between the specified beats.
 * //from w w w. jav a  2s . c  o  m
 * @param startBeat
 *            begin of beat range
 * @param endBeat
 *            not inclusive
 * @return a {@code List} of matching {@code MIDINote}s
 */
public List<MIDINote> getNotesBetweenStartBeatAndEndBeat(final double startBeat, final double endBeat) {
    List<MIDINote> notes = new ArrayList<MIDINote>();
    Range<Double> range = Range.between(startBeat, endBeat - .00001);
    logger.debug("range {}", range);
    logger.debug("looking for  sb {}", startBeat);
    for (final MIDINote n : this) {
        final double s = n.getStartBeat();
        logger.debug("checking sb {} of note {}", s, n);
        if (range.contains(s)) {
            logger.debug("adding note {}", n);
            notes.add(n);
        }
    }
    return notes;
}

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  va 2s  .co  m
        }
        // 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:org.apache.metron.profiler.client.stellar.IntervalPredicate.java

private boolean containsInclusive(Range<Long> interval, long ts) {
    return interval.contains(ts) || interval.getMaximum() == ts;
}

From source file:org.gbif.ipt.struts2.converter.CoordinateFormatConverter.java

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
    // The null value is needed to validate in EmlValidator.java class
    if (values[0].length() == 0) {
        return null;
    }/*w  w  w.  j a  v  a2 s . c o  m*/
    // The full name of the property which call the method contained in the Map context
    Object coordObject = context.get(ANGLE);
    // The latitude is validating in a range of doubles
    // validate coordinates in case the action context doesn't work properly.
    if (coordObject == null) {
        throw new TypeConversionException("Invalid decimal number: " + values[0]);
    } else {
        String coordinate = context.get(ANGLE).toString();
        // Assign the values of the range depending the property who calls the method.
        Range<Double> range;
        if (coordinate.equals(CoordinateUtils.LATITUDE)) {
            // The range of the latitude coordinate. (-90,90)
            range = Range.between(CoordinateUtils.MIN_LATITUDE, CoordinateUtils.MAX_LATITUDE);
        } else {
            // The range of the longitude coordinate. (-180,180)
            range = Range.between(CoordinateUtils.MIN_LONGITUDE, CoordinateUtils.MAX_LONGITUDE);
        }

        Double number;
        try {
            // Converts String to double if fails throws a NumberFormatException.
            // If the String contains a comma, a character, it throws the exception.
            number = Double.parseDouble(values[0]);
            // If the value is in the range, returns the double.
            if (range.contains(number)) {
                return number;
            } else {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        } catch (NumberFormatException e) {
            // Creating a pattern which will convert the comma to period
            // It will return a ParseException if the format was wrong.
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(ALTERNATIVE_DECIMAL_SEPARATOR);
            DecimalFormat decimal = new DecimalFormat(DECIMAL_PATTERN, symbols);
            try {
                number = decimal.parse(values[0]).doubleValue();
                if (range.contains(number)) {
                    return number;
                } else {
                    throw new TypeConversionException("Invalid decimal number: " + values[0]);
                }
            } catch (ParseException e1) {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        }
    }
}

From source file:org.kalypso.model.wspm.core.profil.impl.RangeSelection.java

@Override
public void setRange(final Range<Double> selection) {
    if (Objects.equal(m_selection, selection))
        return;/*from w  w  w  . j a  v  a2s.  c  o  m*/

    m_selection = selection;

    int selectionCount = 0;
    for (final IProfileRecord record : m_profile.getPoints()) {
        final boolean isSelected = selection.contains(record.getBreite());
        ((ProfileRecord) record).setSelected(isSelected);

        if (isSelected)
            selectionCount++;
    }

    if (selection.getMinimum() == selection.getMaximum() && selectionCount == 0) {
        final IProfileRecord previous = m_profile.findPreviousPoint(selection.getMinimum());
        if (previous != null)
            ((ProfileRecord) previous).setSelected(!selection.contains(previous.getBreite()));
    }

    final ProfileChangeHint hint = new ProfileChangeHint(
            ProfileChangeHint.SELECTION_CHANGED | ProfileChangeHint.ACTIVE_POINTS_CHANGED);
    m_profile.fireProfilChanged(hint);
}

From source file:org.kalypso.ui.rrm.internal.timeseries.operations.RepairRueckspruengeOperation.java

private boolean isRuecksprung(final int index) {
    for (final Range<Integer> ruecksprung : m_rueckspruenge) {
        if (ruecksprung.contains(index))
            return true;
    }//from www  .  jav  a2 s. co  m

    return false;
}

From source file:Utils.Distribution.ComparableDistribution.java

/**
 * Create a new distribution only containing objects between lower and upper
 * @param lower The lower object//ww w.  j  av  a2 s .co  m
 * @param upper The upper object
 * @return The new distribution
 */
public ComparableDistribution<V> limitTo(V lower, V upper) {
    Range<V> range = Range.between(lower, upper);
    CountMap<V> newmap = new CountMap<>();
    super.allCounts().filter(p -> range.contains(p.getLeft()))
            .forEach(p -> newmap.add(p.getLeft(), p.getRight()));
    return new ComparableDistribution<>(newmap);
}