Beispiel #1
0
  public static void maxFlow(ListGraph g) {
    ListGraph residualG = g.residualGraph();

    LinkedList<DirEdge> path = residualG.getFlowPath();
    while (path != null) {
      // System.out.println("Got path");
      int minCapacity = ListGraph.minCapacityInPath(path);

      assert minCapacity > 0;
      // augment every edge on the path in the original graph
      int head = g.getSource();
      ListIterator it = path.listIterator();
      while (it.hasNext()) {
        DirEdge rEdge = (DirEdge) it.next();
        int tail = rEdge.end;

        DirEdge e = g.getEdge(head, tail);
        e.flow += minCapacity;

        // System.out.println("Augmenting (" + head + "," + tail + ") to be " + e.flow);

        head = tail;
      }

      residualG = g.residualGraph();

      // System.out.println("g:");
      // g.print();

      // System.out.println("Residual graph:");
      // residualG.print();

      path = residualG.getFlowPath();
    }
  }
Beispiel #2
0
  /** Sorts the static LinkedList mainlineLinks in the order they appear on the freeway */
  private LinkedList<Link> recursiveLinkSort(LinkedList<Link> links2) {

    if (links2.size() == 1) {

      return links2;

    } else {

      boolean swapMade = false;
      ListIterator<Link> itr1 = links2.listIterator();
      while (itr1.hasNext()) {
        Link temp = itr1.next();
        int tempindex = itr1.nextIndex();
        // if this loop makes any switches, set the flag to true
        if (links2.getFirst().getUpNode().getNodeID() == temp.getDownNode().getNodeID()) {
          swapMade = true;
          links2.addFirst(temp);
          links2.remove(tempindex);
          return this.recursiveLinkSort(links2);
        }
      }

      if (!swapMade) {
        // assign last n-1 links to links3
        LinkedList<Link> links3 = new LinkedList<Link>();
        Link temp = links2.getFirst();
        links2.removeFirst();
        links3 = this.recursiveLinkSort(links2);
        links3.addFirst(temp);
        return links3;
      } else {
        return links2;
      }
    }
  }
 /** listIterator only returns those elements after the given index */
 public void testListIterator2() {
   List full = populatedArray(3);
   ListIterator i = full.listIterator(1);
   int j;
   for (j = 0; i.hasNext(); j++) assertEquals(j + 1, ((Integer) i.next()).intValue());
   assertEquals(2, j);
 }
Beispiel #4
0
  /**
   * Reads an array of strings from the TIFF file.
   *
   * @param count Number of strings to read
   * @param value Offset from which to read
   */
  protected String[] readASCIIArray(long count, long value) throws IOException {
    _raf.seek(value);

    int nstrs = 0;
    List list = new LinkedList();
    byte[] buf = new byte[(int) count];
    _raf.read(buf);
    StringBuffer strbuf = new StringBuffer();
    for (int i = 0; i < count; i++) {
      int b = buf[i];
      if (b == 0) {
        list.add(strbuf.toString());
        strbuf.setLength(0);
      } else {
        strbuf.append((char) b);
      }
    }
    /* We can't use ArrayList.toArray because that returns an
    Object[], not a String[] ... sigh. */
    String[] strs = new String[nstrs];
    ListIterator iter = list.listIterator();
    for (int i = 0; i < nstrs; i++) {
      strs[i] = (String) iter.next();
    }
    return strs;
  }
Beispiel #5
0
    public String hasSameContent(JarFile2 file, JarEntry entry) throws IOException {

      String thisName = null;

      Long crcL = new Long(entry.getCrc());

      // check if this jar contains files with the passed in entry's crc
      if (_crcToEntryMap.containsKey(crcL)) {
        // get the Linked List with files with the crc
        LinkedList ll = (LinkedList) _crcToEntryMap.get(crcL);
        // go through the list and check for content match
        ListIterator li = ll.listIterator(0);
        if (li != null) {
          while (li.hasNext()) {
            JarEntry thisEntry = (JarEntry) li.next();

            // check for content match
            InputStream oldIS = getJarFile().getInputStream(thisEntry);
            InputStream newIS = file.getJarFile().getInputStream(entry);

            if (!differs(oldIS, newIS)) {
              thisName = thisEntry.getName();
              return thisName;
            }
          }
        }
      }

      return thisName;
    }
