Ejemplo n.º 1
0
 /**
  * The inventories list is flushed with the current inventory list, so all that remains is the
  * ones still around this scan process. All packets we sent last tick, we'll remove from this
  * round, because no point sending them so quickly. NOTE: This means it's once a second by
  * default.
  *
  * <p>We clear the packetRequest list, so we can begin anew. Add all the inventories we want to
  * view. Clear the temp list, because we have no need of it, until next tick.
  */
 public void setLists() {
   inventories.retainAll(tempInv);
   tempInv.removeAll(requestedList);
   requestedList.clear();
   requestedList.addAll(tempInv);
   tempInv.clear();
 }
Ejemplo n.º 2
0
  private static double jaccardSimilarity(String similar1, String similar2) {
    HashSet<String> h1 = new HashSet<String>();
    HashSet<String> h2 = new HashSet<String>();

    for (String s : similar1.split("\\s+")) {
      h1.add(s);
    }

    for (String s : similar2.split("\\s+")) {
      h2.add(s);
    }

    int sizeh1 = h1.size();
    // Retains all elements in h3 that are contained in h2 ie intersection
    h1.retainAll(h2);
    // h1 now contains the intersection of h1 and h2

    h2.removeAll(h1);
    // h2 now contains unique elements

    // Union
    int union = sizeh1 + h2.size();
    int intersection = h1.size();

    return (double) intersection / union;
  }
Ejemplo n.º 3
0
 @Override
 public synchronized void afterCompletion(int status) {
   completed = true;
   synchronizations.remove(id);
   if (transactionMode == TransactionMode.ISOLATE_READS) {
     for (TempTable table : tables.values()) {
       table.getActive().decrementAndGet();
     }
   } else {
     HashSet<TempTable> current = new HashSet<TempTable>(tempTables.values());
     current.retainAll(tables.values());
     for (TempTable table : current) {
       table.getActive().set(0);
       table.getTree().clearClonedFlags();
     }
   }
   for (TransactionCallback callback : callbacks) {
     if (status == Status.STATUS_COMMITTED) {
       callback.commit();
     } else {
       callback.rollback();
     }
   }
   callbacks.clear();
 }
 /**
  * pathway overlap
  *
  * @param source
  * @param target
  * @return HashSet<String>
  */
 public static HashSet<String> pathwayOverlap(HashSet<String> source, HashSet<String> target) {
   HashSet<String> inter = new HashSet<String>();
   for (String s : source) {
     inter.add(s);
   }
   inter.retainAll(target);
   return inter;
 }
Ejemplo n.º 5
0
  public Row join(Row pRow, String pField) {
    // dbgMsg("Join!");
    RowFormat newFormat = mFormat.join(pRow.mFormat, pField);
    Row newRow = (Row) newFormat.getRowFactory().makeRow();
    // String[] ourFieldNames = mFormat.getFieldNames();
    // String[] theirFieldNames =pRow.mFormat.getFieldNames();
    // dbgMsg("ourFieldNames="+StringUtils.arrayToString(ourFieldNames, ", "));
    // dbgMsg("theirFieldNames="+StringUtils.arrayToString(theirFieldNames, ", "));

    HashSet ourFields = new HashSet(Arrays.asList(mFormat.getFieldNames()));
    HashSet theirFields = new HashSet(Arrays.asList(pRow.mFormat.getFieldNames()));
    ourFields.remove(pField);
    theirFields.remove(pField);
    HashSet commonFields = new HashSet(ourFields);
    commonFields.retainAll(theirFields);
    ourFields.removeAll(commonFields);
    theirFields.removeAll(commonFields);

    // dbgMsg("join field "+pField);
    // dbgMsg("our fields: "+StringUtils.collectionToString(ourFields, " "));
    // dbgMsg("their fields: "+StringUtils.collectionToString(theirFields, " "));
    // dbgMsg("common fields: "+StringUtils.collectionToString(commonFields, " "));

    // copy join field
    newRow.set(pField, get(pField)); // (copied arbitrarily from...us, as should be same!)

    // copy our fields
    Iterator ourFieldsIter = ourFields.iterator();
    while (ourFieldsIter.hasNext()) {
      String field = (String) ourFieldsIter.next();
      newRow.set(field, (get(field)));
    }

    // copy their fields
    Iterator theirFieldsIter = theirFields.iterator();
    while (theirFieldsIter.hasNext()) {
      String field = (String) theirFieldsIter.next();
      newRow.set(field, (pRow.get(field)));
    }

    // copy common fields (renaming fields becomes necessary)
    Iterator commonFieldsIter = commonFields.iterator();
    while (commonFieldsIter.hasNext()) {
      String field = (String) commonFieldsIter.next();
      newRow.set(field + "1", (get(field)));
      newRow.set(field + "2", (pRow.get(field)));
    }

    return newRow;
  }
