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

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

Introduction

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

Prototype

public C upperEndpoint() 

Source Link

Document

Returns the upper endpoint of this range.

Usage

From source file:net.sf.mzmine.modules.masslistmethods.ADAPchromatogrambuilder.ChromatogramBuilderTask.java

/**
 * @see Runnable#run()/*  w  ww.ja v a2  s  .c om*/
 */
public void run() {
    boolean writeChromCDF = true;

    setStatus(TaskStatus.PROCESSING);

    logger.info("Started chromatogram builder on " + dataFile);

    scans = scanSelection.getMatchingScans(dataFile);
    int allScanNumbers[] = scanSelection.getMatchingScanNumbers(dataFile);

    List<Double> rtListForChromCDF = new ArrayList<Double>();

    // Check if the scans are properly ordered by RT
    double prevRT = Double.NEGATIVE_INFINITY;
    for (Scan s : scans) {
        if (isCanceled()) {
            return;
        }

        if (writeChromCDF) {
            rtListForChromCDF.add(s.getRetentionTime());
        }

        if (s.getRetentionTime() < prevRT) {
            setStatus(TaskStatus.ERROR);
            final String msg = "Retention time of scan #" + s.getScanNumber()
                    + " is smaller then the retention time of the previous scan."
                    + " Please make sure you only use scans with increasing retention times."
                    + " You can restrict the scan numbers in the parameters, or you can use the Crop filter module";
            setErrorMessage(msg);
            return;
        }
        prevRT = s.getRetentionTime();
    }

    // Create new peak list
    newPeakList = new SimplePeakList(dataFile + " " + suffix, dataFile);

    // make a list of all the data points
    // sort data points by intensity
    // loop through list 
    //      add data point to chromatogrm or make new one
    //      update mz avg and other stuff
    // 

    // make a list of all the data points
    List<ExpandedDataPoint> allMzValues = new ArrayList<ExpandedDataPoint>();

    for (Scan scan : scans) {
        if (isCanceled())
            return;

        MassList massList = scan.getMassList(massListName);
        if (massList == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Scan " + dataFile + " #" + scan.getScanNumber() + " does not have a mass list "
                    + massListName);
            return;
        }

        DataPoint mzValues[] = massList.getDataPoints();

        if (mzValues == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Mass list " + massListName + " does not contain m/z values for scan #"
                    + scan.getScanNumber() + " of file " + dataFile);
            return;
        }

        for (DataPoint mzPeak : mzValues) {
            ExpandedDataPoint curDatP = new ExpandedDataPoint(mzPeak, scan.getScanNumber());
            allMzValues.add(curDatP);
            //corespondingScanNum.add(scan.getScanNumber());
        }

    }

    //Integer[] simpleCorespondingScanNums = new Integer[corespondingScanNum.size()];
    //corespondingScanNum.toArray(simpleCorespondingScanNums );

    ExpandedDataPoint[] simpleAllMzVals = new ExpandedDataPoint[allMzValues.size()];
    allMzValues.toArray(simpleAllMzVals);

    // sort data points by intensity
    Arrays.sort(simpleAllMzVals, new DataPointSorter(SortingProperty.Intensity, SortingDirection.Descending));

    //Set<Chromatogram> buildingChromatograms;
    //buildingChromatograms = new LinkedHashSet<Chromatogram>();

    double maxIntensity = simpleAllMzVals[0].getIntensity();

    // count starts at 1 since we already have added one with a single point.

    //Stopwatch stopwatch = Stopwatch.createUnstarted(); 
    // stopwatch2 = Stopwatch.createUnstarted(); 
    //Stopwatch stopwatch3 = Stopwatch.createUnstarted(); 

    totalPoints = simpleAllMzVals.length;

    for (ExpandedDataPoint mzPeak : simpleAllMzVals) {
        if (isCanceled()) {
            return;
        }

        if (mzPeak == null) {
            //System.out.println("null Peak");
            continue;
        }

        //////////////////////////////////////////////////

        Range<Double> containsPointRange = rangeSet.rangeContaining(mzPeak.getMZ());

        Range<Double> toleranceRange = mzTolerance.getToleranceRange(mzPeak.getMZ());
        if (containsPointRange == null) {
            // skip it entierly if the intensity is not high enough
            if (mzPeak.getIntensity() < minIntensityForStartChrom) {
                continue;
            }
            // look +- mz tolerance to see if ther is a range near by. 
            // If there is use the proper boundry of that range for the 
            // new range to insure than NON OF THE RANGES OVERLAP.
            Range<Double> plusRange = rangeSet.rangeContaining(toleranceRange.upperEndpoint());
            Range<Double> minusRange = rangeSet.rangeContaining(toleranceRange.lowerEndpoint());
            Double toBeLowerBound;
            Double toBeUpperBound;

            double cur_max_testing_mz = mzPeak.getMZ();

            // If both of the above ranges are null then we make the new range spaning the full
            // mz tolerance range. 
            // If one or both are not null we need to properly modify the range of the new
            // chromatogram so that none of the points are overlapping.
            if ((plusRange == null) && (minusRange == null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();
            } else if ((plusRange == null) && (minusRange != null)) {
                // the upper end point of the minus range will be the lower 
                // range of the new one
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();

            } else if ((minusRange == null) && (plusRange != null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
                //                    double tmp_this = plusRange.upperEndpoint();
                //                    System.out.println("tmp_this");
            } else if ((minusRange != null) && (plusRange != null)) {
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
            } else {
                toBeLowerBound = 0.0;
                toBeUpperBound = 0.0;
            }
            Range<Double> newRange = Range.open(toBeLowerBound, toBeUpperBound);
            Chromatogram newChrom = new Chromatogram(dataFile, allScanNumbers);

            newChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);

            newChrom.setHighPointMZ(mzPeak.getMZ());

            rangeToChromMap.put(newRange, newChrom);
            // also need to put it in the set -> this is where the range can be efficiently found.

            rangeSet.add(newRange);
        } else {
            // In this case we do not need to update the rangeSet

            Chromatogram curChrom = rangeToChromMap.get(containsPointRange);

            curChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);

            //update the entry in the map
            rangeToChromMap.put(containsPointRange, curChrom);

        }

        processedPoints += 1;
    }

    //System.out.println("search chroms (ms): " +  stopwatch.elapsed(TimeUnit.MILLISECONDS));
    //System.out.println("making new chrom (ms): " +  stopwatch2.elapsed(TimeUnit.MILLISECONDS));

    // finish chromatograms
    Iterator<Range<Double>> RangeIterator = rangeSet.asRanges().iterator();

    List<Chromatogram> buildingChromatograms = new ArrayList<Chromatogram>();

    while (RangeIterator.hasNext()) {
        if (isCanceled()) {
            return;
        }

        Range<Double> curRangeKey = RangeIterator.next();

        Chromatogram chromatogram = rangeToChromMap.get(curRangeKey);

        chromatogram.finishChromatogram();

        // And remove chromatograms who dont have a certian number of continous points above the
        // IntensityThresh2 level.
        double numberOfContinuousPointsAboveNoise = chromatogram
                .findNumberOfContinuousPointsAboveNoise(IntensityThresh2);
        if (numberOfContinuousPointsAboveNoise < minimumScanSpan) {
            //System.out.println("skipping chromatogram because it does not meet the min point scan requirements");
            continue;
        } else {
            buildingChromatograms.add(chromatogram);
        }

    }

    Chromatogram[] chromatograms = buildingChromatograms.toArray(new Chromatogram[0]);

    // Sort the final chromatograms by m/z
    Arrays.sort(chromatograms, new PeakSorter(SortingProperty.MZ, SortingDirection.Ascending));

    // Add the chromatograms to the new peak list
    for (Feature finishedPeak : chromatograms) {
        SimplePeakListRow newRow = new SimplePeakListRow(newPeakID);
        newPeakID++;
        newRow.addPeak(dataFile, finishedPeak);
        newPeakList.addRow(newRow);

        //            finishedPeak.outputChromToFile();
    }

    // Add new peaklist to the project
    project.addPeakList(newPeakList);

    // Add quality parameters to peaks
    QualityParameters.calculateQualityParameters(newPeakList);

    setStatus(TaskStatus.FINISHED);

    logger.info("Finished chromatogram builder on " + dataFile);
}

