Beispiel #1
1
  /** @param config */
  public DecorateHandler(TagConfig config) {
    super(config);
    this.template = this.getRequiredAttribute("template");
    this.handlers = new HashMap();

    Iterator itr = this.findNextByType(DefineHandler.class);
    DefineHandler d = null;
    while (itr.hasNext()) {
      d = (DefineHandler) itr.next();
      this.handlers.put(d.getName(), d);
      if (log.isLoggable(Level.FINE)) {
        log.fine(tag + " found Define[" + d.getName() + "]");
      }
    }
    List paramC = new ArrayList();
    itr = this.findNextByType(ParamHandler.class);
    while (itr.hasNext()) {
      paramC.add(itr.next());
    }
    if (paramC.size() > 0) {
      this.params = new ParamHandler[paramC.size()];
      for (int i = 0; i < this.params.length; i++) {
        this.params[i] = (ParamHandler) paramC.get(i);
      }
    } else {
      this.params = null;
    }
  }
  public double getNormalizedActivatedRate() {
    LoadUnloadEdge labeledEdge = (LoadUnloadEdge) this.getEdge();

    Node source = labeledEdge.getA();
    PacketStyleTransportSystem transSystem =
        (PacketStyleTransportSystem)
            ((labeledEdge.isLoadingEdge()) ? (labeledEdge.getB()) : (labeledEdge.getA()));

    Collection<NodeLabel> lbls = source.getLabels();
    double sourcePop = 0;

    // Get the population size of the source node
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PopulationLabel) {
        sourcePop = ((PopulationLabelValue) ((PopulationLabel) lbl).getCurrentValue()).getCount();
        break;
      }
    }
    assert sourcePop > 0;

    lbls = transSystem.getLabels();
    double transCapacity = 0;

    // Get the capacity of the packet transport label
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PacketTransportLabel) {
        transCapacity = ((PacketTransportLabel) lbl).getCurrentValue().getCapacity();
        break;
      }
    }

    return getActivatedRate() * transCapacity / sourcePop;
  }
  /**
   * Returns submap of x and y values according to the given start and end
   *
   * @param start start x value
   * @param stop stop x value
   * @return a submap of x and y values
   */
  public synchronized SortedMap<Double, Double> getRange(
      double start, double stop, int beforeAfterPoints) {
    // we need to add one point before the start and one point after the end (if
    // there are any)
    // to ensure that line doesn't end before the end of the screen

    // this would be simply: start = mXY.lowerKey(start) but NavigableMap is
    // available since API 9
    SortedMap<Double, Double> headMap = mXY.headMap(start);
    if (!headMap.isEmpty()) {
      start = headMap.lastKey();
    }

    // this would be simply: end = mXY.higherKey(end) but NavigableMap is
    // available since API 9
    // so we have to do this hack in order to support older versions
    SortedMap<Double, Double> tailMap = mXY.tailMap(stop);
    if (!tailMap.isEmpty()) {
      Iterator<Double> tailIterator = tailMap.keySet().iterator();
      Double next = tailIterator.next();
      if (tailIterator.hasNext()) {
        stop = tailIterator.next();
      } else {
        stop += next;
      }
    }
    return new TreeMap<Double, Double>(mXY.subMap(start, stop));
  }
