Example usage for com.google.common.collect Range lowerEndpoint

List of usage examples for com.google.common.collect Range lowerEndpoint

Introduction

In this page you can find the example usage for com.google.common.collect Range lowerEndpoint.

Prototype

public C lowerEndpoint() 

Source Link

Document

Returns the lower endpoint of this range.

Usage

From source file:com.google.googlejavaformat.java.JavaInput.java

public RangeSet<Integer> characterRangesToTokenRanges(Collection<Range<Integer>> characterRanges)
        throws FormatterException {
    RangeSet<Integer> tokenRangeSet = TreeRangeSet.create();
    for (Range<Integer> characterRange0 : characterRanges) {
        Range<Integer> characterRange = characterRange0.canonical(DiscreteDomain.integers());
        tokenRangeSet.add(characterRangeToTokenRange(characterRange.lowerEndpoint(),
                characterRange.upperEndpoint() - characterRange.lowerEndpoint()));
    }/*  w w  w. j ava  2  s  .co m*/
    return tokenRangeSet;
}

From source file:org.noroomattheinn.timeseries.PersistentTS.java

@Override
public final synchronized void streamRows(Range<Long> period, RowCollector collector) {
    double accumulator[] = new double[schema.nColumns];
    if (period == null)
        period = Range.all();/*www .  j av a 2  s .co  m*/
    long fromTime = period.hasLowerBound() ? period.lowerEndpoint() : 0L;
    long toTime = period.hasUpperBound() ? period.upperEndpoint() : Long.MAX_VALUE;
    long prevTime = 0;
    BufferedReader rdr = null;
    try {
        rdr = repo.getReader();
        String line;
        while ((line = rdr.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            }
            String[] tokens = line.split("\t");

            // The first entry on the line is the time in delta format
            Long time = longValue(tokens[0]);
            if (time == null) {
                continue;
            } // Invalid format, ignore this line
            time = time < 0 ? -time : time + prevTime;
            prevTime = time; // Keep a running tally of the current time

            time = inflate(time);
            if (time < fromTime)
                continue; // Out of range, ignore & move on
            if (time > toTime)
                break; // Out of range, ignore & stop

            Row row = new Row(time, 0L, schema.nColumns);

            // The second element is a bitvector corresponding to which
            // columns have values on this line
            Long bitVector = longValue("0x" + tokens[1]);
            if (bitVector == null) {
                continue;
            } // Invalid format, Ignore this line
            row.bitVector = bitVector;

            // The remaining entries are readings. There is one reading for
            // each 1 bit in the bitvector. The positions in the bitvector
            // correspond to the columns in the order initially specified
            long bit = 1;
            int tokenIndex = 2;
            for (int i = 0; i < schema.nColumns; i++) {
                row.values[i] = accumulator[i]; // Start off with the previous value
                if (row.includes(bit)) {
                    String valString = tokens[tokenIndex++];
                    switch (valString) {
                    case "*":
                        break;
                    case "!":
                        row.clear(bit);
                        break;
                    default:
                        Double val = doubleValue(valString);
                        if (val == null) {
                            row.clear(bit);
                        } else {
                            accumulator[i] = row.values[i] = val.doubleValue();
                        }
                        break;
                    }
                } else {
                    row.values[i] = accumulator[i];
                }
                bit = bit << 1;
            }
            if (!collector.collect(row))
                break;
        }
    } catch (IOException ex) {
        logger.severe("Error loading from repository" + ex);
    }
    if (rdr != null)
        try {
            rdr.close();
        } catch (IOException e) {
            logger.warning("Failure closing reader: " + e);
        }
}

From source file:com.giaybac.traprange.extractor.PDFTableExtractor.java

/**
 *
 * Remove all texts in excepted lines//ww  w .  j a va 2  s . c  o  m
 *
 * TexPositions are sorted by .getY() ASC
 *
 * @param lineRanges
 * @param textPositions
 * @return
 */