From source file:net.sf.mzmine.modules.masslistmethods.ADAPchromatogrambuilder.ADAPChromatogramBuilderTask.java

/**
 * @see Runnable#run()//from w ww. j a v a2  s .  c o m
 */
public void run() {
    boolean writeChromCDF = true;

    setStatus(TaskStatus.PROCESSING);

    logger.info("Started chromatogram builder on " + dataFile);

    scans = scanSelection.getMatchingScans(dataFile);
    int allScanNumbers[] = scanSelection.getMatchingScanNumbers(dataFile);

    List<Double> rtListForChromCDF = new ArrayList<Double>();

    // Check if the scans are properly ordered by RT
    double prevRT = Double.NEGATIVE_INFINITY;
    for (Scan s : scans) {
        if (isCanceled()) {
            return;
        }

        if (writeChromCDF) {
            rtListForChromCDF.add(s.getRetentionTime());
        }

        if (s.getRetentionTime() < prevRT) {
            setStatus(TaskStatus.ERROR);
            final String msg = "Retention time of scan #" + s.getScanNumber()
                    + " is smaller then the retention time of the previous scan."
                    + " Please make sure you only use scans with increasing retention times."
                    + " You can restrict the scan numbers in the parameters, or you can use the Crop filter module";
            setErrorMessage(msg);
            return;
        }
        prevRT = s.getRetentionTime();
    }

    // Create new peak list
    newPeakList = new SimplePeakList(dataFile + " " + suffix, dataFile);

    // make a list of all the data points
    // sort data points by intensity
    // loop through list 
    //      add data point to chromatogrm or make new one
    //      update mz avg and other stuff
    // 

    // make a list of all the data points
    List<ExpandedDataPoint> allMzValues = new ArrayList<ExpandedDataPoint>();

    for (Scan scan : scans) {
        if (isCanceled())
            return;

        MassList massList = scan.getMassList(massListName);
        if (massList == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Scan " + dataFile + " #" + scan.getScanNumber() + " does not have a mass list "
                    + massListName);
            return;
        }

        DataPoint mzValues[] = massList.getDataPoints();

        if (mzValues == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Mass list " + massListName + " does not contain m/z values for scan #"
                    + scan.getScanNumber() + " of file " + dataFile);
            return;
        }

        for (DataPoint mzPeak : mzValues) {
            ExpandedDataPoint curDatP = new ExpandedDataPoint(mzPeak, scan.getScanNumber());
            allMzValues.add(curDatP);
            //corespondingScanNum.add(scan.getScanNumber());
        }

    }

    //Integer[] simpleCorespondingScanNums = new Integer[corespondingScanNum.size()];
    //corespondingScanNum.toArray(simpleCorespondingScanNums );

    ExpandedDataPoint[] simpleAllMzVals = new ExpandedDataPoint[allMzValues.size()];
    allMzValues.toArray(simpleAllMzVals);

    // sort data points by intensity
    Arrays.sort(simpleAllMzVals, new DataPointSorter(SortingProperty.Intensity, SortingDirection.Descending));

    //Set<Chromatogram> buildingChromatograms;
    //buildingChromatograms = new LinkedHashSet<Chromatogram>();

    double maxIntensity = simpleAllMzVals[0].getIntensity();

    // count starts at 1 since we already have added one with a single point.

    //Stopwatch stopwatch = Stopwatch.createUnstarted(); 
    // stopwatch2 = Stopwatch.createUnstarted(); 
    //Stopwatch stopwatch3 = Stopwatch.createUnstarted(); 

    processedPoints = 0;
    totalPoints = simpleAllMzVals.length;

    for (ExpandedDataPoint mzPeak : simpleAllMzVals) {

        processedPoints++;

        if (isCanceled()) {
            return;
        }

        if (mzPeak == null) {
            //System.out.println("null Peak");
            continue;
        }

        //////////////////////////////////////////////////

        Range<Double> containsPointRange = rangeSet.rangeContaining(mzPeak.getMZ());

        Range<Double> toleranceRange = mzTolerance.getToleranceRange(mzPeak.getMZ());
        if (containsPointRange == null) {
            // skip it entierly if the intensity is not high enough
            if (mzPeak.getIntensity() < minIntensityForStartChrom) {
                continue;
            }
            // look +- mz tolerance to see if ther is a range near by. 
            // If there is use the proper boundry of that range for the 
            // new range to insure than NON OF THE RANGES OVERLAP.
            Range<Double> plusRange = rangeSet.rangeContaining(toleranceRange.upperEndpoint());
            Range<Double> minusRange = rangeSet.rangeContaining(toleranceRange.lowerEndpoint());
            Double toBeLowerBound;
            Double toBeUpperBound;

            double cur_max_testing_mz = mzPeak.getMZ();

            // If both of the above ranges are null then we make the new range spaning the full
            // mz tolerance range. 
            // If one or both are not null we need to properly modify the range of the new
            // chromatogram so that none of the points are overlapping.
            if ((plusRange == null) && (minusRange == null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();
            } else if ((plusRange == null) && (minusRange != null)) {
                // the upper end point of the minus range will be the lower 
                // range of the new one
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();

            } else if ((minusRange == null) && (plusRange != null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
                //                    double tmp_this = plusRange.upperEndpoint();
                //                    System.out.println("tmp_this");
            } else if ((minusRange != null) && (plusRange != null)) {
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
            } else {
                toBeLowerBound = 0.0;
                toBeUpperBound = 0.0;
            }
            Range<Double> newRange = Range.open(toBeLowerBound, toBeUpperBound);
            ADAPChromatogram newChrom = new ADAPChromatogram(dataFile, allScanNumbers);

            newChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);

            newChrom.setHighPointMZ(mzPeak.getMZ());

            rangeToChromMap.put(newRange, newChrom);
            // also need to put it in the set -> this is where the range can be efficiently found.

            rangeSet.add(newRange);
        } else {
            // In this case we do not need to update the rangeSet

            ADAPChromatogram curChrom = rangeToChromMap.get(containsPointRange);

            curChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);

            //update the entry in the map
            rangeToChromMap.put(containsPointRange, curChrom);

        }
    }

    //System.out.println("search chroms (ms): " +  stopwatch.elapsed(TimeUnit.MILLISECONDS));
    //System.out.println("making new chrom (ms): " +  stopwatch2.elapsed(TimeUnit.MILLISECONDS));

    // finish chromatograms
    Iterator<Range<Double>> RangeIterator = rangeSet.asRanges().iterator();

    List<ADAPChromatogram> buildingChromatograms = new ArrayList<ADAPChromatogram>();

    while (RangeIterator.hasNext()) {
        if (isCanceled()) {
            return;
        }

        Range<Double> curRangeKey = RangeIterator.next();

        ADAPChromatogram chromatogram = rangeToChromMap.get(curRangeKey);

        chromatogram.finishChromatogram();

        // And remove chromatograms who dont have a certian number of continous points above the
        // IntensityThresh2 level.
        double numberOfContinuousPointsAboveNoise = chromatogram
                .findNumberOfContinuousPointsAboveNoise(IntensityThresh2);
        if (numberOfContinuousPointsAboveNoise < minimumScanSpan) {
            //System.out.println("skipping chromatogram because it does not meet the min point scan requirements");
            continue;
        } else {
            buildingChromatograms.add(chromatogram);
        }

    }

    ADAPChromatogram[] chromatograms = buildingChromatograms.toArray(new ADAPChromatogram[0]);

    // Sort the final chromatograms by m/z
    Arrays.sort(chromatograms, new PeakSorter(SortingProperty.MZ, SortingDirection.Ascending));

    // Add the chromatograms to the new peak list
    for (Feature finishedPeak : chromatograms) {
        SimplePeakListRow newRow = new SimplePeakListRow(newPeakID);
        newPeakID++;
        newRow.addPeak(dataFile, finishedPeak);
        newPeakList.addRow(newRow);

        //            finishedPeak.outputChromToFile();
    }

    // Add new peaklist to the project
    project.addPeakList(newPeakList);

    // Add quality parameters to peaks
    QualityParameters.calculateQualityParameters(newPeakList);

    setStatus(TaskStatus.FINISHED);

    logger.info("Finished chromatogram builder on " + dataFile);
}

