Esempio n. 1
0
  public static String writeChemkinPdepReactions(ReactionSystem rs) {
    // #[ operation writeChemkinReactions(ReactionModel)

    StringBuilder result = new StringBuilder();
    result.append("REACTIONS	KCAL/MOLE\n");

    LinkedList rList = new LinkedList();
    LinkedList troeList = new LinkedList();
    LinkedList tbrList = new LinkedList();
    LinkedList duplicates = new LinkedList();
    LinkedList lindeList = new LinkedList();

    if (rs.dynamicSimulator instanceof JDASPK) {
      rList = ((JDASPK) rs.dynamicSimulator).rList;
      troeList = ((JDASPK) rs.dynamicSimulator).troeList;
      tbrList = ((JDASPK) rs.dynamicSimulator).thirdBodyList;
      duplicates = ((JDASPK) rs.dynamicSimulator).duplicates;
      lindeList = ((JDASPK) rs.dynamicSimulator).lindemannList;
    } else if (rs.dynamicSimulator instanceof JDASSL) {
      rList = ((JDASSL) rs.dynamicSimulator).rList;
      troeList = ((JDASSL) rs.dynamicSimulator).troeList;
      tbrList = ((JDASSL) rs.dynamicSimulator).thirdBodyList;
      duplicates = ((JDASSL) rs.dynamicSimulator).duplicates;
      lindeList = ((JDASSL) rs.dynamicSimulator).lindemannList;
    }

    for (Iterator iter = rList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      // 10/26/07 gmagoon: changed to avoid use of Global.temperature; I am using
      // getPresentTemperature for the time being; it is possible that
      // getInitialStatus.getTemperature or something similar may be more appropriate
      result.append(r.toChemkinString(rs.getPresentTemperature()) + "\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n");
    }
    for (Iterator iter = troeList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(r.toChemkinString(rs.getPresentTemperature()) + "\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n");
    }
    for (Iterator iter = tbrList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(r.toChemkinString(rs.getPresentTemperature()) + "\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n");
    }
    for (Iterator iter = duplicates.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(r.toChemkinString(rs.getPresentTemperature()) + "\n\tDUP\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n\tDUP\n");
    }
    for (Iterator iter = lindeList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(r.toChemkinString(rs.getPresentTemperature()) + "\n");
    }

    result.append("END\n");

    return result.toString();

    // #]
  }
  @Test
  public void testAStar_distance_slantedRoad() {
    MapGraph mapGraph = new MapGraph();
    mapGraph.addRoad("Road 1", new Point2D.Double(0, 20), new Point2D.Double(100, 20), 35);
    mapGraph.addRoad("Road 2", new Point2D.Double(20, 0), new Point2D.Double(20, 100), 35);
    mapGraph.addRoad("Road 3", new Point2D.Double(0, 80), new Point2D.Double(100, 80), 35);
    mapGraph.addRoad("Road 4", new Point2D.Double(80, 0), new Point2D.Double(80, 100), 35);
    mapGraph.addRoad("Slanted road", new Point2D.Double(25, 15), new Point2D.Double(75, 85), 35);

    GraphVisualizer gv = new GraphVisualizer(mapGraph);
    LinkedList<Intersection> shortestPath1 =
        mapGraph.shortestPath_distance(
            mapGraph.getIntersectionByName("Road 1 + Road 2"),
            mapGraph.getIntersectionByName("Road 1 + Slanted road"));
    if (shortestPath1 == null) fail();
    Iterator<Intersection> test = shortestPath1.iterator();
    assertEquals("Road 1 + Road 2", test.next().toString());
    assertEquals("Road 1 + Slanted road", test.next().toString());
    assertFalse(test.hasNext());

    LinkedList<Intersection> shortestPath2 =
        mapGraph.shortestPath_distance(
            mapGraph.getIntersectionByName("Road 1 + Road 2"),
            mapGraph.getIntersectionByName("Road 3 + Road 4"));
    if (shortestPath2 == null) fail();
    test = shortestPath2.iterator();
    assertEquals("Road 1 + Road 2", test.next().toString());
    assertEquals("Road 1 + Slanted road", test.next().toString());
    assertEquals("Road 3 + Slanted road", test.next().toString());
    assertEquals("Road 3 + Road 4", test.next().toString());
    assertFalse(test.hasNext());
  }