private List<TextPosition> getTextsByLineRanges(List<Range<Integer>> lineRanges,
        List<TextPosition> textPositions) {
    List<TextPosition> retVal = new ArrayList<>();
    int idx = 0;
    int lineIdx = 0;
    while (idx < textPositions.size() && lineIdx < lineRanges.size()) {
        TextPosition textPosition = textPositions.get(idx);
        Range<Integer> textRange = Range.closed((int) textPosition.getY(),
                (int) (textPosition.getY() + textPosition.getHeight()));
        Range<Integer> lineRange = lineRanges.get(lineIdx);
        if (lineRange.encloses(textRange)) {
            retVal.add(textPosition);
            idx++;
        } else if (lineRange.upperEndpoint() < textRange.lowerEndpoint()) {
            lineIdx++;
        } else {
            idx++;
        }
    }
    //return
    return retVal;
}

From source file:it.units.malelab.ege.ge.mapper.BitsSGEMapper.java

@Override
public Node<T> map(BitsGenotype genotype, Map<String, Object> report) throws MappingException {
    int[] bitUsages = new int[genotype.size()];
    //transform genotypes in ints
    if (genotype.size() < overallSize) {
        throw new MappingException(String.format("Short genotype (%d<%d)", genotype.size(), overallSize));
    }/*from   w  ww . java 2  s  .  com*/
    Map<Pair<T, Integer>, List<Range<Integer>>> codonRanges = new LinkedHashMap<>();
    List<Range<Integer>> nonTerminalRanges = Utils.slices(Range.closedOpen(0, genotype.size()),
            nonTerminalSizes);
    for (int i = 0; i < nonTerminals.size(); i++) {
        //int codonSize = (int) Math.max(Math.ceil(Math.log10(nonRecursiveGrammar.getRules().get(nonTerminals.get(i)).size()) / Math.log10(2)), 1);
        List<Range<Integer>> boundaries = Utils.slices(nonTerminalRanges.get(i),
                nonTerminalCodonsNumbers.get(i));
        codonRanges.put(nonTerminals.get(i), boundaries);
    }
    //map
    Multiset<Pair<T, Integer>> expandedSymbols = LinkedHashMultiset.create();
    Node<Pair<T, Integer>> tree = new Node<>(nonRecursiveGrammar.getStartingSymbol());
    while (true) {
        Node<Pair<T, Integer>> nodeToBeReplaced = null;
        for (Node<Pair<T, Integer>> node : tree.leafNodes()) {
            if (nonRecursiveGrammar.getRules().keySet().contains(node.getContent())) {
                nodeToBeReplaced = node;
                break;
            }
        }
        if (nodeToBeReplaced == null) {
            break;
        }
        //get codon
        Range<Integer> range = codonRanges.get(nodeToBeReplaced.getContent())
                .get(expandedSymbols.count(nodeToBeReplaced.getContent()));
        List<List<Pair<T, Integer>>> options = nonRecursiveGrammar.getRules()
                .get(nodeToBeReplaced.getContent());
        int codonSize = (int) Math.max(Math.ceil(Math.log10(options.size()) / Math.log10(2)), 1);
        int codonValue = genotype.slice(range).compress(codonSize).toInt();
        int optionIndex = codonValue % options.size();
        //update usages
        for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
            bitUsages[i] = bitUsages[i] + 1;
        }
        //add children
        for (Pair<T, Integer> p : options.get(optionIndex)) {
            Node<Pair<T, Integer>> newChild = new Node<>(p);
            nodeToBeReplaced.getChildren().add(newChild);
        }
        expandedSymbols.add(nodeToBeReplaced.getContent());
    }
    report.put(BIT_USAGES_INDEX_NAME, bitUsages);
    //transform tree
    return transform(tree);
}

From source file:com.yahoo.gondola.container.RoutingFilter.java

private long getRequestCount(Range<Integer> splitRange) {
    long requestCount = 0;
    for (int i = splitRange.lowerEndpoint(); i <= splitRange.upperEndpoint(); i++) {
        if (bucketRequestCounters.containsKey(i)) {
            requestCount += bucketRequestCounters.get(i).get();
        }//w w w . java 2s .  co  m
    }
    return requestCount;
}

