Example #1
0
  private static LinkedList<Coords> polarSort(LinkedList<Coords> list) {
    // find point with lowest x-coord
    int i = 0;
    double lowest = 9999999999.0;
    int lowIndex = 0;
    Coords tmp;
    while (i < list.size()) {
      tmp = list.get(i);
      if (tmp.getX() < lowest) {
        lowest = tmp.getX();
        lowIndex = i;
      } else if (tmp.getX() == lowest) {
        if (tmp.getY() < list.get(lowIndex).getY()) {
          lowIndex = i;
        }
      }
      i++;
    }
    Coords lowestCoord = list.remove(lowIndex);

    LinkedList<Coords> sorted = new LinkedList<Coords>();
    sorted.add(list.poll());
    while (list.size() > 0) {
      tmp = list.poll();
      i = sorted.size();
      while (i > 0 && compVect(lowestCoord, sorted.get(i - 1), tmp) < 0.0) {
        i--;
      }
      sorted.add(i, tmp);
    }
    sorted.add(0, lowestCoord);
    return sorted;
  }
Example #2
0
  /** Initialise mod hooks */
  private void initHooks() {
    try {
      // Chat hook
      if ((chatListeners.size() > 0 || chatFilters.size() > 0) && !chatHooked) {
        chatHooked = true;
        HookChat.Register();
        HookChat.RegisterPacketHandler(this);
      }

      // Login hook
      if ((preLoginListeners.size() > 0 || loginListeners.size() > 0) && !loginHooked) {
        loginHooked = true;
        ModUtilities.registerPacketOverride(1, HookLogin.class);
        HookLogin.loader = this;
      }

      // Plugin channels hook
      if (pluginChannelListeners.size() > 0 && !pluginChannelHooked) {
        pluginChannelHooked = true;
        HookPluginChannels.Register();
        HookPluginChannels.RegisterPacketHandler(this);
      }

      // Tick hook
      if (!tickHooked) {
        tickHooked = true;
        PrivateFields.minecraftProfiler.SetFinal(minecraft, new HookProfiler(this, logger));
      }
    } catch (Exception ex) {
      logger.log(Level.WARNING, "Error creating hooks", ex);
      ex.printStackTrace();
    }
  }
Example #3
0
 protected void add(Object value) {
   File f = null;
   FileOutputStream fos = null;
   try {
     f = createTempFile("S", dir);
     fos = new FileOutputStream(f);
     ObjectOutputStream fout = new ObjectOutputStream(new BufferedOutputStream(fos));
     fout.writeObject(value);
     fout.flush();
     fos.getFD().sync();
   } catch (Exception e) {
     throw new SpaceError(e);
   } finally {
     if (fos != null) {
       try {
         fos.close();
       } catch (Exception e) {
         throw new SpaceError(e);
       }
     }
   }
   stored.add(f.getAbsolutePath());
   /* fill cache */
   if (cacheSize > data.size()) if ((data.size() + 1) == stored.size()) data.add(value);
 }
Example #4
0
  /**
   * Translates the link structure into the cell structure depending on healthy detector locations
   */
  public void createCellStructure() {

    int i = 0;

    while (i < mainlineLinks.size() - 1) {

      if (mainlineLinks.get(i).isHasDetector()
          & mainlineLinks.get(i).getDetectorML().getHealthStatus() == 100) {
        Cell c = new Cell((int) totalTimeInHours * 60 / 5);
        c.addLink(mainlineLinks.get(i));
        c.setDetectorML(mainlineLinks.get(i).getDetectorML());
        c.setDetectorHOV(mainlineLinks.get(i).getDetectorHOV());
        while (!mainlineLinks.get(i + 1).isHasDetector() & i < mainlineLinks.size() - 2
            | (mainlineLinks.get(i + 1).isHasDetector()
                & mainlineLinks.get(i + 1).getDetectorML().getHealthStatus() != 100)) {
          c.addLink(mainlineLinks.get(i + 1));
          i++;
        }
        // Onramps and Offramps in the Cell
        for (Link l : c.getLinks()) {

          c.addToOnrampPerLink(l.getUpNode().getInLinks().size() - 1);
          c.addToOfframpPerLink(l.getDownNode().getOutLinks().size() - 1);

          for (int linkID : l.getUpNode().getInLinks()) {
            if (links.get(linkID).getLinkType().equals("onramp")) {
              if (links.get(linkID).getDetectorML().getFlowData().isEmpty()
                  | links.get(linkID).getDetectorML().getHealthStatus() != 100) {
                c.addToImputeOR(true);
                c.appendZeroColumnToMeasuredOnrampFlow();
              } else {
                c.appendColumnToMeasuredOnrampFlow(
                    links.get(linkID).getDetectorML().getFlowDataArray());
                c.addToImputeOR(false);
              }
            }
          }
          for (int linkID : l.getDownNode().getOutLinks()) {
            if (links.get(linkID).getLinkType().equals("offramp")) {
              if (links.get(linkID).getDetectorML().getFlowData().isEmpty()
                  | links.get(linkID).getDetectorML().getHealthStatus() != 100) {
                c.addToImputeFR(true);
                c.appendZeroColumnToMeasuredOfframpFlow();
              } else {
                c.appendColumnToMeasuredOfframpFlow(
                    links.get(linkID).getDetectorML().getFlowDataArray());
                c.addToImputeFR(false);
              }
            }
          }
        }

        cells.add(c);
      }

      i++;
    }
    i = 0;
  }
