Example usage for java.util TreeSet first

List of usage examples for java.util TreeSet first

Introduction

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

Prototype

public E first() 

Source Link

Usage

From source file:com.taobao.common.tfs.impl.LocalKey.java

public int getSegmentForWrite(List<SegmentData> segmentDataList, long offset, byte[] data, int start,
        int length) {
    long currentOffset = offset;
    int currentStart = start;
    int remainLength = length, writtenLength = 0, needWriteLength = 0, remainNwLength = 0, // remain_need_write_length
            totalLength = 0;/*from   w w w.j  av a2  s. c o m*/
    List<SegmentInfo> gcSegmentList = new ArrayList<SegmentInfo>();
    SegmentInfo segmentInfo = new SegmentInfo();
    segmentDataList.clear();

    while (segmentDataList.size() < ClientConfig.BATCH_COUNT && remainLength > 0) {
        writtenLength = needWriteLength = 0;

        remainNwLength = Math.min(
                (ClientConfig.BATCH_COUNT - segmentDataList.size()) * ClientConfig.SEGMENT_LENGTH,
                remainLength);

        segmentInfo.setOffset(currentOffset);
        TreeSet<SegmentInfo> tailInfoSet = (TreeSet<SegmentInfo>) segmentInfoSet.tailSet(segmentInfo);

        if (tailInfoSet.size() == 0) {
            needWriteLength = remainNwLength;
            checkOverlap(segmentInfo, gcSegmentList);
        } else {
            SegmentInfo firstInfo = tailInfoSet.first();
            if (firstInfo.getOffset() != currentOffset) {
                needWriteLength = (int) (firstInfo.getOffset() - currentOffset);
                checkOverlap(segmentInfo, gcSegmentList);
            }
            if (needWriteLength > remainNwLength) {
                needWriteLength = remainNwLength;
            } else {
                Iterator it = tailInfoSet.iterator();
                remainNwLength -= needWriteLength;
                while (remainNwLength > 0 && it.hasNext()) {
                    SegmentInfo curInfo = (SegmentInfo) it.next();
                    int tmpCrc = 0, curLength = curInfo.getLength();
                    if (remainNwLength < curLength) {
                        log.info("segment length conflict: " + curLength + " <> " + remainNwLength);
                        needWriteLength += remainNwLength;
                        remainNwLength = 0;
                    } else if ((tmpCrc = TfsUtil.crc32(0, data, currentStart + needWriteLength,
                            curLength)) != curInfo.getCrc()) {
                        log.info("segment crc conflict: " + curInfo.getCrc() + " <> " + tmpCrc);
                        needWriteLength += curLength;
                        remainNwLength -= curLength;
                    } else { // full segment crc is correct use it
                        log.debug("segment data written: " + curInfo);
                        writtenLength += curLength;
                        remainNwLength = 0;
                        break;
                    }
                    gcSegmentList.add(curInfo);
                }
                if (!it.hasNext()) {
                    needWriteLength += remainNwLength;
                }
            }
        }

        getSegment(segmentDataList, currentOffset, data, currentStart, needWriteLength);
        totalLength = needWriteLength + writtenLength;
        remainLength -= totalLength;
        currentStart += totalLength;
        currentOffset += totalLength;
        gcSegment(gcSegmentList);
    }
    return (length - remainLength);
}

From source file:pl.edu.icm.coansys.kwdextraction.langident.Profile.java

/**
 * Generates profile from a text.//from   ww w.  j  av  a  2 s  .  c o m
 *
 * @param text Text to profile
 */
