Example #1
1
  public int count(int b1, int q1, int n1, int b2, int q2, int n2) {
    if (b2 == 0 || q2 <= 1) {
      int tb = b1;
      int tq = q1;
      int tn = n1;
      b1 = b2;
      q1 = q2;
      n1 = n2;
      b2 = tb;
      q2 = tq;
      n2 = tn;
    }

    if (b1 == 0 || q1 <= 1) {
      HashSet<Integer> set = new HashSet<Integer>();
      set.add(b1);
      if (n1 > 1) {
        set.add(b1 * q1);
      }

      long curr = b2;
      for (int i = 0; i < n2; i++) {
        set.add((int) curr);
        curr *= q2;
        if (curr > 500000000) {
          return (n2 - i - 1) + set.size();
        }
      }

      return set.size();
    } else {
      HashSet<String> set = new HashSet<String>();

      int factors[] = findFactors(b1, q1, b2, q2);
      int repb1[] = decompose(b1, factors);
      int repb2[] = decompose(b2, factors);
      int repq1[] = decompose(q1, factors);
      int repq2[] = decompose(q2, factors);

      for (int i = 0; i < n1; i++) {
        set.add(Arrays.toString(repb1));
        for (int j = 0; j < repb1.length; j++) {
          repb1[j] += repq1[j];
        }
      }

      for (int i = 0; i < n2; i++) {
        set.add(Arrays.toString(repb2));
        for (int j = 0; j < repb2.length; j++) {
          repb2[j] += repq2[j];
        }
      }

      return set.size();
    }
  }
Example #2
0
 // experimental - repell only top. neighbourhood
 void layoutRepNeighbors(float strength, float offset, Net net2) {
   Vector3D dist = new Vector3D();
   for (Node a : net2.fNodes) {
     HashSet<Node> tmp = new HashSet<Node>();
     for (Node a1 : a.adList) {
       if (net2.fNodes.contains(a1)) tmp.add(a1);
     }
     for (Node a1 : a.inList) {
       if (net2.fNodes.contains(a1)) tmp.add(a1);
     }
     if (tmp.size() > 1 && tmp.size() < 5) {
       for (Node b : tmp) {
         for (Node c : tmp) {
           if (b != c
               && net2.fNodes.contains(b)
               && net2.fNodes.contains(c)
               && !b.adList.contains(c)
               && !c.adList.contains(b)) {
             dist.setXYZ(c.pos);
             dist.sub(b.pos);
             float d = dist.magnitude();
             float radius = 2 * calcDist(a, b, offset, app.getVal()) / tmp.size();
             if (d < radius) {
               dist.mult((1 - (d / radius)) * strength);
               c.pos.add(dist);
               b.pos.sub(dist);
             }
           }
         }
       }
     }
   }
 }
Example #3
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;
  }
Example #4
0
  @Test
  public void validateGenerate_1() {
    Permutatie iterate = new Permutatie();
    int[] first = new int[100]; // Test 1000 numbers using algoritme 1
    int[] second = new int[100]; // Test 1000 numbers using algoritme 1
    int[] third = new int[100]; // Test 1000 numbers using algoritme 1
    iterate.permutate_1(first);
    iterate.permutate_2(second);
    iterate.permutate_3(third);

    HashSet<Integer> first_test = new HashSet<>();
    HashSet<Integer> second_test = new HashSet<>();
    HashSet<Integer> third_test = new HashSet<>();

    /*
     *  Inserting all values of the permutated arrays into the hashset.
     */
    for (int i : first) {
      first_test.add(i);
    }
    for (int i : second) {
      second_test.add(i);
    }
    for (int i : third) {
      third_test.add(i);
    }
    /*
     * If the size of the hastset which contains only unique elements differs from the array,it means that the algoritme messed up
     */

    Assert.assertEquals(first.length, first_test.size());
    Assert.assertEquals(second.length, second_test.size());
    Assert.assertEquals(third.length, third_test.size());
  }