Beispiel #6
0
 public DirEdge getEdge(int i, int j) {
   ListIterator it = edges.get(i).listIterator();
   while (it.hasNext()) {
     DirEdge edge = (DirEdge) it.next();
     if (edge.end == j) {
       return edge;
     }
   }
   return null;
 }
 /*
  * Print the action sequence (Probably) to the printer
  */
 public void actionPrint(PrintWriter ps) {
   int i = 0;
   ps.println("Stepper - action sequence");
   ps.println("Task ID - " + curTask);
   ps.println();
   ListIterator li = actionSequence.listIterator();
   while (li.hasNext()) {
     i++;
     oclPredicate pred = (oclPredicate) li.next();
     ps.println(i + ": " + pred.toString());
   }
 }
Beispiel #8
0
  public static String writeGridOfRateCoeffs(ReactionModel p_reactionModel) {

    StringBuilder result = new StringBuilder();

    LinkedList pDepList = new LinkedList();
    CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionModel;

    for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
      PDepNetwork pdn = (PDepNetwork) iter.next();
      for (ListIterator pdniter = pdn.getNetReactions().listIterator(); pdniter.hasNext(); ) {
        PDepReaction rxn = (PDepReaction) pdniter.next();
        if (cerm.categorizeReaction(rxn) != 1) continue;
        // check if this reaction is not already in the list and also check if this reaction has a
        // reverse reaction
        // which is already present in the list.
        if (rxn.getReverseReaction() == null) rxn.generateReverseReaction();
        if (!rxn.reactantEqualsProduct()
            && !pDepList.contains(rxn)
            && !pDepList.contains(rxn.getReverseReaction())) {
          pDepList.add(rxn);
        }
      }
    }

    Temperature[] tempsUsedInFame = PDepRateConstant.getTemperatures();
    int numTemps = tempsUsedInFame.length;
    Pressure[] pressUsedInFame = PDepRateConstant.getPressures();
    int numPress = pressUsedInFame.length;

    for (int i = 0; i < numTemps; i++) {
      for (int j = 0; j < numPress; j++) {
        result.append(
            "T=" + tempsUsedInFame[i].getK() + "K,P=" + pressUsedInFame[j].getBar() + "bar\t");
      }
      result.append("\n");
    }
    result.append("\n");

    for (Iterator iter = pDepList.iterator(); iter.hasNext(); ) {
      PDepReaction r = (PDepReaction) iter.next();
      result.append(r.toString() + "\n");
      double[][] rates = new double[numTemps][numPress];
      rates = r.getPDepRate().getRateConstants();
      for (int i = 0; i < numTemps; i++) {
        for (int j = 0; j < numPress; j++) {
          result.append(rates[i][j] + "\t");
        }
        result.append("\n");
      }
      result.append("\n");
    }
    return result.toString();
  }
 public double getBalance() {
   double totalBal = 0.0;
   if (cardCount() == 0) return 0.0;
   else {
     ListIterator iter = cards.dataIterator();
     while (iter.hasNext()) {
       CreditCard tmp = (CreditCard) iter.next();
       totalBal += tmp.getCredit();
     }
   }
   return totalBal;
 }
Beispiel #10
0
  public static int minCapacityInPath(LinkedList<DirEdge> path) {
    int minCapacity = Integer.MAX_VALUE;

    ListIterator it = path.listIterator();
    while (it.hasNext()) {
      DirEdge e = (DirEdge) it.next();
      if (e.capacity < minCapacity) {
        minCapacity = e.capacity;
      }
    }

    return minCapacity;
  }
Beispiel #11
0
  public void print() {
    for (int i = 0; i < v; i++) {
      ListIterator it = edges.get(i).listIterator();

      while (it.hasNext()) {
        DirEdge edge = (DirEdge) it.next();

        System.out.print("->" + edge.end + "(" + edge.flow + "/" + edge.capacity + ")");
      }

      System.out.println();
    }
  }
Beispiel #12
0
  /**
   * Returns the first entity under a point of the map, in the specified layer.
   *
   * @param layer the layer
   * @param x x of the point
   * @param y y of the point
   * @return the entity found, or null if there is no entity here
   */
  public MapEntity getEntityAt(Layer layer, int x, int y) {

    MapEntities entities = allEntities[layer.getId()];
    ListIterator<MapEntity> iterator = entities.listIterator(entities.size());
    while (iterator.hasPrevious()) {

      MapEntity entity = iterator.previous();
      if (entity.containsPoint(x, y)) {
        return entity;
      }
    }

    return null;
  }
  /**
   * Insert the list of <code>newPasses</code> into <code>passes</code> immediately after the pass
   * named <code>id</code>.
   */
  public void afterPass(List passes, Pass.ID id, List newPasses) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
          i.add(j.next());
        }

        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
 private void relabelToFront() {
   assert (!V.isEmpty()) : "No vertices";
   ListIterator<Vertex> iter = V.listIterator();
   while (iter.hasNext()) {
     Vertex v = iter.next();
     // System.out.println("Considering vertex: " + v);
     int oldHeight = v.getHeight();
     discharge(v);
     if (v.getHeight() > oldHeight) {
       iter.remove();
       V.addFirst(v);
       iter = V.listIterator(1);
     }
   }
 }
