Example usage for java.util SortedSet first

List of usage examples for java.util SortedSet first

Introduction

In this page you can find the example usage for java.util SortedSet first.

Prototype

E first();

Source Link

Document

Returns the first (lowest) element currently in this set.

Usage

From source file:org.apache.hadoop.hbase.regionserver.StoreFileReader.java

/**
 * Checks whether the given scan passes the Bloom filter (if present). Only
 * checks Bloom filters for single-row or single-row-column scans. Bloom
 * filter checking for multi-gets is implemented as part of the store
 * scanner system (see {@link StoreFileScanner#seekExactly}) and uses
 * the lower-level API {@link #passesGeneralRowBloomFilter(byte[], int, int)}
 * and {@link #passesGeneralRowColBloomFilter(Cell)}.
 *
 * @param scan the scan specification. Used to determine the row, and to
 *          check whether this is a single-row ("get") scan.
 * @param columns the set of columns. Only used for row-column Bloom
 *          filters./* w  ww.j a  v a2 s .  c om*/
 * @return true if the scan with the given column set passes the Bloom
 *         filter, or if the Bloom filter is not applicable for the scan.
 *         False if the Bloom filter is applicable and the scan fails it.
 */
boolean passesBloomFilter(Scan scan, final SortedSet<byte[]> columns) {
    // Multi-column non-get scans will use Bloom filters through the
    // lower-level API function that this function calls.
    if (!scan.isGetScan()) {
        return true;
    }

    byte[] row = scan.getStartRow();
    switch (this.bloomFilterType) {
    case ROW:
        return passesGeneralRowBloomFilter(row, 0, row.length);

    case ROWCOL:
        if (columns != null && columns.size() == 1) {
            byte[] column = columns.first();
            // create the required fake key
            Cell kvKey = KeyValueUtil.createFirstOnRow(row, 0, row.length, HConstants.EMPTY_BYTE_ARRAY, 0, 0,
                    column, 0, column.length);
            return passesGeneralRowColBloomFilter(kvKey);
        }

        // For multi-column queries the Bloom filter is checked from the
        // seekExact operation.
        return true;

    default:
        return true;
    }
}

From source file:org.apache.hadoop.hbase.regionserver.DefaultMemStore.java

/**
 * Only used by tests. TODO: Remove// w w  w .  j  av a2s. c  o  m
 *
 * Given the specs of a column, update it, first by inserting a new record,
 * then removing the old one.  Since there is only 1 KeyValue involved, the memstoreTS
 * will be set to 0, thus ensuring that they instantly appear to anyone. The underlying
 * store will ensure that the insert/delete each are atomic. A scanner/reader will either
 * get the new value, or the old value and all readers will eventually only see the new
 * value after the old was removed.
 *
 * @param row
 * @param family
 * @param qualifier
 * @param newValue
 * @param now
 * @return  Timestamp
 */
public long updateColumnValue(byte[] row, byte[] family, byte[] qualifier, long newValue, long now) {
    KeyValue firstKv = KeyValueUtil.createFirstOnRow(row, family, qualifier);
    // Is there a KeyValue in 'snapshot' with the same TS? If so, upgrade the timestamp a bit.
    SortedSet<KeyValue> snSs = snapshot.tailSet(firstKv);
    if (!snSs.isEmpty()) {
        KeyValue snKv = snSs.first();
        // is there a matching KV in the snapshot?
        if (CellUtil.matchingRow(snKv, firstKv) && CellUtil.matchingQualifier(snKv, firstKv)) {
            if (snKv.getTimestamp() == now) {
                // poop,
                now += 1;
            }
        }
    }

    // logic here: the new ts MUST be at least 'now'. But it could be larger if necessary.
    // But the timestamp should also be max(now, mostRecentTsInMemstore)

    // so we cant add the new KV w/o knowing what's there already, but we also
    // want to take this chance to delete some kvs. So two loops (sad)

    SortedSet<KeyValue> ss = kvset.tailSet(firstKv);
    for (KeyValue kv : ss) {
        // if this isnt the row we are interested in, then bail:
        if (!CellUtil.matchingColumn(kv, family, qualifier) || !CellUtil.matchingRow(kv, firstKv)) {
            break; // rows dont match, bail.
        }

        // if the qualifier matches and it's a put, just RM it out of the kvset.
        if (kv.getTypeByte() == KeyValue.Type.Put.getCode() && kv.getTimestamp() > now
                && CellUtil.matchingQualifier(firstKv, kv)) {
            now = kv.getTimestamp();
        }
    }

    // create or update (upsert) a new KeyValue with
    // 'now' and a 0 memstoreTS == immediately visible
    List<Cell> cells = new ArrayList<Cell>(1);
    cells.add(new KeyValue(row, family, qualifier, now, Bytes.toBytes(newValue)));
    return upsert(cells, 1L);
}

