Example #1
1
  public SelectMany05Bean() {

    HobbitBean[] hobbits = {
      new HobbitBean("Bilbo", "Ring Finder"),
      new HobbitBean("Frodo", "Ring Bearer"),
      new HobbitBean("Merry", "Trouble Maker"),
      new HobbitBean("Pippin", "Trouble Maker")
    };

    Set<SelectItem> items = new LinkedHashSet<SelectItem>();
    for (HobbitBean hobbit : hobbits) {
      items.add(new SelectItem(hobbit.getName()));
    }
    hobbitCollection = new TreeSet<HobbitBean>();
    hobbitCollection.addAll(Arrays.asList(hobbits));
    possibleValues = Collections.unmodifiableSet(items);
    initialSortedSetValues = new TreeSet<String>(Collections.reverseOrder());
    initialSortedSetValues.add("Pippin");
    initialSortedSetValues.add("Frodo");
    initialCollectionValues = new LinkedHashSet<String>(2);
    initialCollectionValues.add("Bilbo");
    initialCollectionValues.add("Merry");
    initialSetValues = new CopyOnWriteArraySet<String>(); // not Cloneable
    initialSetValues.add("Frodo");
    initialListValues = new Vector<String>();
    initialListValues.add("Bilbo");
    initialListValues.add("Pippin");
    initialListValues.add("Merry");
    hobbitDataModel =
        new ListDataModel<HobbitBean>(new ArrayList<HobbitBean>(Arrays.asList(hobbits)));
  }
  /**
   * Checks if our WPS can really handle this process inputs and outputs
   *
   * @param pf
   * @param name
   * @return
   */
  Set<Name> getProcessBlacklist() {
    synchronized (PROCESS_BLACKLIST) {
      if (PROCESS_BLACKLIST == Collections.EMPTY_SET) {

        Set<Name> blacklist = new HashSet<Name>();

        for (ProcessFactory pf : Processors.getProcessFactories()) {
          int count = 0;
          for (Name name : pf.getNames()) {
            try {
              // check inputs
              for (Parameter<?> p : pf.getParameterInfo(name).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the input "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }

              // check outputs
              for (Parameter<?> p : pf.getResultInfo(name, null).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the output "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }
            } catch (Throwable t) {
              blacklist.add(name);
            }

            if (!blacklist.contains(name)) {
              count++;
            }
          }
          LOGGER.info("Found " + count + " bindable processes in " + pf.getTitle());
        }

        PROCESS_BLACKLIST = blacklist;
      }
    }

    return PROCESS_BLACKLIST;
  }
 private <T> Set<T> createInstances(Class<T> serviceType, Set<Class<? extends T>> providers) {
   Set<T> providerImpls = new LinkedHashSet<T>();
   for (Class<? extends T> serviceClass : providers) {
     providerImpls.add(createInstance(serviceClass));
   }
   return providerImpls;
 }
  @Test
  public void testTwoInclude() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:"
                + ourPort
                + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info(responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(2, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());

    Set<String> values = new HashSet<String>();
    values.add(p.getName().get(0).getFamilyFirstRep().getValue());
    values.add(p.getName().get(1).getFamilyFirstRep().getValue());
    assertThat(values, containsInAnyOrder("foo", "bar"));
  }
  public void populate(PhaseI currentPhase) {
    if (hexMap == null) hexMap = orUIManager.getMapPanel().getMap();

    GUIHex uiHex = hexMap.getSelectedHex();
    MapHex hex = uiHex.getHexModel();
    orUIManager.tileUpgrades = new ArrayList<TileI>();
    List<TileI> tiles;
    Set<String> allowedColours = currentPhase.getTileColours().keySet();

    for (LayTile layTile : hexMap.getTileAllowancesForHex(hex)) {
      tiles = layTile.getTiles();
      if (tiles == null) {
        for (TileI tile :
            uiHex
                .getCurrentTile()
                .getValidUpgrades(hex, orUIManager.gameUIManager.getCurrentPhase())) {
          // Skip if not allowed in LayTile
          // if (!layTile.isTileColourAllowed(tile.getColourName())) continue;

          if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile);
        }
      } else {
        for (TileI tile : tiles) {
          // Skip if colour is not allowed yet
          if (!allowedColours.contains(tile.getColourName())) continue;

          if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile);
        }
      }
    }
  }