From source file:com.nimbits.server.io.BlobStoreImpl.java

@Override
public List<ValueBlobStore> mergeTimespan(final Entity entity, final Range<Date> timespan) {
    PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();

    PrintWriter out = null;//from w w  w.j  a va  2 s .  com
    try {
        String fn = UUID.randomUUID().toString();

        out = new PrintWriter(fn);

        final Query q = pm.newQuery(ValueBlobStoreEntity.class);

        q.setFilter("entity == k && minTimestamp <= et && minTimestamp >= st ");
        q.declareParameters("String k, Long et, Long st");
        q.setOrdering("minTimestamp desc");

        final List<ValueBlobStore> result = (List<ValueBlobStore>) q.execute(entity.getKey(),
                timespan.upperEndpoint().getTime(), timespan.lowerEndpoint().getTime());

        Collection<Value> combined = new ArrayList<Value>();
        Date timestamp = null;
        for (ValueBlobStore store : result) {
            if (timestamp == null || timestamp.getTime() > store.getTimestamp().getTime()) {
                timestamp = store.getTimestamp();

            }
            List<Value> read = readValuesFromFile((store.getBlobKey()));
            combined.addAll(read);
            deleteBlobStore(store.getBlobKey());

        }

        pm.deletePersistentAll(result);

        long max = 0;
        long min = 0;
        for (Value v : combined) {
            if (v.getTimestamp().getTime() > max) {
                max = v.getTimestamp().getTime();
            }
            if (v.getTimestamp().getTime() < min || min == 0) {
                min = v.getTimestamp().getTime();
            }
        }

        String json = gson.toJson(combined);
        // byte[] compressed = CompressionImpl.compressBytes(json);
        out.print(json);
        out.close();

        ValueBlobStore currentStoreEntity = new ValueBlobStoreEntity(entity.getKey(), timestamp, new Date(max),
                new Date(min), fn, json.length(), BlobStore.storageVersion, entity.getUUID());

        currentStoreEntity.validate();
        pm.makePersistent(currentStoreEntity);
        pm.flush();
        return ValueBlobStoreFactory.createValueBlobStore(currentStoreEntity);
    } catch (IOException ex) {
        return Collections.emptyList();

    } finally {
        if (out != null) {
            out.close();
        }
        pm.close();
    }

}