From source file:com.google.googlejavaformat.java.JavaOutput.java

@Override
public void append(String text, Range<Integer> range) {
    if (!range.isEmpty()) {
        boolean sawNewlines = false;
        // Skip over input line we've passed.
        int iN = javaInput.getLineCount();
        while (iLine < iN && (javaInput.getRanges(iLine).isEmpty()
                || javaInput.getRanges(iLine).upperEndpoint() <= range.lowerEndpoint())) {
            if (javaInput.getRanges(iLine).isEmpty()) {
                // Skipped over a blank line.
                sawNewlines = true;/*from  w  w  w .  j  a v  a  2 s  . c  om*/
            }
            ++iLine;
        }
        /*
         * Output blank line if we've called {@link OpsBuilder#blankLine}{@code (true)} here, or if
         * there's a blank line here and it's a comment.
         */
        BlankLineWanted wanted = blankLines.getOrDefault(lastK, BlankLineWanted.NO);
        if (isComment(text) ? sawNewlines : wanted.wanted().orElse(sawNewlines)) {
            ++newlinesPending;
        }
    }
    if (Newlines.isNewline(text)) {
        /*
         * Don't update range information, and swallow extra newlines. The case below for '\n' is for
         * block comments.
         */
        if (newlinesPending == 0) {
            ++newlinesPending;
        }
        spacesPending = 0;
    } else {
        boolean rangesSet = false;
        int textN = text.length();
        for (int i = 0; i < textN; i++) {
            char c = text.charAt(i);
            switch (c) {
            case ' ':
                ++spacesPending;
                break;
            case '\r':
                if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
                    i++;
                }
                // falls through
            case '\n':
                spacesPending = 0;
                ++newlinesPending;
                break;
            default:
                while (newlinesPending > 0) {
                    // drop leading blank lines
                    if (!mutableLines.isEmpty() || lineBuilder.length() > 0) {
                        mutableLines.add(lineBuilder.toString());
                    }
                    lineBuilder = new StringBuilder();
                    rangesSet = false;
                    --newlinesPending;
                }
                while (spacesPending > 0) {
                    lineBuilder.append(' ');
                    --spacesPending;
                }
                lineBuilder.append(c);
                if (!range.isEmpty()) {
                    if (!rangesSet) {
                        while (ranges.size() <= mutableLines.size()) {
                            ranges.add(Formatter.EMPTY_RANGE);
                        }
                        ranges.set(mutableLines.size(), union(ranges.get(mutableLines.size()), range));
                        rangesSet = true;
                    }
                }
            }
        }
    }
    if (!range.isEmpty()) {
        lastK = range.upperEndpoint();
    }
}

From source file:net.sf.mzmine.modules.visualization.histogram.HistogramPlotDataset.java

public HistogramPlotDataset(PeakList peakList, RawDataFile[] rawDataFiles, int numOfBins,
        HistogramDataType dataType, Range<Double> range) {

    this.list = new Vector<HashMap<?, ?>>();
    this.type = HistogramType.FREQUENCY;
    this.dataType = dataType;
    this.peakList = peakList;
    this.numOfBins = numOfBins;
    this.rawDataFiles = rawDataFiles;

    minimum = range.lowerEndpoint();
    maximum = range.upperEndpoint();//from w w  w. j a v  a  2s .c om

    updateHistogramDataset();

}

From source file:net.sf.mzmine.util.components.PeakSummaryComponent.java