Ejemplo n.º 6
0
  /**
   * Find the closest common superclass of multiple classes
   *
   * @param cs
   * @return
   */
  @SuppressWarnings("rawtypes")
  public static Class FindCommonSuperclass(Class[] cs) {
    if (cs.length == 0) {
      return Object.class;
    } else if (cs.length == 1) {
      return cs[0];
    }

    // if any items fail getSuperclass in the passed in array,
    // simply return object.
    boolean isSame = true;
    boolean hasNullSuperclass = false;
    for (Class c : cs) {
      if (c == null) throw new NullPointerException();
      if (c != cs[0]) isSame = false;
      if (c.getSuperclass() == null) hasNullSuperclass = true;
    }
    // no need to do further calculations.. all the same
    if (isSame) return cs[0];
    // at least one item in the list failed getSuperclass... return object
    if (hasNullSuperclass) return Object.class;

    Class c1 = cs[0];
    Class c2 = null;
    HashSet<Class> s1 = new HashSet<>();
    HashSet<Class> s2 = new HashSet<>();

    for (int i = 1; i < cs.length; i++) {
      s1.clear();
      s2.clear();
      c2 = cs[i];

      do {
        s1.add(c1);
        s2.add(c2);
        if (c1 != Object.class) {
          c1 = c1.getSuperclass();
        }
        if (c2 != Object.class) {
          c2 = c2.getSuperclass();
        }
      } while (Collections.disjoint(s1, s2));

      s1.retainAll(s2);
      c1 = s1.iterator().next(); // there can only be one
      if (c1 == Object.class) break; // no superclass above object
    }
    return c1;
  }
  public static void main(String[] args) {

    ConsumerTool consumerTool = new ConsumerTool();
    String[] unknown = CommandLineSupport.setOptions(consumerTool, args);
    HashSet<String> set1 = new HashSet<String>(Arrays.asList(unknown));

    ProducerTool producerTool = new ProducerTool();
    unknown = CommandLineSupport.setOptions(producerTool, args);
    HashSet<String> set2 = new HashSet<String>(Arrays.asList(unknown));

    set1.retainAll(set2);
    if (set1.size() > 0) {
      System.out.println("Unknown options: " + set1);
      System.exit(-1);
    }

    consumerTool.run();
    producerTool.run();
  }
  /** Test extended and built in formats. */
  @Test
  public void testExtendedAndBuiltInFormats() {
    final Calendar cal = Calendar.getInstance();
    cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
    final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
    final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
    final String extendedPattern = "Name: {0,upper} ";
    final String pattern = extendedPattern + builtinsPattern;

    final HashSet<Locale> testLocales = new HashSet<Locale>();
    testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales()));
    testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
    testLocales.add(null);

    for (final Locale locale : testLocales) {
      final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
      final String expectedPattern = extendedPattern + builtins.toPattern();
      DateFormat df = null;
      NumberFormat nf = null;
      ExtendedMessageFormat emf = null;
      if (locale == null) {
        df = DateFormat.getDateInstance(DateFormat.SHORT);
        nf = NumberFormat.getCurrencyInstance();
        emf = new ExtendedMessageFormat(pattern, registry);
      } else {
        df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        nf = NumberFormat.getCurrencyInstance(locale);
        emf = new ExtendedMessageFormat(pattern, locale, registry);
      }
      final StringBuilder expected = new StringBuilder();
      expected.append("Name: ");
      expected.append(args[0].toString().toUpperCase());
      expected.append(" DOB: ");
      expected.append(df.format(args[1]));
      expected.append(" Salary: ");
      expected.append(nf.format(args[2]));
      assertPatternsEqual(
          "pattern comparison for locale " + locale, expectedPattern, emf.toPattern());
      assertEquals(String.valueOf(locale), expected.toString(), emf.format(args));
    }
  }
