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

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

Introduction

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

Prototype

public T getMinimum() 

Source Link

Document

Gets the minimum value in this range.

Usage

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

public String getStringRepresentation() {
    switch (type) {
    case AGE:/*  w w w .  j  a va2 s  .  c  o  m*/
        return "Bericht lter als " + DurationFormatUtils.formatDuration((Long) filterComponent, "dd", false)
                + " Tag(e)";
    case ATTACKER_ALLY:
        return "Angreifende Stmme " + StringUtils.join((List<Ally>) filterComponent, ", ");
    case ATTACKER_TRIBE:
        return "Angreifer " + StringUtils.join((List<Tribe>) filterComponent, ", ");
    case CATA:
        return "Berichte mit Gebudebeschdigung";
    case COLOR:
        StringBuilder result = new StringBuilder();
        int color = (Integer) filterComponent;
        result.append("Farben:");
        if ((color & GREY) > 0)
            result.append(" grau");

        if ((color & BLUE) > 0)
            result.append(" blau");

        if ((color & GREEN) > 0)
            result.append(" grn");

        if ((color & YELLOW) > 0)
            result.append(" gelb");

        if ((color & RED) > 0)
            result.append(" rot");

        return result.toString();
    case CONQUERED:
        return "AG-Angriffe/Eroberungen";
    case DATE:
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy");
        Range<Long> dates = (Range<Long>) filterComponent;
        return "Gesendet zwischen " + df.format(new Date(dates.getMinimum())) + " und "
                + df.format(new Date(dates.getMaximum()));
    case DEFENDER_ALLY:
        return "Verteidigende Stmme " + StringUtils.join((List<Ally>) filterComponent, ", ");
    case DEFENDER_TRIBE:
        return "Verteidiger " + StringUtils.join((List<Tribe>) filterComponent, ", ");
    case FAKE:
        return "Fakes";
    case FARM:
        return "Farmberichte";
    case OFF:
        return "Off-Berichte";
    case WALL:
        return "Berichte mit Wallbeschdigung";
    default:
        throw new IllegalArgumentException("wrong type");
    }
}

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

/**
 * Returns an arrive date that fits into this AttackFitter and is based on the
 * provided runtime//from   w w w . ja  v  a 2  s.com
 *
 * @param pRuntime Runtime to fit into
 * @param pVillage Village for which the arrive date should be valid
 * @param pUsedSendTimes Already used send times (possible times are checked
 * in steps of 1ms). This argument may be 'null'. Then send times are
 * not checked.
 * @return Date Fitted arrive time
 */