Example #6
1
  /**
   * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
   *
   * @return boolean
   */
  public boolean isTenpaySign() {
    StringBuffer sb = new StringBuffer();
    Set es = this.parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String k = (String) entry.getKey();
      String v = (String) entry.getValue();
      if (!"sign".equals(k) && null != v && !"".equals(v)) {
        sb.append(k + "=" + v + "&");
      }
    }

    sb.append("key=" + this.getKey());

    // 算出摘要
    String enc = "UTF-8";
    String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

    String tenpaySign = this.getParameter("sign").toLowerCase();

    // debug信息
    this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + tenpaySign);

    return tenpaySign.equals(sign);
  }
  private static void generateNameByString(
      Set<String> possibleNames,
      String value,
      NameValidator validator,
      boolean forStaticVariable,
      Project project) {
    if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return;
    if (forStaticVariable) {
      StringBuilder buffer = new StringBuilder(value.length() + 10);
      char[] chars = new char[value.length()];
      value.getChars(0, value.length(), chars, 0);
      boolean wasLow = Character.isLowerCase(chars[0]);

      buffer.append(Character.toUpperCase(chars[0]));
      for (int i = 1; i < chars.length; i++) {
        if (Character.isUpperCase(chars[i])) {
          if (wasLow) {
            buffer.append('_');
            wasLow = false;
          }
        } else {
          wasLow = true;
        }

        buffer.append(Character.toUpperCase(chars[i]));
      }
      possibleNames.add(validator.validateName(buffer.toString(), true));
    } else {
      possibleNames.add(validator.validateName(value, true));
    }
  }