public Profile(final String txt) {
    final String text = txt.toLowerCase().replaceAll("[^\\p{L}']+", SPACE_STRING);
    final String[] words = text.split(SPACE_STRING);

    int processedWords = 0;
    int processedLetters = 0;
    final Map<String, Integer> grams = new HashMap<String, Integer>();
    for (final String word : words) {
        final int len = word.length();

        for (int n = 1; n <= MAX_GRAM - 1; n++) {
            if (len >= n) {
                addGram(grams, UNTERLINE_STRING + word.substring(0, n));
                addGram(grams, word.substring(len - n, len) + UNTERLINE_STRING);
            }
        }

        for (int n = 1; n <= MAX_GRAM; n++) {
            for (int i = 0; i < len - n + 1; i++) {
                addGram(grams, word.substring(i, i + n));
            }
        }
        processedWords += 1;
        processedLetters += len;
    }

    LOG.debug(PROCESSED_WORDS + processedWords + LETTERS + processedLetters);

    //        All the N-grams are in the grams map -- now we need
    //        to sort them and put first PROFILE_CUTOFF most valuable
    //        ones in the profile
    final TreeSet<TreeElement> ts = new TreeSet<TreeElement>();
    for (final Map.Entry<String, Integer> me : grams.entrySet()) {
        ts.add(new TreeElement(me.getKey(), me.getValue().intValue()));
    }

    int newSize = grams.entrySet().size();
    if (newSize > PROFILE_CUTOFF) {
        newSize = PROFILE_CUTOFF;
    }

    data = new ArrayList<String>(newSize);
    hash = new HashMap<String, Integer>(newSize);
    for (int i = 0; i < newSize; i++) {
        final TreeElement te = ts.first();
        data.add(te.s);
        hash.put(data.get(i), Integer.valueOf(i));
        ts.remove(te);
    }
}

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Sets the field of a GregorianCalender to its minimum, which is defined as
 * the minimal possible value according to the calendar type possibly
 * superseded by the defined values in the schedule we have. Returns whether
 * the new value has been set and is valid.
 * // ww w .ja va  2 s  .  c  o m
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setFieldToMinimum(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int min;
    TreeSet<Integer> values = getValues(field);
    if (values.isEmpty()) {
        min = cal.getActualMinimum(field);
    } else {
        min = Math.max(values.first().intValue(), cal.getActualMinimum(field));
        if (min > cal.getActualMaximum(field)) {
            min = cal.getActualMaximum(field);
            if (!values.contains(Integer.valueOf(min)) || min < cal.getActualMinimum(field)
                    || min > cal.getActualMaximum(field)) {
                return false;
            }
        }
    }
    cal.set(field, min);
    return true;
}

From source file:org.apache.samza.zk.ZkUtils.java

/**
 * Determines the validity of processor registered with zookeeper.
 *
 * If there are multiple processors registered with same processorId,
 * the processor with lexicographically smallest zookeeperPath is considered valid
 * and all the remaining processors are invalid.
 *
 * Two processors will not have smallest zookeeperPath because of sequentialId guarantees
 * of zookeeper for ephemeral nodes.//from w w  w .  ja v  a2  s  .  c  om
 *
 * @param processor to check for validity condition in processors group.
 * @return true if the processor is valid. false otherwise.
 */
private boolean isValidRegisteredProcessor(final ProcessorNode processor) {
    String processorId = processor.getProcessorData().getProcessorId();
    List<ProcessorNode> processorNodes = getAllProcessorNodes().stream()
            .filter(processorNode -> processorNode.processorData.getProcessorId().equals(processorId))
            .collect(Collectors.toList());
    // Check for duplicate processor condition(if more than one processor exist for this processorId).
    if (processorNodes.size() > 1) {
        // There exists more than processor for provided `processorId`.
        LOG.debug("Processor nodes in zookeeper: {} for processorId: {}.", processorNodes, processorId);
        // Get all ephemeral processor paths
        TreeSet<String> sortedProcessorPaths = processorNodes.stream().map(ProcessorNode::getEphemeralPath)
                .collect(Collectors.toCollection(TreeSet::new));
        // Check if smallest path is equal to this processor's ephemeralPath.
        return sortedProcessorPaths.first().equals(processor.getEphemeralPath());
    }
    // There're no duplicate processors. This is a valid registered processor.
    return true;
}

From source file:com.medigy.persist.model.person.Person.java

@Transient
public MaritalStatusType getCurrentMaritalStatus() {
    final List<MaritalStatus> maritalStatuses = getMaritalStatuses();
    if (maritalStatuses.size() == 0)
        return MaritalStatusType.Cache.UNKNOWN.getEntity();

    TreeSet<MaritalStatus> inverseSorted = new TreeSet<MaritalStatus>(Collections.reverseOrder());
    inverseSorted.addAll(maritalStatuses);
    return inverseSorted.first().getType();
}

From source file:org.obm.push.contacts.ContactsBackendTest.java

@Test
public void sortedByDefaultFolderName() {
    final String defaultFolderName = DEFAULT_PARENT_BOOK_NAME;

    Folder f1 = Folder.builder().name("users").uid(-1).ownerLoginAtDomain(user.getLoginAtDomain()).build();
    Folder f2 = Folder.builder().name("collected_contacts").uid(2).ownerLoginAtDomain(user.getLoginAtDomain())
            .build();/*  ww  w .  j av  a2  s.  com*/
    Folder f3 = Folder.builder().name(defaultFolderName).uid(3).ownerLoginAtDomain(user.getLoginAtDomain())
            .build();
    Folder f4 = Folder.builder().name("my address book").uid(4).ownerLoginAtDomain(user.getLoginAtDomain())
            .build();

    TreeSet<Folder> treeset = new TreeSet<Folder>(new ComparatorUsingFolderName(defaultFolderName));
    treeset.addAll(ImmutableList.of(f1, f2, f3, f4));

    assertThat(treeset).hasSize(4);
    assertThat(treeset).contains(f1, f2, f3, f4);
    assertThat(treeset.first().getName()).isEqualTo(defaultFolderName);
    assertThat(treeset.last().getName()).isEqualTo("users");
}