From source file:controllers.Statistics.java

private static void getElapsedTimeStatistics(long secondInMillis, String target, ObjectNode objectNode) {
    TitanGraph g = Global.getGraph();//from   ww w  . ja v a  2s  .  c o m

    long second = (secondInMillis / 1000) * 1000;

    Iterator<Vertex> it = g.getVertices("second", second).iterator();
    Vertex v = null;
    SortedSet<Integer> numSet = new TreeSet<Integer>();
    int value = 0;
    int sum = 0;
    int count = 0;
    //if(it.hasNext()) {
    while (it.hasNext()) {
        v = it.next();
        for (Vertex vertex : v.query().labels("include").has("event", target).vertices()) {
            if (vertex == null) {
                continue;
            }
            value = (Integer) vertex.getProperty("elapsedTime");
            count++;
            sum += value;
            numSet.add(value);
        }
    }

    objectNode.put("cnt", count);
    if (count > 0) {
        objectNode.put("avg", sum / count);
        objectNode.put("min", numSet.first());
        objectNode.put("max", numSet.last());
    } else {
        objectNode.put("avg", 0);
        objectNode.put("min", 0);
        objectNode.put("max", 0);
    }
}

From source file:org.sakaiproject.dash.entity.ScheduleSupport.java

public Integer findSmallest(Set<Integer> numbers) {
    SortedSet<Integer> set = new TreeSet<Integer>(numbers);
    return set.first();
}

From source file:org.wrml.werminal.Werminal.java

private void addKeySlotValuesToHistory(final URI historyListSchemaUri, final Keys keys) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    if (keys == null || keys.getCount() == 0) {
        return;/*  w w  w . j  a  v  a 2  s  .  co m*/
    }

    for (final URI keyedSchemaUri : keys.getKeyedSchemaUris()) {
        final Object keyValue = keys.getValue(keyedSchemaUri);

        final Prototype keyDeclaredPrototype = schemaLoader.getPrototype(keyedSchemaUri);
        if (keyDeclaredPrototype == null) {
            continue;
        }
        final SortedSet<String> keySlotNames = keyDeclaredPrototype.getDeclaredKeySlotNames();

        if (keySlotNames == null || keySlotNames.isEmpty()) {
            continue;
        }

        if (keySlotNames.size() == 1) {
            final String keySlotName = keySlotNames.first();

            addSlotValueToHistory(historyListSchemaUri, keySlotName, keyValue);
        } else {
            final CompositeKey compositeKey = (CompositeKey) keyValue;
            if (compositeKey == null) {
                continue;
            }

            final Map<String, Object> compositeKeySlots = compositeKey.getKeySlots();
            for (final String compositeKeySlotName : compositeKeySlots.keySet()) {
                final Object compositeKeySlotValue = compositeKeySlots.get(compositeKeySlotName);
                if (compositeKeySlotValue != null) {
                    addSlotValueToHistory(historyListSchemaUri, compositeKeySlotName, compositeKeySlotValue);
                }
            }
        }
    }
}

From source file:org.assertj.assertions.generator.BaseAssertionGenerator.java