Beispiel #4
1
  private void analyzeEdges(UniversalGraph<Node, Edge> graph, int colCount) {
    for (Node node : graph.getNodes()) {
      node.conLeft = false;
      node.conRight = false;
      node.conTop = false;
      node.conBottom = false;
      node.conLeftTop = 0;
      node.conLeftBottom = 0;
      node.conRightTop = 0;
      node.conRightBottom = 0;
    }

    int rowCount = coordinates.size();
    ArrayList<Edge> edgesList = new ArrayList<Edge>(graph.getEdges());
    for (int row = 0; row < rowCount; row++) {
      for (int jump = 0; jump < colCount - 1; jump++) {
        Iterator<Edge> edges = edgesList.iterator();
        while (edges.hasNext()) {
          Edge edge = edges.next();
          if (edge.forward() && edge.sameRow(row) && edge.jump() == jump) {
            analyzeEdge(row, jump, edge);
            edges.remove();
          }
        }
        edges = edgesList.iterator();
        while (edges.hasNext()) {
          Edge edge = edges.next();
          if (edge.backward() && edge.sameRow(row) && edge.jump() == jump) {
            analyzeEdge(row, jump, edge);
            edges.remove();
          }
        }
      }
    }
  }
 private List getTypeNames() throws PureException {
   List typeNames = new ArrayList();
   switch (m_nSortType) {
     case TYPE_PROJECT_KIND:
       {
         List values = NamedValueHelper.getNamedValues(SRMNamedValueTypes.PRJ_KIND, true);
         for (Iterator iter = values.iterator(); iter.hasNext(); ) {
           typeNames.add(((INamedValue) iter.next()).getName());
         }
       }
       break;
     case TYPE_RESEARCH_TYPE:
       {
         List values = NamedValueHelper.getNamedValues(SRMNamedValueTypes.RESEARCH_TYPE, true);
         for (Iterator iter = values.iterator(); iter.hasNext(); ) {
           typeNames.add(((INamedValue) iter.next()).getName());
         }
       }
       break;
     case TYPE_PROJECT_SOURCE:
       {
         List values = NamedValueHelper.getNamedValues(SRMNamedValueTypes.PRJ_SOURCE, true);
         for (Iterator iter = values.iterator(); iter.hasNext(); ) {
           typeNames.add(((INamedValue) iter.next()).getName());
         }
       }
       break;
   }
   return typeNames;
 }
  @Override
  public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTextures(
      GameProfile profile, boolean requireSecure) {
    LogHelper.debug("getTextures, Username: '******'", profile.getName());
    Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures =
        new EnumMap<>(MinecraftProfileTexture.Type.class);

    // Add skin URL to textures map
    Iterator<Property> skinURL =
        profile.getProperties().get(ClientLauncher.SKIN_URL_PROPERTY).iterator();
    Iterator<Property> skinHash =
        profile.getProperties().get(ClientLauncher.SKIN_DIGEST_PROPERTY).iterator();
    if (skinURL.hasNext() && skinHash.hasNext()) {
      String urlValue = skinURL.next().getValue();
      String hashValue = skinHash.next().getValue();
      textures.put(
          MinecraftProfileTexture.Type.SKIN, new MinecraftProfileTexture(urlValue, hashValue));
    }

    // Add cloak URL to textures map
    Iterator<Property> cloakURL =
        profile.getProperties().get(ClientLauncher.CLOAK_URL_PROPERTY).iterator();
    Iterator<Property> cloakHash =
        profile.getProperties().get(ClientLauncher.CLOAK_DIGEST_PROPERTY).iterator();
    if (cloakURL.hasNext() && cloakHash.hasNext()) {
      String urlValue = cloakURL.next().getValue();
      String hashValue = cloakHash.next().getValue();
      textures.put(
          MinecraftProfileTexture.Type.CAPE, new MinecraftProfileTexture(urlValue, hashValue));
    }

    // Return filled textures
    return textures;
  }
  /* (non-Javadoc)
   * @see org.eclipse.jdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
   */
  @Override
  public boolean containsAll(TypeSet other) {
    // Optimization: if other is also a SubTypeOfSingleton, just compare bounds
    if (other instanceof SuperTypesOfSingleton) {
      SuperTypesOfSingleton otherSuper = (SuperTypesOfSingleton) other;
      return TTypes.canAssignTo(fLowerBound, otherSuper.fLowerBound);
    }
    // Optimization: if other is a SubTypesSet, just compare all its bounds to mine
    if (other instanceof SuperTypesSet) {
      SuperTypesSet otherSuper = (SuperTypesSet) other;
      TypeSet otherLowerBounds = otherSuper.lowerBound();

      for (Iterator<TType> iter = otherLowerBounds.iterator(); iter.hasNext(); ) {
        TType t = iter.next();
        if (!TTypes.canAssignTo(fLowerBound, t)) return false;
      }
      return true;
    }
    if (other.isUniverse()) {
      return false;
    }
    // For now, no more tricks up my sleeve; get an iterator
    for (Iterator<TType> iter = other.iterator(); iter.hasNext(); ) {
      TType t = iter.next();

      if (!TTypes.canAssignTo(fLowerBound, t)) return false;
    }
    return true;
  }
  protected void parseAxesElement(SOAPElement axesElement) throws SOAPException {
    // Cycle over Axis-Elements
    Name aName = sf.createName("Axis", "", MDD_URI);
    Iterator itAxis = axesElement.getChildElements(aName);
    while (itAxis.hasNext()) {
      SOAPElement axisElement = (SOAPElement) itAxis.next();
      Name name = sf.createName("name");
      String axisName = axisElement.getAttributeValue(name);

      if (axisName.equals(SLICER_AXIS_NAME)) {
        continue;
      }

      // LookUp for the Axis
      JRXmlaResultAxis axis = xmlaResult.getAxisByName(axisName);

      // retrieve the tuples by <Tuples>
      name = sf.createName("Tuples", "", MDD_URI);
      Iterator itTuples = axisElement.getChildElements(name);
      if (itTuples.hasNext()) {
        SOAPElement eTuples = (SOAPElement) itTuples.next();
        handleTuplesElement(axis, eTuples);
      }
    }
  }