From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java

/**
 * Used to limit the files if any starting or ending date exist
 * So only few files to be searched./* w ww .java  2 s .c  o  m*/
 *
 * @param filelist Iterator
 * @param startDate Date
 * @param endDate Date
 * @param reverseOrder reverse order of files
 * @return Vector
 */
static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate,
        final boolean reverseOrder) {
    if (startDate == null && endDate == null) {
        // no filtering needed then just return the same list
        Vector<String> result = new Vector<String>();
        while (filelist.hasNext()) {
            result.add(filelist.next());
        }

        Collections.sort(result, new Comparator<String>() {

            public int compare(String o1, String o2) {
                if (reverseOrder)
                    return o2.compareTo(o1);
                else
                    return o1.compareTo(o2);
            }
        });

        return result;
    }
    // first convert all files to long
    TreeSet<Long> files = new TreeSet<Long>();
    while (filelist.hasNext()) {
        String filename = filelist.next();

        files.add(Long.parseLong(filename.substring(0, filename.length() - 4)));
    }

    TreeSet<Long> resultAsLong = new TreeSet<Long>();

    // Temporary fix of a NoSuchElementException
    if (files.size() == 0) {
        return new Vector<String>();
    }

    Long startLong;
    Long endLong;

    if (startDate == null)
        startLong = Long.MIN_VALUE;
    else
        startLong = startDate.getTime();

    if (endDate == null)
        endLong = Long.MAX_VALUE;
    else
        endLong = endDate.getTime();

    // get all records inclusive the one before the startdate
    for (Long f : files) {
        if (startLong <= f && f <= endLong) {
            resultAsLong.add(f);
        }
    }

    // get the subset before the start date, to get its last element
    // if exists
    if (!files.isEmpty() && files.first() <= startLong) {
        SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true);
        if (!setBeforeTheInterval.isEmpty())
            resultAsLong.add(setBeforeTheInterval.last());
    }

    Vector<String> result = new Vector<String>();

    Iterator<Long> iter = resultAsLong.iterator();
    while (iter.hasNext()) {
        Long item = iter.next();
        result.add(item.toString() + ".xml");
    }

    Collections.sort(result, new Comparator<String>() {

        public int compare(String o1, String o2) {
            if (reverseOrder)
                return o2.compareTo(o1);
            else
                return o1.compareTo(o2);
        }
    });

    return result;
}

From source file:org.rhwlab.BHC.BHCTree.java

public TreeMap<Integer, Double> allPosteriorProb(int maxProbs) {
    TreeMap<Integer, TreeSet<NucleusLogNode>> allCuts = allTreeCuts(maxProbs);
    TreeMap<Integer, Double> ret = new TreeMap<>();
    for (Integer i : allCuts.keySet()) {
        TreeSet<NucleusLogNode> nodes = allCuts.get(i);
        double p = Math.exp(nodes.first().getLogPosterior());
        ret.put(i, p);/*from   w w  w.  j a  va2 s .  co m*/
    }

    return ret;
}

From source file:com.joliciel.jochre.boundaries.RecursiveShapeSplitter.java