Esempio n. 3
0
  /**
   * Measure of statistical dependence between two variables
   *
   * <p>http://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient
   *
   * @param X
   * @param Y
   * @return
   */
  public double spearmanCC(List<T> X, List<T> Y) {
    LinkedList<ValueRank> valueRankX = new LinkedList<ValueRank>();
    LinkedList<ValueRank> valueRankY = new LinkedList<ValueRank>();
    Iterator itX = X.iterator();
    Iterator itY = Y.iterator();
    int size = 0;
    while (itX.hasNext() && itY.hasNext()) {
      size++;
      valueRankX.add(new ValueRank<T>((T) itX.next(), size));
      valueRankY.add(new ValueRank<T>((T) itY.next(), size));
    }

    Collections.sort(valueRankX);
    Collections.sort(valueRankY);

    itX = valueRankX.iterator();
    itY = valueRankY.iterator();

    LinkedList<Double> rankX = new LinkedList<Double>();
    LinkedList<Double> rankY = new LinkedList<Double>();
    while (itX.hasNext() && itY.hasNext()) {
      ValueRank vrx = (ValueRank) itX.next();
      ValueRank vry = (ValueRank) itY.next();
      rankX.add(vrx.getRank());
      rankY.add(vry.getRank());
    }

    Stats<Double> stat = new Stats<Double>();
    return stat.personCC(rankX, rankY);
  }
Esempio n. 4
0
 public void onSent(int totalPacketLength, BasePeerNode pn) {
   Iterator<MessageFragment> fragIt = fragments.iterator();
   int totalMessageData = 0;
   int size = fragments.size();
   int biggest = 0;
   while (fragIt.hasNext()) {
     MessageFragment frag = fragIt.next();
     totalMessageData += frag.fragmentLength;
     size++;
     if (biggest < frag.messageLength) biggest = frag.messageLength;
   }
   int overhead = totalPacketLength - totalMessageData;
   if (logDEBUG)
     Logger.debug(
         this,
         "Total packet overhead: "
             + overhead
             + " for "
             + size
             + " messages total message length "
             + totalMessageData
             + " total packet length "
             + totalPacketLength
             + " biggest message "
             + biggest);
   fragIt = fragments.iterator();
   while (fragIt.hasNext()) {
     MessageFragment frag = fragIt.next();
     // frag.wrapper is always non-null on sending.
     frag.wrapper.onSent(
         frag.fragmentOffset, frag.fragmentOffset + frag.fragmentLength - 1, overhead / size, pn);
   }
 }
  public void updateRecentlyOpenedFiles(String s) {
    // try to add this file to the list and update the preference
    Iterator i = list.iterator();

    // update the maxFile count in case it changed...
    list.remove(0);
    list.add(0, maxSize);

    // is file already in list?
    if (list.contains(s)) {
      int index = list.indexOf(s);
      list.remove(index);
      list.add(1, s);

    } else {
      // if it's not in the list add it to the top and deal with it later
      list.add(1, s);
    }

    // trim list if necessary...
    while (list.size() > (maxsize + 1)) list.removeLast();

    // build a new pref String;
    StringBuffer sbuffer = new StringBuffer();

    i = list.iterator();

    while (i.hasNext()) {
      sbuffer.append((String) i.next());
      sbuffer.append("*");
    }
    // update the preference
    openFilePref.setValue(sbuffer.toString());
  }
Esempio n. 6
0
  public Script2() {
    mobs = new LinkedList<IMob>();
    sleepBetweenNextMob = new LinkedList<Long>();

    mobs.add(new Mob1());
    sleepBetweenNextMob.add(4000L);
    mobs.add(new Mob2());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(4000L);
    mobs.add(new Mob2());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);
    mobs.add(new Mob1());
    sleepBetweenNextMob.add(1000L);

    mobsIte = mobs.iterator();
    sleepIte = sleepBetweenNextMob.iterator();
  }
