Example usage for java.util ListIterator hasPrevious

List of usage examples for java.util ListIterator hasPrevious

Introduction

In this page you can find the example usage for java.util ListIterator hasPrevious.

Prototype

boolean hasPrevious();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the reverse direction.

Usage

From source file:gr.iit.demokritos.cru.cps.ai.ComputationalCreativityMetrics.java

public double MinClosure(String phrase, String story) {
    double closure = 0.0;
    //in case minclosue is not called by ComputeRar_Eff
    if (story.equalsIgnoreCase("")) {
        story = phrase;/*from  w ww.  j  a  va 2s.  c o m*/
    }
    //hashmap of the terms and their index
    HashMap<String, Double> termIndex = new HashMap<String, Double>();
    //take the top terms of the phrase by their stems tf
    // HashMap<ArrayList<String>, Double> termsTf = inf.TopTerms(story.toLowerCase(), true);

    for (String s : phrase.split(" ")) {
        termIndex.put(s, 1.0 * story.indexOf(s));
    }

    //sort the hashamp (descending) and traverse it reversely, to start from the first word in the phrase
    LinkedHashMap<String, Double> sorted = inf.sortHashMapByValues(termIndex);
    ListIterator iter = new ArrayList(sorted.keySet()).listIterator(sorted.size());

    HashMap<String, Double> graph = new HashMap<String, Double>();
    //store the first word in the phrase, in order to be found in the first iteration
    graph.put(sorted.keySet().toArray()[sorted.keySet().size() - 1].toString(), 0.0);
    //for each word that comes next in the phrase
    while (iter.hasPrevious()) {
        String s = iter.previous().toString();
        //find the shortest distance from it to the root (first word)
        double min = 1.0;
        //looking through every word that has already defined its min distance to the root
        for (String k : graph.keySet()) {
            double dist = getDistance(s, k); //+ graph.get(k);
            if (dist < min) {
                min = dist;
            }
        }
        graph.put(s, min);
        //keep the overal sum of weights of the edges
        closure += min;
    }
    return closure;

}

From source file:com.alibaba.wasp.fserver.SplitTransaction.java

/**
 * @param server/*  w ww . j a  v a2 s .  c o  m*/
 *          Hosting server instance (May be null when testing).
 * @param services
 * @throws java.io.IOException
 *           If thrown, rollback failed. Take drastic action.
 * @return True if we successfully rolled back, false if we got to the point
 *         of no return and so now need to abort the server to minimize
 *         damage.
 */
public boolean rollback(final Server server, final FServerServices services) throws IOException {
    boolean result = true;
    ListIterator<JournalEntry> iterator = this.journal.listIterator(this.journal.size());
    // Iterate in reverse.
    while (iterator.hasPrevious()) {
        JournalEntry je = iterator.previous();
        switch (je) {

        case STARTED_SPLITTING:
            if (server != null && server.getZooKeeper() != null) {
                cleanZK(server, this.parent.getEntityGroupInfo(), false);
            }
            break;

        case SET_SPLITTING_IN_ZK:
            if (server != null && server.getZooKeeper() != null) {
                cleanZK(server, this.parent.getEntityGroupInfo(), true);
            }
            break;

        case CREATE_SPLIT_STOREAGE:
            this.parent.writestate.writesEnabled = true;
            break;

        case CLOSED_PARENT_ENTITYGROUP:
            try {
                this.parent.initialize();
            } catch (IOException e) {
                LOG.error("Failed rollbacking CLOSED_PARENT_ENTITYGROUP of entityGroup "
                        + this.parent.getEntityGroupNameAsString(), e);
                throw new RuntimeException(e);
            }
            break;

        case STARTED_ENTITYGROUP_A_CREATION:
            break;

        case STARTED_ENTITYGROUP_B_CREATION:
            break;

        case OFFLINED_PARENT:
            if (services != null)
                services.addToOnlineEntityGroups(this.parent);
            break;

        case PONR:
            // We got to the point-of-no-return so we need to just abort. Return
            // immediately. Do not clean up created daughter entityGroups. They need
            // to be in place so we don't delete the parent entityGroup mistakenly.
            // See HBASE-3872.
            return false;

        default:
            throw new RuntimeException("Unhandled journal entry: " + je);
        }
    }
    return result;
}

From source file:org.springframework.ldap.core.DistinguishedName.java