Example #5
0
 protected Object getFirst() {
   Object object = null;
   if (data.size() > 0) {
     object = data.getFirst();
   } else if (stored.size() > 0) {
     object = readValue((String) stored.getFirst());
   }
   return object;
 }
Example #6
0
 /* process the list of pending constraints */
 protected void processWorklist() {
   int iter = 0;
   while (!w.isEmpty()) {
     int size = w.size();
     Constraint c = w.removeFirst();
     c.accept(this);
     size -= w.size();
     iter++;
   }
 }
Example #7
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;
      }
    }
  }
 @Override
 public synchronized void write(byte[] ba, int str, int len) {
   try {
     curLength += len;
     if (bytesEndWith(ba, str, len, LINE_SEP)) {
       lineLengths.addLast(new Integer(curLength));
       curLength = 0;
       if (lineLengths.size() > maxLines) {
         textArea.replaceRange(null, 0, lineLengths.removeFirst().intValue());
       }
     }
     for (int xa = 0; xa < 10; xa++) {
       try {
         textArea.append(new String(ba, str, len));
         break;
       } catch (
           Throwable
               thr) { // sometimes throws a java.lang.Error: Interrupted attempt to aquire write
                      // lock
         if (xa == 9) {
           thr.printStackTrace();
         }
       }
     }
     textArea.setCaretPosition(textArea.getText().length());
   } catch (Throwable thr) {
     CharArrayWriter caw = new CharArrayWriter();
     thr.printStackTrace(new PrintWriter(caw, true));
     textArea.append(System.getProperty("line.separator", "\n"));
     textArea.append(caw.toString());
   }
 }
Example #9
0
 public void updateStatus() {
   txaStatus.setText("");
   txaStatus.append("size\t" + store.getRowCount() + "\n");
   txaStatus.append("total\t" + store.sumLengths() + "KB\n");
   txaStatus.append("\nThreads:\n");
   for (int i = 0; i < numThreads; i++) {
     txaStatus.append(" " + i + "- ");
     String jb = encryptDecryptThreads[i].getCur();
     if (jb == null) txaStatus.append("idle\n");
     else {
       txaStatus.append(jobString(jb) + "\n");
     }
   }
   txaStatus.append("\nJobs:\n");
   int c = 6 + numThreads;
   int i = 0;
   synchronized (jobs) {
     for (String s : jobs) {
       if (c + i < TXA_HEIGHT - 1) txaStatus.append(" - " + jobString(s) + "\n");
       else if (c + i == TXA_HEIGHT - 1) {
         txaStatus.append(" - [" + (jobs.size() - i) + "more ]");
       }
       i++;
     }
   }
 }
Example #10
0
 public void solve() {
   n = ni();
   m = ni();
   map = new char[n][m];
   for (int i = 0; i < n; i++) {
     map[i] = nwrd().toCharArray();
   }
   boolean use[][] = new boolean[n][m];
   long ans = 0;
   LinkedList<Integer> ls = new LinkedList<Integer>();
   for (int i = 0; i < n; i++) {
     for (int j = 0; j < m; j++) {
       if (map[i][j] == '#') {
         ls.add(i * 10000 + j);
         while (ls.size() != 0) {
           int t = ls.pollFirst();
           int jx = t % 10000;
           int ix = t / 10000;
           use[ix][jx] = true;
           map[ix][jx] = '.';
           for (int k = 0; k < 4; k++) {
             if (is(ix + dx[k], jx + dy[k])
                 && !use[ix + dx[k]][jx + dy[k]]
                 && map[ix + dx[k]][jx + dy[k]] == '#') {
               ls.add((ix + dx[k]) * 10000 + jx + dy[k]);
               use[ix + dx[k]][jx + dy[k]] = true;
             }
           }
         }
         ans++;
       } else use[i][j] = true;
     }
   }
   pw.print(ans);
 }