List<ShapeSequence> split(Shape shape, int depth, Shape originalShape, boolean leftToRight) {
    String padding = "-";
    for (int i = 0; i < depth; i++)
        padding += "-";
    padding += " ";
    LOG.trace(padding + "Splitting shape: " + shape.getLeft() + " , " + shape.getRight());
    LOG.trace(padding + "depth: " + depth);
    List<ShapeSequence> shapeSequences = new ArrayList<ShapeSequence>();
    // check if shape is wide enough to bother with
    double widthRatio = (double) shape.getWidth() / (double) shape.getXHeight();
    LOG.trace(padding + "widthRatio: " + widthRatio);

    if (widthRatio < minWidthRatio || depth >= maxDepth) {
        LOG.trace(padding + "too narrow or too deep");
        ShapeSequence shapeSequence = this.boundaryServiceInternal.getEmptyShapeSequence();
        shapeSequence.addShape(shape, originalShape);
        shapeSequences.add(shapeSequence);
    } else {/*w ww  .  j a  v a  2 s . c  o  m*/
        List<Split> splitCandidates = this.splitCandidateFinder.findSplitCandidates(shape);
        TreeSet<ShapeSequence> myShapeSequences = new TreeSet<ShapeSequence>();

        TreeSet<WeightedOutcome<Split>> weightedSplits = new TreeSet<WeightedOutcome<Split>>();
        for (Split splitCandidate : splitCandidates) {
            double splitProb = this.shouldSplit(splitCandidate);
            WeightedOutcome<Split> weightedSplit = new WeightedOutcome<Split>(splitCandidate, splitProb);
            weightedSplits.add(weightedSplit);
        }

        double maxSplitProb = 0.0;
        if (weightedSplits.size() > 0)
            maxSplitProb = weightedSplits.first().getWeight();

        double noSplitProb = 1 - maxSplitProb;
        if (noSplitProb > maxSplitProb)
            maxSplitProb = noSplitProb;

        Split noSplit = boundaryServiceInternal.getEmptySplit(shape);
        noSplit.setPosition(-1);
        WeightedOutcome<Split> weightedNoSplit = new WeightedOutcome<Split>(noSplit, noSplitProb);
        weightedSplits.add(weightedNoSplit);

        boolean topCandidate = true;
        double topCandidateWeight = 1.0;
        for (WeightedOutcome<Split> weightedSplit : weightedSplits) {
            Split splitCandidate = weightedSplit.getOutcome();
            double splitProb = weightedSplit.getWeight();
            LOG.trace(padding + "splitCandidate: left=" + splitCandidate.getShape().getLeft() + ", pos="
                    + splitCandidate.getPosition() + ", initial prob: " + splitProb);

            if (topCandidate) {
                LOG.trace(padding + "topCandidate");
            }
            if (splitCandidate.getPosition() < 0) {
                // This is the no-split candidate
                if (topCandidate)
                    topCandidateWeight = 1.0;

                ShapeSequence shapeSequence = boundaryServiceInternal.getEmptyShapeSequence();
                shapeSequence.addShape(shape, originalShape);
                double prob = (splitProb / maxSplitProb) * topCandidateWeight;
                LOG.trace(padding + "noSplit prob=(" + splitProb + " / " + maxSplitProb + ") * "
                        + topCandidateWeight + " = " + prob);

                Decision<SplitMergeOutcome> decision = boundaryDecisionFactory
                        .createDecision(SplitOutcome.DO_NOT_SPLIT.getCode(), prob);
                shapeSequence.addDecision(decision);
                myShapeSequences.add(shapeSequence);
            } else {
                // a proper split
                Shape leftShape = shape.getJochreImage().getShape(shape.getLeft(), shape.getTop(),
                        shape.getLeft() + splitCandidate.getPosition(), shape.getBottom());
                Shape rightShape = shape.getJochreImage().getShape(
                        shape.getLeft() + splitCandidate.getPosition() + 1, shape.getTop(), shape.getRight(),
                        shape.getBottom());

                // for each split recursively try to split it again up to depth of m
                // Note: m=2 is probably enough, since we're not expecting more than 4 letters per shape (3 splits)
                List<ShapeSequence> leftShapeSequences = this.split(leftShape, depth + 1, originalShape,
                        leftToRight);
                List<ShapeSequence> rightShapeSequences = this.split(rightShape, depth + 1, originalShape,
                        leftToRight);

                if (topCandidate) {
                    // find the no-split sequence in each sub-sequence
                    ShapeSequence noSplitLeft = null;
                    for (ShapeSequence leftShapeSequence : leftShapeSequences) {
                        if (leftShapeSequence.size() == 1) {
                            noSplitLeft = leftShapeSequence;
                            break;
                        }
                    }

                    ShapeSequence noSplitRight = null;
                    for (ShapeSequence rightShapeSequence : rightShapeSequences) {
                        if (rightShapeSequence.size() == 1) {
                            noSplitRight = rightShapeSequence;
                            break;
                        }
                    }

                    // we should be guaranteed to find a noSplitLeft and noSplitRight
                    // since a no-split candidate is always returned
                    topCandidateWeight = noSplitLeft.getScore() * noSplitRight.getScore();
                    LOG.trace(padding + "topCandidateWeight=" + noSplitLeft.getScore() + " *"
                            + noSplitRight.getScore() + " = " + topCandidateWeight);
                }

                for (ShapeSequence leftShapeSequence : leftShapeSequences) {
                    for (ShapeSequence rightShapeSequence : rightShapeSequences) {
                        ShapeSequence newSequence = null;
                        if (leftToRight)
                            newSequence = boundaryServiceInternal.getShapeSequence(leftShapeSequence,
                                    rightShapeSequence);
                        else
                            newSequence = boundaryServiceInternal.getShapeSequence(rightShapeSequence,
                                    leftShapeSequence);
                        if (LOG.isTraceEnabled()) {
                            StringBuilder sb = new StringBuilder();
                            for (ShapeInSequence splitShape : newSequence) {
                                sb.append("(" + splitShape.getShape().getLeft() + ","
                                        + splitShape.getShape().getRight() + ") ");
                            }
                            LOG.trace(padding + sb.toString());
                        }
                        double totalProb = 1.0;
                        for (Decision<SplitMergeOutcome> decision : newSequence.getDecisions()) {
                            totalProb = totalProb * decision.getProbability();
                        }
                        newSequence.getDecisions().clear();
                        double prob = 0.0;
                        if (topCandidate) {
                            prob = totalProb * (splitProb / maxSplitProb);
                            LOG.trace(padding + "prob=" + totalProb + " * (" + splitProb + " / " + maxSplitProb
                                    + ") = " + prob);
                        } else {
                            prob = totalProb * (splitProb / maxSplitProb) * topCandidateWeight;
                            LOG.trace(padding + "prob=" + totalProb + " * (" + splitProb + " / " + maxSplitProb
                                    + ") * " + topCandidateWeight + " = " + prob);
                        }

                        Decision<SplitMergeOutcome> decision = this.boundaryDecisionFactory
                                .createDecision(SplitOutcome.DO_SPLIT.getCode(), prob);
                        newSequence.addDecision(decision);
                        myShapeSequences.add(newSequence);
                    }
                }
            }

            topCandidate = false;
        }

        int i = 0;
        for (ShapeSequence shapeSequence : myShapeSequences) {
            // Note: we always return the no-split option, even it it's very low probability
            if (shapeSequence.size() == 1 || i < beamWidth) {
                shapeSequences.add(shapeSequence);
            }
            i++;
        }
    }

    return shapeSequences;
}

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

