Exemplo n.º 1
0
 /** Show the last element in the list of adapters */
 private void showList() {
   if (mAdapters.isEmpty() || mAdapters.getLast().isEmpty()) {
     mList.setEmptyView(mEmptyLibrary);
   } else {
     LibraryAdapter adapter = mAdapters.getLast();
     adapter.getFilter().filter(mLastFilter);
     mList.setAdapter(adapter);
     if (adapter.isEmpty() || adapter.getCount() == 0) {
       buildSubActionBar("", "");
     } else {
       MyLibraryItem item = adapter.getItem(0);
       switch (item.getLevel()) {
         case MyLibrary.LVL_ARTIST:
           buildSubActionBar("", "");
           break;
         case MyLibrary.LVL_ALBUM:
           buildSubActionBar(item.getArtist(), "");
           break;
         default:
           buildSubActionBar(item.getArtist(), item.getAlbum());
           break;
       }
     }
   }
 }
Exemplo n.º 2
0
 @Override
 public String toString() {
   String str = "=================================================\n";
   str += "Freecells: ";
   for (LinkedList<Card> freecell : freecells) {
     if (freecell.isEmpty()) str += " ";
     else str += freecell.getLast().toString() + " ";
   }
   str += "\t\tFoundations: ";
   for (LinkedList<Card> foundation : foundations) {
     if (foundation.isEmpty()) str += " ";
     else str += foundation.getLast().toString() + "(" + foundation.size() + ") ";
   }
   str += "\n\n";
   for (LinkedList<Card> cascade : cascades) {
     if (cascade.isEmpty()) str += "\n";
     else {
       for (Card c : cascade) {
         str += c.toString() + " ";
       }
       str += "\n";
     }
   }
   str += "\nF: " + f + "\tG: " + g + "\tH: " + h + "\n";
   str += "=================================================\n";
   return str;
 }