Esempio n. 7
0
  /**
   * Change the status This is the master function which may change the status of one or more
   * instances.
   */
  public static void changeStatus(int status, String messageText) {
    if (Preferences.getBoolean("jeti", "statusLinked", true)) {
      for (Iterator i = subInstances.iterator(); i.hasNext(); ) {
        StatusButton sub = (StatusButton) i.next();
        sub.changeInstanceStatus(status, messageText);
      }
      master.changeInstanceStatus(status, messageText);

    } else {
      if (currentParent == master || currentParent == null) {
        for (Iterator i = subInstances.iterator(); i.hasNext(); ) {
          StatusButton sub = (StatusButton) i.next();
          if (sub.status == master.status
              && ((sub.message == null && master.message == null)
                  || (sub.message != null && sub.message.equals(master.message)))) {
            sub.changeInstanceStatus(status, messageText);
          }
        }
      }
      if (currentParent != null) {
        currentParent.changeInstanceStatus(status, messageText);
      } else {
        master.changeInstanceStatus(status, messageText);
      }
    }
  }
Esempio n. 8
0
 /**
  * Output conflict list as XML.
  *
  * @param ch Content handler to output the conflict to.
  * @throws SAXException precolated up from the content handler
  */
 public void writeConflicts(ContentHandler ch) throws SAXException {
   AttributesImpl atts = new AttributesImpl();
   ch.startDocument();
   ch.startElement("", "", "conflictlist", atts);
   if (!conflicts.isEmpty()) {
     atts = new AttributesImpl();
     ch.startElement("", "", "conflicts", atts);
     for (Iterator i = conflicts.iterator(); i.hasNext(); )
       outputConflict((ConflictEntry) i.next(), ch);
     ch.endElement("", "", "conflicts");
   }
   if (!warnings.isEmpty()) {
     atts = new AttributesImpl();
     ch.startElement("", "", "warnings", atts);
     for (Iterator i = warnings.iterator(); i.hasNext(); )
       outputConflict((ConflictEntry) i.next(), ch);
     ch.endElement("", "", "warnings");
   }
   ch.endElement("", "", "conflictlist");
   if (!conflicts.isEmpty())
     System.err.println("MERGE FAILED: " + conflicts.size() + " conflicts.");
   if (!warnings.isEmpty())
     System.err.println("Warning: " + warnings.size() + " conflict warnings.");
   ch.endDocument();
 }
 // assume intervals in l1, l2 already sorted
 public static LinkedList<Pair> mergeIntervals(LinkedList<Pair> l1, LinkedList<Pair> l2) {
   Iterator<Pair> i1 = l1.iterator(), i2 = l2.iterator();
   LinkedList<Pair> ret = new LinkedList<Pair>();
   try {
     Pair p1 = i1.next(), p2 = i2.next();
     while (true) {
       if (p1.a <= p2.a) {
         if (p1.b > p2.a)
           if (p1.b < p2.b) {
             ret.add(new Pair(p2.a, p1.b));
             p1 = i1.next();
           } else {
             ret.add(new Pair(p2.a, p2.b));
             p2 = i2.next();
           }
         else p1 = i1.next();
       } else {
         if (p2.b > p1.a)
           if (p2.b < p1.b) {
             ret.add(new Pair(p1.a, p2.b));
             p2 = i2.next();
           } else {
             ret.add(new Pair(p1.a, p1.b));
             p1 = i1.next();
           }
         else p2 = i2.next();
       }
     }
   } catch (NoSuchElementException e) {
   }
   return ret;
 }
  /**
   * Removes given value from the set and returns the instance stored in the set or {@code null} if
   * value was not found.
   *
   * @param val Value to remove.
   * @return The instance that was stored in the set or {@code null}.
   */
  @Nullable
  public V removex(V val) {
    A.notNull(val, "val");

    if (comp == null || !strict) {
      for (Iterator<V> it = vals.iterator(); it.hasNext(); ) {
        V v = it.next();

        if (v.equals(val)) {
          it.remove();

          return v;
        }
      }

      return null;
    }

    assert comp != null && strict;

    for (Iterator<V> it = vals.iterator(); it.hasNext(); ) {
      V v = it.next();

      // Prefer equals to comparator.
      if (v.equals(val)) {
        it.remove();

        return v;
      }

      if (comp.compare(v, val) > 0) break;
    }

    return null;
  }