Example #5
0
  private void updateHiliteFilter() {
    // legal states false,false true,false false, true
    assert (m_showHilitedOnly && (m_showUnhilitedOnly != true));

    if (!m_showHilitedOnly && !m_showUnhilitedOnly) {
      // show all
      m_hiliteFilter.clear();
    } else if (m_showHilitedOnly) {
      // only hilited
      final HashSet<String> filterSet = new HashSet<String>();
      if ((m_hilitedLabels != null) && (m_hilitedLabels.size() > 0)) {
        for (final L o : m_regions.getExistingLabels()) {
          if (!m_hilitedLabels.contains(o.toString())) {
            filterSet.add(o.toString());
          }
        }
      } else {
        for (final L o : m_regions.getExistingLabels()) {
          filterSet.add(o.toString());
        }
      }
      m_hiliteFilter.setFilterSet(filterSet);
    } else {
      // only unhilited
      if ((m_hilitedLabels != null) && (m_hilitedLabels.size() > 0)) {
        m_hiliteFilter.setFilterSet((HashSet<String>) m_hilitedLabels.clone());
      } else {
        m_hiliteFilter.clear();
      }
    }
  }
Example #6
0
  @Test
  public void doTest() {
    setPrimes(TEMP);

    HashSet<BigInteger> f = new HashSet<BigInteger>();
    BigInteger temp = new BigInteger("70000");
    while (true) {
      f = getFactors(temp);
      if (f.size() == 4) {
        f = getFactors(temp.add(ONE));
        if (f.size() == 4) {
          f = getFactors(temp.add(TWO));
          if (f.size() == 4) {
            f = getFactors(temp.add(THREE));
            if (f.size() == 4) {
              System.out.println(temp);
              break;
            }
          }
        }
      }
      temp = temp.add(ONE);
      if (temp.compareTo(new BigInteger("143050")) == 1) break;
      if (temp.compareTo(new BigInteger("80000")) == 1) break;
    }
  }
  /**
   * Run some random insertions/ deletions and compare the results against <code>java.util.HashSet
   * </code>.
   */
  @Test
  public void testAgainstHashMap() {
    final java.util.Random rnd = new java.util.Random(0x11223344);
    final java.util.HashSet<Integer> other = new java.util.HashSet<Integer>();

    for (int size = 1000; size < 20000; size += 4000) {
      other.clear();
      set.clear();

      for (int round = 0; round < size * 20; round++) {
        Integer key = rnd.nextInt(size);

        if (rnd.nextBoolean()) {
          assertEquals(other.add(key), set.add(key));
          assertTrue(set.contains(key));
        } else {
          assertEquals(other.remove(key), set.remove(key));
        }

        assertEquals(other.size(), set.size());
      }

      int[] actual = set.toArray();
      int[] expected = new int[other.size()];
      int i = 0;
      for (Integer v : other) expected[i++] = v;
      Arrays.sort(expected);
      Arrays.sort(actual);
      assertArrayEquals(expected, actual);
    }
  }
Example #8
0
 @Override
 public boolean okMessage(final Environmental myHost, final CMMsg msg) {
   if ((affected != null)
       && (((msg.target() instanceof Room) && (msg.targetMinor() == CMMsg.TYP_ENTER))
           || ((msg.target() instanceof Rideable) && (msg.targetMinor() == CMMsg.TYP_SIT)))
       && ((msg.amITarget(affected)) || (msg.tool() == affected) || (affected instanceof Area))
       && (!CMLib.flags().isFalling(msg.source()))) {
     final HashSet<MOB> H = new HashSet<MOB>();
     if (noFollow) H.add(msg.source());
     else {
       msg.source().getGroupMembers(H);
       int hsize = 0;
       while (hsize != H.size()) {
         hsize = H.size();
         final HashSet H2 = (HashSet) H.clone();
         for (final Iterator e = H2.iterator(); e.hasNext(); ) {
           final Object O = e.next();
           if (O instanceof MOB) ((MOB) O).getRideBuddies(H);
         }
       }
     }
     for (final Object O : H) {
       if ((!(O instanceof MOB)) || (passesMuster((MOB) O))) return super.okMessage(myHost, msg);
     }
     msg.source().tell(L("You are not allowed in there."));
     return false;
   }
   return super.okMessage(myHost, msg);
 }