Ejemplo n.º 9
0
  private void visitObjModel(IObject objModel) {
    // A reference to a design model is used to check whether a potential
    // decorator extends or implements one of its constructor parameter
    // types.
    if (designModel == null) return;

    // Build up a set of components that the object may decorate.
    HashSet<String> possibleComponents = new HashSet<String>();

    // The object may decorate one of its constructor parameter types.
    for (IMethod m : objModel.getAllMethodModels()) {
      if (m.isConstructor() && (m.getAccessLevel() == AccessLevel.Public)
          || (m.getAccessLevel() == AccessLevel.Protected)) {
        Collection<String> paramTypes = Arrays.asList(m.getParamTypeNames());
        possibleComponents.addAll(paramTypes);
      }
    }

    // The object may decorate a type if the object extends or implements
    // the type. (This assumes that a class cannot decorate itself. This may
    // not be correct.)
    possibleComponents.remove(objModel.getName());
    List<String> possibleComponentsList = new ArrayList<String>(possibleComponents);
    for (String possibleComp : possibleComponentsList) {
      if (!designModel.isSubType(objModel.getName(), possibleComp)) {
        possibleComponents.remove(possibleComp);
      }
    }

    // The object may decorate a type if it also has a field of that type.
    Set<String> fieldTypes = new HashSet<String>();
    for (IField field : objModel.getAllFieldModels()) {
      fieldTypes.add(field.getTypeName());
    }
    possibleComponents.retainAll(fieldTypes);

    // Record the components that this object decorates.
    if (!possibleComponents.isEmpty()) {
      decoratorToComponents.put(objModel.getName(), possibleComponents);
    }
  }
Ejemplo n.º 10
0
    Match(Set<String> parameterNames, M method) {
      this.method = method;

      // The number of matched parameters
      HashSet<String> a = new HashSet<String>(parameterNames);
      a.retainAll(getParameterNames(method));
      this.score1 = a.size();

      // The number of unmatched arguments
      a = new HashSet<String>(getParameterNames(method));
      a.removeAll(parameterNames);
      this.score2 = a.size();

      // The number of unmatched parameters
      a = new HashSet<String>(parameterNames);
      a.removeAll(getParameterNames(method));
      this.score3 = a.size();

      // The default method
      this.score4 = isDefault(method) ? 0 : 1;
    }