Beispiel #15
0
  void removeUnboundConnections() {
    ListIterator<Long> iter = UnboundConnections.listIterator(0);
    while (iter.hasNext()) {
      long b = iter.next();

      EventableChannel ec = Connections.remove(b);
      if (ec != null) {
        eventCallback(b, EM_CONNECTION_UNBOUND, null);
        ec.close();

        EventableSocketChannel sc = (EventableSocketChannel) ec;
        if (sc != null && sc.isAttached()) DetachedConnections.add(sc);
      }
    }
    UnboundConnections.clear();
  }
  /** Remove the pass named <code>id</code> from <code>passes</code>. */
  public void removePass(List passes, Pass.ID id) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        if (p instanceof BarrierPass) {
          throw new InternalCompilerError("Cannot remove a barrier pass.");
        }

        i.remove();
        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
  void runTimers() {
    long now = new Date().getTime();
    while (!Timers.isEmpty()) {
      long k = Timers.firstKey();
      if (k > now) break;

      ArrayList<Long> callbacks = Timers.get(k);
      Timers.remove(k);

      // Fire all timers at this timestamp
      ListIterator<Long> iter = callbacks.listIterator(0);
      while (iter.hasNext()) {
        eventCallback(0, EM_TIMER_FIRED, null, iter.next().longValue());
      }
    }
  }
Beispiel #18
0
 public void configureCar(Automotive car) {
   System.out.println("Configure the Car-\nPlease enter option choice.");
   Scanner read = new Scanner(System.in);
   ListIterator<String> it = car.getOptionSetNamesIterator();
   while (it.hasNext()) {
     String optionSetName = it.next().toString();
     System.out.println(optionSetName + ":");
     try {
       car.setOptionChoice(optionSetName, read.nextLine());
     } catch (InvalidOptionException e) {
       e.fixException();
     }
   }
   car.calculateFinalPrice();
   System.out.println("\nFinal Configuration-");
   car.printFinalConfig();
 }
Beispiel #19
0
  /**
   * Brings the specified entities to the back, keeping their layer. The order of the specified
   * entities in the map is unchanged.
   *
   * @param entities the entities to move
   */
  public void bringToBack(List<MapEntity> entities) {

    List<MapEntity> sortedEntities = getSortedEntities(entities);

    // bring to back each entity from sortedEntities
    ListIterator<MapEntity> iterator = sortedEntities.listIterator(sortedEntities.size());
    while (iterator.hasPrevious()) {

      MapEntity entity = iterator.previous();
      Layer layer = entity.getLayer();
      allEntities[layer.getId()].remove(entity);
      allEntities[layer.getId()].addFirst(entity);
    }

    setChanged();
    notifyObservers();
  }
Beispiel #20
0
  /**
   * Brings the specified entities to the front, keeping their layer. The order of the specified
   * entities in the map is unchanged.
   *
   * @param entities the entities to move
   */
  public void bringToFront(List<MapEntity> entities) {

    List<MapEntity> sortedEntities = getSortedEntities(entities);

    // bring to front each entity from sortedEntities
    ListIterator<MapEntity> iterator = sortedEntities.listIterator(0);
    while (iterator.hasNext()) {

      MapEntity entity = iterator.next();
      Layer layer = entity.getLayer();
      allEntities[layer.getId()].remove(entity);
      allEntities[layer.getId()].addLast(entity);
    }

    setChanged();
    notifyObservers();
  }
Beispiel #21
0
  public ListGraph residualGraph() {
    ListGraph residualG = new ListGraph(getNumNodes(), this.source, this.sink);
    for (int i = 0; i < v; i++) {
      ListIterator it = edges.get(i).listIterator();

      while (it.hasNext()) {
        DirEdge edge = (DirEdge) it.next();
        int leftCapacity = edge.capacity - edge.flow;
        if (leftCapacity > 0) residualG.addEdge(i, edge.end, leftCapacity);

        if (edge.flow > 0)
          residualG.addEdge(edge.end, i, edge.flow); // add the reverse direction capacity
      }
    }

    return residualG;
  }
  /**
   * Insert the list of <code>newPasses</code> into <code>passes</code> immediately before the pass
   * named <code>id</code>.
   */
  public void beforePass(List passes, Pass.ID id, List newPasses) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        // Backup one position.
        i.previous();

        for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
          i.add(j.next());
        }

        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