From source file:org.robotframework.ide.eclipse.main.plugin.tableeditor.settings.GeneralSettingsFormFragment.java

private void setDocumentationMatches(final HeaderFilterMatchesCollection settingsMatches) {
    clearDocumentationMatches();//from w  w  w  .  j av a  2s .c  o  m
    final Collection<Range<Integer>> ranges = settingsMatches.getRanges(documentation.getText());
    for (final Range<Integer> range : ranges) {
        final Color bg = ColorsManager.getColor(255, 255, 175);
        documentation.setStyleRange(
                new StyleRange(range.lowerEndpoint(), range.upperEndpoint() - range.lowerEndpoint(), null, bg));
    }
}

From source file:org.graylog2.commands.journal.JournalDecode.java

@Override
protected void runCommand() {

    Range<Long> range;
    try {/*w  ww. j  av a  2 s .  co  m*/
        final List<String> offsets = Splitter.on("..").limit(2).splitToList(rangeArg);
        if (offsets.size() == 1) {
            range = Range.singleton(Long.valueOf(offsets.get(0)));
        } else if (offsets.size() == 2) {
            final String first = offsets.get(0);
            final String second = offsets.get(1);
            if (first.isEmpty()) {
                range = Range.atMost(Long.valueOf(second));
            } else if (second.isEmpty()) {
                range = Range.atLeast(Long.valueOf(first));
            } else {
                range = Range.closed(Long.valueOf(first), Long.valueOf(second));
            }
        } else {
            throw new RuntimeException();
        }
    } catch (Exception e) {
        System.err.println("Malformed offset range: " + rangeArg);
        return;
    }

    final Map<String, Codec.Factory<? extends Codec>> codecFactory = injector
            .getInstance(Key.get(new TypeLiteral<Map<String, Codec.Factory<? extends Codec>>>() {
            }));

    final Long readOffset = range.lowerEndpoint();
    final long count = range.upperEndpoint() - range.lowerEndpoint() + 1;
    final List<Journal.JournalReadEntry> entries = journal.read(readOffset, count);
    for (final Journal.JournalReadEntry entry : entries) {
        final RawMessage raw = RawMessage.decode(entry.getPayload(), entry.getOffset());
        if (raw == null) {
            System.err.println(
                    MessageFormatter.format("Journal entry at offset {} failed to decode", entry.getOffset()));
            continue;
        }

        final Codec codec = codecFactory.get(raw.getCodecName()).create(raw.getCodecConfig());
        final Message message = codec.decode(raw);
        if (message == null) {
            System.err.println(
                    MessageFormatter.format("Could not use codec {} to decode raw message id {} at offset {}",
                            new Object[] { raw.getCodecName(), raw.getId(), entry.getOffset() }));
        } else {
            message.setJournalOffset(raw.getJournalOffset());
        }

        final ResolvableInetSocketAddress remoteAddress = raw.getRemoteAddress();
        final String remote = remoteAddress == null ? "unknown address"
                : remoteAddress.getInetSocketAddress().toString();

        final StringBuffer sb = new StringBuffer();
        sb.append("Message ").append(raw.getId()).append('\n').append(" at ").append(raw.getTimestamp())
                .append('\n').append(" in format ").append(raw.getCodecName()).append('\n')
                .append(" at offset ").append(raw.getJournalOffset()).append('\n')
                .append(" received from remote address ").append(remote).append('\n').append(" (source field: ")
                .append(message == null ? "unparsed" : message.getSource()).append(')').append('\n');
        if (message != null) {
            sb.append(" contains ").append(message.getFieldNames().size()).append(" fields.");
        } else {
            sb.append("The message could not be parse by the given codec.");
        }
        System.out.println(sb);
    }

}