Exemplo n.º 3
0
  private void readGraph() throws IOException {
    InputStream is = ProgrammingSet4.class.getResourceAsStream("SCC.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    graph = new HashMap<Integer, List<Integer>>();
    rGraph = new HashMap<Integer, List<Integer>>();

    String l = null;
    while ((l = reader.readLine()) != null) {
      LinkedList<Integer> line = readEdge(l);

      List<Integer> edges = graph.get(line.getFirst());
      if (edges == null) {
        edges = new ArrayList<Integer>();
        graph.put(line.getFirst(), edges);
      }
      edges.add(line.getLast());

      List<Integer> rEdges = rGraph.get(line.getLast());
      if (rEdges == null) {
        rEdges = new ArrayList<Integer>();
        rGraph.put(line.getLast(), rEdges);
      }
      rEdges.add(line.getFirst());
    }

    reader.close();
  }
Exemplo n.º 4
0
    private void endCondition(String name) throws SAXException {
      Condition cond = conditionStack.removeLast();
      if (cond.isEmpty()) throw new SAXException('<' + name + "> must not be empty");

      if (!values.isEmpty()) {
        try {
          MemberOf memberOf = (MemberOf) cond;
          if (memberOf.vr.isIntType()) memberOf.setValues(parseInts(values));
          else memberOf.setValues(values.toArray(new String[values.size()]));
        } catch (Exception e) {
          throw new SAXException("unexpected <Value> contained by <" + name + ">");
        }
        values.clear();
      }

      if (!codes.isEmpty()) {
        try {
          ((MemberOf) cond).setValues(codes.toArray(new Code[codes.size()]));
        } catch (Exception e) {
          throw new SAXException("unexpected <Code> contained by <" + name + ">");
        }
        codes.clear();
      }

      if (conditionStack.isEmpty()) {
        if (elementConditions) getLastDataElement().setCondition(cond.trim());
        else iodStack.getLast().setCondition(cond.trim());
        elementConditions = false;
        itemConditions = false;
      } else conditionStack.getLast().addChild(cond.trim());
    }
Exemplo n.º 5
0
 @Override
 public Object handle() throws GAIInterpreterException {
   String condition = getFirstMatch(getCommand(), RH.VAL_OR_EXP);
   String action = getActionName(getCommand().replace(condition, ""));
   LinkedList<GAIObject> actionChain = getSession().getObjectOrAttribute(action);
   if (isPathValid(action)) {
     throw new GAIInterpreterException(wrongPath(actionChain));
   }
   Object result;
   AbstractHandler handler;
   if (hasMatch(condition, RH.ANY_VAL)) {
     result = getValue(condition);
   } else if (hasMatch(condition, RH.NUMERIC_EXP)) {
     handler = new NumericExpHandler(condition, getInterpreter());
     result = handler.handle();
   } else if (hasMatch(condition, RH.ACT_EXE)) {
     handler = new ActionExecHandler(condition, getInterpreter());
     result = handler.handle();
   } else {
     throw new GAIInterpreterException(INVALID_FOR_CONDITION);
   }
   if (result == null) {
     throw new GAIInterpreterException(INVALID_FOR_CONDITION);
   }
   if (isArray(result)) {
     GAIObject arrayObject = (GAIObject) result;
     for (Object e : arrayObject.getElements()) {
       executeAction(actionChain.getLast(), e);
     }
   } else {
     executeAction(actionChain.getLast(), result);
   }
   return null;
 }
Exemplo n.º 6
0
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case MessageId.UPDATE_CLIENT_ID_FAIL:
              {
                BaseUtil.innerComm.webappclient.updateClientId(
                    BaseUtil.getSelfUserInfo().getUserId(), clientId);
                break;
              }
            case MessageId.APK_DOWN_LOAD_DONE:
              {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(
                    Uri.fromFile(
                        new File(
                            FileUtil.APK_PATH + BaseUtil.getSystemInfo().getLatestClientName())),
                    "application/vnd.android.package-archive");
                InnerCommAdapter.ct.startActivity(intent);
                break;
              }

            default:
              {
                if (!innerCommQue.isEmpty()) {
                  Log.i(
                      "InnerCommAdapter",
                      "baseutil send msg:" + msg.what + "to->" + innerCommQue.getLast());
                  innerCommQue.getLast().processMessage(msg);
                } else {
                  Log.e("BaseUtil", "UI activity innerCommQue is empty,drop msgid:!!" + msg.what);
                }
                break;
              }
          }
        }
  public MemorySet(
      int numberOfLevels,
      int[] assocs,
      int[] cacheszs,
      int[] blockszs,
      int[] latencies,
      int policy,
      int mainMemoryLatency,
      HashMap<Integer, int[]> initialMemory) {
    if (policy == 0) {
      writeThrough = true;
    } else {
      writeThrough = false;
    }
    cycles = 0;
    mainMemory = new MainMemory(initialMemory, mainMemoryLatency);
    caches = new LinkedList<Cache>();
    // int x, y, z, cyc;

    for (int i = 0; i < numberOfLevels; i++) {
      caches.add(new Cache(assocs[i], cacheszs[i], blockszs[i], latencies[i]));
      if (i > 0) {
        caches.get(i - 1).setHigherLevel(caches.getLast());
      }
    }
    caches.getLast().setMainMemory(mainMemory);
    firstCache = caches.getFirst();
  }
Exemplo n.º 8
0
  public static void postOrderNoIn(TreeNode root) {

    if (root == null) return;
    LinkedList<TreeNode> stack = new LinkedList<>();
    LinkedList<Boolean> flag = new LinkedList<>();

    boolean curFlag;
    while (!stack.isEmpty() || root != null) {
      while (root != null) {
        stack.addLast(root);
        flag.addLast(true);
        root = root.left;
      }
      root = stack.getLast();
      curFlag = flag.getLast();
      flag.removeLast();
      if (curFlag) { //
        flag.addLast(false);
        root = root.right;
      } else {
        stack.removeLast();
        System.out.print(root.val + " ");
        root = null; // 第一次的时候缺少这一句,陷入死循环。
      }
    }
  }
 public void addState(World x) {
   double growthRate = calGrowthRate(x), deathRate = calDeathRate(x);
   int population = x.getPopulation();
   listPopulationChange.add(generation == 0 ? population : population - listPopulation.getLast());
   listPopulation.add(population);
   listGrowthRate.add(growthRate);
   listDeathRate.add(deathRate);
   if (generation == 1) {
     minPopulation = maxPopulation = population;
     maxGrowthRate = minGrowthRate = growthRate;
     maxDeathRate = deathRate;
     maxPopulationChange = minPopulationChange = listPopulationChange.getLast();
   }
   if (generation > 1) {
     minPopulation = minPopulation > population ? population : minPopulation;
     maxPopulation = maxPopulation < population ? population : maxPopulation;
     maxGrowthRate = maxGrowthRate < growthRate ? growthRate : maxGrowthRate;
     maxDeathRate = maxDeathRate < deathRate ? deathRate : maxDeathRate;
     maxPopulationChange = Math.max(maxPopulationChange, listPopulationChange.getLast());
     minPopulationChange = Math.min(minPopulationChange, listPopulationChange.getLast());
     maxGrowthRate = Math.max(maxGrowthRate, listGrowthRate.getLast());
     minGrowthRate = Math.min(minGrowthRate, listGrowthRate.getLast());
   }
   generation++;
   listCells.add(x);
 }