Esempio n. 11
0
  public static void main(String[] args) {
    ArrayList<Pessoa> vp = new ArrayList<>();

    for (int i = 0; i < 10; i++)
      vp.add(new Pessoa("Bebe?? no Vector " + i, 1000 + i, Data.today()));

    Iterator<Pessoa> vec = vp.iterator();
    printSet(vp.iterator());

    LinkedList<Pessoa> lp = new LinkedList<>();

    while (vec.hasNext()) lp.add(vec.next());

    Iterator<Pessoa> lista = lp.iterator();

    while (lista.hasNext()) System.out.println(lista.next());

    LinkedList<Figura> figList = new LinkedList<>();

    figList.add(new Circulo(1, 3, 1));
    figList.add(new Quadrado(3, 4, 2));
    figList.add(new Rectangulo(1, 2, 2, 5));

    printSet(figList.iterator());

    System.out.println("Soma da Area de Lista de Figuras: " + sumArea(figList));

    // Partindo do principio que Quadrado extends Rectangulo:
    LinkedList<Rectangulo> quadList = new LinkedList<>();

    quadList.add(new Quadrado(3, 4, 2));
    quadList.add(new Rectangulo(1, 2, 2, 5));

    System.out.println("Soma da Area de Lista de Quadrados: " + sumArea(quadList));
  }
  public StronglyConnectedComponentsBV(BitVector typeVariableList, TypeResolverBV resolver)
      throws TypeException {
    this.resolver = resolver;
    variables = typeVariableList;

    black = new TreeSet();
    finished = new LinkedList();

    for (BitSetIterator i = variables.iterator(); i.hasNext(); ) {
      TypeVariableBV var = resolver.typeVariableForId(i.next());

      if (!black.contains(var)) {
        black.add(var);
        dfsg_visit(var);
      }
    }

    black = new TreeSet();

    for (Iterator i = finished.iterator(); i.hasNext(); ) {
      TypeVariableBV var = (TypeVariableBV) i.next();

      if (!black.contains(var)) {
        current_tree = new LinkedList();
        forest.add(current_tree);
        black.add(var);
        dfsgt_visit(var);
      }
    }

    for (Iterator i = forest.iterator(); i.hasNext(); ) {
      LinkedList list = (LinkedList) i.next();
      TypeVariableBV previous = null;
      StringBuffer s = null;
      if (DEBUG) {
        s = new StringBuffer("scc:\n");
      }

      for (Iterator j = list.iterator(); j.hasNext(); ) {
        TypeVariableBV current = (TypeVariableBV) j.next();

        if (DEBUG) {
          s.append(" " + current + "\n");
        }

        if (previous == null) {
          previous = current;
        } else {
          try {
            previous = previous.union(current);
          } catch (TypeException e) {
            if (DEBUG) {
              G.v().out.println(s);
            }
            throw e;
          }
        }
      }
    }
  }
Esempio n. 13
0
  /**
   * Map the actors on to the Services. The mapping is trivial in the sense that no effort is made
   * to optimize the mapping. ALL the actors are distributed to a Service not taking into account
   * any QoS. One might want to create smarter ways to do the mapping... this is the place to do so.
   * Create the client threads. For every actor that is distributed (ALL) a local clientThread is
   * created to allow for parallel execution.
   *
   * @see ptolemy.distributed.client.ClientThread
   */
  private void mapActorsOntoServers() {
    if (VERBOSE) {
      System.out.println("Mapping Actors Onto Servers");
    }

    LinkedList actors = getActors();
    LinkedList servers = getServers();

    if (actors.size() <= servers.size()) {
      Iterator serversIterator = servers.iterator();

      for (Iterator actorsIterator = actors.iterator(); actorsIterator.hasNext(); ) {
        Object auxActor = actorsIterator.next();
        Object auxServer = serversIterator.next();
        ClientThread auxClientThread = new ClientThread(synchronizer, (ServiceItem) auxServer);
        actorsThreadsMap.put(auxActor, auxClientThread);
        auxClientThread.start();
      }
    } else {
      System.out.println("Not enough servers");
    }

    if (true) {
      printActorsOntoServersMap();
    }
  }
  public static boolean isValid(LinkedList<?> expected, LinkedList<?> actual) {
    if (actual == null) {
      return false;
    }

    Iterator<?> expectedEntries = expected.iterator();
    Iterator<?> actualEntries = actual.iterator();
    return equals(expectedEntries, actualEntries);
  }