Beispiel #23
0
  public static void dumpcode(final MethodEditor m) {

    final PrintWriter out = new PrintWriter(System.out, true);
    final StackHeightCounter shc = new StackHeightCounter(m);

    out.println("Code for method " + m.name() + m.type());
    final List instructions = m.code();
    final ListIterator iter = instructions.listIterator();
    while (iter.hasNext()) {
      final Object obj = iter.next();
      if (obj instanceof Label) {
        shc.handle((Label) obj);
      } else if (obj instanceof Instruction) {
        shc.handle((Instruction) obj);
      }

      System.out.println("        " + obj + " (sh: " + shc.height() + ")");
    }
  }
Beispiel #24
0
  public LinkedList<DirEdge> getFlowPath() {
    // do a depth first search to see if there is path from source to the sink
    boolean[] visited = new boolean[v];
    Arrays.fill(visited, false);

    Stack<Integer> tobeVisited = new Stack<Integer>();
    tobeVisited.push(source);

    int[] predecessor = new int[v];
    Arrays.fill(predecessor, -1);

    while (!tobeVisited.isEmpty()) {
      int vertex = tobeVisited.pop();
      if (!visited[vertex]) {
        // System.out.println("Visiting " + vertex);
        visited[vertex] = true;

        // put vertex's next hop nodes into the stack
        ListIterator it = edges.get(vertex).listIterator();
        while (it.hasNext()) {
          DirEdge e = (DirEdge) it.next();
          if (predecessor[e.end] == -1) {
            predecessor[e.end] = vertex;
          }

          if (e.end == sink) {
            return constructPath(predecessor);
          }

          if (!visited[e.end]) {
            tobeVisited.push(e.end);
          }
        }
      }
    }

    return null; // we cannot find an augment path
  }
  void close() {
    try {
      if (mySelector != null) mySelector.close();
    } catch (IOException e) {
    }
    mySelector = null;

    // run down open connections and sockets.
    Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
    while (i.hasNext()) {
      try {
        i.next().close();
      } catch (IOException e) {
      }
    }

    // 29Sep09: We create an ArrayList of the existing connections, then iterate over
    // that to call unbind on them. This is because an unbind can trigger a reconnect,
    // which will add to the Connections HashMap, causing a ConcurrentModificationException.
    // XXX: The correct behavior here would be to latch the various reactor methods to return
    // immediately if the reactor is shutting down.
    ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
    Iterator<EventableChannel> i2 = Connections.values().iterator();
    while (i2.hasNext()) {
      EventableChannel ec = i2.next();
      if (ec != null) {
        conns.add(ec);
      }
    }
    Connections.clear();

    ListIterator<EventableChannel> i3 = conns.listIterator(0);
    while (i3.hasNext()) {
      EventableChannel ec = i3.next();
      eventCallback(ec.getBinding(), EM_CONNECTION_UNBOUND, null);
      ec.close();

      EventableSocketChannel sc = (EventableSocketChannel) ec;
      if (sc != null && sc.isAttached()) DetachedConnections.add(sc);
    }

    ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
    while (i4.hasNext()) {
      EventableSocketChannel ec = i4.next();
      ec.cleanup();
    }
    DetachedConnections.clear();
  }
  void addNewConnections() {
    ListIterator<EventableSocketChannel> iter = DetachedConnections.listIterator(0);
    while (iter.hasNext()) {
      EventableSocketChannel ec = iter.next();
      ec.cleanup();
    }
    DetachedConnections.clear();

    ListIterator<Long> iter2 = NewConnections.listIterator(0);
    while (iter2.hasNext()) {
      long b = iter2.next();

      EventableChannel ec = Connections.get(b);
      if (ec != null) {
        try {
          ec.register();
        } catch (ClosedChannelException e) {
          UnboundConnections.add(ec.getBinding());
        }
      }
    }
    NewConnections.clear();
  }