Exemplo n.º 10
0
  /**
   * Removes the least recently used elements if the cache size is greater than or equal to the
   * maximum allowed size until the cache is at least 10% empty.
   */
  protected synchronized void cullCache() {
    // Check if a max cache size is defined.
    if (maxCacheSize < 0) {
      return;
    }

    // See if the cache is too big. If so, clean out cache until it's 10% free.
    if (map.size() > maxCacheSize) {
      // First, delete any old entries to see how much memory that frees.
      deleteExpiredEntries();
      // Next, delete the least recently used elements until 10% of the cache
      // has been freed.
      int desiredSize = (int) (maxCacheSize * .90);
      for (int i = map.size(); i > desiredSize; i--) {
        // Get the key and invoke the remove method on it.
        if (remove(lastAccessedList.getLast().object, true) == null) {
          LOGGER.warning(
              "Error attempting to cullCache with remove("
                  + lastAccessedList.getLast().object.toString()
                  + ") - cacheObject not found in cache!");
          lastAccessedList.getLast().remove();
        }
      }
    }
  }
Exemplo n.º 11
0
  /* (non-Javadoc)
   * @see org.apache.batik.parser.PathHandler#linetoVerticalRel(float)
   */
  public void linetoVerticalRel(float y) throws ParseException {
    if (verbose) System.out.println("linetoVerticalRel: " + y);

    Vertex vert = new Vertex(pathPoints.getLast().getX(), pathPoints.getLast().getY() + y, 0);
    pathPoints.add(vert);
    currentSubPath.add(vert);
  }
Exemplo n.º 12
0
  private void sendBatchNonTransacted() {
    try {
      if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE) {
        // We client ack before sending

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Client acking source session");
        }

        messages.getLast().acknowledge();

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Client acked source session");
        }
      }

      sendMessages();

      if (maxBatchSize > 1) {
        // The sending session is transacted - we need to commit it

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Committing target session");
        }

        targetSession.commit();

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Committed source session");
        }
      }

      if (qualityOfServiceMode == QualityOfServiceMode.DUPLICATES_OK) {
        // We client ack after sending

        // Note we could actually use Session.DUPS_OK_ACKNOWLEDGE here
        // For a slightly less strong delivery guarantee

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Client acking source session");
        }

        messages.getLast().acknowledge();

        if (JMSBridgeImpl.trace) {
          HornetQJMSServerLogger.LOGGER.trace("Client acked source session");
        }
      }

      // Clear the messages
      messages.clear();
    } catch (Exception e) {
      HornetQJMSServerLogger.LOGGER.bridgeAckError(e);

      handleFailureOnSend();
    }
  }