Example #11
0
  private void writeTo(ObjectOutput o) throws IOException {
    o.writeInt(x);
    o.writeInt(y);
    o.writeInt(width);
    o.writeInt(height);
    o.writeInt(measuredWidth);
    o.writeInt(measuredHeight);
    o.writeInt(scrollX);
    o.writeInt(scrollY);
    o.writeInt(absoluteX);
    o.writeInt(absoluteY);
    o.writeFloat(cameraDistance);
    o.writeBoolean(visible);
    o.writeLong(drawingTime);
    o.writeBoolean(isShown);
    o.writeBoolean(hasFocus);
    o.writeBoolean(focusable);
    o.writeBoolean(hasOnClickListener);
    o.writeObject(viewType);
    o.writeObject(textContent);
    o.writeBoolean(isEditText);
    o.writeBoolean(isInputMethodTarget);
    o.writeBoolean(isContainer);
    o.writeInt(inputMethod);
    o.writeInt(id);

    if (children != null) {
      o.writeInt(children.size());
      for (ViewComponentInfo child : children) {
        child.writeTo(o);
      }
    } else {
      o.writeInt(0);
    }
  }
Example #12
0
  private static LinkedList<Coords> graham(LinkedList<Coords> list) {
    LinkedList<Coords> stack = new LinkedList<Coords>();
    Coords next;
    stack.push(list.get(0));
    stack.push(list.get(1));
    int i = 2;
    int n = list.size();
    double debug;
    while (i < n) {
      System.out.println("Stack: ");
      printCoords(stack);
      System.out.println("Now comparing: ");
      System.out.print("P0: ");
      printCoord(stack.get(1));
      System.out.print(" - ");
      System.out.print("P1: ");
      printCoord(stack.get(0));
      System.out.print(" - ");
      System.out.print("P2: ");
      printCoord(list.get(i));
      System.out.println();
      if ((debug = compVect(stack.get(1), stack.get(0), list.get(i))) >= 0.0) {
        System.out.println("P2 is left of P0->P1: putting P2 on stack...");
        stack.push(list.get(i));
        i++;
      } else {
        System.out.println("P2 is right of P0->P1: removing P1 from stack...");
        stack.pop();
      }
    }

    return stack;
  }
Example #13
0
 public static String normalizePath(String path) {
   if (!path.contains("./")) {
     return path;
   }
   boolean absolute = path.startsWith("/");
   String[] elements = path.split(Repository.SEPARATOR);
   LinkedList<String> list = new LinkedList<String>();
   for (String e : elements) {
     if ("..".equals(e)) {
       if (list.isEmpty() || "..".equals(list.getLast())) {
         list.add(e);
       } else {
         list.removeLast();
       }
     } else if (!".".equals(e) && e.length() > 0) {
       list.add(e);
     }
   }
   StringBuilder sb = new StringBuilder(path.length());
   if (absolute) {
     sb.append("/");
   }
   int count = 0, last = list.size() - 1;
   for (String e : list) {
     sb.append(e);
     if (count++ < last) sb.append("/");
   }
   return sb.toString();
 }
Example #14
0
 protected Data(Object name) {
   super();
   data = new LinkedList();
   stored = new LinkedList();
   listeners = null;
   String n = "space" + File.separatorChar;
   if (name instanceof String) n += name;
   else n += "H" + Integer.toString(name.hashCode());
   dir = new File(n);
   dir.mkdirs();
   FilenameFilter filter =
       new FilenameFilter() {
         public boolean accept(File f, String name) {
           return name.toUpperCase().startsWith("S");
         }
       };
   File file[] = dir.listFiles(filter);
   Arrays.sort(file);
   for (int i = 0; file.length > i; i++) {
     if (cacheSize > data.size()) {
       Object value = readValue(file[i].getAbsolutePath());
       if (value == null) {
         (new File(file[i].getAbsolutePath())).delete();
       } else {
         stored.add(file[i].getAbsolutePath());
         data.add(value);
       }
     } else stored.add(file[i].getAbsolutePath());
   }
 }
 public double getAvgNeighbourScore(Region region, BotState state) {
   LinkedList<Region> neighbours = region.getNeighbors();
   double sum = 0;
   for (Region neighbour : neighbours) {
     if (neighbour.ownedByPlayer(state.getMyPlayerName())) sum += 0.5;
     else if (neighbour.ownedByPlayer(state.getOpponentPlayerName())) sum += 1;
     else sum += 0.1;
   }
   return sum / neighbours.size();
 }