Esempio n. 15
0
  /** Rimuove tutti gli elementi della lista. */
  public void removeAll() {
    if (lista == null) return;

    Iterator ite = lista.iterator();
    while (ite.hasNext()) {
      this.removeElement((ElementoConstraint) ite.next());
      ite = lista.iterator();
    }
  }
  public static void main(String[] args) {
    if (args.length < 2) System.exit(1);
    if (args.length > 2) {
      callMainSearch(args[1]);
      System.exit(1);
    }
    try {
      Indexer indexer = new Indexer(new File(args[1]));
      IndexerPool.addIndexer(indexer);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    String[] sfxes = {".PDF", ".pdf"};
    Collection<File> files = FileSystemUtils.getFiles(args[0], sfxes);
    LinkedList<TextExtractorRunner> extractorRunners = new LinkedList<TextExtractorRunner>();
    LinkedList<Thread> threads = new LinkedList<Thread>();
    LinkedBlockingDeque<File> queue = new LinkedBlockingDeque<File>();
    int i = 0;
    while (i++ < 8) {
      extractorRunners.add(new TextExtractorRunner(new TextExtractor(), queue));
    }

    Iterator<TextExtractorRunner> rit = extractorRunners.iterator();
    while (rit.hasNext()) {
      Thread t = new Thread(rit.next());
      threads.add(t);
      t.start();
    }

    for (File f : files) {
      queue.offer(f);
    }
    while (true) {
      if (queue.isEmpty()) {
        break;
      }
      Utility.Sleep(100);
    }

    rit = extractorRunners.iterator();
    while (rit.hasNext()) {
      rit.next().stop();
    }

    Iterator<Thread> thIt = threads.iterator();
    while (thIt.hasNext()) {
      try {
        thIt.next().join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    System.out.println("Done ....................");
  }
  /**
   * set history in database
   *
   * @param list list with history data
   */
  public void setHistory(LinkedList<T> list) throws SQLException {
    PreparedStatement preparedStatement;

    synchronized (lock) {
      Database database = null;
      try {
        // open database
        database = new Database(HISTORY_DATABASE_NAME);

        // delete old history
        preparedStatement = database.prepareStatement("DELETE FROM " + name);
        preparedStatement.executeUpdate();
        database.commit();

        // add new history
        Iterator<T> iterator = null;
        switch (direction) {
          case ASCENDING:
            iterator = list.descendingIterator();
            break;
          case DESCENDING:
            iterator = list.iterator();
            break;
          case SORTED:
            Collections.sort(
                list,
                new Comparator<T>() {
                  public int compare(T data0, T data1) {
                    return dataCompareTo(data0, data1);
                  }
                });
            iterator = list.iterator();
            break;
        }
        while (iterator.hasNext()) {
          T data = iterator.next();

          preparedStatement = prepareInsert(database, data);
          preparedStatement.executeUpdate();
        }
        database.commit();

        // close database
        database.close();
        database = null;
      } finally {
        if (database != null)
          try {
            database.close();
          } catch (SQLException unusedException) {
            /* ignored */
          }
      }
    }
  }
Esempio n. 18
0
 void doCommit() throws XAException, SystemException {
   boolean onePhase = isOnePhase();
   boolean readOnly = true;
   if (!onePhase) {
     // prepare
     status = Status.STATUS_PREPARING;
     LinkedList<Xid> preparedXids = new LinkedList<Xid>();
     Iterator<ResourceElement> itr = resourceList.iterator();
     while (itr.hasNext()) {
       ResourceElement re = itr.next();
       if (!preparedXids.contains(re.getXid())) {
         preparedXids.add(re.getXid());
         int vote = re.getResource().prepare(re.getXid());
         if (vote == XAResource.XA_OK) {
           readOnly = false;
         } else if (vote == XAResource.XA_RDONLY) {
           re.setStatus(RS_READONLY);
         } else {
           // rollback tx
           status = Status.STATUS_MARKED_ROLLBACK;
           return;
         }
       } else {
         // set it to readonly, only need to commit once
         re.setStatus(RS_READONLY);
       }
     }
     status = Status.STATUS_PREPARED;
   }
   // commit
   if (!onePhase && readOnly) {
     status = Status.STATUS_COMMITTED;
     return;
   }
   if (!onePhase) {
     try {
       txManager.getTxLog().markAsCommitting(getGlobalId());
     } catch (IOException e) {
       log.log(Level.SEVERE, "Error writing transaction log", e);
       txManager.setTmNotOk();
       throw Exceptions.withCause(
           new SystemException("TM encountered a problem, " + " error writing transaction log"),
           e);
     }
   }
   status = Status.STATUS_COMMITTING;
   Iterator<ResourceElement> itr = resourceList.iterator();
   while (itr.hasNext()) {
     ResourceElement re = itr.next();
     if (re.getStatus() != RS_READONLY) {
       re.getResource().commit(re.getXid(), onePhase);
     }
   }
   status = Status.STATUS_COMMITTED;
 }
  private static void createSubscriberArray(
      int noTopicsPublished,
      int numberOfSubscriber,
      NotificationManager[] notifManagerArray,
      int arrayIndex)
      throws Exception, IOException {
    if ("false".equalsIgnoreCase(configurations.getProperty(ConfigKeys.IS_XPATH_ENABLED))) {
      if (numberOfSubscriber <= noTopicsPublished) {
        for (int i = 0; i < noTopicsPublished; ++i) {
          notifManagerArray[arrayIndex].createTopicSubscription(topicPrefix + i);
          notifManagerArray[arrayIndex++].incNoTopicsSubscribed();
          if (arrayIndex >= numberOfSubscriber) {
            arrayIndex = 0;
          }
        }
      } else {
        int topicIndex = 0;
        for (int i = 0; i < numberOfSubscriber; ++i) {
          notifManagerArray[i].createTopicSubscription(topicPrefix + topicIndex++);
          notifManagerArray[i].incNoTopicsSubscribed();
          if (topicIndex >= noTopicsPublished) {
            topicIndex = 0;
          }
        }
      }
    } else {
      xpathList = LoadXpath.getInstace().getXpathList("xpath.list");
      if (numberOfSubscriber <= noTopicsPublished) {
        Iterator<String> ite = xpathList.iterator();
        for (int i = 0; i < noTopicsPublished; ++i) {
          if (!ite.hasNext()) ite = xpathList.iterator();

          notifManagerArray[arrayIndex].createXpathSubscription(topicPrefix + i, ite.next());
          notifManagerArray[arrayIndex++].incNoTopicsSubscribed();
          if (arrayIndex >= numberOfSubscriber) {
            arrayIndex = 0;
          }
        }
      } else {
        int topicIndex = 0;
        for (int i = 0; i < numberOfSubscriber; ++i) {
          notifManagerArray[i].incNoTopicsSubscribed();
          if (topicIndex >= noTopicsPublished) {
            topicIndex = 0;
          }
        }
      }
    }
  }
  @Override
  public boolean incrementToken() throws IOException {
    if (!terms.isEmpty()) {
      char[] buffer = terms.poll();
      termAttribute.setEmpty();
      termAttribute.copyBuffer(buffer, 0, buffer.length);
      posIncAttr.setPositionIncrement(1);
      return true;
    }

    if (!input.incrementToken()) {
      return false;
    } else {
      final char term[] = termAttribute.buffer();
      final int length = termAttribute.length();

      int k = 0;
      for (; k < length; k++) {
        if (term[k] == tokenDelimiter) {
          break;
        }
      }

      LinkedList<CharBuffer> buffers = permuteTerms(term, 0, length);

      Iterator iter = buffers.iterator();
      while (iter.hasNext()) {
        CharBuffer cb = (CharBuffer) iter.next();
        terms.add(cb.array());
      }

      // we return true and leave the original token unchanged
      return true;
    }
  }
Esempio n. 21
0
 /**
  * @param grid
  * @return an array of vertex coordinates, one vertex per edge end, 3 coords per vertex
  */
 public double[] getCoords(float[][] grid) {
   double[] ret = new double[edges.size() * 3];
   Iterator<Integer> it = edges.iterator();
   switch (direction) {
     case 0:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][it.next().intValue()];
         ret[i + 1] = grid[1][c1];
         ret[i + 2] = grid[2][c2];
       }
       break;
     case 1:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][c1];
         ret[i + 1] = grid[1][it.next().intValue()];
         ret[i + 2] = grid[2][c2];
       }
       break;
     case 2:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][c1];
         ret[i + 1] = grid[1][c2];
         ret[i + 2] = grid[2][it.next().intValue()];
       }
       break;
   }
   return ret;
 }