/**
 * Add an LDAP path first in this DistinguishedName. E.g.:
 * //w  w  w.jav  a 2s  .  co m
 * <pre>
 * DistinguishedName name1 = new DistinguishedName(&quot;ou=people&quot;);
 * DistinguishedName name2 = new DistinguishedName(&quot;c=SE, dc=jayway, dc=se&quot;);
 * name1.prepend(name2);
 * </pre>
 * 
 * will result in <code>ou=people, c=SE, dc=jayway, dc=se</code>
 * 
 * @param path the path to prepend.
 */
public void prepend(DistinguishedName path) {
    ListIterator i = path.getNames().listIterator(path.getNames().size());
    while (i.hasPrevious()) {
        names.add(0, i.previous());
    }
}

From source file:com.offbynull.voip.kademlia.model.NodeMostRecentSet.java

public ActivityChangeSet touch(Instant time, Node node, boolean allowLinkMismatch) {
    Validate.notNull(time);/*  ww  w  .j a  v  a  2 s  . c o m*/
    Validate.notNull(node);

    Id nodeId = node.getId();

    InternalValidate.matchesLength(baseId.getBitLength(), nodeId);
    //        Validate.isTrue(!nodeId.equals(baseId)); // Don't reject adding self

    // TODO: You can make this way more efficient if you used something like MultiTreeSet (guava) and sorted based on entry time

    // Remove existing entry
    Activity oldEntry = null;
    ListIterator<Activity> it = entries.listIterator();
    while (it.hasNext()) {
        Activity entry = it.next();

        Id entryId = entry.getNode().getId();

        if (entryId.equals(nodeId)) {
            if (!allowLinkMismatch) {
                InternalValidate.matchesLink(entry.getNode(), node);
            }

            // remove
            it.remove();
            oldEntry = entry;
            break;
        }
    }

    // Add entry
    Activity newEntry = new Activity(node, time);
    it = entries.listIterator(entries.size());
    boolean added = false;
    while (it.hasPrevious()) {
        Activity entry = it.previous();

        if (entry.getTime().isBefore(time)) {
            it.next(); // move forward 1 space, we want to add to element just after entry
            it.add(newEntry);
            added = true;
            break;
        }
    }

    if (!added) { // special case where newEntry needs to be added at the end of entries, not handled by loop above
        entries.addFirst(newEntry);
    }

    // Set has become too large, remove the item with the earliest time
    Activity discardedEntry = null;
    if (entries.size() > maxSize) {
        // if the node removed with the earliest time is the one we just added, then report that node couldn't be added
        discardedEntry = entries.removeFirst();
        if (discardedEntry.equals(newEntry)) {
            return ActivityChangeSet.NO_CHANGE;
        }
    }

    // Add successful
    if (oldEntry != null) {
        Validate.validState(discardedEntry == null); // sanity check, must not have discarded anything

        // updated existing node
        return ActivityChangeSet.updated(newEntry);
    } else {
        // if block above ensures oldEntry is null if we're in this else block, so sanity check below isn't nessecary
        // Validate.validState(oldEntry == null); // sanity check, node being touched must not have already existed

        // added new node
        Collection<Activity> addedEntries = singletonList(newEntry);
        Collection<Activity> removedEntries = discardedEntry == null ? emptyList()
                : singletonList(discardedEntry);
        Collection<Activity> updatedEntries = emptyList();
        return new ActivityChangeSet(addedEntries, removedEntries, updatedEntries);
    }
}

From source file:org.apache.ambari.server.scheduler.ExecutionScheduleManager.java