Ejemplo n.º 11
0
 public Arc(Node n0, Node n1) {
   if (n0 != n1) {
     // create separator
     /*
      * if (n0.mb.bucket == n1.mb.bucket)
      * separator.add(n0.mb.bucket.bucketNode); else {
      */
     separator = (HashSet<BeliefNode>) n0.nodes.clone();
     separator.retainAll(n1.nodes);
     // }
     // arc informations
     nodes.add(n0);
     nodes.add(n1);
     n0.addArc(n1, this);
     n1.addArc(n0, this);
     outMessage.put(n0, new HashSet<MessageFunction>());
     outMessage.put(n1, new HashSet<MessageFunction>());
     outCPTMessage.put(n0, new HashSet<BeliefNode>());
     outCPTMessage.put(n1, new HashSet<BeliefNode>());
   } else throw new RuntimeException("1-node loop in graph");
 }
  @Override
  public void onReferencesBuild(RefElement refElement) {
    if (refElement instanceof RefClass) {
      final PsiClass psiClass = (PsiClass) refElement.getElement();
      if (psiClass != null) {

        if (refElement.isEntry()) {
          ((RefClassImpl) refElement).setFlag(false, CAN_BE_FINAL_MASK);
        }

        PsiMethod[] psiMethods = psiClass.getMethods();
        PsiField[] psiFields = psiClass.getFields();

        HashSet<PsiVariable> allFields = new HashSet<PsiVariable>();
        ContainerUtil.addAll(allFields, psiFields);
        ArrayList<PsiVariable> instanceInitializerInitializedFields = new ArrayList<PsiVariable>();
        boolean hasInitializers = false;
        for (PsiClassInitializer initializer : psiClass.getInitializers()) {
          PsiCodeBlock body = initializer.getBody();
          hasInitializers = true;
          ControlFlow flow;
          try {
            flow =
                ControlFlowFactory.getInstance(body.getProject())
                    .getControlFlow(
                        body, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false);
          } catch (AnalysisCanceledException e) {
            flow = ControlFlow.EMPTY;
          }
          Collection<PsiVariable> writtenVariables = new ArrayList<PsiVariable>();
          ControlFlowUtil.getWrittenVariables(flow, 0, flow.getSize(), false, writtenVariables);
          for (PsiVariable psiVariable : writtenVariables) {
            if (allFields.contains(psiVariable)) {
              if (instanceInitializerInitializedFields.contains(psiVariable)) {
                allFields.remove(psiVariable);
                instanceInitializerInitializedFields.remove(psiVariable);
              } else {
                instanceInitializerInitializedFields.add(psiVariable);
              }
            }
          }
          for (PsiVariable psiVariable : writtenVariables) {
            if (!instanceInitializerInitializedFields.contains(psiVariable)) {
              allFields.remove(psiVariable);
            }
          }
        }

        for (PsiMethod psiMethod : psiMethods) {
          if (psiMethod.isConstructor()) {
            PsiCodeBlock body = psiMethod.getBody();
            if (body != null) {
              hasInitializers = true;
              ControlFlow flow;
              try {
                flow =
                    ControlFlowFactory.getInstance(body.getProject())
                        .getControlFlow(
                            body, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false);
              } catch (AnalysisCanceledException e) {
                flow = ControlFlow.EMPTY;
              }

              Collection<PsiVariable> writtenVariables =
                  ControlFlowUtil.getWrittenVariables(flow, 0, flow.getSize(), false);
              for (PsiVariable psiVariable : writtenVariables) {
                if (instanceInitializerInitializedFields.contains(psiVariable)) {
                  allFields.remove(psiVariable);
                  instanceInitializerInitializedFields.remove(psiVariable);
                }
              }
              List<PsiMethod> redirectedConstructors =
                  HighlightControlFlowUtil.getChainedConstructors(psiMethod);
              if (redirectedConstructors == null || redirectedConstructors.isEmpty()) {
                List<PsiVariable> ssaVariables = ControlFlowUtil.getSSAVariables(flow);
                ArrayList<PsiVariable> good = new ArrayList<PsiVariable>(ssaVariables);
                good.addAll(instanceInitializerInitializedFields);
                allFields.retainAll(good);
              } else {
                allFields.removeAll(writtenVariables);
              }
            }
          }
        }

        for (PsiField psiField : psiFields) {
          if ((!hasInitializers || !allFields.contains(psiField))
              && psiField.getInitializer() == null) {
            final RefFieldImpl refField = (RefFieldImpl) myManager.getReference(psiField);
            if (refField != null) {
              refField.setFlag(false, CAN_BE_FINAL_MASK);
            }
          }
        }
      }
    } else if (refElement instanceof RefMethod) {
      final RefMethod refMethod = (RefMethod) refElement;
      if (refMethod.isEntry()) {
        ((RefMethodImpl) refMethod).setFlag(false, CAN_BE_FINAL_MASK);
      }
    }
  }
Ejemplo n.º 13
0
  @Override
  protected Object doExecute() throws Exception {
    OsgiModuleRegistry registry = Activator.registry;
    List<ModuleRegistry.Module> modules = registry.getApplicationModules();
    Map<VersionedDependencyId, Bundle> installed = registry.getInstalled();
    for (ModuleRegistry.Module module : modules) {
      if (name.equals(module.getName())) {
        HashSet<VersionedDependencyId> s =
            new HashSet<VersionedDependencyId>(module.getVersionIds());
        s.retainAll(installed.keySet());
        boolean isInstalled = !s.isEmpty();
        if (isInstalled && !force) {
          throw new Exception("The module is already installed");
        }

        ModuleRegistry.VersionedModule versionedModule = null;
        if (version != null) {
          versionedModule = module.getVersions().get(version);
          if (versionedModule == null) {
            throw new Exception("Invalid version: " + version);
          }
        } else {
          versionedModule = module.latest();
        }

        VersionedDependencyId id = versionedModule.getId();
        String v = version != null ? version : id.getVersion();

        List<String> extensionAdjustments = Arrays.asList(extensions);
        if (!extensionAdjustments.isEmpty()) {
          List<String> enabled = new ArrayList<String>(versionedModule.getDefaultExtensions());
          for (String adjustment : extensionAdjustments) {
            if (adjustment.startsWith("+")) {
              String name = adjustment.substring(1);
              enabled.add(name);
            } else if (adjustment.startsWith("-")) {
              String name = adjustment.substring(1);
              enabled.remove(name);
            } else {
              throw new IllegalArgumentException(
                  "Expected extension argument '"
                      + adjustment
                      + "' to be prefixed with '+' or '-'");
            }
          }
          versionedModule.setEnabledExtensions(enabled);
          if (!enabled.isEmpty()) {
            println("Enabling extensions: " + join(enabled, ", "));
          }
        }
        //

        String url =
            "fab:mvn:"
                + id.getGroupId()
                + "/"
                + id.getArtifactId()
                + "/"
                + v
                + "/"
                + id.getExtension()
                + (id.getClassifier() == null ? "" : "/" + id.getClassifier());

        println("Installing: " + url);

        Bundle bundle = install(url);
        if (bundle != null) {
          println("Installed bundle: %d", bundle.getBundleId());
          if (!noStart) {
            bundle.start();
          }
        }
      }
    }

    return null;
  }