public void actionPerformed(ActionEvent e) {

    String command = e.getActionCommand();

    if (command.equals("SHOW")) {

        String visualizerType = (String) comboShow.getSelectedItem();
        int[] indexesRow = peaksInfoList.getSelectedRows();
        Feature[] selectedPeaks = new Feature[indexesRow.length];
        RawDataFile[] dataFiles = new RawDataFile[indexesRow.length];
        Range<Double> rtRange = null, mzRange = null;
        for (int i = 0; i < indexesRow.length; i++) {
            selectedPeaks[i] = listElementModel.getElementAt(indexesRow[i]);
            dataFiles[i] = selectedPeaks[i].getDataFile();

            if ((rtRange == null) || (mzRange == null)) {
                rtRange = dataFiles[i].getDataRTRange(1);
                mzRange = selectedPeaks[i].getRawDataPointsMZRange();
            } else {
                rtRange = rtRange.span(dataFiles[i].getDataRTRange(1));
                mzRange = mzRange.span(selectedPeaks[i].getRawDataPointsMZRange());
            }//from   w  w w.  j  av  a2  s.com
        }

        if (dataFiles.length == 0) {
            return;
        }

        if (visualizerType.equals("Chromatogram")) {

            // Label best peak with preferred identity.
            final Feature bestPeak = row.getBestPeak();
            final PeakIdentity peakIdentity = row.getPreferredPeakIdentity();
            final Map<Feature, String> labelMap = new HashMap<Feature, String>(1);
            if (bestPeak != null && peakIdentity != null) {

                labelMap.put(bestPeak, peakIdentity.getName());
            }

            ScanSelection scanSelection = new ScanSelection(rtRange, 1);

            TICVisualizerModule.showNewTICVisualizerWindow(dataFiles, selectedPeaks, labelMap, scanSelection,
                    TICPlotType.BASEPEAK, mzRange);
            return;

        } else if (visualizerType.equals("Mass spectrum")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i],
                        selectedPeaks[i].getRepresentativeScanNumber());
            }
        } else if (visualizerType.equals("Peak in 2D")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                Range<Double> peakRTRange = selectedPeaks[i].getRawDataPointsRTRange();
                Range<Double> peakMZRange = selectedPeaks[i].getRawDataPointsMZRange();
                final double rtLen = peakRTRange.upperEndpoint() - peakRTRange.lowerEndpoint();
                Range<Double> localRTRange = Range.closed(Math.max(0, peakRTRange.lowerEndpoint() - rtLen),
                        peakRTRange.upperEndpoint() + rtLen);

                final double mzLen = peakMZRange.upperEndpoint() - peakMZRange.lowerEndpoint();
                Range<Double> localMZRange = Range.closed(Math.max(0, peakMZRange.lowerEndpoint() - mzLen),
                        peakMZRange.upperEndpoint() + mzLen);
                TwoDVisualizerModule.show2DVisualizerSetupDialog(dataFiles[i], localMZRange, localRTRange);
            }
        } else if (visualizerType.equals("Peak in 3D")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                Range<Double> peakRTRange = selectedPeaks[i].getRawDataPointsRTRange();
                Range<Double> peakMZRange = selectedPeaks[i].getRawDataPointsMZRange();
                final double rtLen = peakRTRange.upperEndpoint() - peakRTRange.lowerEndpoint();
                Range<Double> localRTRange = Range.closed(Math.max(0, peakRTRange.lowerEndpoint() - rtLen),
                        peakRTRange.upperEndpoint() + rtLen);
                final double mzLen = peakMZRange.upperEndpoint() - peakMZRange.lowerEndpoint();
                Range<Double> localMZRange = Range.closed(Math.max(0, peakMZRange.lowerEndpoint() - mzLen),
                        peakMZRange.upperEndpoint() + mzLen);
                ThreeDVisualizerModule.setupNew3DVisualizer(dataFiles[i], localMZRange, localRTRange);
            }
        } else if (visualizerType.equals("MS/MS")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                int scanNumber = selectedPeaks[i].getMostIntenseFragmentScanNumber();
                if (scanNumber > 0) {
                    SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i], scanNumber);
                } else {
                    JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this);
                    MZmineCore.getDesktop().displayMessage(frame, "There is no fragment for the mass "
                            + MZmineCore.getConfiguration().getMZFormat().format(selectedPeaks[i].getMZ())
                            + "m/z in the current raw data.");
                    return;
                }
            }

        } else if (visualizerType.equals("Isotope pattern")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                IsotopePattern ip = selectedPeaks[i].getIsotopePattern();
                if (ip == null) {
                    return;
                }
                SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i],
                        selectedPeaks[i].getMostIntenseFragmentScanNumber(), ip);

            }
        }
        return;
    }

    if (command.equals("CHANGE")) {
        int indexRow = peaksInfoList.getSelectedRow();
        if (indexRow == -1) {
            return;
        }
        Feature selectedPeak = listElementModel.getElementAt(indexRow);
        ManualPeakPickerModule.runManualDetection(selectedPeak.getDataFile(), row, null, null);

        return;
    }

}