Beispiel #27
0
  // ---------------------------------------------------------------------------
  private BuildAction addToBuildQueue(String target, boolean primaryTarget, int insertPosition)
      throws TablesawException {
    // The target was already checked and does not need to be built
    if (m_noBuildCache.contains(target)) return (null);

    Debug.print("addToBuildQueue(" + target + ", " + primaryTarget + ", " + insertPosition + ")");
    Debug.indent();

    Rule trule = findTargetRule(target);

    CachedFile targetFile = null;
    BuildAction[] buildDep = null;
    BuildAction targetBA = null;
    BuildAction depBA = null;
    BuildAction ret = null;

    if (trule == null) {
      targetFile = m_fileManager.locateFile(target);

      // TODO: Add the rule that required this target to the error message
      if (targetFile == null)
        throw new TablesawException("Unable to locate rule for '" + target + "'");

      if (m_sourceFiles != null)
        m_sourceFiles.add(
            new File(
                targetFile.getPath())); // Doing this because locateFile will return a CachedFile

      // TODO: check file against cache file stamps and if changed return dummy rule
      Debug.print("Cache lookup for " + targetFile.getPath());

      // Add file to cache for next run
      m_newModificationCache.put(targetFile.getPath(), targetFile.lastModified());

      Long cacheModTime = m_modificationCache.get(targetFile.getPath());
      if (cacheModTime != null) {
        Debug.print("Cache hit " + cacheModTime + ":" + targetFile.lastModified());
        if (cacheModTime != targetFile.lastModified()) {
          Debug.print("returning obj for " + targetFile);
          Debug.popIndent();
          targetBA =
              new BuildAction(
                  m_fileManager, new ModifiedFileRule(targetFile.getPath()), m_classAnnotations);
          m_buildQueue.add(insertPosition, targetBA);
          return (targetBA);
        }
      } else Debug.print("Cache miss");

      // System.out.println("File "+targetFile);
      m_noBuildCache.add(target);
      Debug.print("Target " + target + " is a file with no rule");
      Debug.popIndent();
      return (null);
    }

    if ((m_sourceFiles != null) && (trule instanceof SourceFileSet)) {
      m_sourceFiles.addAll(((SourceFileSet) trule).getSourceFiles());
    }

    long targetTime = 0;
    boolean tExists = true;
    boolean tDir = false;
    boolean tPhony = true;

    boolean rebuild = false;

    targetBA = new BuildAction(m_fileManager, trule, m_classAnnotations);
    int index;

    if (m_buildQueueCache.containsKey(targetBA)) {
      // Get the build action from the queue
      targetBA = m_buildQueueCache.get(targetBA);

      Debug.print("target: " + trule + " already in build queue.");
      // Target has already been added to build queue
      Debug.popIndent();
      return (targetBA);
    }

    File f;

    trule.preBuild(m_depCache, m_modificationCache);

    // NOTE: need to add in dependencies that are individually declared
    // NOTE: getPrerequisites is also where dependency parsing happens to include C headers and
    // other java classes
    // String[] prereqs = getPrerequisites(trule, true);
    List<String> prereqs = new ArrayList<String>();

    for (String dn : trule.getDependNames()) {
      Debug.print("adding depend name " + dn);
      prereqs.add(dn);
    }

    for (Rule r : trule.getDependRules()) {
      Debug.print("adding depend rule " + r);
      if (r.getName() == null) {
        // Generate name for rule
        String genRuleName = NAMED_RULE_PREFIX + (m_ruleNameCounter++);
        r.setName(genRuleName);
        m_nameRuleMap.put(genRuleName, r);
      }

      prereqs.add(r.getName());
    }

    Debug.print("rule dependents " + prereqs.size());

    if (prereqs.size() > 0) {
      ListIterator<String> it = prereqs.listIterator();

      while (it.hasNext()) {
        String prereq = it.next();

        if (prereq.equals(target))
          throw new TablesawException("Target " + target + " depends on itself");

        /* //See if the prereq is the name of a rule first
        Rule nameRule = m_nameRuleMap.get(prereq);

        //Add the new rule targets to the prereqs list
        // TODO: some kind of check so we dont add the same named rule again and again.
        if (nameRule != null)
        	{
        	Iterable<String> ruleTargets = nameRule.getTargets();
        	boolean hasTargets = false;
        	for (String t : ruleTargets)
        		{
        		hasTargets = true;
        		it.add(t);
        		it.previous();
        		}

        	if (hasTargets)
        		continue;
        	} */

        // Add dependencies to build queue first.
        // f = m_fileManager.getFile(prereq);
        if ((depBA = addToBuildQueue(prereq, false, insertPosition)) != null) {
          targetBA.addDependency(depBA);
          // trule.addNewerDepend(prereq);
          if (depBA.isBinding()) {
            Debug.print("Rebuild: " + trule + " because rebuild of " + depBA.getTargetRule());
            rebuild = true;
          }
        }
      }
    }

    if (!rebuild) {
      rebuild = trule.needToRun();
      Debug.print("Rule needToRun() returned " + rebuild);
    }

    // TODO: change this to get depends from above and check if no depends
    if ((!rebuild)
        && (primaryTarget
            && (!trule
                .getTargets()
                .iterator()
                .hasNext()))) { // If target is the primary target and it has no targets
      Debug.print("Adding primary target: " + trule + " to build queue.");
      rebuild = true;
    }

    if (rebuild) { // Add target to build queue
      m_buildQueue.add(insertPosition, targetBA);
      m_buildQueueCache.put(targetBA, targetBA);
      Debug.print("Adding " + targetBA + " to build queue at pos " + insertPosition);
      // System.out.println("Adding "+targetBA+" to build queue at pos "+insertPosition);

      ret = targetBA;
    }

    // Add target to cache if it does not need to be built
    // This is to speed up incremental builds
    if (ret == null) m_noBuildCache.add(target);

    Debug.popIndent();
    return (ret);
  }