Example #9
0
  void filterServiceEventReceivers(
      final ServiceEvent evt, final Collection /*<ServiceListenerEntry>*/ receivers) {
    ArrayList srl = fwCtx.services.get(EventHook.class.getName());
    if (srl != null) {
      HashSet ctxs = new HashSet();
      for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
        ctxs.add(((ServiceListenerEntry) ir.next()).getBundleContext());
      }
      int start_size = ctxs.size();
      RemoveOnlyCollection filtered = new RemoveOnlyCollection(ctxs);

      for (Iterator i = srl.iterator(); i.hasNext(); ) {
        ServiceReferenceImpl sr = ((ServiceRegistrationImpl) i.next()).reference;
        EventHook eh = (EventHook) sr.getService(fwCtx.systemBundle);
        if (eh != null) {
          try {
            eh.event(evt, filtered);
          } catch (Exception e) {
            fwCtx.debug.printStackTrace(
                "Failed to call event hook  #" + sr.getProperty(Constants.SERVICE_ID), e);
          }
        }
      }
      // NYI, refactor this for speed!?
      if (start_size != ctxs.size()) {
        for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
          if (!ctxs.contains(((ServiceListenerEntry) ir.next()).getBundleContext())) {
            ir.remove();
          }
        }
      }
    }
  }
  private String buildSql(
      HashSet<String> pk_cumandoc,
      HashSet<String> cproductid,
      HashSet<String> cbiztypeid,
      String temptable) {
    StringBuffer where = new StringBuffer();
    String table = null;
    if (pk_cumandoc.size() > 0) {
      table = temptable;
      where.append(
          GeneralSqlString.formInSQL("pk_cumandoc", pk_cumandoc.toArray(new String[0]), table));
    }
    if (cproductid.size() > 0) {
      table = temptable + "b1";
      where.append(
          GeneralSqlString.formInSQL("cproductid", cproductid.toArray(new String[0]), table));
    }
    if (cbiztypeid.size() > 0) {
      table = temptable + "b2";
      where.append(
          GeneralSqlString.formInSQL("cbiztypeid", cbiztypeid.toArray(new String[0]), table));
    }

    if (where.length() > 4) return where.substring(4);
    else return where.toString();
  }
Example #11
0
  public void getTopics(
      ArrayList<HashSet<String>> aTopics, String argKey, double threshold, int num) {
    ArrayList<JObjectDoubleTuple<String>> aTA;
    Prob2dMap pTA, pAT;
    HashSet<String> topics, clone;

    outer:
    for (String id : m_ta.keySet()) {
      pTA = m_ta.get(id);
      pAT = m_at.get(id);
      if ((aTA = pTA.getProb1dList(argKey)) == null) continue;
      topics = new HashSet<String>();

      for (JObjectDoubleTuple<String> tup : aTA) {
        tup.value *= pAT.get1dProb(tup.object, argKey);
        if (tup.value >= threshold) topics.add(tup.object);
      }

      if (topics.size() >= num) {
        for (HashSet<String> pSet : aTopics) {
          clone = new HashSet<String>(topics);
          clone.removeAll(pSet);

          if (clone.size() < num) continue outer;
        }

        aTopics.add(topics);
      }
    }
  }