Example #16
0
  int[] findEmptySiteCancer(int x, int y) {
    LinkedList vacantSitesCancer = new LinkedList();
    int[] tp1 = new int[2];
    int[] tp2 = new int[2];
    int[] tp3 = new int[2];
    int[] tp4 = new int[2];
    int[] tp5 = new int[2];
    int[] tp6 = new int[2];
    int[] tp7 = new int[2];
    int[] tp8 = new int[2];

    tp1 = convertCoordinatesNoFlux(x + 1, y - 1);
    if ((Cells[tp1[0]][tp1[1]] == 0) || (Cells[tp1[0]][tp1[1]] == 4)) vacantSitesCancer.add(tp1);
    tp2 = convertCoordinatesNoFlux(x + 1, y);
    if ((Cells[tp2[0]][tp2[1]] == 0) || (Cells[tp2[0]][tp2[1]] == 4)) vacantSitesCancer.add(tp2);
    tp3 = convertCoordinatesNoFlux(x + 1, y + 1);
    if ((Cells[tp3[0]][tp3[1]] == 0) || (Cells[tp3[0]][tp3[1]] == 4)) vacantSitesCancer.add(tp3);
    tp4 = convertCoordinatesNoFlux(x, y - 1);
    if ((Cells[tp4[0]][tp4[1]] == 0) || (Cells[tp4[0]][tp4[1]] == 4)) vacantSitesCancer.add(tp4);
    tp5 = convertCoordinatesNoFlux(x, y + 1);
    if ((Cells[tp5[0]][tp5[1]] == 0) || (Cells[tp5[0]][tp5[1]] == 4)) vacantSitesCancer.add(tp5);
    tp6 = convertCoordinatesNoFlux(x - 1, y - 1);
    if ((Cells[tp6[0]][tp6[1]] == 0) || (Cells[tp6[0]][tp6[1]] == 4)) vacantSitesCancer.add(tp6);
    tp7 = convertCoordinatesNoFlux(x - 1, y);
    if ((Cells[tp7[0]][tp7[1]] == 0) || (Cells[tp7[0]][tp7[1]] == 4)) vacantSitesCancer.add(tp7);
    tp8 = convertCoordinatesNoFlux(x - 1, y + 1);
    if ((Cells[tp8[0]][tp8[1]] == 0) || (Cells[tp8[0]][tp8[1]] == 4)) vacantSitesCancer.add(tp8);

    // Now let's see where.
    if (vacantSitesCancer.size()
        > 0) { // Now choose a vacant one, otherwise return the original location
      // pick a vacant site and return it
      int vacantElemIndexCancer = random.nextInt(vacantSitesCancer.size());
      int[] p = (int[]) vacantSitesCancer.get(vacantElemIndexCancer);
      return (int[]) p;
    } else {
      int[] p = new int[2];
      p[0] = x;
      p[1] = y; // Just return the original
      System.out.println("wrong!:" + vacantSitesCancer(x, y) + " - " + vacantSitesCancer.size());
      return p;
    }
  }
Example #17
0
 private static void printCoords(LinkedList<Coords> list) {
   int i = 0;
   Coords tmp;
   System.out.println("--------");
   while (i < list.size()) {
     tmp = list.get(i);
     System.out.println("(" + tmp.getX() + "," + tmp.getY() + ")");
     i++;
   }
   System.out.println("--------");
 }
Example #18
0
 /**
  * Returns an array of all action names in this action set that should be cached; namely, <code>
  * BeanShellAction</code>s.
  *
  * @since jEdit 4.2pre1
  */
 public String[] getCacheableActionNames() {
   LinkedList<String> retVal = new LinkedList<String>();
   for (Object obj : actions.values()) {
     if (obj == placeholder) {
       // ??? this should only be called with
       // fully loaded action set
       Log.log(Log.WARNING, this, "Action set not up " + "to date");
     } else if (obj instanceof JEditBeanShellAction)
       retVal.add(((JEditBeanShellAction) obj).getName());
   }
   return retVal.toArray(new String[retVal.size()]);
 } // }}}