public Date getFittedArriveTime(long pRuntime, List<Long> pUsedSendTimes) {
    List<Range<Long>> startRanges = startTimespansToRanges();
    List<Range<Long>> arriveRanges = arriveTimespansToRanges();
    List<Range<Long>> possible = new ArrayList();
    for (Range<Long> currentStartRange : startRanges) {
        Range<Long> arriveRangeForStartRange = Range.between(currentStartRange.getMinimum() + pRuntime,
                currentStartRange.getMaximum() + pRuntime);
        for (Range<Long> currentArriveRange : arriveRanges) {
            if (currentArriveRange.isOverlappedBy(arriveRangeForStartRange)) {
                //movement possible for these 'currentStartRange' and 'currentArriveRange' so fit runtime into
                //           |-----------|
                //   |--------------|
                long minArrive = currentArriveRange.getMinimum();
                long minArriveForStartRange = arriveRangeForStartRange.getMinimum();
                long checkStart = 0;
                if (minArrive < minArriveForStartRange) {
                    //|----------- (Arrive)
                    //   |-------------- (ArriveForStart)
                    //check everything beginning with 'minArriveForStartRange'
                    checkStart = minArriveForStartRange;
                } else if (minArriveForStartRange <= minArrive) {
                    //     |----------- (Arrive)
                    //|-------------- (ArriveForStart)
                    //check everything beginning with 'minArrive'
                    checkStart = minArrive;
                }
                long maxArrive = currentArriveRange.getMaximum();
                long maxArriveForStartRange = arriveRangeForStartRange.getMaximum();
                long checkEnd = 0;
                if (maxArrive < maxArriveForStartRange) {
                    //-----------| (Arrive)
                    //---------------| (ArriveForStart)
                    //check everything until 'maxArrive'
                    checkEnd = maxArrive;
                } else if (maxArriveForStartRange <= maxArrive) {
                    //-------------| (Arrive)
                    //---------| (ArriveForStart)
                    //check everything until 'maxArriveForStartRange'
                    checkEnd = maxArriveForStartRange;
                }

                if (checkStart != checkEnd) {
                    //We are handling real Ranges
                    int cnt = 0;
                    while (cnt < 20) {
                        long arriveTime = checkStart + Math.round(Math.random() * (checkEnd - checkStart));
                        if (pUsedSendTimes == null || !pUsedSendTimes.contains(arriveTime - pRuntime)) {
                            if (pUsedSendTimes != null) {
                                pUsedSendTimes.add(arriveTime - pRuntime);
                            }
                            return new Date(arriveTime);
                        }
                        cnt++;
                    }
                    //We found nothing with random, try systematic search
                    for (long i = checkStart; i <= checkEnd; i++) {
                        if (!pUsedSendTimes.contains(i - pRuntime)) {
                            pUsedSendTimes.add(i - pRuntime);
                            return new Date(i);
                        }
                    }
                } else {
                    //We are handling a fixed arrive Time
                    if (pUsedSendTimes == null || !pUsedSendTimes.contains(checkStart - pRuntime)) {
                        if (pUsedSendTimes != null) {
                            pUsedSendTimes.add(checkStart - pRuntime);
                        }
                        return new Date(checkStart);
                    }
                }
                possible.add(Range.between(checkStart, checkEnd));
            }
        }
    }

    if (!possible.isEmpty()) {
        long cnt = 0;
        for (Range<Long> r : possible) {
            cnt += r.getMaximum() - r.getMinimum() + 1;
        }
        cnt = (long) (Math.random() * cnt);
        for (Range<Long> r : possible) {
            Long span = r.getMaximum() - r.getMinimum() + 1;
            if (cnt < span) {
                return new Date(r.getMinimum() + cnt);
            }
            cnt -= span;
        }
    }

    return null;
}

From source file:forge.deck.DeckFormat.java