Example #12
0
  /*method to compare the output of relationships generated from the system and expert knowledge*/
  private void compareOutputRelations() {
    ClassRelation expertRelation;
    ClassRelation machineRelation;

    relationship_Expert_Count = expertOutputRelations.size();
    totalRelation_Machine_Count = machineOutputRelations.size();

    for (Object expertRelationShipItem : expertOutputRelations) {
      expertRelation = (ClassRelation) expertRelationShipItem;
      if (expertRelation != null) {
        for (Object machineRelationShipItem : machineOutputRelations) {
          machineRelation = (ClassRelation) machineRelationShipItem;
          if (expertRelation
              .getRelationType()
              .equalsIgnoreCase(machineRelation.getRelationType())) {
            if (expertRelation
                .getParentElement()
                .equalsIgnoreCase(machineRelation.getParentElement())) {
              if (expertRelation
                  .getChildElement()
                  .equalsIgnoreCase(machineRelation.getChildElement())) {
                relationship_Machine_Count++;
              }
            }
          }
        }
      }
    }
  }
  public void PrintCrawlingInformation(long timeDuration) {
    PrintQuestionNumber(1);
    System.out.println("Time spent: " + timeDuration + " seconds");

    PrintQuestionNumber(2);
    System.out.println("Number of unique pages:" + visitedURLs.size());

    PrintQuestionNumber(3);
    System.out.println("Number of subdomains:" + subdomains.size());

    List<Map.Entry<String, Integer>> subdomain_Sorted_List =
        new ArrayList<Map.Entry<String, Integer>>(subdomain_List.entrySet());
    Collections.sort(subdomain_Sorted_List, new subdomainComparor());
    for (int i = 0; i < subdomain_Sorted_List.size(); i++) {
      Map.Entry<String, Integer> entry = subdomain_Sorted_List.get(i);
      System.out.println(entry.getKey() + ".uci.edu, " + entry.getValue());
    }

    PrintQuestionNumber(4);
    PrintLongestPage();

    PrintQuestionNumber(5);
    tokenizer.PrintTopWordFrequencies(500);

    PrintQuestionNumber(6);
    tokenizer.PrintTwoGramFrequencies(20);
  }
 /**
  * calculate the gene set similarity using the data given
  *
  * @param source
  * @param target
  * @param dataIn
  * @return
  */
 public double geneSetSim(
     HashSet<String> source, HashSet<String> target, HashMap<String, Double> dataIn) {
   double d = 0.0;
   HashMap<String, Double> back = new HashMap<String, Double>();
   for (int i = 0; i < source.size(); i++) {
     Object[] obj = source.toArray();
     double tmp = 0.0;
     for (int j = 0; j < target.size(); j++) {
       Object objt = target.toArray()[j];
       String key = obj[i].toString() + "->" + objt.toString();
       if (dataIn.keySet().contains(key)) {
         tmp = Math.max(tmp, dataIn.get(key).doubleValue());
         // 存储当前j所在基因的最大相似值
         Double dobj =
             back.containsKey(objt.toString())
                 ? Double.valueOf(
                     Math.max(
                         back.get(objt.toString()).doubleValue(), dataIn.get(key).doubleValue()))
                 : dataIn.get(key);
         back.put(objt.toString(), dobj);
       }
     }
     d += tmp;
   }
   for (String s : back.keySet()) {
     d += back.get(s).doubleValue();
   }
   return d / (source.size() + target.size() + 0.0001);
 }
Example #15
0
    private String fixTypes2(
        ArrayList<TypeVar> scc, HashSet<String> lowersSet, org.hotswap.agent.javassist.ClassPool cp)
        throws org.hotswap.agent.javassist.NotFoundException {
      Iterator<String> it = lowersSet.iterator();
      if (lowersSet.size() == 0) {
        return null; // only NullType
      } else if (lowersSet.size() == 1) {
        return it.next();
      } else {
        org.hotswap.agent.javassist.CtClass cc = cp.get(it.next());
        while (it.hasNext()) {
          cc = commonSuperClassEx(cc, cp.get(it.next()));
        }

        if (cc.getSuperclass() == null || isObjectArray(cc)) {
          cc = fixByUppers(scc, cp, new HashSet<TypeVar>(), cc);
        }

        if (cc.isArray()) {
          return org.hotswap.agent.javassist.bytecode.Descriptor.toJvmName(cc);
        } else {
          return cc.getName();
        }
      }
    }
  /** Find all methods in this framework which raise SQLFeatureNotSupportedException. */
  public void testSupportedMethods() throws Exception {
    getTestConfiguration().setVerbosity(true);

    HashSet<String> vanishedMethodList = new HashSet<String>();
    HashSet<String> unsupportedList = new HashSet<String>();
    HashSet<String> notUnderstoodList = new HashSet<String>();

    // Build map of interfaces to their methods which may raise SQLFeatureNotSupportedException.
    initializeExcludableMap(vanishedMethodList);

    vetDataSource(unsupportedList, notUnderstoodList);
    vetConnectionPooledDataSource(unsupportedList, notUnderstoodList);
    vetXADataSource(unsupportedList, notUnderstoodList);

    //
    // Print methods which behave unexpectedly.
    //
    printVanishedMethodList(vanishedMethodList);
    printUnsupportedList(unsupportedList);
    printNotUnderstoodList(notUnderstoodList);

    int actualErrorCount =
        vanishedMethodList.size() + unsupportedList.size() + notUnderstoodList.size();

    assertEquals("Unexpected discrepancies.", 0, actualErrorCount);
  }