From source file:com.github.drbookings.ui.controller.MainController.java

private void updateStatusLabelFX() {

    final ObservableList<RoomBean> selectedRooms = RoomBeanSelectionManager.getInstance().selectionProperty();
    final List<BookingEntry> selectedBookings = selectedRooms.stream()
            .flatMap(r -> r.getBookingEntries().stream())
            .filter(new BookingFilter(guestNameFilterInput.getText())).collect(Collectors.toList());
    Range<LocalDate> selectedRange = DateBeanSelectionManager.getInstance().getSelectedDateRange();
    if (selectedRange == null) {

    } else {/*from   ww w  .ja  va2 s  .  co  m*/
        StringBuilder sb = new StringBuilder();
        sb.append(selectedRange.lowerEndpoint());
        sb.append("  ");
        sb.append(selectedRange.upperEndpoint());
        selectedDatesLabel.setText(sb.toString());
    }

    final BookingsByOrigin<BookingEntry> bo = new BookingsByOrigin<>(selectedBookings);
    final StringBuilder sb = new StringBuilder(new StatusLabelStringFactory(bo).build());

    // sb.append("\tPerformance total:" +
    // StatusLabelStringFactory.DECIMAL_FORMAT.format(pc.getProfit()) + "
    // \t"
    // + "Performance/hour:" +
    // StatusLabelStringFactory.DECIMAL_FORMAT.format(pc.getProfitPerHour()));
    statusLabel.textProperty().set(sb.toString());
}

