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:de.julielab.jcore.utility.JCoReAnnotationTools.java

/**
 * Returns the leftmost annotation of type <tt>cls</tt> that completely includes <tt>focusAnnotation</tt>. That is,
 * if multiple annotations of type <tt>cls</tt> include <tt>focusAnnotation</tt>, the one with the lowest begin
 * offset will be chosen.//from  www .  ja va2  s. c o  m
 * <p>
 * This algorithm has <tt>O(n)</tt> runtime with <tt>n</tt> being the number of annotations in the annotation index.
 * </p>
 * <p>
 * TODO: A start offset parameter could be introduced from where to start looking. This way, when iterating over a
 * number of different focusAnnotations in ascending order, one would have only to check from focusAnnotation to
 * focusAnnotation and not always from the very beginning of the annotation index. Same thing for
 * getPartiallyOverlappingAnnotation().
 * </p>
 * 
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return the leftmost annotation of type <tt>cls</tt> that completely includes <tt>focusAnnotation</tt>.
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> T getIncludingAnnotation(JCas aJCas, Annotation focusAnnotation,
        Class<T> cls) {
    FSIterator<Annotation> cursor = aJCas.getAnnotationIndex().iterator();

    // Annotations are sorted by begin offset and may be arbitrarily long. Thus we just have to start from the
    // beginning.
    cursor.moveToFirst();

    // Now go to the right as long as we don't yet overlap with the focus annotation, then stop.
    Annotation currentAnnotation = null;
    while (cursor.isValid() && ((currentAnnotation = cursor.get()).getEnd() < focusAnnotation.getEnd()
            || !cls.isInstance(currentAnnotation))) {
        cursor.moveToNext();
    }

    // Check whether we have found an overlapping annotation.
    Range<Integer> currentRange = Range.between(currentAnnotation.getBegin(), currentAnnotation.getEnd());
    Range<Integer> focusRange = Range.between(focusAnnotation.getBegin(), focusAnnotation.getEnd());
    if (cursor.isValid() && cls.isInstance(currentAnnotation) && currentRange.containsRange(focusRange))
        return (T) cursor.get();

    return null;
}

From source file:de.tor.tribes.util.algo.types.TimeFrame.java

public List<Range<Long>> arriveTimespansToRanges() {
    List<Range<Long>> ranges = new LinkedList<>();
    Date arriveDate = DateUtils.truncate(new Date(arriveNotBefore), Calendar.DAY_OF_MONTH);

    for (TimeSpan span : arriveTimeSpans) {
        if (!span.isValidAtEveryDay()) {
            Range<Long> range;
            //just copy range
            range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum());

            if (range.getMaximum() > System.currentTimeMillis()) {
                if (range.getMinimum() <= System.currentTimeMillis()) {
                    //rebuild Range
                    range = Range.between(System.currentTimeMillis(), range.getMaximum());
                }//from  ww w .  jav  a2  s. co m
                //add range only if it is in future
                ranges.add(range);
            }
        } else {
            //span is valid for every day
            Date thisDate = new Date(arriveDate.getTime());
            //go through all days from start to end
            while (thisDate.getTime() < arriveNotAfter) {
                long spanStart = thisDate.getTime() + span.getSpan().getMinimum();
                long spanEnd = thisDate.getTime() + span.getSpan().getMaximum();
                Range<Long> newRange = null;
                //check span location relative to start frame
                if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore && spanStart < arriveNotAfter
                        && spanEnd <= arriveNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //  |----| (SpanStart - SpanEnd)
                    newRange = Range.between(spanStart, spanEnd);
                } else if (spanStart < arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart < arriveNotAfter && spanEnd <= arriveNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|----| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(arriveNotBefore, spanEnd);
                } else if (spanStart <= arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart > arriveNotAfter && spanEnd >= arriveNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|--------------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(arriveNotBefore, arriveNotAfter);
                } else if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart < arriveNotAfter && spanEnd >= arriveNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //    |---------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(spanStart, arriveNotAfter);
                }

                if (newRange != null) {
                    if (newRange.getMinimum() < System.currentTimeMillis()) {
                        //check minimum as current minimum is in past
                        if (newRange.getMaximum() > System.currentTimeMillis()) {
                            newRange = Range.between(System.currentTimeMillis(), newRange.getMaximum());
                            ranges.add(newRange);
                        } //ignore as entire range is in past
                    } else {
                        //add range as it is in future
                        ranges.add(newRange);
                    }
                }
                //increment current date by one day
                thisDate = DateUtils.addDays(thisDate, 1);
            }
        }
    }
    Collections.sort(ranges, new Comparator<Range<Long>>() {
        @Override
        public int compare(Range<Long> o1, Range<Long> o2) {
            return o1.getMinimum().compareTo(o2.getMinimum());
        }
    });
    return ranges;
}

From source file:de.julielab.jcore.utility.JCoReAnnotationTools.java

/**
 * Returns the nearest annotation of class <tt>cls</tt> to <tt>focusAnnotation</tt>, i.e. the one (or just one, if
 * multiple exist) with the highest start-offset that completely overlaps <tt>focusAnnotation</tt>.
 * <p>/*w  ww. j a  v a 2s  .c  o m*/
 * This method has nice performance properties when it is known that the annotation looked for is near, e.g. finding
 * the nearest token or sentence.
 * </p>
 * 
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return the leftmost annotation of type <tt>cls</tt> that completely includes <tt>focusAnnotation</tt>.
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> T getNearestIncludingAnnotation(JCas aJCas, Annotation focusAnnotation,
        Class<T> cls) {
    FSIterator<Annotation> cursor = aJCas.getAnnotationIndex().iterator();

    if (!cursor.isValid())
        throw new IllegalArgumentException(
                "Given FocusAnnotation was not found in the JCas' annotation index: " + focusAnnotation);

    // The annotations are sorted by begin offset. So go to the first annotation with a larger begin offset compared
    // to the focusAnnotation. Afterwards we we search for an including annotation to the left.
    cursor.moveTo(focusAnnotation);
    while (cursor.isValid() && cursor.get().getBegin() <= focusAnnotation.getBegin()) {
        cursor.moveToNext();
    }
    if (!cursor.isValid())
        cursor.moveTo(focusAnnotation);
    else
        cursor.moveToPrevious();

    // Now that we have our starting point, we go to the left until we find the first annotation of correct type
    // completely overlapping the focus annotation.
    while (cursor.isValid()) {
        Annotation currentAnnotation = cursor.get();
        if (!cls.isInstance(currentAnnotation)) {
            cursor.moveToPrevious();
            continue;
        }
        Range<Integer> currentRange = Range.between(currentAnnotation.getBegin(), currentAnnotation.getEnd());
        Range<Integer> focusRange = Range.between(focusAnnotation.getBegin(), focusAnnotation.getEnd());
        if (cursor.isValid() && cls.isInstance(currentAnnotation) && currentRange.containsRange(focusRange))
            return (T) currentAnnotation;
        cursor.moveToPrevious();
    }
    return null;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Range<Long> extractRangeIfAvailable(String min, String max, Long absoluteMin, Long absoluteMax) {
    if (!NumberUtils.isNumber(min) || !NumberUtils.isNumber(max)) {
        return null;
    }//  w ww.  j  a v a 2 s. c  o m

    Range<Long> ret = Range.between(Long.valueOf(min), Long.valueOf(max));

    if (absoluteMin != null && ret.getMinimum() < absoluteMin) {
        return null;
    }

    if (absoluteMax != null && ret.getMaximum() > absoluteMax) {
        return null;
    }

    return ret;
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * fromInclusive &le; o &le; toInclusive.
 *
 * @param o the object, number or string.
 * @param fromInclusive start of range./*from   www . j  a  va2  s  .  com*/
 * @param toInclusive end of range.
 * @return fromInclusive &le; o &le; toInclusive.
 */
public static boolean contains(final Object o, final Number fromInclusive, final Number toInclusive) {
    if (fromInclusive == null && toInclusive == null)
        return false;
    if (valueOf(o) == null)
        return false;
    if (isNaN(o))
        return isNaN(fromInclusive) || isNaN(toInclusive);
    if (BigDecimal.class.equals((fromInclusive == null ? toInclusive : fromInclusive).getClass())) {
        if (fromInclusive == null)
            return compareTo(valueOf(o, BigDecimal.class), (BigDecimal) toInclusive) < 1;
        if (toInclusive == null)
            return compareTo((BigDecimal) fromInclusive, valueOf(o, BigDecimal.class)) < 1;
    }
    if (BigInteger.class.equals((fromInclusive == null ? toInclusive : fromInclusive).getClass())) {
        if (fromInclusive == null)
            return compareTo(valueOf(o, BigDecimal.class), new BigDecimal((BigInteger) toInclusive)) < 1;
        if (toInclusive == null)
            return compareTo(new BigDecimal((BigInteger) fromInclusive), valueOf(o, BigDecimal.class)) < 1;
    }
    if (fromInclusive == null)
        return compareTo(valueOf(o, Double.class), valueOf(toInclusive, Double.class)) < 1;
    if (toInclusive == null)
        return compareTo(valueOf(fromInclusive, Double.class), valueOf(o, Double.class)) < 1;

    return Range.between(valueOf(fromInclusive, Double.class), valueOf(toInclusive, Double.class))
            .contains(valueOf(o, Double.class));
}

From source file:de.tor.tribes.ui.wiz.ref.SupportRefillCalculationPanel.java

protected TimeFrame getTimeFrame() {
    if (jRadioNoArrive.isSelected()) {
        //add 1 Jear to timespan to ensure that every movement is possible
        TimeFrame f = new TimeFrame(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
                new Date(System.currentTimeMillis() + 60 * 60 * 24 * 365 * 1000),
                new Date(System.currentTimeMillis() + 60 * 60 * 24 * 365 * 1000));

        f.addArriveTimeSpan(new TimeSpan(Range.between(0l, 24l * DateUtils.MILLIS_PER_HOUR), true));
        f.addStartTimeSpan(new TimeSpan(Range.between(0l, 24l * DateUtils.MILLIS_PER_HOUR), true));
        return f;
    } else if (jRadioLastArrive.isSelected()) {
        Date arrive = jArriveTime.getSelectedDate();
        TimeFrame f = new TimeFrame(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
                arrive, arrive);//from   w w w  .  java 2s.c om
        f.addStartTimeSpan(new TimeSpan(Range.between(System.currentTimeMillis(), arrive.getTime()), false));
        f.addArriveTimeSpan(new TimeSpan(Range.between(0l, 24l * DateUtils.MILLIS_PER_HOUR), true));
        return f;
    } else if (jRadioFixedArrive.isSelected()) {
        Date arrive = jArriveTime.getSelectedDate();
        TimeFrame f = new TimeFrame(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
                arrive, arrive);
        f.addArriveTimeSpan(new TimeSpan(arrive));
        f.addStartTimeSpan(new TimeSpan(Range.between(0l, 24l * DateUtils.MILLIS_PER_HOUR), true));
        return f;
    } else {
        notifyStatusUpdate("Kein Ankunftszeit Typ gew\u00E4hlt");
        notifyStatusUpdate("Berechnung abgebrochen!");
        return null;
    }
}

From source file:de.tor.tribes.ui.windows.ReportRulesDialog.java

private void fireAddRuleEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireAddRuleEvent

    Component c = jRuleSettingsPanel.getComponent(0);
    String targetReportSet = jTargetReportSet.getText();
    if (targetReportSet == null || targetReportSet.length() == 0) {
        return;/*from  ww  w.j  ava2 s  . c om*/
    }
    try {
        ReportRule rule;
        if (c == jReportColorPanel) {
            Integer value = 0;
            value += (jGreyBox.isSelected()) ? ReportRule.GREY : 0;
            value += (jBlueBox.isSelected()) ? ReportRule.BLUE : 0;
            value += (jGreenBox.isSelected()) ? ReportRule.GREEN : 0;
            value += (jYellowBox.isSelected()) ? ReportRule.YELLOW : 0;
            value += (jRedBox.isSelected()) ? ReportRule.RED : 0;
            rule = new ReportRule(ReportRule.RuleType.COLOR, value, targetReportSet);
        } else if (c == jDatePanel) {
            Range<Long> span = Range.between(jMinDate.getDate().getTime(),
                    jMaxDate.getDate().getTime() + DateUtils.MILLIS_PER_DAY);
            rule = new ReportRule(ReportRule.RuleType.DATE, span, targetReportSet);
        } else if (c == jAgePanel) {
            long val;
            try {
                val = Long.parseLong(jMaxAge.getText());
            } catch (Exception e) {
                val = 365;
            }
            val = val * DateUtils.MILLIS_PER_DAY;
            rule = new ReportRule(ReportRule.RuleType.AGE, val, targetReportSet);
        } else if (c == jAttackerPanel) {
            List<Tribe> tribeList = new ArrayList<>();

            for (String tribe : jAttackerTextArea.getText().split(";")) {
                Tribe t = DataHolder.getSingleton().getTribeByName(tribe);
                if (t != null) {
                    tribeList.add(t);
                }
            }
            rule = new ReportRule(ReportRule.RuleType.ATTACKER_TRIBE, tribeList, targetReportSet);
        } else if (c == jDefenderPanel) {
            List<Tribe> tribeList = new ArrayList<>();

            for (String tribe : jDefenderTextArea.getText().split(";")) {
                Tribe t = DataHolder.getSingleton().getTribeByName(tribe);
                if (t != null) {
                    tribeList.add(t);
                }
            }
            rule = new ReportRule(ReportRule.RuleType.DEFENDER_TRIBE, tribeList, targetReportSet);
        } else if (c == jAttackerAllyPanel) {
            List<Ally> allyList = new ArrayList<>();

            for (String ally : jAttackerAllyTextArea.getText().split(";")) {
                Ally a = DataHolder.getSingleton().getAllyByName(ally);
                if (a != null) {
                    allyList.add(a);
                }
            }
            rule = new ReportRule(ReportRule.RuleType.ATTACKER_ALLY, allyList, targetReportSet);
        } else if (c == jDefenderAllyPanel) {
            List<Ally> allyList = new ArrayList<>();

            for (String ally : jDefenderAllyTextArea.getText().split(";")) {
                Ally a = DataHolder.getSingleton().getAllyByName(ally);
                if (a != null) {
                    allyList.add(a);
                }
            }
            rule = new ReportRule(ReportRule.RuleType.DEFENDER_ALLY, allyList, targetReportSet);
        } else {
            //no settings panel
            if (jNoSettingsType.getText().equals("OFF")) {
                rule = new ReportRule(ReportRule.RuleType.OFF, null, targetReportSet);
            } else if (jNoSettingsType.getText().equals("FAKE")) {
                rule = new ReportRule(ReportRule.RuleType.FAKE, null, targetReportSet);
            } else if (jNoSettingsType.getText().equals("SNOB")) {
                rule = new ReportRule(ReportRule.RuleType.CONQUERED, null, targetReportSet);
            } else if (jNoSettingsType.getText().equals("WALL")) {
                rule = new ReportRule(ReportRule.RuleType.WALL, null, targetReportSet);
            } else if (jNoSettingsType.getText().equals("BUILDING")) {
                rule = new ReportRule(ReportRule.RuleType.CATA, null, targetReportSet);
            } else {
                logger.warn("Reached unreachable code part");
                return;
            }
        }

        ReportManager.getSingleton().addRule(rule);
        rebuildRuleList();
    } catch (IllegalArgumentException e) {
        logger.debug("Failed to create Rule", e);
        String message = "Regel konnte nicht erstellt werden.\nBitte prfe die Einstellungen.";
        if (e.getMessage() != null) {
            message += "\n\nFehler: " + e.getMessage();
        }
        JOptionPaneHelper.showWarningBox(this, message, "Warnung");
    }
}

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

/**
 * Return the notes that have a start beat between the specified beats.
 * //from ww  w .j a v  a2s. co  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:nl.minvenj.pef.util.TestUtil.java

public static Range<Long> range(final long fromInclusive, final long toInclusive) {
    return Range.between(fromInclusive, toInclusive);
}

From source file:org.amanzi.awe.distribution.model.type.impl.NumberDistributionType.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from  w  ww.  j  a  v  a  2 s.c  om*/
public Set<SimpleRange> getRanges() {
    if (ranges == null) {

        ranges = new LinkedHashSet<SimpleRange>();

        double min = Double.MAX_VALUE;
        double max = -Double.MAX_VALUE;

        for (final Object value : getModel().getPropertyStatistics().getValues(getNodeType(),
                getPropertyName())) {
            final double currentValue = ((Number) value).doubleValue();

            min = Math.min(min, currentValue);
            max = Math.max(max, currentValue);
        }

        final double step = getStep(min, max, numberDistributionRange.getDelta());

        while (Precision.compareTo(max, min, PRECISION_DELTA) > 0) {
            final boolean includeMax = Precision.compareTo(max, min + step, PRECISION_DELTA) > 0;

            final double curMax = includeMax ? increaseMinimum(min, step) : max;
            final RangeFilterType filterType = includeMax ? RangeFilterType.INCLUDE_START_AND_END
                    : RangeFilterType.INCLUDE_START_EXCLUDE_END;

            final Range range = Range.between(min, curMax);

            final RangeFilter filter = new RangeFilter(getPropertyName(), range, filterType);
            ranges.add(new SimpleRange(getNumberDistributionRangeName(min, curMax), filter));

            min = increaseMinimum(min, step);
        }
    }

    return ranges;
}