private String determineBestEntryPointsAssertionsClassPackage(final Set<ClassDescription> classDescriptionSet) {
    SortedSet<String> packages = new TreeSet<String>(new Comparator<String>() {
        @Override//from ww  w.  j  av  a 2 s. c  o m
        public int compare(final String o1, final String o2) {
            return o1.length() - o2.length();
        }
    });
    for (ClassDescription classDescription : classDescriptionSet) {
        packages.add(classDescription.getPackageName());
    }
    // takes the base package of all given classes assuming they all belong to a common package, i.e a.b.c. over a.b.c.d
    // this can certainly be improved ...
    return packages.first();
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java

/**
 * @throws ParseException //from ww  w  .ja  v  a  2s . co m
 * @throws InputFormatException 
 * 
 */
@Test
public void testTwentyMinuteDuration() throws InputFormatException, ParseException {
    SimpleDateFormat dateFormat = CommonDateOperations.getDateFormat();
    SortedSet<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("9:00 AM", "11:40 AM", "MW",
            dateFormat.parse("20100830"), dateFormat.parse("20100903"));
    Assert.assertEquals(2, blocks.size());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-0900"),
            blocks.first().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-1140"),
            blocks.first().getEndTime());

    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100901-0900"),
            blocks.last().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100901-1140"),
            blocks.last().getEndTime());

    SortedSet<AvailableBlock> expanded = AvailableBlockBuilder.expand(blocks, 20);
    Assert.assertEquals(16, expanded.size());

    Date originalStart = CommonDateOperations.getDateTimeFormat().parse("20100830-0900");

    Date currentStart = originalStart;
    for (AvailableBlock e : expanded) {
        if (!DateUtils.isSameDay(e.getStartTime(), currentStart)) {
            currentStart = DateUtils.addDays(originalStart, 2);
        }
        Assert.assertEquals(currentStart, e.getStartTime());
        currentStart = DateUtils.addMinutes(currentStart, 20);
        Assert.assertEquals(currentStart, e.getEndTime());
    }
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java

/**
 * Test that highlights the problem when a customer specifies a start/end range
 * for blocks and a meeting duration that leaves a remainder.
 * //from  ww  w  . j a  v  a  2  s  .  c o m
 * @throws ParseException 
 * @throws InputFormatException 
 */
@Test
public void testDurationLeavesRemainder() throws InputFormatException, ParseException {
    SimpleDateFormat dateFormat = CommonDateOperations.getDateFormat();
    SortedSet<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("9:03 AM", "3:19 PM", "MWF",
            dateFormat.parse("20100830"), dateFormat.parse("20100903"));
    Assert.assertEquals(3, blocks.size());

    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-0903"),
            blocks.first().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-1519"),
            blocks.first().getEndTime());

    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100903-0903"),
            blocks.last().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100903-1519"),
            blocks.last().getEndTime());

    SortedSet<AvailableBlock> expanded = AvailableBlockBuilder.expand(blocks, 17);
    AvailableBlock last = null;

    long millisIn17Minutes = 1020000L;
    for (AvailableBlock e : expanded) {
        if (last != null) {
            if (DateUtils.isSameDay(e.getStartTime(), last.getStartTime())) {
                Assert.assertEquals(last.getEndTime(), e.getStartTime());
                Assert.assertEquals(e.getEndTime().getTime() - last.getEndTime().getTime(), millisIn17Minutes);
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(e.getStartTime());
                Assert.assertEquals(9, cal.get(Calendar.HOUR_OF_DAY));
                Assert.assertEquals(3, cal.get(Calendar.MINUTE));

                cal.setTime(e.getEndTime());
                Assert.assertEquals(9, cal.get(Calendar.HOUR_OF_DAY));
                Assert.assertEquals(20, cal.get(Calendar.MINUTE));

                // double check yesterday's endpoint
                cal.setTime(last.getStartTime());
                Assert.assertEquals(15, cal.get(Calendar.HOUR_OF_DAY));
                Assert.assertEquals(0, cal.get(Calendar.MINUTE));

                cal.setTime(last.getEndTime());
                Assert.assertEquals(15, cal.get(Calendar.HOUR_OF_DAY));
                Assert.assertEquals(17, cal.get(Calendar.MINUTE));
            }
        } else {
            // first block in the series
            Calendar cal = Calendar.getInstance();
            cal.setTime(e.getStartTime());
            Assert.assertEquals(9, cal.get(Calendar.HOUR_OF_DAY));
            Assert.assertEquals(3, cal.get(Calendar.MINUTE));

            cal.setTime(e.getEndTime());
            Assert.assertEquals(9, cal.get(Calendar.HOUR_OF_DAY));
            Assert.assertEquals(20, cal.get(Calendar.MINUTE));
        }
        last = e;
    }

    Assert.assertEquals(66, expanded.size());

    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-0903"),
            expanded.first().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100830-0920"),
            expanded.first().getEndTime());

    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100903-1500"),
            expanded.last().getStartTime());
    Assert.assertEquals(CommonDateOperations.getDateTimeFormat().parse("20100903-1517"),
            expanded.last().getEndTime());

}

From source file:net.big_oh.algorithms.search.informed.astar.AStarSearch.java