From source file:fr.openwide.core.export.excel.AbstractExcelTableExport.java

/**
 * Ajoute les en-ttes dans la feuille de calcul et cache les colonnes qui doivent l'tre.
 * /* w w w  . j a  v a2s . c  o  m*/
 * @param sheet feuille de calcul
 * @param rowIndex numro de la ligne
 * @param columnInfos RangeMap contenant les informations de colonnes (valeurs) et les index sur auxquelles s'appliquent ces colonnes (cls).
 *                    Les "colonnes" s'tendant sur plus d'un index seront automatiquement fusionnes.
 */
protected void addHeadersToSheet(Sheet sheet, int rowIndex, RangeMap<Integer, ColumnInformation> columnInfos) {
    Row rowHeader = sheet.createRow(rowIndex);
    for (Map.Entry<Range<Integer>, ColumnInformation> entry : columnInfos.asMapOfRanges().entrySet()) {
        Range<Integer> range = entry.getKey();
        ColumnInformation columnInformation = entry.getValue();

        addHeaderCell(rowHeader, range.lowerEndpoint(), getColumnLabel(columnInformation.getHeaderKey()));

        for (Integer columnIndex : ContiguousSet.create(range, DiscreteDomain.integers())) {
            sheet.setColumnHidden(columnIndex, columnInformation.isHidden());
        }

        int beginIndex = range.lowerEndpoint();
        int endIndex = range.upperEndpoint();
        if (beginIndex != endIndex) {
            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, beginIndex, endIndex));
        }
    }
}

From source file:org.apache.calcite.rex.RexSimplify.java