Beispiel #9
0
  /**
   * Given a new LimitOrder, it will replace and old matching limit order in the orderbook or simply
   * get added. Finally, it is sorted.
   *
   * @param limitOrder
   */
  public void update(LimitOrder limitOrder) {

    if (limitOrder.getType().equals(OrderType.ASK)) {

      Iterator<LimitOrder> it = asks.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      asks.add(limitOrder); // just add it
      Collections.sort(asks); // finally sort

    } else {

      Iterator<LimitOrder> it = bids.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      bids.add(limitOrder); // just add it
      Collections.sort(bids); // finally sort
    }
  }
Beispiel #10
0
  /**
   * Search the tree of objects starting at the given <code>ServerActiveHtml</code> and return the
   * content of the first <code>Element</code> with the same name as this <code>Placeholder</code>
   * as the children of a new <code>List</code> if the <code>Element</code> does not have a any
   * placeholder (of the form placeholder-x = "foo").
   *
   * <p>Otherise return a singleton list of a <code>ServerActiveHtml</code> which has the children
   * of the found <code>Element</code> and the placeholders of this <code>Element</code>
   *
   * <p>Packaging the content of the matched <code>Element</code> as a <code>ServerActiveHtml</code>
   * allows the placeholders of the <code>Element</code> to be transferred to the <code>
   * ServerActiveHtml</code>
   *
   * <p>If no matching <code>Element</code> return a <code>List</code> with a <code>Fragment</code>
   * warning message
   *
   * @return A <code>ServerActiveHtml</code> containing the child of the matched <code>Element
   *     </code> or a warning <code>Fragment</code> if no matching <code>Element</code>
   */
  public List getReplacement(ServerActiveHtml sah) throws ServerActiveHtmlException {

    List result = new LinkedList();

    Element match = sah.findElement(getUseElement());

    if (match == null) {
      result.add(
          new Fragment(
              "<b>Warning: missing element for placeholder '" + getUseElement() + "'</b>"));
      return result;
    }

    if (match.getPlaceholders().isEmpty()) {
      for (Iterator children = match.getChildren().iterator(); children.hasNext(); ) {
        Deserializable child = (Deserializable) children.next();
        result.add(child);
      }
    } else {
      ServerActiveHtml wrapper = new ServerActiveHtml(REPLACEMENT_NAME);
      wrapper.setPlaceholders(match.getPlaceholders());
      for (Iterator children = match.getChildren().iterator(); children.hasNext(); ) {
        Deserializable child = (Deserializable) children.next();
        wrapper.add(child);
      }
      result.add(wrapper);
    }

    return result;
  }
  /**
   * Get the JSON data for the Case Study
   *
   * @return boolean indicates whether the case study data is loaded
   */
  private boolean cacheJSON() {
    if (this.getType().equals("LOCAL")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromAsset(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else if (this.getType().equals("DISK")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromStorage(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else {
      return false;
    }
  }
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response saveListItem(InputStream incomingData) {
    StringBuilder listBuilder = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
      String line = null;
      while ((line = in.readLine()) != null) {
        listBuilder.append(line);
      }
    } catch (Exception e) {
      System.out.println("Error Parsing: - ");
    }

    try {
      JSONObject json = new JSONObject(listBuilder.toString());
      Iterator<String> iterator = json.keys();
      if (list == null) {
        list = new ArrayList<ListItem>();
      }
      ListItem item =
          new ListItem(
              (String) json.get(iterator.next()),
              (String) json.get(iterator.next()),
              (Boolean) json.get(iterator.next()));
      list.add(item);
    } catch (JSONException e) {
      e.printStackTrace();
      return Response.status(500).entity(listBuilder.toString()).build();
    }
    // return HTTP response 200 in case of success
    return Response.status(200).entity(listBuilder.toString()).build();
  }
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response addUpdateListItem(InputStream incomingData) {
    StringBuilder listBuilder = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
      String line = null;
      while ((line = in.readLine()) != null) {
        listBuilder.append(line);
      }
    } catch (Exception e) {
      System.out.println("Error Parsing :- ");
    }

    try {
      JSONObject json = new JSONObject(listBuilder.toString());
      Iterator<String> iterator = json.keys();
      ListItem item =
          new ListItem(
              (String) json.get(iterator.next()),
              (String) json.get(iterator.next()),
              Boolean.parseBoolean((String) json.get(iterator.next())));
      int index = list.indexOf(item);
      item = list.get(index);
      list.remove(index);
      item.setTitle((String) json.get(iterator.next()));
      item.setBody((String) json.get(iterator.next()));
      list.add(index, item);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    // return HTTP response 200 in case of success
    return Response.status(200).entity(listBuilder.toString()).build();
  }
  protected void visitConfig(TestResult testResult, ConfigResult configResult) {
    // the faulty command is necessarily the last one
    List<CommandResult> commandResults = configResult.getSubResults();
    CommandResult commandResult = commandResults.get(commandResults.size() - 1);

    sb.append("Test: \"")
        .append(testResult.getTestElem().getName())
        .append("\" Config: \"")
        .append(configResult.getTestElem().getName())
        .append("\" FAILLED\n");
    sb.append("  Command: ").append(commandResult.getExecutedCommand()).append("\n");
    Iterator<String> commandArgs = commandResult.getCommandArgs().iterator();
    if (commandArgs.hasNext()) {
      sb.append("     args: ").append(commandArgs.next()).append("\n");
      while (commandArgs.hasNext()) {
        sb.append("           ").append(commandArgs.next()).append("\n");
      }
    }
    sb.append("  Output: ");
    for (String outputLine : commandResult.getOutput().split("\n")) {
      sb.append(outputLine).append("\n          ");
    }
    sb.append(
        "\n================================================================================\n\n");
  }
Beispiel #15
0
 /**
  * @param grid
  * @return an array of vertex coordinates, one vertex per edge end, 3 coords per vertex
  */
 public double[] getCoords(float[][] grid) {
   double[] ret = new double[edges.size() * 3];
   Iterator<Integer> it = edges.iterator();
   switch (direction) {
     case 0:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][it.next().intValue()];
         ret[i + 1] = grid[1][c1];
         ret[i + 2] = grid[2][c2];
       }
       break;
     case 1:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][c1];
         ret[i + 1] = grid[1][it.next().intValue()];
         ret[i + 2] = grid[2][c2];
       }
       break;
     case 2:
       for (int i = 0; i < ret.length; i += 3) {
         ret[i + 0] = grid[0][c1];
         ret[i + 1] = grid[1][c2];
         ret[i + 2] = grid[2][it.next().intValue()];
       }
       break;
   }
   return ret;
 }
  public void testSortWithoutId() throws Exception {
    SortIteratorTag tag = new SortIteratorTag();

    tag.setComparator("comparator");
    tag.setSource("source");

    tag.setPageContext(pageContext);
    tag.doStartTag();

    // if not an Iterator, just let the ClassCastException be thrown as error instead of failure
    Iterator sortedIterator = (Iterator) stack.findValue("top");

    assertNotNull(sortedIterator);
    // 1
    assertTrue(sortedIterator.hasNext());
    assertEquals(sortedIterator.next(), new Integer(1));
    // 2
    assertTrue(sortedIterator.hasNext());
    assertEquals(sortedIterator.next(), new Integer(2));
    // 3.
    assertTrue(sortedIterator.hasNext());
    assertEquals(sortedIterator.next(), new Integer(3));
    // 4.
    assertTrue(sortedIterator.hasNext());
    assertEquals(sortedIterator.next(), new Integer(4));
    // 5
    assertTrue(sortedIterator.hasNext());
    assertEquals(sortedIterator.next(), new Integer(5));

    assertFalse(sortedIterator.hasNext());
    tag.doEndTag();
  }