Example #8
1
  @Test
  public void testGetExistingAccount() throws Exception {
    Set<Authority> authorities = new HashSet<>();
    Authority authority = new Authority();
    authority.setName(AuthoritiesConstants.ADMIN);
    authorities.add(authority);

    User user = new User();
    user.setLogin("test");
    user.setFirstName("john");
    user.setLastName("doe");
    user.setEmail("john.doe@jhipter.com");
    user.setAuthorities(authorities);
    when(mockUserService.getUserWithAuthorities()).thenReturn(user);

    restUserMockMvc
        .perform(get("/api/account").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.login").value("test"))
        .andExpect(jsonPath("$.firstName").value("john"))
        .andExpect(jsonPath("$.lastName").value("doe"))
        .andExpect(jsonPath("$.email").value("john.doe@jhipter.com"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
  }
  public boolean equals(Object object) {
    if (Util.THIS.isLoggable()) /* then */ Util.THIS.debug("-=#| TreeNodeFilter.equals");

    if ((object instanceof TreeNodeFilter) == false) {
      return false;
    }

    TreeNodeFilter peer = (TreeNodeFilter) object;

    Set thisSet = new HashSet(Arrays.asList(this.nodeTypes));
    Set peerSet = new HashSet(Arrays.asList(peer.nodeTypes));

    if (Util.THIS.isLoggable()) /* then */ Util.THIS.debug("-=#|    thisSet = " + thisSet);
    if (Util.THIS.isLoggable()) /* then */ Util.THIS.debug("-=#|    peerSet = " + peerSet);
    if (Util.THIS.isLoggable()) /* then */
      Util.THIS.debug("-=#|    acceptPolicy? " + (this.acceptPolicy == peer.acceptPolicy));
    if (Util.THIS.isLoggable()) /* then */
      Util.THIS.debug("-=#|    nodeTypes   ? " + (thisSet.equals(peerSet)));

    if (this.acceptPolicy != peer.acceptPolicy) {
      return false;
    }

    return thisSet.equals(peerSet);
  }
 static {
   reservedParameters.add("reportId");
   reservedParameters.add("magicKey");
   reservedParameters.add("format");
   reservedParameters.add("__format");
   reservedParameters.add("__report");
 }
Example #11
0
  @Override
  public ResourceSchema getSchema(String location, Job job) throws IOException {

    if (!partitionKeysSet) {
      Set<String> keys = getPartitionColumns(location, job);

      if (!(keys == null || keys.size() == 0)) {

        // re-edit the pigSchema to contain the new partition keys.
        ResourceFieldSchema[] fields = pigSchema.getFields();

        LOG.debug("Schema: " + Arrays.toString(fields));

        ResourceFieldSchema[] newFields = Arrays.copyOf(fields, fields.length + keys.size());

        int index = fields.length;

        for (String key : keys) {
          newFields[index++] = new ResourceFieldSchema(new FieldSchema(key, DataType.CHARARRAY));
        }

        pigSchema.setFields(newFields);

        LOG.debug("Added partition fields: " + keys + " to loader schema");
        LOG.debug("Schema is: " + Arrays.toString(newFields));
      }

      partitionKeysSet = true;
    }

    return pigSchema;
  }
  public Element getState() {
    Element element = new Element("state");

    for (Map.Entry<GroupDescriptor, Map<String, Set<UsageDescriptor>>> appData :
        getApplicationData().entrySet()) {
      Element groupElement = new Element(GROUP_TAG);
      groupElement.setAttribute(GROUP_NAME_ATTR, appData.getKey().getId());
      boolean isEmptyGroup = true;

      for (Map.Entry<String, Set<UsageDescriptor>> projectData : appData.getValue().entrySet()) {
        Element projectElement = new Element(PROJECT_TAG);
        projectElement.setAttribute(PROJECT_ID_ATTR, projectData.getKey());
        final Set<UsageDescriptor> projectDataValue = projectData.getValue();
        if (!projectDataValue.isEmpty()) {
          projectElement.setAttribute(VALUES_ATTR, joinUsages(projectDataValue));
          groupElement.addContent(projectElement);
          isEmptyGroup = false;
        }
      }

      if (!isEmptyGroup) {
        element.addContent(groupElement);
      }
    }

    return element;
  }
  private Variance calculateArgumentProjectionKindFromSuper(
      @NotNull TypeProjection argument,
      @NotNull List<TypeProjectionAndVariance> projectionsFromSuper) {
    Set<Variance> projectionKindsInSuper = Sets.newLinkedHashSet();
    for (TypeProjectionAndVariance projectionAndVariance : projectionsFromSuper) {
      projectionKindsInSuper.add(projectionAndVariance.typeProjection.getProjectionKind());
    }

    Variance defaultProjectionKind = argument.getProjectionKind();
    if (projectionKindsInSuper.size() == 0) {
      return defaultProjectionKind;
    } else if (projectionKindsInSuper.size() == 1) {
      Variance projectionKindInSuper = projectionKindsInSuper.iterator().next();
      if (defaultProjectionKind == INVARIANT || defaultProjectionKind == projectionKindInSuper) {
        return projectionKindInSuper;
      } else {
        reportError(
            "Incompatible projection kinds in type arguments of super methods' return types: "
                + projectionsFromSuper
                + ", defined in current: "
                + argument);
        return defaultProjectionKind;
      }
    } else {
      reportError(
          "Incompatible projection kinds in type arguments of super methods' return types: "
              + projectionsFromSuper);
      return defaultProjectionKind;
    }
  }
 private Set<UUID> getAgentsInLane(int lane, int from, int to) {
   Set<UUID> agents = new HashSet<UUID>();
   for (int y = from; y <= to; y++) {
     agents.addAll(getAreaService().getCell(lane, y % areaLength, 0));
   }
   return agents;
 }
 @EventListener
 public int checkForCollisions(EndOfTimeCycle e) throws CollisionException {
   int collisionsThisCycle = 0;
   HashMap<UUID, Set<UUID>> collisions = new HashMap<UUID, Set<UUID>>();
   for (CollisionCheck c : this.checks) {
     Set<UUID> cCollisions = c.checkForCollision();
     collisionsThisCycle += cCollisions.size();
     collisions.put(c.self, cCollisions);
   }
   this.checks.clear();
   this.collisions += collisionsThisCycle;
   if (this.persist != null) {
     this.persist.setProperty(
         "collisions", e.getTime().intValue(), Integer.toString(collisionsThisCycle));
   }
   // Only count is as a collision if collisions are all paired.
   Pair<UUID, UUID> collision = this.checkForMutualCollisions(collisions);
   if (collision != null) {
     Time time = null;
     if (e == null) {
       time = null;
     } else {
       time = e.getTime();
     }
     this.throwCollision(collision, time);
   }
   // return "collisions" this cycle as near-misses ?
   return collisionsThisCycle;
 }
  public Set /*<FileObject>*/ instantiate(/*ProgressHandle handle*/ ) throws IOException {
    Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
    dirF.mkdirs();

    FileObject template = Templates.getTemplate(wiz);
    FileObject dir = FileUtil.toFileObject(dirF);
    unZipFile(template.getInputStream(), dir);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration<? extends FileObject> e = dir.getFolders(true);
    while (e.hasMoreElements()) {
      FileObject subfolder = e.nextElement();
      if (ProjectManager.getDefault().isProject(subfolder)) {
        resultSet.add(subfolder);
      }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
      ProjectChooser.setProjectsFolder(parent);
    }

    return resultSet;
  }
Example #17
0
  private BlockNode processMonitorEnter(
      IRegion curRegion, BlockNode block, InsnNode insn, RegionStack stack) {
    SynchronizedRegion synchRegion = new SynchronizedRegion(curRegion, insn);
    synchRegion.getSubBlocks().add(block);
    curRegion.getSubBlocks().add(synchRegion);

    Set<BlockNode> exits = new HashSet<BlockNode>();
    cacheSet.clear();
    traverseMonitorExits(synchRegion, insn.getArg(0), block, exits, cacheSet);

    for (InsnNode exitInsn : synchRegion.getExitInsns()) {
      InstructionRemover.unbindInsn(mth, exitInsn);
    }

    BlockNode body = getNextBlock(block);
    if (body == null) {
      ErrorsCounter.methodError(mth, "Unexpected end of synchronized block");
      return null;
    }
    BlockNode exit;
    if (exits.size() == 1) {
      exit = getNextBlock(exits.iterator().next());
    } else {
      cacheSet.clear();
      exit = traverseMonitorExitsCross(body, exits, cacheSet);
    }

    stack.push(synchRegion);
    stack.addExit(exit);
    synchRegion.getSubBlocks().add(makeRegion(body, stack));
    stack.pop();
    return exit;
  }
 private IPortTemplateDesc addConfig(final IConfigurationElement element) {
   if (element.getName().equals(CodeGeneratorPortTemplatesRegistry.ATTR_TEMPLATE)) {
     final PortTemplateDescriptor desc = new PortTemplateDescriptor(element);
     if (!this.templateMap.containsKey(desc.getId())) {
       this.templateMap.put(desc.getId(), desc);
       final String[] ifaces = desc.getInterfaces();
       for (final String i : ifaces) {
         if (i == null) {
           continue;
         }
         Set<String> ids = this.repToIdMap.get(i);
         if (ids == null) {
           ids = new HashSet<String>();
           this.repToIdMap.put(i, ids);
         }
         ids.add(desc.getId());
       }
       return desc;
     } else {
       RedhawkCodegenActivator.logError(
           "Duplicate Code Generator registered with an ID of: " + desc.getId(), null);
     }
   }
   return null;
 }
Example #19
0
  /**
   * Returns a new graph with the same structure as the one wrapped here, and with vertices
   * generated by the given {@link Function1}. Edges are copied in direction and weight.
   *
   * @param factory the vertex factory used to instantiate new vertices in the new graph
   * @param function the function used to set values of a new vertex in the new graph, from the
   *     matching spot
   * @param mappings a map that will receive mappings from {@link Spot} to the new vertices. Can be
   *     <code>null</code> if you do not want to get the mappings
   * @return a new {@link SimpleDirectedWeightedGraph}.
   */
  public <V> SimpleDirectedWeightedGraph<V, DefaultWeightedEdge> copy(
      final VertexFactory<V> factory,
      final Function1<Spot, V> function,
      final Map<Spot, V> mappings) {
    final SimpleDirectedWeightedGraph<V, DefaultWeightedEdge> copy =
        new SimpleDirectedWeightedGraph<V, DefaultWeightedEdge>(DefaultWeightedEdge.class);
    final Set<Spot> spots = graph.vertexSet();
    // To store mapping of old graph vs new graph
    Map<Spot, V> map;
    if (null == mappings) {
      map = new HashMap<Spot, V>(spots.size());
    } else {
      map = mappings;
    }

    // Generate new vertices
    for (final Spot spot : Collections.unmodifiableCollection(spots)) {
      final V vertex = factory.createVertex();
      function.compute(spot, vertex);
      map.put(spot, vertex);
      copy.addVertex(vertex);
    }

    // Generate new edges
    for (final DefaultWeightedEdge edge : graph.edgeSet()) {
      final DefaultWeightedEdge newEdge =
          copy.addEdge(map.get(graph.getEdgeSource(edge)), map.get(graph.getEdgeTarget(edge)));
      copy.setEdgeWeight(newEdge, graph.getEdgeWeight(edge));
    }

    return copy;
  }
  public void loadState(final Element element) {
    List groups = element.getChildren(GROUP_TAG);

    for (Object group : groups) {
      Element groupElement = (Element) group;
      String groupName = groupElement.getAttributeValue(GROUP_NAME_ATTR);

      final GroupDescriptor groupDescriptor = GroupDescriptor.create(groupName);

      List projectsList = groupElement.getChildren(PROJECT_TAG);
      for (Object project : projectsList) {
        Element projectElement = (Element) project;
        String projectId = projectElement.getAttributeValue(PROJECT_ID_ATTR);
        String frameworks = projectElement.getAttributeValue(VALUES_ATTR);
        if (!StringUtil.isEmptyOrSpaces(projectId) && !StringUtil.isEmptyOrSpaces(frameworks)) {
          Set<UsageDescriptor> frameworkDescriptors = new HashSet<UsageDescriptor>();
          for (String key : StringUtil.split(frameworks, TOKENIZER)) {
            final UsageDescriptor descriptor = getUsageDescriptor(key);
            if (descriptor != null) frameworkDescriptors.add(descriptor);
          }
          getApplicationData(groupDescriptor).put(projectId, frameworkDescriptors);
        }
      }
    }
  }
    private boolean callsWritingConstructor(
        MethodDeclaration methodDeclaration,
        HashSet writingConstructorBindings,
        Set visitedMethodDeclarations) {
      Block body = methodDeclaration.getBody();
      if (body == null) return false;

      List statements = body.statements();
      if (statements.size() == 0) return false;

      Statement statement = (Statement) statements.get(0);
      if (!(statement instanceof ConstructorInvocation)) return false;

      ConstructorInvocation invocation = (ConstructorInvocation) statement;
      IMethodBinding constructorBinding = invocation.resolveConstructorBinding();
      if (constructorBinding == null) return false;

      if (writingConstructorBindings.contains(constructorBinding)) {
        return true;
      } else {
        ASTNode declaration =
            ASTNodes.findDeclaration(constructorBinding, methodDeclaration.getParent());
        if (!(declaration instanceof MethodDeclaration)) return false;

        if (visitedMethodDeclarations.contains(declaration)) {
          return false;
        }
        visitedMethodDeclarations.add(methodDeclaration);
        return callsWritingConstructor(
            (MethodDeclaration) declaration, writingConstructorBindings, visitedMethodDeclarations);
      }
    }
Example #22
0
    @Override
    public void vertexRemoved(final GraphVertexChangeEvent<Spot> event) {
      if (null == connectedEdgeSets) {
        return;
      }

      final Spot v = event.getVertex();
      vertexToID.remove(v);
      final Integer id = vertexToID.get(v);
      if (id != null) {
        final Set<Spot> set = connectedVertexSets.get(id);
        if (null == set) {
          return; // it was removed when removing the
          // last edge of a track, most
          // likely.
        }
        set.remove(v);

        if (set.isEmpty()) {
          connectedEdgeSets.remove(id);
          connectedVertexSets.remove(id);
          names.remove(id);
          visibility.remove(id);
        }
      }
    }
Example #23
0
    private void serve(InputStream sis, OutputStream sos) throws IOException {

      // kills the process if client closes the stream;
      // closes the stream if process is terminated/ended output.
      // therefore we need the interruption mechanism.
      Process process = Runtime.getRuntime().exec("bash");
      InputStream pis = process.getInputStream();
      InputStream pes = process.getErrorStream();
      OutputStream pos = process.getOutputStream();

      try {
        threads.add(new CopyThread(pis, sos));
        threads.add(new CopyThread(pes, sos));
        threads.add(new CopyThread(sis, pos));
        threads.add(
            new InterruptibleThread() {
              protected void run0() throws InterruptedException {
                process.waitFor();
              }
            });

        Util.startJoin(threads);
      } finally {
        process.destroy();
      }
    }
Example #24
0
  public void sendSupportedChannels() {
    if (getHandle().field_71135_a == null) return;
    Set<String> listening = server.getMessenger().getIncomingChannels();

    if (!listening.isEmpty()) {
      net.minecraft.network.packet.Packet250CustomPayload packet =
          new net.minecraft.network.packet.Packet250CustomPayload();

      packet.field_73630_a = "REGISTER";
      ByteArrayOutputStream stream = new ByteArrayOutputStream();

      for (String channel : listening) {
        try {
          stream.write(channel.getBytes("UTF8"));
          stream.write((byte) 0);
        } catch (IOException ex) {
          Logger.getLogger(CraftPlayer.class.getName())
              .log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex);
        }
      }

      packet.field_73629_c = stream.toByteArray();
      packet.field_73628_b = packet.field_73629_c.length;

      getHandle().field_71135_a.func_72567_b(packet);
    }
  }
  /**
   * 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;
  }
Example #26
0
 public Set<String> getCommandNames() {
   // using TreeSet to sort alphabetically
   Set<String> commands = new TreeSet(subCommands.keySet());
   // removing default "commands" command as it's not normally shown or run like other commands
   commands.remove("commands");
   return commands;
 }
Example #27
0
  public Action choose(LightsOut.Player actor, Set<Action> options) {
    if (presses == null) {
      presses = new HashSet<Location>();

      // linear algebra solution
      boolean[][] state = actor.state();

      boolean[] s = stateVector(state);
      boolean[][] M = stateMatrix(state[0].length, state.length);
      gauss(M, s);

      // translate to locations
      Location[][] locations = actor.locations();
      for (int x = 0; x < s.length; x++) {
        if (s[x]) {
          presses.add(locations[x / state.length][x % state[0].length]);
        }
      }
    }

    Location next = Groups.first(presses);
    presses.remove(next);

    for (Action action : Groups.ofType(LightsOut.Move.class, options)) {
      if (((LightsOut.Move) action).target.location().equals(next)) {
        return action;
      }
    }

    return null;
  }
  @Override
  public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
    if (mProgressDialog.isShowing()) {
      // should always be showing here
      mProgressDialog.dismiss();
    }

    // add our list of completed uploads to "completed"
    // and remove them from our toSend list.
    ArrayList<Long> workingSet = new ArrayList<Long>();
    Collections.addAll(workingSet, mInstancesToSend);
    if (doneSoFar != null) {
      Set<String> uploadedInstances = doneSoFar.keySet();
      Iterator<String> itr = uploadedInstances.iterator();

      while (itr.hasNext()) {
        Long removeMe = Long.valueOf(itr.next());
        boolean removed = workingSet.remove(removeMe);
        if (removed) {
          Log.i(t, removeMe + " was already sent, removing from queue before restarting task");
        }
      }
      mUploadedInstances.putAll(doneSoFar);
    }

    // and reconstruct the pending set of instances to send
    Long[] updatedToSend = new Long[workingSet.size()];
    for (int i = 0; i < workingSet.size(); ++i) {
      updatedToSend[i] = workingSet.get(i);
    }
    mInstancesToSend = updatedToSend;

    mUrl = url.toString();
    showDialog(AUTH_DIALOG);
  }
Example #29
0
 /*
  * This function inspects a .class file for a given .java file,
  * infers the package name and all used classes, and adds to "all"
  * the class file names of those classes used that have been found
  * in the same class path.
  */
 protected void java2classFiles(
     String java, File cwd, File buildDir, List<String> result, Set<String> all) {
   if (java.endsWith(".java")) java = java.substring(0, java.length() - 5) + ".class";
   else if (!java.endsWith(".class")) {
     if (!all.contains(java)) {
       if (buildDir == null) sortClassesAtEnd(result);
       result.add(java);
       all.add(java);
     }
     return;
   }
   byte[] buffer = Util.readFile(Util.makePath(cwd, java));
   if (buffer == null) {
     if (!java.endsWith("/package-info.class"))
       err.println("Warning: " + java + " does not exist.  Skipping...");
     return;
   }
   ByteCodeAnalyzer analyzer = new ByteCodeAnalyzer(buffer);
   String fullClass = analyzer.getPathForClass() + ".class";
   if (!java.endsWith(fullClass))
     throw new RuntimeException("Huh? " + fullClass + " is not a suffix of " + java);
   java = java.substring(0, java.length() - fullClass.length());
   for (String className : analyzer.getClassNames()) {
     String path = java + className + ".class";
     if (new File(Util.makePath(cwd, path)).exists() && !all.contains(path)) {
       result.add(path);
       all.add(path);
       java2classFiles(path, cwd, buildDir, result, all);
     }
   }
 }
 private void performImport() {
   FileDialog dialog = new FileDialog(this.fDialog.getShell(), SWT.OPEN);
   dialog.setText("Export environment variables to file");
   String file = dialog.open();
   if (file != null) {
     File handle = new File(file);
     if (!handle.exists()) {
       String text = "Selected file not exists.";
       showErrorMessage("Environment import", text);
       return;
     }
     EnvironmentVariable[] vars = null;
     try {
       vars = EnvironmentVariablesFileUtils.load(file);
     } catch (Exception e) {
       showErrorMessage("Environment import", e.getMessage());
     }
     if (vars != null) {
       EnvironmentVariable[] variables = this.fEnvironmentVariablesContentProvider.getVariables();
       Set nvars = new HashSet();
       nvars.addAll(Arrays.asList(vars));
       nvars.addAll(Arrays.asList(variables));
       this.fEnvironmentVariablesContentProvider.setVariables(
           (EnvironmentVariable[]) nvars.toArray(new EnvironmentVariable[nvars.size()]));
     }
   }
 }