From source file:com.wealdtech.utils.RangeFormatter.java

/**
 * Format the dates of a date/time range.
 *
 * @param range the range to format/*from   ww  w .  j av a 2  s  .com*/
 * @return the formatted range, or {@code null} if the input is {@code null}
 */
@Nullable
public String formatDate(@Nullable final Range<DateTime> range) {
    if (range == null || style == Style.TIME_ONLY) {
        return null;
    }

    final DateTime curDateTime = DateTime.now();
    final StringBuilder sb = new StringBuilder(64);

    // Dates.  Note that because we are working with dates and dates are closed/open we need to take a day away from the upper
    // date to make the format look right
    final DateTime lower = range.lowerEndpoint();
    final DateTime upper = range.upperEndpoint().minusDays(1);
    if (upper.isBefore(lower)) {
        throw new DataError.Bad("Upper part of range must be after lower part of range");
    }

    final boolean singleDay = isSameDay(lower, upper);

    // Lower date
    final Details lowerDetails = new Details();
    lowerDetails.showTime = false;
    lowerDetails.showDayOfWeek = true;
    lowerDetails.showDayOfMonth = true;

    if (!isSameMonth(lower, upper) || singleDay) {
        lowerDetails.showMonthOfYear = true;
    }
    if ((!isSameYear(lower, curDateTime)) && (singleDay || !isSameYear(lower, upper))) {
        lowerDetails.showYear = true;
    }
    sb.append(doFormat(lower, lowerDetails));

    if (!isSameDay(lower, upper)) {
        sb.append(" - ");

        final Details upperDetails = new Details();
        upperDetails.showTime = false;
        upperDetails.showDayOfWeek = true;
        upperDetails.showDayOfMonth = true;
        upperDetails.showMonthOfYear = true;
        if ((!isSameYear(lower, upper)) || (!isSameYear(upper, curDateTime))) {
            upperDetails.showYear = true;
        }

        sb.append(doFormat(upper, upperDetails));
    } else {
        // Need to append month and year if applicable
        if (!isSameMonth(lower, curDateTime)) {
            lowerDetails.showMonthOfYear = true;
        }
        if (!isSameYear(lower, curDateTime)) {
            lowerDetails.showYear = true;
        }
    }

    return sb.toString();
}

From source file:coolmap.application.widget.impl.WidgetUserGroup.java

private void init() {

    table.getTableHeader().setReorderingAllowed(false);
    table.setAutoCreateRowSorter(true);/*from   w  w  w .  j a v  a  2s. c  om*/
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (isSelected) {
                return label;
            }

            if (column == 1) {
                try {
                    label.setBackground(
                            nodeColor.get(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0)));
                } catch (Exception e) {

                }
            } else {
                label.setBackground(UI.colorWhite);
            }

            return label;
        }

    });
    //Need a search box as well.

    //
    getContentPane().setLayout(new BorderLayout());

    //
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    JToolBar t = new JToolBar();
    getContentPane().add(t, BorderLayout.NORTH);
    t.setFloatable(false);

    try {
        //also add an action to add group nodes
        JMenuItem item = new JMenuItem("selected row nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedRows();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeRow(i));
                    }
                }

                createNewGroup(selectedNodes);

                //create a group
            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);

        item = new JMenuItem("selected column nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedColumns();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeColumn(i));
                    }
                }

                createNewGroup(selectedNodes);

            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);
    } catch (Exception e) {
        //
        //Error handling.
    }

}