Ejemplo n.º 14
0
 @DSLMethod(production = "p0  ⋂  p1")
 public Set intersection(Set a, Set b) {
   HashSet set = new HashSet(a);
   set.retainAll(b);
   return set;
 }
Ejemplo n.º 15
0
  // Given two input synsets, finds the least common subsumer (LCS) of them.
  // If there are multiple candidates for the LCS (due to multiple inheritance in WordNet), the LCS
  // with the
  // greatest depth is chosen (i.e., the candidate whose shortest path to the root is the longest).
  public HashSet<ISynsetID> getLCSbyDepth(ISynset synset1, ISynset synset2, String pos) {
    HashSet<ISynsetID> lcs = new HashSet<ISynsetID>();

    if (synset1.equals(synset2)) {
      HashSet<ISynsetID> identity = new HashSet<ISynsetID>();
      identity.add(synset1.getID());
      return (identity);
    }
    // !!! could be <roots>, in which case there is no subsumer !!!
    double d1 = getSynsetDepth(synset1, pos);
    double d2 = getSynsetDepth(synset2, pos);
    if (d1 == 0.0 && d2 == 0.0) {
      return (lcs); // !!! return empty set !!!
    }
    // !!! *1* of them could be a <root>, in which case there is no subsumer !!!
    // double d1 = getSynsetDepth(synset1, pos);
    // double d2 = getSynsetDepth(synset2, pos);
    if (d1 == 0.0 || d2 == 0.0) {
      if (d1 == 0.0) {
        lcs.add(synset1.getID());
      }
      if (d2 == 0.0) {
        lcs.add(synset2.getID());
      }
      return (lcs); // !!! return !!!
    }
    TreeMap<Integer, HashSet<ISynsetID>> map = new TreeMap<Integer, HashSet<ISynsetID>>();
    // synset 1 <hypernyms>
    HashSet<ISynsetID> s1 = new HashSet<ISynsetID>();
    s1.add(synset1.getID());
    HashSet<ISynsetID> h1 = new HashSet<ISynsetID>();
    getHypernyms(s1, h1); // i.e. fill 'h1' with <hypernyms> of synset1
    // synset 2 <hypernyms>
    HashSet<ISynsetID> s2 = new HashSet<ISynsetID>();
    s2.add(synset2.getID());
    HashSet<ISynsetID> h2 = new HashSet<ISynsetID>();
    getHypernyms(s2, h2); // i.e. fill 'h2' with <hypernyms> of synset2
    h1.retainAll(h2);
    // System.out.println(h1);
    for (ISynsetID h : h1) {
      // System.out.println(dict.getSynset(h));
      // System.out.println(h + "\t\t\t" + getSynsetDepth(h.getOffset(), pos));
      TreeMap<Integer, HashSet<ISynsetID>> set = getSynsetDepth(h.getOffset(), pos);
      for (Integer i : set.keySet()) {

        HashSet<ISynsetID> subset = set.get(i);
        // EasyIn.pause(h + "\t" + i + "\t<" + subset + ">");
        if (map.containsKey(i)) {
          HashSet<ISynsetID> store = map.get(i);
          store.add(h);
          map.put(i, store);
        } else {
          HashSet<ISynsetID> store = new HashSet<ISynsetID>();
          store.add(h);
          map.put(i, store);
        }
      }
    }
    int key = map.lastKey();
    lcs = map.get(key);
    return (lcs);
  }
Ejemplo n.º 16
0
 /**
  * Returns the intersection between this mapping and that.
  *
  * @param that The mapping to be intersected to this mapping.
  * @return The intersection bewteen this and that.
  */
 public Alignment getIntersection(Alignment that) {
   HashSet<Correspondence> thisCSet = this.getCorrespondencesAsSet();
   HashSet<Correspondence> thatCSet = that.getCorrespondencesAsSet();
   thisCSet.retainAll(thatCSet);
   return (new Alignment(thisCSet));
 }