/**
 * // w w  w .  ja va  2s .co m
 * @throws Exception
 */
@Test
public void testOddAppointmentMultipleAttendees() throws Exception {
    Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("9:00 AM", "12:00 PM", "MTRF",
            makeDateTime("20090202-0830"), makeDateTime("20090206-1600"), 1, null);

    TreeSet<AvailableBlock> expanded = new TreeSet<AvailableBlock>(AvailableBlockBuilder.expand(blocks, 45));
    LOG.info("expanded set first: " + expanded.first() + ", last: " + expanded.last());
    AvailableSchedule schedule = new AvailableSchedule(expanded);

    DateTime eventStart = new net.fortuna.ical4j.model.DateTime(makeDateTime("20090203-1000"));
    eventStart.setTimeZone(americaChicago);
    DateTime eventEnd = new net.fortuna.ical4j.model.DateTime(makeDateTime("20090203-1030"));
    eventEnd.setTimeZone(americaChicago);
    VEvent someEvent = new VEvent(eventStart, eventEnd, "some conflicting appointment");

    Attendee attendee = new Attendee();
    attendee.setValue("mailto:person@domain.edu");
    attendee.getParameters().add(new XParameter("X-ORACLE-SHOWASFREE", "FREE"));
    attendee.getParameters().add(new Cn("GIVEN SURNAME"));

    Attendee attendee2 = new Attendee();
    attendee2.setValue("mailto:person2@domain.edu");
    attendee2.getParameters().add(new Cn("GIVEN2 SURNAME2"));

    someEvent.getProperties().add(attendee);
    someEvent.getProperties().add(attendee2);
    ComponentList components = new ComponentList();
    components.add(someEvent);

    MockCalendarAccount person1 = new MockCalendarAccount();
    person1.setEmailAddress("someowner@wisc.edu");
    person1.setDisplayName("Some Owner");
    MockScheduleOwner owner = new MockScheduleOwner(person1, 1);
    owner.setPreference(Preferences.DURATIONS, MeetingDurations.FORTYFIVE.getKey());
    VisibleSchedule visible = this.builder.calculateVisibleSchedule(makeDateTime("20090202-0830"),
            makeDateTime("20090206-1600"), new Calendar(components), schedule, owner);

    Assert.assertEquals(16, visible.getSize());
    List<AvailableBlock> free = visible.getFreeList();
    Assert.assertEquals(16, free.size());
    List<AvailableBlock> busy = visible.getBusyList();
    Assert.assertEquals(0, busy.size());
}