Esempio n. 22
0
 /**
  * empty the who wait list
  *
  * @return true when the book's wait list is empty
  */
 public boolean emptyQ() {
   this.iwaitlist = waitlist.iterator();
   if (iwaitlist.hasNext()) {
     return false;
   }
   return true; // TRUE if and only if waiting list is empty
 }
 /**
  * Notifies the listeners to refresh the screen
  *
  * @param ne the edge that has been removed
  */
 protected void notifyListenersOfRemove(NamedEdge ne) {
   Iterator i = listeners.iterator();
   while (i.hasNext()) {
     WorkingMemoryListener wml = (WorkingMemoryListener) i.next();
     wml.WMERemoved(new WorkingMemoryEvent(ne));
   }
 }
Esempio n. 24
0
  @Test
  public void testAStar_distance_tictac() {
    MapGraph mapGraph = new MapGraph();
    mapGraph.addRoad("Road 1", new Point2D.Double(0, 20), new Point2D.Double(100, 20), 35);
    mapGraph.addRoad("Road 2", new Point2D.Double(20, 0), new Point2D.Double(20, 100), 35);
    mapGraph.addRoad("Road 3", new Point2D.Double(0, 80), new Point2D.Double(100, 80), 35);
    LinkedList<Intersection> shortestPath1 =
        mapGraph.shortestPath_distance(
            mapGraph.getIntersectionByName("Road 1 + Road 2"),
            mapGraph.getIntersectionByName("Road 2 + Road 3"));
    if (shortestPath1 == null) fail();
    Iterator<Intersection> test = shortestPath1.iterator();
    assertEquals("Road 1 + Road 2", test.next().toString());
    assertEquals("Road 2 + Road 3", test.next().toString());
    assertFalse(test.hasNext());

    mapGraph.addRoad("Road 4", new Point2D.Double(80, 0), new Point2D.Double(80, 100), 35);

    LinkedList<Intersection> shortestPath1b =
        mapGraph.shortestPath_distance(
            mapGraph.getIntersectionByName("Road 1 + Road 2"),
            mapGraph.getIntersectionByName("Road 3 + Road 4"));
    if (shortestPath1b == null) fail();
    //		System.out.println(shortestPath1b);
    //		test = shortestPath1b.iterator();
    //		assertEquals("Road 1 + Road 2",test.next().toString());
    //		assertEquals("Road 2 + Road 3",test.next().toString());
    //		assertFalse(test.hasNext());
  }