Beispiel #17
0
  protected void prepareCommandline() throws BuildException {
    for (int i = 0; i < variables.length; i++) {
      variables[i].addToCommandline(cmdl);
    }

    if (metadata != null) metadata.addToCommandline(cmdl);

    if (fonts != null) fonts.addToCommandline(cmdl);

    if (dLimits != null) dLimits.addToCommandline(cmdl);

    if (dSize != null) dSize.addToCommandline(cmdl);

    Iterator it = nestedAttribs.iterator();

    while (it.hasNext()) ((OptionSource) it.next()).addToCommandline(cmdl);

    it = nestedFileSets.iterator();

    while (it.hasNext()) ((OptionSource) it.next()).addToCommandline(cmdl);

    if (output != null) {
      (new ConfigString(new OptionSpec(null, "output", "o"), output)).addToCommandline(cmdl);
    }

    // end of arguments
    cmdl.createArgument().setValue("--");

    // file-spec may not be specified if building, e.g. a resource bundle SWF
    if (file != null) {
      cmdl.createArgument().setValue(file);
    }
  }
 private String a()
 {
   boolean bool = DialogToastListActivity.f;
   StringBuffer localStringBuffer = new StringBuffer();
   TreeSet localTreeSet = new TreeSet();
   Iterator localIterator1 = this.p.iterator();
   do
   {
     if (!localIterator1.hasNext())
       break;
     zq localzq = (zq)localIterator1.next();
     if (localzq.l)
       localTreeSet.add(localzq.b);
   }
   while (!bool);
   Iterator localIterator2 = localTreeSet.iterator();
   do
   {
     if (!localIterator2.hasNext())
       break;
     localStringBuffer.append((String)localIterator2.next()).append(",");
   }
   while (!bool);
   if (localStringBuffer.length() > 0);
   for (String str = localStringBuffer.substring(0, -1 + localStringBuffer.length()); ; str = null)
   {
     return str;
     localTreeSet.clear();
   }
 }
 public void run(Object[] selection) {
   final Set elements = new HashSet();
   final Set resources = new HashSet();
   for (int i = 0; i < selection.length; ++i) {
     Object o = selection[i];
     ValidatorUtils.processResourcesToElements(o, elements, resources);
   }
   for (Iterator i = elements.iterator(); i.hasNext(); ) {
     final ISourceModule module = (ISourceModule) i.next();
     final IScriptProject sproject = module.getScriptProject();
     if (sproject != null) {
       final IProject project = sproject.getProject();
       if (project != null) {
         getProjectInfo(project).elements.add(module);
       }
     }
   }
   for (Iterator i = resources.iterator(); i.hasNext(); ) {
     final IResource resource = (IResource) i.next();
     final IProject project = resource.getProject();
     if (project != null) {
       getProjectInfo(project).resources.add(resource);
     }
   }
   setRule(buildSchedulingRule(elements, resources));
   setUser(true);
   schedule();
 }
 /** @generated */
 protected Command getDestroyElementCommand(DestroyElementRequest req) {
   View view = (View) getHost().getModel();
   CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null);
   cmd.setTransactionNestingEnabled(false);
   for (Iterator<?> it = view.getTargetEdges().iterator(); it.hasNext(); ) {
     Edge incomingLink = (Edge) it.next();
     if (CrystalVisualIDRegistry.getVisualID(incomingLink) == TransitionEditPart.VISUAL_ID) {
       DestroyElementRequest r = new DestroyElementRequest(incomingLink.getElement(), false);
       cmd.add(new DestroyElementCommand(r));
       cmd.add(new DeleteCommand(getEditingDomain(), incomingLink));
       continue;
     }
   }
   for (Iterator<?> it = view.getSourceEdges().iterator(); it.hasNext(); ) {
     Edge outgoingLink = (Edge) it.next();
     if (CrystalVisualIDRegistry.getVisualID(outgoingLink) == TransitionEditPart.VISUAL_ID) {
       DestroyElementRequest r = new DestroyElementRequest(outgoingLink.getElement(), false);
       cmd.add(new DestroyElementCommand(r));
       cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink));
       continue;
     }
   }
   EAnnotation annotation = view.getEAnnotation("Shortcut"); // $NON-NLS-1$
   if (annotation == null) {
     // there are indirectly referenced children, need extra commands: false
     addDestroyShortcutsCommand(cmd, view);
     // delete host element
     cmd.add(new DestroyElementCommand(req));
   } else {
     cmd.add(new DeleteCommand(getEditingDomain(), view));
   }
   return getGEFWrapper(cmd.reduce());
 }
  protected void handleCellErrors(Iterator errorElems) throws SOAPException {
    SOAPElement errorElem = (SOAPElement) errorElems.next();

    StringBuffer errorMsg = new StringBuffer();
    errorMsg.append("Cell error: ");

    Iterator descriptionElems =
        errorElem.getChildElements(sf.createName("Description", "", MDD_URI));
    if (descriptionElems.hasNext()) {
      SOAPElement descrElem = (SOAPElement) descriptionElems.next();
      errorMsg.append(descrElem.getValue());
      errorMsg.append("; ");
    }

    Iterator sourceElems = errorElem.getChildElements(sf.createName("Source", "", MDD_URI));
    if (sourceElems.hasNext()) {
      SOAPElement sourceElem = (SOAPElement) sourceElems.next();
      errorMsg.append("Source: ");
      errorMsg.append(sourceElem.getValue());
      errorMsg.append("; ");
    }

    Iterator codeElems = errorElem.getChildElements(sf.createName("ErrorCode", "", MDD_URI));
    if (codeElems.hasNext()) {
      SOAPElement codeElem = (SOAPElement) codeElems.next();
      errorMsg.append("Code: ");
      errorMsg.append(codeElem.getValue());
      errorMsg.append("; ");
    }

    throw new JRRuntimeException(errorMsg.toString());
  }
  /**
   * Returns the child at the indicated index or null if there is fewer children
   *
   * @param object the parent object.
   * @param childIndex the index of the child to return.
   * @return the child at the indicated index or null if there is fewer children
   */
  @SuppressWarnings("unchecked")
  public Object getChild(Object object, int childIndex) {
    if (!(object instanceof EObject)) return null;
    int currentIndex = 0;
    Collection<? extends EStructuralFeature> features = getChildrenFeatures(object);
    for (EStructuralFeature feature : features) {
      Object value = getFeatureValue((EObject) object, feature);
      if (value instanceof Collection) {
        Collection<Object> collection = (Collection) value;

        // index of child is in another feature
        if (currentIndex + collection.size() < childIndex) continue;
        // ok the child is in this feature lets find it.
        if (value instanceof List) {
          List list = ((List) value);
          if (currentIndex + list.size() <= childIndex) {
            currentIndex += list.size();
            continue;
          }
          return list.get(childIndex);
        } else {
          Iterator<Object> iter = collection.iterator();
          while (currentIndex < childIndex) {
            iter.next();
            currentIndex++;
          }
          return iter.next();
        }
      }
      currentIndex++;
      if (currentIndex == childIndex) return value;
    }
    return null;
  }
  @Override
  public void dealWithAnnotationOnField(
      ClassNode from, FieldNode on, ClassNode to, AnnotationNode details) {
    Iterator<MethodNode> iter = from.methods.iterator();
    MethodNode staticInitF = null;
    while (iter.hasNext()) {
      MethodNode next = iter.next();
      if (next.name.equals("<clinit>")) {
        staticInitF = next;
        break; // only one class (static) init
      }
    }
    if (staticInitF == null) {
      // what SHOULD be done here? :/
      return; // ?
    }

    Iterator<FieldNode> iter2 = to.fields.iterator();
    FieldNode targetField = null;
    while (iter2.hasNext()) {
      FieldNode next = iter2.next();
      if (next.name.equals(on.name)) {
        targetField = next;
        break;
      }
    }
    if (targetField == null) {
      // what SHOULD be done here? :/
      return; // ?
    }
    throw new UnsupportedOperationException();
    /*staticInitF.instructions.
    StaticInitMerger.
    */
  }
  @Override
  public List<Activity> getRecommendations(Long myUserId) {

    Long closestUserId = getClosestUser(createDistancesVector(myUserId));

    Iterable<UserRating> myRatings = userRatingRepository.findByUserId(myUserId);

    Iterable<UserRating> ratings = userRatingRepository.findByUserId(closestUserId);
    Iterator<UserRating> ratingsIterator = ratings.iterator();

    List<Activity> recommendations = new ArrayList<Activity>();

    while (ratingsIterator.hasNext()) {
      Iterator<UserRating> myRatingsIterator = myRatings.iterator();
      UserRating rating = ratingsIterator.next();
      boolean activityFound = false;
      if (rating.getRating() >= 3) {
        while (myRatingsIterator.hasNext()) {
          UserRating myRating = myRatingsIterator.next();

          if (rating.getActivity().getId() == myRating.getActivity().getId()) {
            activityFound = true;
            break;
          }
        }
        if (!activityFound) {
          recommendations.add(rating.getActivity());
        }
      }
    }

    return recommendations;
  }