private static RexNode processRange(RexBuilder rexBuilder, List<RexNode> terms,
        Map<String, Pair<Range, List<RexNode>>> rangeTerms, RexNode term, RexNode ref, RexLiteral constant,
        SqlKind comparison) {/*from www.  java 2  s  .  c  om*/
    final Comparable v0 = constant.getValue();
    Pair<Range, List<RexNode>> p = rangeTerms.get(ref.toString());
    if (p == null) {
        Range r;
        switch (comparison) {
        case EQUALS:
            r = Range.singleton(v0);
            break;
        case LESS_THAN:
            r = Range.lessThan(v0);
            break;
        case LESS_THAN_OR_EQUAL:
            r = Range.atMost(v0);
            break;
        case GREATER_THAN:
            r = Range.greaterThan(v0);
            break;
        case GREATER_THAN_OR_EQUAL:
            r = Range.atLeast(v0);
            break;
        default:
            throw new AssertionError();
        }
        rangeTerms.put(ref.toString(), new Pair(r, ImmutableList.of(term)));
    } else {
        // Exists
        boolean removeUpperBound = false;
        boolean removeLowerBound = false;
        Range r = p.left;
        switch (comparison) {
        case EQUALS:
            if (!r.contains(v0)) {
                // Range is empty, not satisfiable
                return rexBuilder.makeLiteral(false);
            }
            rangeTerms.put(ref.toString(), new Pair(Range.singleton(v0), ImmutableList.of(term)));
            // remove
            terms.removeAll(p.right);
            break;
        case LESS_THAN: {
            int comparisonResult = 0;
            if (r.hasUpperBound()) {
                comparisonResult = v0.compareTo(r.upperEndpoint());
            }
            if (comparisonResult <= 0) {
                // 1) No upper bound, or
                // 2) We need to open the upper bound, or
                // 3) New upper bound is lower than old upper bound
                if (r.hasLowerBound()) {
                    if (v0.compareTo(r.lowerEndpoint()) < 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x < b OR a < x < b
                    r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.OPEN);
                } else {
                    // x < b
                    r = Range.lessThan(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev upper bound
                removeUpperBound = true;
            } else {
                // Remove this term as it is contained in current upper bound
                terms.remove(term);
            }
            break;
        }
        case LESS_THAN_OR_EQUAL: {
            int comparisonResult = -1;
            if (r.hasUpperBound()) {
                comparisonResult = v0.compareTo(r.upperEndpoint());
            }
            if (comparisonResult < 0) {
                // 1) No upper bound, or
                // 2) New upper bound is lower than old upper bound
                if (r.hasLowerBound()) {
                    if (v0.compareTo(r.lowerEndpoint()) < 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x <= b OR a < x <= b
                    r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.CLOSED);
                } else {
                    // x <= b
                    r = Range.atMost(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev upper bound
                removeUpperBound = true;
            } else {
                // Remove this term as it is contained in current upper bound
                terms.remove(term);
            }
            break;
        }
        case GREATER_THAN: {
            int comparisonResult = 0;
            if (r.hasLowerBound()) {
                comparisonResult = v0.compareTo(r.lowerEndpoint());
            }
            if (comparisonResult >= 0) {
                // 1) No lower bound, or
                // 2) We need to open the lower bound, or
                // 3) New lower bound is greater than old lower bound
                if (r.hasUpperBound()) {
                    if (v0.compareTo(r.upperEndpoint()) > 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a < x <= b OR a < x < b
                    r = Range.range(v0, BoundType.OPEN, r.upperEndpoint(), r.upperBoundType());
                } else {
                    // x > a
                    r = Range.greaterThan(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev lower bound
                removeLowerBound = true;
            } else {
                // Remove this term as it is contained in current lower bound
                terms.remove(term);
            }
            break;
        }
        case GREATER_THAN_OR_EQUAL: {
            int comparisonResult = 1;
            if (r.hasLowerBound()) {
                comparisonResult = v0.compareTo(r.lowerEndpoint());
            }
            if (comparisonResult > 0) {
                // 1) No lower bound, or
                // 2) New lower bound is greater than old lower bound
                if (r.hasUpperBound()) {
                    if (v0.compareTo(r.upperEndpoint()) > 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x <= b OR a <= x < b
                    r = Range.range(v0, BoundType.CLOSED, r.upperEndpoint(), r.upperBoundType());
                } else {
                    // x >= a
                    r = Range.atLeast(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev lower bound
                removeLowerBound = true;
            } else {
                // Remove this term as it is contained in current lower bound
                terms.remove(term);
            }
            break;
        }
        default:
            throw new AssertionError();
        }
        if (removeUpperBound) {
            ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder();
            for (RexNode e : p.right) {
                if (e.isA(SqlKind.LESS_THAN) || e.isA(SqlKind.LESS_THAN_OR_EQUAL)) {
                    terms.remove(e);
                } else {
                    newBounds.add(e);
                }
            }
            newBounds.add(term);
            rangeTerms.put(ref.toString(), new Pair(r, newBounds.build()));
        } else if (removeLowerBound) {
            ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder();
            for (RexNode e : p.right) {
                if (e.isA(SqlKind.GREATER_THAN) || e.isA(SqlKind.GREATER_THAN_OR_EQUAL)) {
                    terms.remove(e);
                } else {
                    newBounds.add(e);
                }
            }
            newBounds.add(term);
            rangeTerms.put(ref.toString(), new Pair(r, newBounds.build()));
        }
    }
    // Default
    return null;
}

From source file:io.github.mzmine.modules.plots.chromatogram.ChromatogramPlotModule.java

@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
        @Nonnull Collection<Task<?>> tasks) {

    final List<RawDataFile> dataFiles = parameters.getParameter(ChromatogramPlotParameters.inputFiles)
            .getValue().getMatchingRawDataFiles();
    final ScanSelection scanSelection = parameters.getParameter(ChromatogramPlotParameters.scanSelection)
            .getValue();//  w  w  w.j  a v a 2s. c  o m
    final ChromatogramPlotType plotType = parameters.getParameter(ChromatogramPlotParameters.plotType)
            .getValue();
    final Range<Double> mzRange = parameters.getParameter(ChromatogramPlotParameters.mzRange).getValue();

    try {
        // Load the main window
        URL mainFXML = this.getClass().getResource(PLOT_FXML);
        FXMLLoader loader = new FXMLLoader(mainFXML);

        Parent node = loader.load();
        MZmineGUI.addWindow(node, "Chromatogram");
        ChromatogramPlotWindowController controller = loader.getController();

        for (RawDataFile dataFile : dataFiles) {

            // Load the actual data in a separate thread to avoid blocking
            // the GUI
            threadPool.execute(() -> {
                try {
                    DataPointStore store = DataPointStoreFactory.getMemoryDataStore();
                    List<MsScan> scans = scanSelection.getMatchingScans(dataFile);
                    ChromatogramType chromatogramType = ChromatogramType.TIC;
                    if (plotType == ChromatogramPlotType.BASEPEAK)
                        chromatogramType = ChromatogramType.BPC;
                    MSDKXICMethod xicExtractor = new MSDKXICMethod(dataFile, scans, mzRange, chromatogramType,
                            store);
                    Chromatogram chromatogram = xicExtractor.execute();
                    String title = dataFile.getName() + " " + chromatogramType + " [" + mzRange.lowerEndpoint()
                            + "-" + mzRange.upperEndpoint() + " m/z]";
                    Platform.runLater(() -> controller.addChromatogram(chromatogram, title));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.pingcap.tikv.predicates.ScanBuilder.java

private List<KeyRange> buildIndexScanKeyRange(TiTableInfo table, TiIndexInfo index,
        List<IndexRange> indexRanges) {
    requireNonNull(table, "Table cannot be null to encoding keyRange");
    requireNonNull(index, "Index cannot be null to encoding keyRange");
    requireNonNull(index, "indexRanges cannot be null to encoding keyRange");

    List<KeyRange> ranges = new ArrayList<>(indexRanges.size());

    for (IndexRange ir : indexRanges) {
        CodecDataOutput cdo = new CodecDataOutput();
        List<Object> values = ir.getAccessPoints();
        List<DataType> types = ir.getTypes();
        for (int i = 0; i < values.size(); i++) {
            Object v = values.get(i);
            DataType t = types.get(i);/*ww  w  .j  a  v a  2  s.c o  m*/
            t.encode(cdo, DataType.EncodeType.KEY, v);
        }

        byte[] pointsData = cdo.toBytes();

        cdo.reset();
        Range r = ir.getRange();
        byte[] lPointKey;
        byte[] uPointKey;

        byte[] lKey;
        byte[] uKey;
        if (r == null) {
            lPointKey = pointsData;
            uPointKey = KeyUtils.prefixNext(lPointKey.clone());

            lKey = new byte[0];
            uKey = new byte[0];
        } else {
            lPointKey = pointsData;
            uPointKey = pointsData;

            DataType type = ir.getRangeType();
            if (!r.hasLowerBound()) {
                // -INF
                type.encodeMinValue(cdo);
                lKey = cdo.toBytes();
            } else {
                Object lb = r.lowerEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, lb);
                lKey = cdo.toBytes();
                if (r.lowerBoundType().equals(BoundType.OPEN)) {
                    lKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
            if (!r.hasUpperBound()) {
                // INF
                type.encodeMaxValue(cdo);
                uKey = cdo.toBytes();
            } else {
                Object ub = r.upperEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, ub);
                uKey = cdo.toBytes();
                if (r.upperBoundType().equals(BoundType.CLOSED)) {
                    uKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
        }
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), lPointKey, lKey);

        ByteString lbsKey = ByteString.copyFrom(cdo.toBytes());

        cdo.reset();
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), uPointKey, uKey);
        ByteString ubsKey = ByteString.copyFrom(cdo.toBytes());

        ranges.add(KeyRange.newBuilder().setStart(lbsKey).setEnd(ubsKey).build());
    }

    if (ranges.isEmpty()) {
        ranges.add(INDEX_FULL_RANGE);
    }
    return ranges;
}