public AStarSearchResult<SearchNodeType> doSearch(SearchNodeType startNode) {

    Duration searchDuration = new Duration();

    // create priority queue
    SortedSet<SearchNodeType> prioritySet = new TreeSet<SearchNodeType>(new Comparator<SearchNodeType>() {

        public int compare(SearchNodeType o1, SearchNodeType o2) {
            switch (searchType) {
            case MIN:
                return Double.compare(getF(o1), getF(o2));
            case MAX:
                return -1 * Double.compare(getF(o1), getF(o2));
            default:
                throw new RuntimeException("Unexpected search type: " + searchType);
            }//from  www. j  a v  a2 s  .co  m
        }

    });

    // enqueue the start node
    prioritySet.add(startNode);

    // declare tracking member variables
    int numSearchNodesGenerated = 0;
    int numSearchNodesConsidered = 0;
    int maxPossibleBranchingFactor = 1;

    // search for a goal state
    SearchNodeType goalNode = null;
    while (!prioritySet.isEmpty()) {

        // Remove the best candidate node from the queue
        SearchNodeType candidateSearchNode = prioritySet.first();
        prioritySet.remove(candidateSearchNode);
        numSearchNodesConsidered++;

        // get the next search node candidates
        Collection<SearchNodeType> nextSearchNodes = nextNodesGenerator.getNextSearchNodes(candidateSearchNode);

        // do some record keeping
        numSearchNodesGenerated += nextSearchNodes.size();
        maxPossibleBranchingFactor = Math.max(maxPossibleBranchingFactor, nextSearchNodes.size());

        if (candidateSearchNode.isGoalState()) {
            // sanity check
            assert (nextSearchNodes.isEmpty());

            // found an optimal solution
            goalNode = candidateSearchNode;
            break;
        } else {
            // enqueue all next search nodes
            Duration enqueueDuration = new Duration();

            prioritySet.addAll(nextSearchNodes);

            if (logger.isDebugEnabled()) {
                logger.debug("Enqueued " + nextSearchNodes.size() + " A* search nodes in "
                        + enqueueDuration.stop() + " milliseconds.");
            }
        }

    }

    // return the search results
    AStarSearchResult<SearchNodeType> results = new AStarSearchResult<SearchNodeType>(goalNode,
            numSearchNodesGenerated, calculateEffectiveBranchingFactor(goalNode.getNodeDepth(),
                    numSearchNodesConsidered, maxPossibleBranchingFactor));

    logger.debug("Completed an A* search in " + searchDuration.stop() + " milliseconds.");
    logger.debug("Number of nodes generated: " + results.getNumSearchNodesGenerated());
    logger.debug("Depth of goal node: " + results.getGoalNode().getNodeDepth());
    logger.debug("Effective branching factor: " + results.getEfectiveBranchingFactor());

    return results;

}

From source file:org.wrml.runtime.DefaultModel.java

private void initKeySlots(final Model model, final Keys keys) {

    final SchemaLoader schemaLoader = getContext().getSchemaLoader();
    final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri();

    URI uri = null;// ww w .java2  s .c om

    // Apply all of these Keys to the cached model (in case any Key values are "new").
    for (final URI keyedSchemaUri : keys.getKeyedSchemaUris()) {
        final Object keyValue = keys.getValue(keyedSchemaUri);

        final Prototype keyedPrototype = schemaLoader.getPrototype(keyedSchemaUri);
        final SortedSet<String> keySlotNames = keyedPrototype.getDeclaredKeySlotNames();

        if (keySlotNames.size() == 1) {
            if (documentSchemaUri.equals(keyedSchemaUri)) {
                // Save the document key slot (uri) for last so that the hypermedia engine has all other keys
                // available
                // (to auto-generate the Link href values).
                uri = (URI) keyValue;
            } else {
                setSlotValue(model, keySlotNames.first(), keyValue, keyedSchemaUri, false);
            }
        } else if (keyValue instanceof CompositeKey) {
            final CompositeKey compositeKey = (CompositeKey) keyValue;
            final Map<String, Object> keySlots = compositeKey.getKeySlots();
            for (final String keySlotName : keySlots.keySet()) {
                setSlotValue(model, keySlotName, keySlots.get(keySlotName), keyedSchemaUri, false);
            }
        }
    }

    // See comment above regarding saving the uri key slot for last.
    if (uri != null) {
        setSlotValue(model, Document.SLOT_NAME_URI, uri, documentSchemaUri, false);
    }
}