Beispiel #28
0
  public static void runPhraseSpellCheck() throws Exception {
    String S, collocatedString = "";
    Scanner enable = new Scanner(new File("/home/tanmay/workspace/SpellCheck/src/enable1.txt"));
    while (enable.hasNext()) {
      S = enable.next();
      // a = input.nextLong();
      // System.out.print(S+"\t"+ a+"\t");
      correctWords.add(S);
    }
    enable = new Scanner(new File("/home/tanmay/workspace/SpellCheck/src/stop.txt"));
    while (enable.hasNext()) {
      S = enable.next();
      // a = input.nextLong();
      // System.out.print(S+"\t"+ a+"\t");
      stopWords.add(S);
    }
    ArrayList<String> misspeltWords = new ArrayList<String>();
    ArrayList<Integer> misspeltWordsIndex = new ArrayList<Integer>();
    ArrayList<String> corrections = new ArrayList<String>();
    ArrayList<String> finalCorrections = new ArrayList<String>();
    ArrayList<String> phraseWords = new ArrayList<String>();
    int count;
    WordCheck w = new WordCheck();
    w.createDictionary();
    w.createConfusionMatrix();
    double candidateScore = 0;
    PhraseCheck p = new PhraseCheck();
    p.createNgrams();
    System.out.println("Preprocessing Done");
    String input = null;
    String phrase = null;
    BufferedReader br =
        new BufferedReader(
            new FileReader(new File("/home/tanmay/workspace/SpellCheck/src/phrases.txt")));
    while ((input = br.readLine()) != null) {
      long t1 = System.currentTimeMillis();
      misspeltWords.clear();
      misspeltWordsIndex.clear();
      // phrase = input.toLowerCase();
      phrase = input;
      // String[] words = null;
      ArrayList<String> words = new ArrayList<String>();
      String[] words1 = phrase.split(" ");
      /*  for(int i=0;i<words1.length;i++)
      {
      	System.out.print(words1[i] + " ");
      }*/
      for (int wordc = 0; wordc < words1.length / 2; wordc++) {
        words.add(words1[wordc]);
      }
      /*
      for(int wordCount=0;wordCount<words.length;wordCount++)
      {
      	phraseWords.add(words[wordCount]);
      }

        for (String word : phraseWords)
        {
           if(!correctWords.contains(word)&&!stopWords.contains(word))
           {
        	   misspeltWords.add(word);
        	   misspeltWordsIndex.add(phraseWords.indexOf(word));
           }
        }*/
      int wordc1 = 0;
      for (String word : words) {
        //	System.out.println("Wordc = " + wordc1);
        if (!correctWords.contains(word) && !stopWords.contains(word)) {
          misspeltWords.add(word);
          //  System.out.println("Word is "+word);
          misspeltWordsIndex.add(wordc1);
        }
        wordc1++;
      }
      wordc1 = 0;
      //        System.out.println(misspeltWords);

      /*Collocation Based*/
      /*
      int misspeltWordCount = 0;
      for (String misspeltWord : misspeltWords)
      {
      	w.getCandidates(misspeltWord);
      	corrections = w.candidates;
      	candidateScores.clear();
      	for(String correction : corrections)
      	{
      	for(int collocSizeLeft = 1;collocSizeLeft<MAXCONTEXTSIZE;collocSizeLeft++)
      	{
      		for(int collocSizeRight = 1;collocSizeRight<MAXCONTEXTSIZE;collocSizeRight++)
      		{
      			collocatedString= "";
      			for(int size = 0;size<collocSizeLeft;size++)
      			{
      				if(!(misspeltWordsIndex.get(misspeltWordCount)-size<0))
      					collocatedString += phraseWords.get(misspeltWordsIndex.get(misspeltWordCount)-size)+" ";
      			}
      		collocatedString +=correction;
      		for(int size = 0;size<collocSizeRight;size++)
      		{
      			if(misspeltWordsIndex.get(misspeltWordCount)+size<phraseWords.size())
      				collocatedString += phraseWords.get(misspeltWordsIndex.get(misspeltWordCount)-size)+" ";
      		}
      		collocatedString = collocatedString.substring(0,collocatedString.length());
      		}
      		if(collocatedString.length()<6 && collocatedString.length()>1)
      		{
      			candidateScore += p.NgramsFull[collocatedString.length()-2].get(collocatedString);
      		}

      	}
      	candidateScores.put(correction, candidateScore);
      	candidateScore = 0.0;
      }
      	misspeltWordCount++;
      }

      */

      /* Context Based*/

      // System.out.println(words1.length);
      for (String misspeltword : misspeltWords) {
        float score = 0;
        //		System.out.println(words1.length);
        //	System.out.println("wordc =" + wordc1 + "words1.length/2 " + words1.length/2 +
        // "misspeltwordindex " +misspeltWordsIndex.get(wordc1) );
        int total = misspeltWordsIndex.get(wordc1) + words1.length / 2;
        //	System.out.println("Total = " + total );
        String correctWord = words1[misspeltWordsIndex.get(wordc1) + words1.length / 2];
        //	System.out.println("Correct Word " + correctWord);
        wordc1++;
        finalCorrections.clear();
        candidateScores.clear();
        w.getCandidates(misspeltword);
        corrections = w.candidates;
        //  System.out.println(corrections);
        // System.out.println("Over");
        /*   System.out.println(p.Ngrams[0].get("ground turmeric"));
        System.out.println(p.Ngrams[1].get("baby carriage"));
        System.out.println(p.Ngrams[2].get("moon earth"));
        System.out.println(p.Ngrams[3].get("perspective society"));*/
        for (String correction : corrections) {
          if (!stopWords.contains(correction)) {
            candidateScore = 0;
            candidateScores.put(correction, 0.0);
            for (String word : words) {
              if (!stopWords.contains(word)) {
                for (int i = 0; i < 4; i++) {
                  if (p.Ngrams[i].containsKey(correction + " " + word))
                    candidateScore += p.Ngrams[i].get(correction + " " + word);
                  else candidateScore += 0;
                }
              }
            }
            candidateScores.put(correction, candidateScore);
          }
        }
        LinkedHashMap<String, Double> map = w.sortByValues(candidateScores);
        //     System.out.println(map);
        ListIterator<String> iter = new ArrayList(map.keySet()).listIterator(map.size());
        while (iter.hasPrevious()) {
          String key = iter.previous();
          //  System.out.println(key);
          if (map.get(key) != 0.0) {
            finalCorrections.add(key);
          } else break;
          if (finalCorrections.size() == 3) break;
        }

        // Interpolation
        while (finalCorrections.size() < 3) {
          for (int q = 0; q < corrections.size(); q++) {
            if (!finalCorrections.contains(corrections.get(q))
                && !stopWords.contains(corrections.get(q)))
              finalCorrections.add(corrections.get(q));
            if (finalCorrections.size() == 3) break;
          }
        }
        System.out.println(System.currentTimeMillis() - t1);
        int wc1 = 0;
        for (String word : finalCorrections) {
          if (word.equals(correctWord)) score = 1 / (float) (wc1 + 1);
        }
        System.out.println(misspeltword + " " + finalCorrections + "Score = " + score);
      }
    }
  }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