Esempio n. 25
0
  /// @pre --
  /// @post Si NauEnemiga està a prop d'algun Meteorit de lm llavors l'evita i retorna cert
  // altrament no fa res i retorna fals
  private boolean evitarMeteorits(LinkedList<Meteorit> lm) {
    double[] c = obtenirCentreTriangle();

    double[] v = null;
    double distMin = l_ * 2;

    Iterator<Meteorit> it = lm.iterator();
    while (it.hasNext()) {
      double[] aux = it.next().puntVertexMesProper(c[0], c[1]);
      double distAct = distancia(aux[0], aux[1]);

      if (distAct < distMin) {
        v = aux;
        distMin = distAct;
      }
    }
    if (v != null) {
      int angle = angleApuntar(v);
      angle += 180;
      if (angle >= 360) {
        angle -= 360;
      }
      alinearse(angle);
      propulsarEndavant();
    }

    return v != null;
  }
    /**
     * Find the maximum weight matching of a path using dynamic programming.
     *
     * @param path a list of edges. The code assumes that the list of edges is a valid simple path,
     *     and that is not a cycle.
     * @return a maximum weight matching of the path
     */
    public Pair<Double, Set<E>> getMaximumWeightMatching(Graph<V, E> g, LinkedList<E> path) {
      int pathLength = path.size();

      // special cases
      switch (pathLength) {
        case 0:
          // special case, empty path
          return Pair.of(Double.valueOf(0d), Collections.emptySet());
        case 1:
          // special case, one edge
          E e = path.getFirst();
          double eWeight = g.getEdgeWeight(e);
          if (comparator.compare(eWeight, 0d) > 0) {
            return Pair.of(eWeight, Collections.singleton(e));
          } else {
            return Pair.of(Double.valueOf(0d), Collections.emptySet());
          }
      }

      // make sure work array has enough space
      if (a.length < pathLength + 1) {
        a = new double[pathLength + 1];
      }

      // first pass to find solution
      Iterator<E> it = path.iterator();
      E e = it.next();
      double eWeight = g.getEdgeWeight(e);
      a[0] = 0d;
      a[1] = (comparator.compare(eWeight, 0d) > 0) ? eWeight : 0d;
      for (int i = 2; i <= pathLength; i++) {
        e = it.next();
        eWeight = g.getEdgeWeight(e);
        if (comparator.compare(a[i - 1], a[i - 2] + eWeight) > 0) {
          a[i] = a[i - 1];
        } else {
          a[i] = a[i - 2] + eWeight;
        }
      }

      // reverse second pass to build solution
      Set<E> matching = new HashSet<>();
      it = path.descendingIterator();
      int i = pathLength;
      while (i >= 1) {
        e = it.next();
        if (comparator.compare(a[i], a[i - 1]) > 0) {
          matching.add(e);
          // skip next edge
          if (i > 1) {
            e = it.next();
          }
          i--;
        }
        i--;
      }

      // return solution
      return Pair.of(a[pathLength], matching);
    }