Beispiel #25
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
    public int contextMatchCheck() {
      final Iterable<String> contextLines = myContext.getPreviousLinesIterable();

      // we ignore spaces.. at least at start/end, since some version controls could ignore their
      // changes when doing annotate
      final Iterator<String> iterator = contextLines.iterator();
      if (iterator.hasNext()) {
        String contextLine = iterator.next().trim();

        while (myChangedLinesIterator.hasNext()) {
          final Pair<Integer, String> pair = myChangedLinesIterator.next();
          if (pair.getSecond().trim().equals(contextLine)) {
            if (!iterator.hasNext()) break;
            contextLine = iterator.next().trim();
          }
        }
        if (iterator.hasNext()) {
          return -1;
        }
      }
      if (!myChangedLinesIterator.hasNext()) return -1;

      final String targetLine = myContext.getTargetString().trim();
      while (myChangedLinesIterator.hasNext()) {
        final Pair<Integer, String> pair = myChangedLinesIterator.next();
        if (pair.getSecond().trim().equals(targetLine)) {
          return pair.getFirst();
        }
      }
      return -1;
    }
 @Override
 public boolean addAll(final Collection<? extends E> c) {
   if (c.isEmpty()) {
     return false;
   }
   boolean modified = false;
   if (c instanceof SortedListSet && this.comparator == ((SortedListSet<?>) c).getComparator()) {
     int index = 0;
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       index = addE(index, iter.next());
       if (index >= 0) {
         modified = true;
         index++;
       } else {
         index = -(index + 1);
       }
     }
   } else {
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       if (addE(iter.next()) >= 0) {
         modified = true;
       }
     }
   }
   return modified;
 }
  public void testSortWithIdIteratorAvailableInPageContext() throws Exception {
    SortIteratorTag tag = new SortIteratorTag();

    tag.setId("myId");
    tag.setComparator("comparator");
    tag.setSource("source");

    tag.setPageContext(pageContext);
    tag.doStartTag();

    {
      Iterator sortedIterator = (Iterator) pageContext.getAttribute("myId");

      assertNotNull(sortedIterator);
      // 1
      assertTrue(sortedIterator.hasNext());
      assertEquals(sortedIterator.next(), new Integer(1));
      // 2
      assertTrue(sortedIterator.hasNext());
      assertEquals(sortedIterator.next(), new Integer(2));
      // 3
      assertTrue(sortedIterator.hasNext());
      assertEquals(sortedIterator.next(), new Integer(3));
      // 4
      assertTrue(sortedIterator.hasNext());
      assertEquals(sortedIterator.next(), new Integer(4));
      // 5
      assertTrue(sortedIterator.hasNext());
      assertEquals(sortedIterator.next(), new Integer(5));

      assertFalse(sortedIterator.hasNext());
    }

    tag.doEndTag();
  }
  /**
   * Finds common instruments for all missions in compare list.
   *
   * @return the set of common instruments names
   */
  public static Set<String> findCommonInstruments() {
    // calculate common instruments
    Set<String> commonInstruments = new HashSet<String>();
    if (ITEMS.size() > 1) {
      // add first instruments of first item to list
      Iterator<CompareItem> i = ITEMS.iterator();
      for (EntityInfo instrument : i.next().getInstruments()) {
        commonInstruments.add(instrument.getName());
      }

      // check data with others
      while (i.hasNext()) {
        CompareItem next = i.next();
        for (Iterator<String> j = commonInstruments.iterator(); j.hasNext(); ) {
          String commonInstrument = j.next();

          // find instrument in next item
          boolean present = true;
          for (EntityInfo entityInfo : next.getInstruments()) {
            if (!entityInfo.getName().equalsIgnoreCase(commonInstrument)) {
              present = false;
              break;
            }
          }

          // remove instrument if it is not present in next
          if (!present) {
            j.remove();
          }
        }
      }
    }
    return commonInstruments;
  }
 public void deleteTaxByTenantIdx(long TenantId) {
   CFAccTaxByTenantIdxKey key =
       ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newTenantIdxKey();
   key.setRequiredTenantId(TenantId);
   if (indexByTenantIdx == null) {
     indexByTenantIdx = new HashMap<CFAccTaxByTenantIdxKey, Map<CFAccTaxPKey, ICFAccTaxObj>>();
   }
   if (indexByTenantIdx.containsKey(key)) {
     Map<CFAccTaxPKey, ICFAccTaxObj> dict = indexByTenantIdx.get(key);
     ((ICFAccSchema) schema.getBackingStore())
         .getTableTax()
         .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId);
     Iterator<ICFAccTaxObj> iter = dict.values().iterator();
     ICFAccTaxObj obj;
     List<ICFAccTaxObj> toForget = new LinkedList<ICFAccTaxObj>();
     while (iter.hasNext()) {
       obj = iter.next();
       toForget.add(obj);
     }
     iter = toForget.iterator();
     while (iter.hasNext()) {
       obj = iter.next();
       obj.forget(true);
     }
     indexByTenantIdx.remove(key);
   } else {
     ((ICFAccSchema) schema.getBackingStore())
         .getTableTax()
         .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId);
   }
 }