Beispiel #30
0
  // ## operation writeChemkinReactions(ReactionModel)
  public static String writeChemkinPdepReactions(
      ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
    // #[ operation writeChemkinReactions(ReactionModel)

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

    String reactionHeader = "";

    String units4Ea = ArrheniusKinetics.getEaUnits();
    if (units4Ea.equals("cal/mol")) reactionHeader = "CAL/MOL\t";
    else if (units4Ea.equals("kcal/mol")) reactionHeader = "KCAL/MOL\t";
    else if (units4Ea.equals("J/mol")) reactionHeader = "JOULES/MOL\t";
    else if (units4Ea.equals("kJ/mol")) reactionHeader = "KJOULES/MOL\t";
    else if (units4Ea.equals("Kelvins")) reactionHeader = "KELVINS\t";

    String units4A = ArrheniusKinetics.getAUnits();
    if (units4A.equals("moles")) reactionHeader += "MOLES\n";
    else if (units4A.equals("molecules")) reactionHeader += "MOLECULES\n";

    result.append("REACTIONS\t" + reactionHeader);

    LinkedList pDepList = new LinkedList();
    LinkedList nonPDepList = new LinkedList();
    LinkedList duplicates = new LinkedList();

    CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionModel;
    // first get troe and thirdbodyreactions
    for (Iterator iter = cerm.getReactionSet().iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      /*
       * 1Jul2009-MRH:
       * 	Added extra set of parenthesis.  Before, if the rxn was reverse but an instance of
       * 		TROEReaction, it would also be added to the pDepList, resulting in RMG reporting
       * 		both rxns (forward and reverse) in the chem.inp file, w/o a DUP tag.  Furthermore,
       * 		both rxns were given the same set of Arrhenius parameters.  Running this in
       * 		Chemkin-v4.1.1 resulted in an error.
       */
      if (r.isForward()
          && (r instanceof ThirdBodyReaction
              || r instanceof TROEReaction
              || r instanceof LindemannReaction)) {
        pDepList.add(r);
      }
    }

    for (Iterator iter = PDepNetwork.getNetworks().iterator(); iter.hasNext(); ) {
      PDepNetwork pdn = (PDepNetwork) iter.next();
      for (ListIterator pdniter = pdn.getNetReactions().listIterator(); pdniter.hasNext(); ) {
        PDepReaction rxn = (PDepReaction) pdniter.next();
        if (cerm.categorizeReaction(rxn) != 1) continue;

        // check if this reaction is not already in the list and also check if this reaction has a
        // reverse reaction
        // which is already present in the list.
        if (rxn.getReverseReaction() == null) rxn.generateReverseReaction();

        if (!rxn.reactantEqualsProduct()
            && !pDepList.contains(rxn)
            && !pDepList.contains(rxn.getReverseReaction())) {
          pDepList.add(rxn);
        }
      }
    }
    LinkedList removeReactions = new LinkedList();
    for (Iterator iter = p_reactionModel.getReactionSet().iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();

      boolean presentInPDep = false;
      if (r.isForward()
          && !(r instanceof ThirdBodyReaction)
          && !(r instanceof TROEReaction)
          && !(r instanceof LindemannReaction)) {
        Iterator r_iter = pDepList.iterator();
        while (r_iter.hasNext()) {
          Reaction pDepr = (Reaction) r_iter.next();
          if (pDepr.equals(r)) {
            //      				removeReactions.add(pDepr);
            //      				duplicates.add(pDepr);
            //      				if (!r.hasAdditionalKinetics()){
            //      					duplicates.add(r);
            //      					presentInPDep = true;
            //      				}
            presentInPDep = true;
            nonPDepList.add(r);
          }
        }
        if (!presentInPDep) nonPDepList.add(r);
      }
    }

    for (Iterator iter = removeReactions.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      pDepList.remove(r);
    }

    for (Iterator iter = pDepList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      // 6Jul2009-MRH:
      //	Pass both system temperature and pressure to function toChemkinString.
      //		The only PDepKineticsModel that uses the passed pressure is RATE
      result.append(
          r.toChemkinString(p_beginStatus.getTemperature(), p_beginStatus.getPressure())
              + "\n"); // 10/26/07 gmagoon: eliminating use of Global.temperature; **** I use
                       // beginStatus here, which may or may not be appropriate
      // result.append(r.toChemkinString(Global.temperature)+"\n");
    }
    for (Iterator iter = nonPDepList.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(
          r.toChemkinString(p_beginStatus.getTemperature(), p_beginStatus.getPressure()) + "\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n");
    }
    for (Iterator iter = duplicates.iterator(); iter.hasNext(); ) {
      Reaction r = (Reaction) iter.next();
      result.append(
          r.toChemkinString(p_beginStatus.getTemperature(), p_beginStatus.getPressure())
              + "\n\tDUP\n");
      // result.append(r.toChemkinString(Global.temperature)+"\n\tDUP\n");
    }

    result.append("END\n");

    return result.toString();

    // #]
  }