public String getDeckConformanceProblem(Deck deck) {
    if (deck == null) {
        return "is not selected";
    }/*ww  w  . ja v  a 2s. c om*/

    int deckSize = deck.getMain().countAll();

    int min = getMainRange().getMinimum();
    int max = getMainRange().getMaximum();

    // TODO "Your minimum deck size is reduced by five."
    // Adjust minimum base on number of Advantageous Proclamation or similar cards

    if (deckSize < min) {
        return String.format("should have at least %d cards", min);
    }

    if (deckSize > max) {
        return String.format("should have no more than %d cards", max);
    }

    if (hasCommander()) { //Must contain exactly 1 legendary Commander and a sideboard of 10 or zero cards.
        final CardPool cmd = deck.get(DeckSection.Commander);
        if (cmd == null || cmd.isEmpty()) {
            return "is missing a commander";
        }
        if (!isLegalCommander(cmd.get(0).getRules())) {
            return "has an illegal commander";
        }

        final ColorSet cmdCI = cmd.get(0).getRules().getColorIdentity();
        final List<PaperCard> erroneousCI = new ArrayList<PaperCard>();

        for (final Entry<PaperCard, Integer> cp : deck.get(DeckSection.Main)) {
            if (!cp.getKey().getRules().getColorIdentity().hasNoColorsExcept(cmdCI.getColor())) {
                erroneousCI.add(cp.getKey());
            }
        }
        if (deck.has(DeckSection.Sideboard)) {
            for (final Entry<PaperCard, Integer> cp : deck.get(DeckSection.Sideboard)) {
                if (!cp.getKey().getRules().getColorIdentity().hasNoColorsExcept(cmdCI.getColor())) {
                    erroneousCI.add(cp.getKey());
                }
            }
        }

        if (erroneousCI.size() > 0) {
            StringBuilder sb = new StringBuilder(
                    "contains one or more cards that do not match the commanders color identity:");

            for (PaperCard cp : erroneousCI) {
                sb.append("\n").append(cp.getName());
            }

            return sb.toString();
        }
    }

    if (cardPoolFilter != null) {
        final List<PaperCard> erroneousCI = new ArrayList<PaperCard>();
        for (final Entry<PaperCard, Integer> cp : deck.getAllCardsInASinglePool()) {
            if (!cardPoolFilter.apply(cp.getKey().getRules())) {
                erroneousCI.add(cp.getKey());
            }
        }
        if (erroneousCI.size() > 0) {
            final StringBuilder sb = new StringBuilder("contains the following illegal cards:\n");

            for (final PaperCard cp : erroneousCI) {
                sb.append("\n").append(cp.getName());
            }

            return sb.toString();
        }
    }

    final int maxCopies = getMaxCardCopies();
    if (maxCopies < Integer.MAX_VALUE) {
        //Must contain no more than 4 of the same card
        //shared among the main deck and sideboard, except
        //basic lands, Shadowborn Apostle and Relentless Rats

        final CardPool allCards = deck.getAllCardsInASinglePool(hasCommander());
        final ImmutableSet<String> limitExceptions = ImmutableSet.of("Relentless Rats", "Shadowborn Apostle");

        // should group all cards by name, so that different editions of same card are really counted as the same card
        for (final Entry<String, Integer> cp : Aggregates.groupSumBy(allCards, PaperCard.FN_GET_NAME)) {
            final IPaperCard simpleCard = StaticData.instance().getCommonCards().getCard(cp.getKey());
            if (simpleCard == null) {
                return String.format("contains the nonexisting card %s", cp.getKey());
            }

            final boolean canHaveMultiple = simpleCard.getRules().getType().isBasicLand()
                    || limitExceptions.contains(cp.getKey());
            if (!canHaveMultiple && cp.getValue() > maxCopies) {
                return String.format("must not contain more than %d copies of the card %s", maxCopies,
                        cp.getKey());
            }
        }
    }

    // The sideboard must contain either 0 or 15 cards
    int sideboardSize = deck.has(DeckSection.Sideboard) ? deck.get(DeckSection.Sideboard).countAll() : 0;
    Range<Integer> sbRange = getSideRange();
    if (sbRange != null && sideboardSize > 0 && !sbRange.contains(sideboardSize)) {
        return sbRange.getMinimum() == sbRange.getMaximum()
                ? String.format("must have a sideboard of %d cards or no sideboard at all",
                        sbRange.getMaximum())
                : String.format("must have a sideboard of %d to %d cards or no sideboard at all",
                        sbRange.getMinimum(), sbRange.getMaximum());
    }

    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());
                }// ww  w  . ja  va  2s .  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.tor.tribes.types.TimeSpan.java