Exemplo n.º 13
0
  private ArrayList<String> helper(WifiMapData unknown) {
    Vd2_3MapData unknownStat = new Vd2_3MapData(unknown);
    // debug("here stat");
    // debug(unknownStat, unknownStat.fullScan.size());
    LinkedList<LocationEvaluation> possible = new LinkedList<LocationEvaluation>();
    ArrayList<String> possibleLocations = new ArrayList<String>();

    for (String locationID : cache.keySet()) {
      LocationEvaluation eval = new LocationEvaluation(locationID);
      possible.add(eval);
    }

    if (possible.isEmpty()) {
      System.out.println("+++++++++++++++++++++++++++++++++");
      return possibleLocations;
    }

    {
      // Remove the ones that has too little low-var Aps
      for (LocationEvaluation eval : possible) {
        eval.score = nHavingLowVariance(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      // debug(possible);

      double min = possible.getFirst().score - maxAbsenceAP;
      while (!possible.isEmpty() && possible.getLast().score < min) possible.removeLast();
    }

    {
      // Remove the ones that miss too much Low-var APs
      for (LocationEvaluation eval : possible) {
        eval.score = nMissingLowVariance(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      // debug(possible);
      double min = possible.getFirst().score - maxAbsenceAP;
      while (!possible.isEmpty() && possible.getLast().score < min) possible.removeLast();
    }

    {
      // Sort the average this distance
      for (LocationEvaluation eval : possible) {
        eval.score = differenceAverage(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      while (!possible.isEmpty() && possible.getLast().score < VERY_NEGATIVE) {
        possible.removeLast();
      }
    }

    for (int i = 0; i < possible.size(); ++i) {
      possibleLocations.add(possible.get(i).name);
    }

    return possibleLocations;
  }
Exemplo n.º 14
0
 /**
  * flashback! Throws an unsupported operation exception
  *
  * @param location where to flash back to
  */
 public void flashBackTo(GenomeLoc location) {
   if (!canFlashBackTo(location))
     throw new UnsupportedOperationException("we can't flash back to " + location);
   if (pastQueue.size() == 0) return; // the iterator can do it alone
   while (pastQueue.size() > 0 && !pastQueue.getLast().getLocation().isBefore(location)) {
     aheadQueue.addFirst(pastQueue.getLast());
     pastQueue.removeLast();
   }
 }
Exemplo n.º 15
0
 public int theNthNum(int n) {
   Integer[] a = {1, 2, 3, 4, 5};
   if (n <= 5) return a[n - 1];
   LinkedList<Integer> arrayIntegers = new LinkedList<Integer>();
   for (int aa : a) arrayIntegers.add(aa);
   for (int i = 6; i <= n; i++) {
     int x = getNext(arrayIntegers.getLast(), arrayIntegers);
     arrayIntegers.add(x);
   }
   return arrayIntegers.getLast();
 }
Exemplo n.º 16
0
 private void updateEtaAndSpeed() {
   long now = dates.getFirst();
   long past = dates.getLast();
   long loadedKbNow = loaded.getFirst();
   long loadedKbPast = loaded.getLast();
   long kiloBytesRemaining = max - loadedKbNow;
   // speed kb/
   speedKbPerSecond = (float) ((double) (loadedKbNow - loadedKbPast)) / ((now - past) / 1000);
   timeleft = (long) (kiloBytesRemaining / speedKbPerSecond);
   eta.setTime(now + timeleft * 1000);
 }
Exemplo n.º 17
0
  /** Starts adding points to the mouseEvents list every 2 milliseconds */
  private void collect() {
    int same = 0; // The number of times that the mouse has been in same position.
    pause = false; // whether or not the mouse is currently idle
    while (record) {
      if (!pause) {
        // If the mouse is not currently idle, A new point is added to the "mouseEvents" List. point
        // has x and y coordinates
        mouseEvents.add(
            new SimpleMouseEvent(
                MouseInfo.getPointerInfo().getLocation().x,
                MouseInfo.getPointerInfo().getLocation().y,
                0));
      }
      // If the mouse is currently set as idle, but mouvement has been detected: that is, if the
      // current position is different than
      // where the mouse is when it was set as idle...
      if (pause
          && ((MouseInfo.getPointerInfo().getLocation().x) != mouseEvents.getLast().gx()
              || MouseInfo.getPointerInfo().getLocation().y != mouseEvents.getLast().gy())) {
        unpause();
      }

      // Detects if the current position of the mouse is the same as the last time it was checked.
      if (mouseEvents.size() > 5
          && (mouseEvents
              .getLast()
              .toString()
              .equals(mouseEvents.get(mouseEvents.size() - 2).toString()))) {
        // If position is the same, the "same" count is increased.
        same++;
        // Once the mouse has been in the same place for 10 cycles, it is said to be idle.
        if (same == 10) {
          pause = true;
          // The stopwatch will count how long the mouse has been idle for
          stopWatch.start();
          System.out.println("Pause");
        }
      } else {
        // If the mouse has moved since last cycle, then the number of times it has been in the same
        // position is set to 0.
        same = 0;
      }
      try {
        Thread.sleep(2); // Delay between cycles.
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }
      if (!record) {
        gui.log("Recording Stopped.");
        gui.refreshActionList();
      }
    }
  }
Exemplo n.º 18
0
 public Register getDestinationRegister() {
   /*
         for(int i = fields.size() - 1; i >= 0; i--) {
            if(fields.get(i) instanceof Register) {
               return (Register)fields.get(i);
            }
         }
   */
   if (fields.size() > 0 && fields.getLast() instanceof Register)
     return (Register) fields.getLast();
   return null;
 }
Exemplo n.º 19
0
  public void removeFromStacks(UndoableGroup group) {
    if (group.getAffectedDocuments().isEmpty()) return;

    if (group.isGlobal()) {
      assert myGlobalStack.getLast() == group;
      myGlobalStack.removeLast();
    }
    for (DocumentReference each : group.getAffectedDocuments()) {
      LinkedList<UndoableGroup> stack = getStack(each);
      assert stack.getLast() == group;
      stack.removeLast();
    }
  }
Exemplo n.º 20
0
  /* (non-Javadoc)
   * @see org.apache.batik.parser.PathHandler#curvetoQuadraticSmoothRel(float, float)
   */
  public void curvetoQuadraticSmoothRel(float x, float y) throws ParseException {
    if (verbose) System.out.println("curvetoQuadraticSmoothRel: " + x + "," + y);

    Vertex lastPoint = pathPoints.getLast();
    if (lastPoint instanceof BezierVertex
        && cubicBezVertTOQuadricControlPoint.get(lastPoint) != null) {
      Vertex lastEndPoint =
          new Vertex(
              pathPoints.getLast().getX(),
              pathPoints.getLast().getY(),
              pathPoints.getLast().getZ());

      // Get control point of last QuadTo
      Vertex lastQuadControlPoint = cubicBezVertTOQuadricControlPoint.get(lastPoint);
      cubicBezVertTOQuadricControlPoint.remove(lastPoint);

      // Rotate that controlpoint around the end point of the last QuadTo
      lastQuadControlPoint.rotateZ(lastEndPoint, 180);

      // Put in startPoint = last QuadTo Endpoint of this smoothQuadTo, the calculated control
      // point, and the endpoint of smoothQuadTo
      BezierVertex b5 =
          Tools3D.getCubicFromQuadraticCurve(
              lastEndPoint,
              lastQuadControlPoint,
              new Vertex(lastPoint.getX() + x, lastPoint.getY() + y, 0));

      // Save last quad control point
      cubicBezVertTOQuadricControlPoint.put(b5, lastQuadControlPoint);
      pathPoints.add(b5);
      currentSubPath.add(b5);
    } else {
      if (verbose)
        System.out.println(
            "couldnt get last control point at curvetoQuadraticSmoothRel - using last point as the control point");

      Vertex lastEndPoint = new Vertex(lastPoint.getX(), lastPoint.getY(), 0);
      Vertex quadControlPoint = new Vertex(lastPoint.getX(), lastPoint.getY(), 0);

      BezierVertex b5 =
          Tools3D.getCubicFromQuadraticCurve(
              lastEndPoint,
              quadControlPoint,
              new Vertex(lastPoint.getX() + x, lastPoint.getY() + y, 0));

      cubicBezVertTOQuadricControlPoint.put(b5, quadControlPoint);
      pathPoints.add(b5);
      currentSubPath.add(b5);
    }
  }
Exemplo n.º 21
0
  public synchronized boolean enqueue(ByteBuffer byteBuffer) {
    if (byteBuffer.remaining() == 0) {
      return false;
    }

    if (queue.size() > 0) {
      ByteBuffer tail = queue.getLast();

      if (tail.hasRemaining()) {
        topUpBuffer(tail, byteBuffer);
      }
    }

    while (byteBuffer.hasRemaining()) {
      ByteBuffer newBuf = bufferFactory.newBuffer();

      topUpBuffer(newBuf, byteBuffer);

      queue.addLast(newBuf);
    }

    facade.modifyInterestOps(SelectionKey.OP_WRITE, 0);

    return true;
  }
 public void actionPerformed(ActionEvent event) {
   int i;
   JButton aux = (JButton) event.getSource();
   if (aux == closeCompra) {
     try {
       String[] information = {
         JOptionPane.showInputDialog(null, "nombre"),
         JOptionPane.showInputDialog(null, "numero de targeta")
       };
       ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
       oos.writeObject(information);
       oos.flush();
       oos.writeObject(products);
       oos.flush();
       oos.writeObject(comprados);
       oos.flush();
       cleanTable();
       comprados.clear();
     } catch (Exception e) {
       System.out.print("\nerror al cerrar la compra " + e.getMessage());
     }
     return;
   }
   for (i = 0; aux != mostrador.addCar[i]; i++) {;
   }
   if (products.get(i).getPiesas() > 0) {
     products.get(i).popParts();
     addCompra(products.get(i));
     total.setText("total: " + comprados.getLast().getTotal());
   } else {
     JOptionPane.showMessageDialog(null, "no seas menso ya no hay mas piesas! :@");
   }
 }
Exemplo n.º 23
0
  /**
   * @param cacheCtx Cache context.
   * @param cand Cache lock candidate to add.
   * @return {@code True} if added as a result of this operation, {@code false} if was previously
   *     added.
   */
  public boolean addNext(GridCacheContext cacheCtx, GridCacheMvccCandidate cand) {
    assert cand != null;
    assert !cand.reentry() : "Lock reentries should not be linked: " + cand;

    // Don't order near candidates by thread as they will be ordered on
    // DHT node. Also, if candidate is implicit, no point to order him.
    if (cacheCtx.isNear() || cand.singleImplicit()) return true;

    LinkedList<GridCacheMvccCandidate> queue = pending.get();

    GridCacheMvccCandidate prev = null;

    if (!queue.isEmpty()) prev = queue.getLast();

    queue.add(cand);

    if (prev != null) {
      prev.next(cand);

      cand.previous(prev);
    }

    if (log.isDebugEnabled()) log.debug("Linked new candidate: " + cand);

    return true;
  }
Exemplo n.º 24
0
 public void handleEvents() {
   for (int i = 0; i < eventQueue.size(); i++) {
     Event e = eventQueue.getLast();
     if (e.timestamp > ProcessingSketch.getGameTimeline().getIterations()) break;
     if (e.type == EventType.NEW_OBJECT) {
       ProcessingSketch.addGameObject(((NewObjectEvent) e).newObj);
     } else if (e.type == EventType.SHOT_COLLISION) {
       ProcessingSketch.removeObjByGUID(((ShotCollisionEvent) e).obj1GUID);
       ProcessingSketch.removeObjByGUID(((ShotCollisionEvent) e).obj2GUID);
     } else {
       for (GameObject obj : ProcessingSketch.getObjects()) {
         if (handlerMap.get(obj.getGUID()) == null) continue;
         if (handlerMap.get(obj.getGUID()).contains(e.type)) {
           if (e.type == EventType.COLLISION) {
             if (((CollisionEvent) e).obj1.getGUID() != obj.getGUID()
                 && ((CollisionEvent) e).obj2.getGUID() != obj.getGUID()) {
               continue; // if obj is neither of the collided objects, don't send the collision
                         // event to obj
             }
           }
           obj.onEvent(e);
         }
       }
     }
     eventQueue.removeLast();
     System.out.println("Events handled: " + i);
   }
 }
Exemplo n.º 25
0
  /* (non-Javadoc)
   * @see org.apache.batik.parser.PathHandler#curvetoCubicSmoothAbs(float, float, float, float)
   */
  public void curvetoCubicSmoothAbs(float x2, float y2, float x, float y) throws ParseException {
    if (verbose)
      System.out.println("curvetoCubicSmoothAbs x2:" + x2 + " y2:" + y2 + " x:" + x + " y:" + y);

    Vertex lastPoint = pathPoints.getLast();
    if (lastPoint instanceof BezierVertex) {
      BezierVertex lastBez = (BezierVertex) lastPoint;

      Vertex lastConPointCopy = (Vertex) lastBez.getSecondCtrlPoint().getCopy();
      // reflect the last controlpoint at the current point
      lastConPointCopy.rotateZ(lastPoint, 180);
      BezierVertex b =
          new BezierVertex(lastConPointCopy.getX(), lastConPointCopy.getY(), 0, x2, y2, 0, x, y, 0);

      pathPoints.add(b);
      currentSubPath.add(b);
    } else {
      if (verbose)
        System.out.println(
            "Couldnt get last controlpoint at: curvetoCubicSmoothAbs - using last point as first controlpoint");

      Vertex lastEndPoint = new Vertex(lastPoint.getX(), lastPoint.getY(), 0);
      BezierVertex b =
          new BezierVertex(lastEndPoint.getX(), lastEndPoint.getY(), 0, x2, y2, 0, x, y, 0);

      pathPoints.add(b);
      currentSubPath.add(b);
    }
  }
Exemplo n.º 26
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();
 }
 /**
  * Calculate largest prime factor.
  *
  * @return the largest prime factor
  */
 public int getLargestPrimeFactor() {
   int divider = PrimeChecker.FIRST_PRIME;
   double divideIt = this.divideIt;
   this.factors.addLast(PrimeChecker.FIRST_PRIME);
   while (divideIt > 1) {
     if (String.valueOf(divideIt).endsWith(String.valueOf(PrimeChecker.END_PRIME))) {
       divider = PrimeChecker.END_PRIME;
       divideIt = divideIt / divider;
     } else {
       boolean hasNext = false;
       for (final int prime : this.factors) {
         if (divideIt % prime == 0) {
           divider = prime;
           hasNext = true;
           break;
         }
       }
       if (!hasNext) {
         while (divideIt % divider == 0) {
           this.factors.addLast(divider);
           divider = PrimeChecker.getNextPrime(this.factors);
         }
         hasNext = false;
       }
     }
     divideIt = divideIt / divider;
     if (!factors.contains(divider)) {
       factors.add(divider);
     }
   }
   System.out.println("processed primes : " + factors.toString());
   return factors.getLast();
 }
  /**
   * Caches the path that was just found.
   *
   * @param smiod
   * @param endNode
   * @param startNode
   */
  private void cachePath(StreetMobilityInfoOD smiod, SegmentNode startNode, SegmentNode endNode) {
    if (hm != null && smiod.path.size() > MIN_CACHED_PATH_LENGTH) {
      Location startPoint = startNode.point;

      LinkedList ll = (LinkedList) hm.get(startPoint);
      if (ll == null) {
        ll = new LinkedList();
      }
      // make sure that path doesn't already exist...
      // must iterate through all of them...
      ListIterator li = ll.listIterator();
      boolean found = false;
      while (li.hasNext()) {
        LinkedList existingPath = (LinkedList) li.next();
        if (existingPath.getFirst().equals(startNode)
            && existingPath.getLast().equals(smiod.path.getLast())) {
          found = true;
          break;
        }
      }
      if (!found) {
        LinkedList newPath = (LinkedList) smiod.path.clone();
        newPath.addFirst(startNode);
        ll.add(newPath);
        hm.put(startPoint, ll);
      }
    }
  }
Exemplo n.º 29
0
  /* (non-Javadoc)
   * @see org.apache.batik.parser.PathHandler#arcAbs(float, float, float, boolean, boolean, float, float)
   */
  public void arcAbs(
      float rx, float ry, float phi, boolean large_arc, boolean sweep, float x, float y)
      throws ParseException {
    if (verbose)
      System.out.println(
          "arcAbs: "
              + rx
              + " "
              + ry
              + " "
              + phi
              + " "
              + large_arc
              + " "
              + sweep
              + " "
              + x
              + " "
              + y);

    Vertex lastPoint = pathPoints.getLast();
    List<Vertex> arcVertices =
        Tools3D.arcTo(lastPoint.x, lastPoint.y, rx, ry, phi, large_arc, sweep, x, y, 40);

    // Prevent odd picking behavour, in which the normal is
    // not correctly computed, because the 2 points are the same
    if (!arcVertices.isEmpty() && lastPoint != null && arcVertices.get(0).equalsVector(lastPoint)) {
      arcVertices.remove(0);
    }
    pathPoints.addAll(arcVertices);
    currentSubPath.addAll(arcVertices);
  }
Exemplo n.º 30
0
  /* (non-Javadoc)
   * @see org.apache.batik.parser.PathHandler#linetoHorizontalAbs(float)
   */
  public void linetoHorizontalAbs(float x) throws ParseException {
    if (verbose) System.out.println("linetoHorizontalAbs x:" + x);

    Vertex vert = new Vertex(x, pathPoints.getLast().getY(), 0);
    pathPoints.add(vert);
    currentSubPath.add(vert);
  }