Example #17
0
  static void runTest(HashSet<Integer> caseSet) {
    int cases = 0, passed = 0;
    while (true) {
      String label = Reader.nextLine();
      if (label == null || !label.startsWith("--")) break;

      int N = Integer.parseInt(Reader.nextLine());
      Reader.nextLine();
      double __answer = Double.parseDouble(Reader.nextLine());

      cases++;
      if (caseSet.size() > 0 && !caseSet.contains(cases - 1)) continue;
      System.err.print(String.format("  Testcase #%d ... ", cases - 1));

      if (doTest(N, __answer)) passed++;
    }
    if (caseSet.size() > 0) cases = caseSet.size();
    System.err.println(String.format("%nPassed : %d/%d cases", passed, cases));

    int T = (int) (System.currentTimeMillis() / 1000) - 1398529188;
    double PT = T / 60.0, TT = 75.0;
    System.err.println(
        String.format(
            "Time   : %d minutes %d secs%nScore  : %.2f points",
            T / 60, T % 60, 950 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT))));
  }
  @Test
  public void readTest() {
    String insertKey = "user0";
    Map<String, ByteIterator> insertMap = insertRow(insertKey);
    HashSet<String> readFields = new HashSet<>();
    HashMap<String, ByteIterator> readResultMap = new HashMap<>();

    // Test reading a single field
    readFields.add("FIELD0");
    orientDBClient.read(CLASS, insertKey, readFields, readResultMap);
    assertEquals(
        "Assert that result has correct number of fields", readFields.size(), readResultMap.size());
    for (String field : readFields) {
      assertEquals(
          "Assert " + field + " was read correctly",
          insertMap.get(field).toString(),
          readResultMap.get(field).toString());
    }

    readResultMap = new HashMap<>();

    // Test reading all fields
    readFields.add("FIELD1");
    readFields.add("FIELD2");
    orientDBClient.read(CLASS, insertKey, readFields, readResultMap);
    assertEquals(
        "Assert that result has correct number of fields", readFields.size(), readResultMap.size());
    for (String field : readFields) {
      assertEquals(
          "Assert " + field + " was read correctly",
          insertMap.get(field).toString(),
          readResultMap.get(field).toString());
    }
  }
  public void testIterable() throws Exception {
    _store.clear();

    // Generate keys
    HashSet<String> keySet = new HashSet<String>(199);
    while (keySet.size() < 100) {
      keySet.add(UUID.randomUUID().toString());
    }
    assertEquals(100, keySet.size());

    // Populate store
    for (String key : keySet) {
      byte[] value = RandomBytes.getBytes();
      _store.put(key.getBytes(), value);
    }

    HashSet<String> keySet2 = new HashSet<String>(199);
    for (Entry<byte[], byte[]> e : _store) {
      keySet2.add(new String(e.getKey()));
    }

    assertEquals(keySet.size(), keySet2.size());

    keySet2.removeAll(keySet);
    assertEquals(0, keySet2.size());
  }