public boolean intersects(TimeSpan pSpan) {
    if (!this.getDirection().equals(pSpan.getDirection())) {
        //different directions
        return false;
    }/*from   www .j a  va2s. 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:de.tor.tribes.util.algo.types.TimeFrame.java

public List<Range<Long>> startTimespansToRanges() {
    List<Range<Long>> ranges = new LinkedList<>();
    Date startDate = DateUtils.truncate(new Date(startNotBefore), Calendar.DATE);

    for (TimeSpan span : sendTimeSpans) {
        if (!span.isValidAtEveryDay()) {
            Range<Long> range;
            //just copy range
            if (span.isValidAtExactTime()) {
                range = Range.between(span.getSpan().getMinimum(),
                        span.getSpan().getMaximum() + fixedStartTimeRangeSize);
            } else {
                range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum());
            }/*  w w  w .  j  a  va  2 s  .  c  o m*/

            if (range.getMaximum() > System.currentTimeMillis()) {
                if (range.getMinimum() <= System.currentTimeMillis()) {
                    //rebuild Range
                    range = Range.between(System.currentTimeMillis(), range.getMaximum());
                }
                //add range only if it is in future
                ranges.add(range);
            }
        } else {
            //span is valid for every day
            Date thisDate = new Date(startDate.getTime());
            //go through all days from start to end
            while (thisDate.getTime() < startNotAfter) {
                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 >= startNotBefore && spanEnd > startNotBefore && spanStart < startNotAfter
                        && spanEnd <= startNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //  |----| (SpanStart - SpanEnd)
                    newRange = Range.between(spanStart, spanEnd);
                } else if (spanStart < startNotBefore && spanEnd > startNotBefore && spanStart < startNotAfter
                        && spanEnd <= startNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|----| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(startNotBefore, spanEnd);
                } else if (spanStart <= startNotBefore && spanEnd > startNotBefore && spanStart > startNotAfter
                        && spanEnd >= startNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|--------------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(startNotBefore, startNotAfter);
                } else if (spanStart >= startNotBefore && spanEnd > startNotBefore && spanStart < startNotAfter
                        && spanEnd >= startNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //    |---------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(spanStart, startNotAfter);
                }

                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.tor.tribes.ui.algo.AttackTimePanel.java

/**
 * Get the currently set up send span/*w  w w .  j av  a  2 s.c  om*/
 *
 * @return TimeSpan The send span
 */
private TimeSpan getSendSpan() {
    TimeSpan start = null;
    Range<Long> range = Range.between(
            Math.round(jSendTimeFrame.getMinimumColoredValue()) * DateUtils.MILLIS_PER_HOUR,
            Math.round(jSendTimeFrame.getMaximumColoredValue()) * DateUtils.MILLIS_PER_HOUR);
    if (Objects.equals(range.getMinimum(), range.getMaximum()) && !jExactTimeButton.isSelected()) {
        return null;
    }

    if (jAlwaysButton.isSelected()) {
        start = new TimeSpan(range, true);
    } else if (jDayButton.isSelected()) {
        range = Range.between(dateTimeField.getSelectedDate().getTime() + range.getMinimum(),
                dateTimeField.getSelectedDate().getTime() + range.getMaximum());
        start = new TimeSpan(range, false);
    } else if (jExactTimeButton.isSelected()) {
        start = new TimeSpan(dateTimeField.getSelectedDate());
    }
    if (start != null) {
        start.setDirection(TimeSpan.DIRECTION.SEND);
    }

    return start;
}

From source file:de.tor.tribes.ui.algo.AttackTimePanel.java

/**
 * Get the currently set up arrive span/*from w  ww .  jav  a  2 s .co  m*/
 *
 * @return TimeSpan The arrive span
 */
private TimeSpan getArriveSpan() {
    TimeSpan arrive = null;
    Range<Long> range = Range.between(
            Math.round(jSendTimeFrame.getMinimumColoredValue()) * DateUtils.MILLIS_PER_HOUR,
            Math.round(jSendTimeFrame.getMaximumColoredValue()) * DateUtils.MILLIS_PER_HOUR);
    if (Objects.equals(range.getMinimum(), range.getMaximum()) && !jExactTimeButton.isSelected()) {
        return null;
    }

    if (jAlwaysButton.isSelected()) {
        arrive = new TimeSpan(range, true);
    } else if (jDayButton.isSelected()) {
        range = Range.between(dateTimeField.getSelectedDate().getTime() + range.getMinimum(),
                dateTimeField.getSelectedDate().getTime() + range.getMaximum());
        arrive = new TimeSpan(range, false);
    } else if (jExactTimeButton.isSelected()) {
        arrive = new TimeSpan(dateTimeField.getSelectedDate());
    }
    if (arrive != null) {
        arrive.setDirection(TimeSpan.DIRECTION.ARRIVE);
    }

    return arrive;
}

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   ww  w.  j a  v a 2  s . com
        }
        // 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.bitbucket.mlopatkin.android.logviewer.TooltipGenerator.java

/**
 * Splits the text into several parts: unhighlighted - highlighted -
 * unhighlighted - ... Each part can be empty.
 * /*w  w  w  .j  av a2s. c om*/
 * @return parts of the text splitted accorded to highlighting
 */
private String[] splitWithHighlights() {
    String[] result = new String[highlightRanges.size() * 2 + 1];
    int strPos = 0;
    int resultPos = 0;
    for (Range<Integer> r : highlightRanges) {
        result[resultPos++] = text.substring(strPos, r.getMinimum());
        result[resultPos++] = text.substring(r.getMinimum(), r.getMaximum());
        strPos = r.getMaximum();
    }
    result[resultPos] = text.substring(strPos);
    return result;
}