Example #19
0
  /**
   * Find mod classes in the class path and enumerated mod files list
   *
   * @param classPathEntries Java class path split into string entries
   * @return map of classes to load
   */
  private HashMap<String, Class> findModClasses(
      String[] classPathEntries, LinkedList<File> modFiles) {
    // To try to avoid loading the same mod multiple times if it appears in more than one entry in
    // the class path, we index
    // the mods by name and hopefully match only a single instance of a particular mod
    HashMap<String, Class> modsToLoad = new HashMap<String, Class>();

    try {
      logger.info("Searching protection domain code source...");

      File packagePath =
          new File(LiteLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI());
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    } catch (Throwable th) {
      logger.warning("Error loading from local class path: " + th.getMessage());
    }

    // Search through the class path and find mod classes
    for (String classPathPart : classPathEntries) {
      logger.info(String.format("Searching %s...", classPathPart));

      File packagePath = new File(classPathPart);
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    // Search through mod files and find mod classes
    for (File modFile : modFiles) {
      logger.info(String.format("Searching %s...", modFile.getAbsolutePath()));

      LinkedList<Class> modClasses =
          getSubclassesFor(modFile, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    return modsToLoad;
  }
 protected boolean isConfigured() {
   boolean isConfigured = true;
   // check if there are input files and if they exist.
   if (inputFiles.size() > 0) {
     for (Iterator<File> iterator = inputFiles.iterator(); iterator.hasNext(); ) {
       File next = iterator.next();
       if (!next.exists()) {
         isConfigured = false;
         System.err.println("Input file " + next.getPath() + " does not exist.");
       }
     }
   }
   return isConfigured;
 }
Example #21
0
 public void run() {
   try {
     for (; ; ) {
       Target t = null;
       synchronized (pending) {
         while (pending.size() == 0) pending.wait();
         t = (Target) pending.removeFirst();
       }
       t.show();
     }
   } catch (InterruptedException x) {
     return;
   }
 }
 public void printFinishedTargets() {
   // 打印finisedTargets队列中的任务
   try {
     for (; ; ) {
       Target target = null;
       synchronized (finishedTargets) {
         while (finishedTargets.size() == 0) finishedTargets.wait();
         target = (Target) finishedTargets.removeFirst();
       }
       target.show();
     }
   } catch (InterruptedException x) {
     return;
   }
 }
Example #23
0
  public static synchronized Connection getConnection() {
    clearClosedConnection();
    while (m_notUsedConnection.size() > 0) {
      try {
        ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst();
        if (wrapper.connection.isClosed()) {
          continue;
        }
        m_usedUsedConnection.add(wrapper);
        if (DEBUG) {
          wrapper.debugInfo = new Throwable("Connection initial statement");
        }
        return wrapper.connection;
      } catch (Exception e) {
      }
    }
    int newCount = getIncreasingConnectionCount();
    LinkedList list = new LinkedList();
    ConnectionWrapper wrapper = null;
    for (int i = 0; i < newCount; i++) {
      wrapper = getNewConnection();
      if (wrapper != null) {
        list.add(wrapper);
      }
    }
    if (list.size() == 0) {
      return null;
    }
    wrapper = (ConnectionWrapper) list.removeFirst();
    m_usedUsedConnection.add(wrapper);

    m_notUsedConnection.addAll(list);
    list.clear();

    return wrapper.connection;
  }
 public int bfs() {
   int[] record = new int[n];
   Arrays.fill(record, Integer.MAX_VALUE);
   LinkedList<Integer> queue = new LinkedList<Integer>();
   queue.addLast(0);
   int distance = 0;
   int count = 1;
   while (queue.size() > 0) {
     int newCount = 0;
     while (count > 0) {
       int tempPoint = queue.pollFirst();
       ArrayList<Road> tempRoads = roads[tempPoint];
     }
     distance++;
   }
 }
Example #25
0
    @Override
    public void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {
      Hashtable<String, Integer> wordCounts = new Hashtable<String, Integer>();
      ArrayList docName = new ArrayList<String>();
      LinkedList wordName = new LinkedList<String>();
      while (values.iterator().hasNext()) {
        String[] items = values.iterator().next().toString().split("@");
        if (!wordName.contains(items[0])) {
          wordName.add(items[0]);
        }
        String[] keys = items[1].split(":|,");
        for (int i = 0; i < keys.length; i += 2) {
          if (!docName.contains(keys[i])) {
            docName.add(keys[i]);
            wordCounts.put(keys[i], 0);
          }
          int tmp = wordCounts.get(keys[i]);
          tmp += Integer.parseInt(keys[i + 1]);
          wordCounts.put(keys[i], tmp);
        }
      }

      for (int i = 0; i < docName.size() - 1; ++i) {
        for (int j = i + 1; j < docName.size(); ++j) {
          if (wordCounts.get(docName.get(i)) < wordCounts.get(docName.get(j))) {
            String stmp = docName.get(i).toString();
            docName.set(i, docName.get(j).toString());
            docName.set(j, stmp);
          }
        }
      }

      String retKey = wordName.get(0).toString();
      for (int i = 1; i < wordName.size(); ++i) {
        retKey += "," + wordName.get(i);
      }

      String retValue =
          ""; // ="\n" + docName.get(0).toString() + ":" +
              // wordCounts.get(docName.get(0).toString());
      for (int i = 0; i < docName.size(); ++i) {
        retValue +=
            "\n" + docName.get(i).toString() + ": " + wordCounts.get(docName.get(i).toString());
      }
      context.write(new Text(retKey), new Text(retValue));
    }
Example #26
0
    void processPendingTargets() throws IOException {
      synchronized (pending) {
        while (pending.size() > 0) {
          Target t = (Target) pending.removeFirst();
          try {

            t.channel.register(sel, SelectionKey.OP_CONNECT, t);

          } catch (IOException x) {

            t.channel.close();
            t.failure = x;
            printer.add(t);
          }
        }
      }
    }
  private void initialize() {
    Set<Employee> Lset = pp.getEmployees(0);
    Set<Employee> Rset = pp.getEmployees(1);

    // FIXME!!!
    // flow = new HashMap<Vertex, Map<Vertex, Integer>>(2 * (Lset.size() + Rset.size()));
    // capacity = new HashMap<Vertex, Map<Vertex, Integer>>(2 * (Lset.size() + Rset.size()));
    flow = new TreeMap<Vertex, Map<Vertex, Integer>>();
    capacity = new TreeMap<Vertex, Map<Vertex, Integer>>();

    setupSourceSide(Lset);
    setupSinkSide(Rset);

    setupLRNeighbors();
    biasForFriend();

    source.setHeight(V.size() + 2);
  }
Example #28
0
  private static void clearClosedConnection() {
    long time = System.currentTimeMillis();
    // sometimes user change system time,just return
    if (time < m_lastClearClosedConnection) {
      m_lastClearClosedConnection = time;
      return;
    }
    // no need check very often
    if (time - m_lastClearClosedConnection < CHECK_CLOSED_CONNECTION_TIME) {
      return;
    }
    m_lastClearClosedConnection = time;

    // begin check
    Iterator iterator = m_notUsedConnection.iterator();
    while (iterator.hasNext()) {
      ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
      try {
        if (wrapper.connection.isClosed()) {
          iterator.remove();
        }
      } catch (Exception e) {
        iterator.remove();
        if (DEBUG) {
          System.out.println("connection is closed, this connection initial StackTrace");
          wrapper.debugInfo.printStackTrace();
        }
      }
    }

    // make connection pool size smaller if too big
    int decrease = getDecreasingConnectionCount();
    if (m_notUsedConnection.size() < decrease) {
      return;
    }

    while (decrease-- > 0) {
      ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst();
      try {
        wrapper.connection.close();
      } catch (Exception e) {
      }
    }
  }
Example #29
0
  public void outAMultiNewExpr(AMultiNewExpr node) {

    LinkedList arrayDesc = node.getArrayDescriptor();

    int descCnt = arrayDesc.size();
    List sizes = new LinkedList();

    Iterator it = arrayDesc.iterator();
    while (it.hasNext()) {
      AArrayDescriptor o = (AArrayDescriptor) it.next();
      if (o.getImmediate() != null) sizes.add(0, (Value) mProductions.removeLast());
      else break;
    }

    Type type = (Type) mProductions.removeLast();
    ArrayType arrayType = ArrayType.v(type, descCnt);

    mProductions.addLast(Jimple.v().newNewMultiArrayExpr(arrayType, sizes));
  }
  public static int[] bfs(int s, int e, int[][] f) {
    int[] prev = new int[f.length];
    Arrays.fill(prev, -1);
    LinkedList<Integer> q = new LinkedList<Integer>();
    q.add(s);

    while (q.size() > 0) {
      int at = q.poll();
      for (int i = 0; i < f.length; i++) {
        if (prev[i] != -1 || i == at) continue;
        if (f[at][i] > 0) {
          prev[i] = at;
          if (i == e) return prev;
          q.addLast(i);
        }
      }
    }
    return null;
  }