Example #20
0
  /* method to compare the output generated from the system and the expert knowledge*/
  private void compareOutput() {
    boolean classStatus = false;
    Iterator expertIterator = expertOutput.keySet().iterator();
    while (expertIterator.hasNext()) {
      className_Expert = expertIterator.next().toString();
      className_Expert_Count++;

      storingArtefacts_Expert = (StoringArtefacts) expertOutput.get(className_Expert);
      attributeList_Expert = storingArtefacts_Expert.getAttributes();
      methodList_Expert = storingArtefacts_Expert.getMethods();

      // searching className
      classStatus = searchClassName(className_Expert);

      // if class is found in both files search other elements
      if (classStatus) {
        // searchAttributes
        attribute_Expert_Count += attributeList_Expert.size();
        attribute_Machine_Count += searchArtefact(attributeList_Expert, attributeList_Machine);
        System.out.println("attribute Machine count: " + attribute_Machine_Count);
        System.out.println("attribute Expert count: " + attribute_Expert_Count);

        // search method
        method_Expert_Count += methodList_Expert.size();
        method_Machine_Count += searchArtefact(methodList_Expert, methodList_Machine);

        System.out.println("method Machine count: " + method_Machine_Count);
        System.out.println("method Expert count: " + method_Expert_Count);
      }
    }

    System.out.println("class machine count: " + className_Machine_Count);
    System.out.println("class expert count: " + className_Expert_Count);
  }
Example #21
0
  public void computeIndeterminates() {
    HashMap<String, HashSet<PeptideHit>> scan2pep = new HashMap<String, HashSet<PeptideHit>>();
    HashSet<PeptideHit> pepList;

    for (PeptideHit p : peptideHits) {
      String scan = p.getScanTuple();
      if (scan2pep.containsKey(scan)) {
        pepList = scan2pep.get(scan);
      } else {
        pepList = new HashSet<PeptideHit>();
        scan2pep.put(scan, pepList);
      }
      pepList.add(p);
    }
    for (HashSet<PeptideHit> pepSet : scan2pep.values()) {
      boolean indeterm = false;
      if (pepSet.size() > 1) {
        HashSet<String> pepSeqs = new HashSet<String>();
        for (PeptideHit p : pepSet) {
          pepSeqs.add(p.getSequence());
        }
        if (pepSeqs.size() > 1) indeterm = true;
      }
      for (PeptideHit p : pepSet) {
        p.setIndeterminate(indeterm);
      }
    }
  }
Example #22
0
 /** java.util.HashSet#add(java.lang.Object) */
 public void test_addLjava_lang_Object() {
   // Test for method boolean java.util.HashSet.add(java.lang.Object)
   int size = hs.size();
   hs.add(new Integer(8));
   assertTrue("Added element already contained by set", hs.size() == size);
   hs.add(new Integer(-9));
   assertTrue("Failed to increment set size after add", hs.size() == size + 1);
   assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
 }