Esempio n. 27
0
 private boolean pageMeetsConditions(WikiPage page) {
   for (Iterator<XmlizePageCondition> iterator = pageConditions.iterator(); iterator.hasNext(); ) {
     XmlizePageCondition xmlizePageCondition = iterator.next();
     if (!xmlizePageCondition.canBeXmlized(page)) return false;
   }
   return true;
 }
  /** Specified in Node */
  protected Node removeNeighbour(Node neighbour) {
    Iterator it = edges.iterator();
    Edge next;
    while (it.hasNext()) {
      next = (Edge) it.next();
      if (next.to == neighbour) {
        it.remove();
        break;
      }
    }

    // collapse this node if it has degree 2 after removal of neighbour
    if (edges.size() == 2) {
      Edge e1 = (Edge) edges.getFirst();
      Edge e2 = (Edge) edges.getLast();
      Edge ne1, ne2;

      ne1 = e1.to.addNeighbour(e2.to);
      ne2 = e2.to.addNeighbour(e1.to);
      ne1.backedge = ne2;
      ne2.backedge = ne1;
      e1.to.removeNeighbour(this);
      return e2.to.removeNeighbour(this);
    }
    return this;
  }
Esempio n. 29
0
 /** Remove referenced sign messages */
 private void removeReferencedMessages() {
   Iterator<SignMessageImpl> it = reapable.iterator();
   while (it.hasNext()) {
     SignMessage sm = it.next();
     if (isReferenced(sm)) it.remove();
   }
 }
  /**
   * Override the base class to break inside links on ports as well as outside lists. This method is
   * write-synchronized on the workspace and increments its version number.
   */
  public void unlinkAll() {
    // NOTE: Do not just use _portList.unlinkAll() because then the
    // containers of the ports are not notified of the change.
    // Also, have to first copy the ports references, then remove
    // them, to avoid a corrupted enumeration exception.
    // Unlink the outside links of linked ports.
    super.unlinkAll();
    try {

      // Next, remove the links that are inside links of ports.
      _workspace.getWriteAccess();

      LinkedList ports = new LinkedList();
      Enumeration links = _linkList.getContainers();

      while (links.hasMoreElements()) {
        Object link = links.nextElement();

        if (link instanceof ComponentPort) {
          ports.add(link);
        }
      }

      Iterator portsIterator = ports.iterator();

      while (portsIterator.hasNext()) {
        ((ComponentPort) (portsIterator.next())).unlinkInside(this);
      }
    } finally {
      _workspace.doneWriting();
    }
  }