private JobDetail persistBatch(RequestExecution requestExecution) throws AmbariException {

    Batch batch = requestExecution.getBatch();
    JobDetail jobDetail = null;// w w w .  ja  v  a 2  s .c o  m

    if (batch != null) {
        List<BatchRequest> batchRequests = batch.getBatchRequests();
        if (batchRequests != null) {
            Collections.sort(batchRequests);
            ListIterator<BatchRequest> iterator = batchRequests.listIterator(batchRequests.size());
            String nextJobName = null;
            while (iterator.hasPrevious()) {
                BatchRequest batchRequest = iterator.previous();

                String jobName = getJobName(requestExecution.getId(), batchRequest.getOrderId());

                Integer separationSeconds = requestExecution.getBatch().getBatchSettings()
                        .getBatchSeparationInSeconds();

                // Create Job and store properties to get next batch request details
                jobDetail = newJob(BatchRequestJob.class)
                        .withIdentity(jobName, ExecutionJob.LINEAR_EXECUTION_JOB_GROUP)
                        .usingJobData(ExecutionJob.NEXT_EXECUTION_JOB_NAME_KEY, nextJobName)
                        .usingJobData(ExecutionJob.NEXT_EXECUTION_JOB_GROUP_KEY,
                                ExecutionJob.LINEAR_EXECUTION_JOB_GROUP)
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_EXECUTION_ID_KEY, requestExecution.getId())
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_BATCH_ID_KEY, batchRequest.getOrderId())
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_CLUSTER_NAME_KEY,
                                requestExecution.getClusterName())
                        .usingJobData(BatchRequestJob.NEXT_EXECUTION_SEPARATION_SECONDS,
                                separationSeconds != null ? separationSeconds : 0)
                        .storeDurably().build();

                try {
                    executionScheduler.addJob(jobDetail);
                } catch (SchedulerException e) {
                    LOG.error("Failed to add job detail. " + batchRequest, e);
                }

                nextJobName = jobName;
            }
        }
    }
    return jobDetail;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Searches the finger table for the right-most occurrence of {@code ptr}.
 * @param ptr pointer to search for/*  w ww.  ja va2s  .  c o m*/
 * @return index of occurrence, or -1 if not found
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code ptr}'s id has a different limit bit size than the base pointer's id
 */
public int getMaximumIndex(Pointer ptr) {
    Validate.notNull(ptr);
    Validate.isTrue(IdUtils.getBitLength(ptr.getId()) == bitCount);

    Id id = ptr.getId();
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();

        if (ie.pointer.equals(ptr)) {
            return lit.previousIndex() + 1;
        }
    }

    return -1;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Searches the finger table for the closest to the id being searched for (closest in terms of being {@code <}).
 *
 * @param id id being searched for/* www  .jav a2 s .  co m*/
 * @return closest preceding pointer
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id}'s has a different limit bit size than base pointer's id
 */
public Pointer findClosestPreceding(Id id) {
    Validate.notNull(id);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    Id selfId = basePtr.getId();

    InternalEntry foundEntry = null;
    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        // if finger[i] exists between n (exclusive) and id (exclusive)
        // then return it
        Id fingerId = ie.pointer.getId();
        if (fingerId.isWithin(selfId, false, id, false)) {
            foundEntry = ie;
            break;
        }
    }

    return foundEntry == null ? basePtr : foundEntry.pointer;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Searches the finger table for the closest id to the id being searched for (closest in terms of being {@code <=} to).
 *
 * @param id id being searched for/*from  w  w w  .  j a va2 s .co  m*/
 * @return closest pointer (closest in terms of being {@code <=} to)
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id}'s has a different limit bit size than base pointer's id
 */
public Pointer findClosest(Id id) {
    Validate.notNull(id);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    Id selfId = basePtr.getId();

    InternalEntry foundEntry = null;
    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        // if finger[i] exists between n (exclusive) and id (exclusive)
        // then return it
        Id fingerId = ie.pointer.getId();
        if (fingerId.isWithin(selfId, false, id, true)) {
            foundEntry = ie;
            break;
        }
    }

    return foundEntry == null ? basePtr : foundEntry.pointer;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Gets finger before {@code id}.//from   w ww.  j  a va2 s  . co m
 *
 * @param id id to search for
 * @return finger before (@code id}, or {@code null} if not found
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id} has a different limit bit size than base pointer's id, or if {@code id} is equivalent
 * to base pointer's id
 */
public Pointer getBefore(Id id) {
    Validate.notNull(id);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    Id baseId = basePtr.getId();

    if (id.equals(baseId)) {
        throw new IllegalArgumentException();
    }

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        Id testId = ie.pointer.getId();

        if (Id.comparePosition(baseId, id, testId) > 0) {
            return lit.hasPrevious() ? lit.previous().pointer : null;
        }
    }

    return null;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Removes all fingers before {@code id} (does not remove {@code id} itself).
 *
 * @param id id of which all fingers before it will be removed
 * @return number of fingers that were cleared
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id} has a different limit bit size than base pointer's id, or if {@code id} is equivalent
 * to base pointer's id//from w ww . j a  v  a2  s .  c  o  m
 */
public int clearBefore(Id id) {
    Validate.notNull(id);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    Id baseId = basePtr.getId();

    if (id.equals(baseId)) {
        throw new IllegalArgumentException();
    }

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        Id testId = ie.pointer.getId();

        if (Id.comparePosition(baseId, id, testId) > 0) {
            int position = lit.previousIndex() + 1;
            clearBefore(position);
            return position;
        }
    }

    return 0;
}