Example #23
0
  public void process()
      throws CannotReadException, IOException, TagException, ReadOnlyFileException,
          InvalidAudioFrameException {
    artistSet = new HashSet<>();
    albumSet = new HashSet<>();
    yearSet = new HashSet<>();
    nameSet = new ArrayList<>();

    for (File file : fileArray) {
      MP3File mp3file = (MP3File) AudioFileIO.read(file);
      Tag tag = mp3file.getTag();

      if (!tag.getFirst(FieldKey.YEAR).isEmpty()) {
        yearSet.add(tag.getFirst(FieldKey.YEAR));
      }
      if (tag.getFirst(FieldKey.TITLE).isEmpty()) {
        nameSet.add(file.getName());
      } else {
        nameSet.add(tag.getFirst(FieldKey.TITLE));
      }
      if (tag.getFirst(FieldKey.ALBUM).isEmpty()) {
        albumSet.add(file.getParentFile().getName());
      } else {
        albumSet.add(tag.getFirst(FieldKey.ALBUM));
      }
      if (tag.getFirst(FieldKey.ARTIST).isEmpty()) {
        if (file.getParentFile().getParentFile().exists()) {
          artistSet.add(file.getParentFile().getParentFile().getName());
        } else {
          artistSet.add(file.getParentFile().getName());
        }
      } else {
        artistSet.add(tag.getFirst(FieldKey.ARTIST));
      }

      if (tag.getFirst(FieldKey.DISC_NO).isEmpty()) {
        if (file.getParentFile().getName().toLowerCase().contentEquals("cd")) {}

      } else {
        cd = tag.getFirst(FieldKey.DISC_NO);
      }
    }

    if (artistSet.size() == 1) {
      setTypeFlag(1);
    } else if (artistSet.size() == 2) {
      setTypeFlag(2);
    } else if (artistSet.size() > 2) {
      setTypeFlag(3);
    }

    try {
      parse();
    } catch (SQLException ex) {
      Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
 public static double sim(String s1, String s2) {
   HashMap<String, Integer> h1 = Extract.Unique(s1);
   HashMap<String, Integer> h2 = Extract.Unique(s2);
   HashSet<String> hs = Extract.Intersect(h1, h2);
   if (hs.isEmpty()) return 0;
   double up = hs.size();
   double down = h1.size() + h2.size() - hs.size();
   return up / down;
 }
 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {
   if (mCheckedPhoneNumbers.size() > 0 || mLocalGroups.size() > 0 || mVCardNumber != null) {
     menu.findItem(MENU_DONE).setVisible(true);
   } else {
     menu.findItem(MENU_DONE).setVisible(false);
   }
   return super.onPrepareOptionsMenu(menu);
 }
  public void testKeyIndexedIterator() throws Exception {
    IndexedIterator<byte[]> keyIter;

    _store.clear();
    keyIter = _store.keyIterator();
    assertFalse(keyIter.hasNext());

    // Generate keys
    HashSet<String> keySet = new HashSet<String>(199);
    while (keySet.size() < 100) {
      keySet.add(UUID.randomUUID().toString());
    }
    assertEquals(100, keySet.size());

    // Populate store
    for (String key : keySet) {
      byte[] value = RandomBytes.getBytes();
      _store.put(key.getBytes(), value);
    }

    // Check keys
    keyIter = _store.keyIterator();
    byte[] key1a = keyIter.next();

    keyIter.reset(0);
    byte[] key1b = keyIter.next();

    for (int i = 0; i < 10; i++) {
      keyIter.next();
    }
    keyIter.reset(keyIter.index());
    byte[] key1c = keyIter.next();

    assertTrue(Arrays.equals(key1a, key1b));

    // Re-open store
    _store.close();
    _store.open();

    // check keys
    keyIter = _store.keyIterator();
    byte[] key2a = keyIter.next();

    keyIter.reset(0);
    byte[] key2b = keyIter.next();

    for (int i = 0; i < 10; i++) {
      keyIter.next();
    }
    keyIter.reset(keyIter.index());
    byte[] key2c = keyIter.next();

    assertTrue(Arrays.equals(key1a, key2a));
    assertTrue(Arrays.equals(key1b, key2b));
    assertTrue(Arrays.equals(key1c, key2c));
  }
  public static void main(String[] args) throws Exception {
    String graphName = args[0];
    int nShards = Integer.parseInt(args[1]);

    CircleOfTrustSalsa csalsa = new CircleOfTrustSalsa(new VertexQuery(graphName, nShards), 10000);

    VertexIdTranslate vertexTrans =
        VertexIdTranslate.fromFile(
            new File(ChiFilenames.getVertexTranslateDefFile(graphName, nShards)));

    BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
      System.out.print("Enter vertex id to query >> :: ");
      String ln = cmdIn.readLine();
      int vertex = Integer.parseInt(ln);

      // Circle of trust is just the vertex's followers for now
      HashSet<Integer> circle = csalsa.queryService.queryOutNeighbors(vertexTrans.forward(vertex));

      int maxCircleSize = 300;
      // max 500
      if (circle.size() > maxCircleSize) {
        int[] all = new int[circle.size()];
        int i = 0;
        for (Integer v : circle) all[i++] = v;
        HashSet<Integer> filteredCircle = new HashSet<Integer>();
        Random r = new Random(260379);
        for (i = 0; i < maxCircleSize; i++)
          filteredCircle.add(all[Math.abs(r.nextInt()) % all.length]);
        circle = filteredCircle;
      }

      csalsa.initializeGraph(circle);

      long t = System.currentTimeMillis();
      csalsa.computeSALSA(3);
      logger.info("SALSA computation took " + (System.currentTimeMillis() - t) + "ms");

      circle.add(vertexTrans.forward(vertex));
      ArrayList<SalsaVertex> top = csalsa.topAuthorities(20, circle);
      int j = 1;
      for (SalsaVertex sv : top) {
        int originalId = vertexTrans.backward(sv.id);
        logger.info(
            "Top "
                + (j++)
                + " = "
                + originalId
                + " "
                + csalsa.namify(originalId)
                + " ("
                + sv.value
                + ")");
      }
    }
  }
Example #28
0
  /**
   * *************************************************************** Return the most specific type
   * for skolem variable.
   *
   * @param tpp The structure learned from E's response
   * @param kb The knowledge base used to find skolem term's types
   *     <p>For example, original binding = esk3_0 set binding = "An instance of Human" (Human is
   *     the most specific type for esk3_0 in the given proof)
   *     <p>original binding = esk3_1 set binding = "An instance of Human, Agent" (If multiple types
   *     are found for esk3_1)
   */
  public static void findTypesForSkolemTerms(TPTP3ProofProcessor tpp, KB kb) {

    ArrayList<String> bindings = tpp.bindings;
    FormulaPreprocessor fp = new FormulaPreprocessor();
    for (int i = 0; i < bindings.size(); i++) {
      String binding = bindings.get(i);
      if (binding.startsWith("esk")) {
        ArrayList<String> skolemStmts = ProofProcessor.returnSkolemStmt(binding, tpp.proof);
        HashSet<String> types = new HashSet<>();
        for (String skolemStmt : skolemStmts) {
          Pattern p = Pattern.compile("\\(instance ([a-zA-Z0-9\\-_]+) ([a-zA-Z0-9\\-_]+)");
          Matcher m = p.matcher(skolemStmt);
          while (m.find()) {
            String cl = m.group(2);
            types.add(cl);
          }

          p = Pattern.compile("\\(subclass ([a-zA-Z0-9\\-_]+) ([a-zA-Z0-9\\-]+)");
          m = p.matcher(skolemStmt);
          while (m.find()) {
            String cl = m.group(2);
            types.add(cl);
          }
        }
        if (kb.kbCache.checkDisjoint(kb, types) == true) {
          // check if there are contradiction among the types returned from E
          bindings.remove(binding);
          binding = "Get type contradiction for " + binding + " in " + types;
          bindings.add(binding);
        } else {
          fp.winnowTypeList(types, kb);
          if (types != null && types.size() > 0) {
            if (types.size() == 1) {
              binding = "an instance of " + types.toArray()[0];
            } else {
              binding = "an instance of ";
              boolean start = true;
              for (String t : types) {
                if (start) {
                  binding += t;
                  start = false;
                } else {
                  binding += ", " + t;
                }
              }
            }
            bindings.set(i, binding);
          }
        }
      } else {
        binding = TPTP2SUMO.transformTerm(binding);
        bindings.set(i, binding);
      }
    }
  }
 /**
  * Keep only the maximum permitted number of parameters for a connection. Ignoring the rest. This
  * can be extended to create multiple sets to be crawled by different threads.
  */
 private void FilterKeywords(HashSet<String> hashtags) {
   if (hashtags != null) {
     int maxsize = MAX_KEYWORDS;
     if (hashtags.size() < maxsize) {
       maxsize = hashtags.size();
     }
     for (String tag : hashtags) {
       Keywords.add(tag);
     }
   }
 }
 public void testMultipleCollectionsSize() {
   setUpTest();
   HashSet set = new HashSet();
   set.add("a");
   set.add("b");
   c.addComposited(set);
   HashSet other = new HashSet();
   other.add("c");
   c.addComposited(other);
   assertEquals(set.size() + other.size(), c.size());
 }