Пример #1
1
 public int ladderLength1(String beginWord, String endWord, Set<String> wordList) {
   Set<String> startList = new HashSet<String>();
   Set<String> endList = new HashSet<String>();
   startList.add(beginWord);
   endList.add(endWord);
   int result = 1;
   while (!startList.isEmpty() && !endList.isEmpty()) {
     if (startList.size() > endList.size()) {
       Set<String> k = startList;
       startList = endList;
       endList = k;
     }
     Set<String> newSet = new HashSet<String>();
     for (String word : startList) {
       for (int i = 0; i < word.length(); i++) {
         for (char a = 'a'; a <= 'z'; a++) {
           if (a == word.charAt(i)) continue;
           StringBuilder temp = new StringBuilder(word);
           temp.setCharAt(i, a);
           String newString = temp.toString();
           if (endList.contains(newString)) return result + 1;
           if (wordList.contains(newString)) {
             wordList.remove(newString);
             newSet.add(newString);
           }
         }
       }
     }
     startList = newSet;
     result++;
   }
   return 0;
 }
 @Override
 protected void postProcess(Sector.Triangle[] triangles) {
   if (show.contains("triangles")) {
     int i = 0;
     for (Sector.Triangle t : triangles) {
       GeoPoint[] trianglePoints = t.getPoints('A');
       double x = 0, y = 0;
       int l = trianglePoints.length;
       double[] points = new double[l * 2 + 2];
       for (int j = 0; j <= l; j++) {
         Point p = trianglePoints[j % l].toPoint(1000.0);
         points[j * 2] = p.x;
         points[j * 2 + 1] = p.z;
         if (j < l) {
           x += p.x;
           y += p.z;
         }
       }
       x /= l;
       y /= l;
       for (int j = 0; j <= l; j++) {
         points[j * 2] = points[j * 2] * 0.95 + x * 0.05;
         points[j * 2 + 1] = points[j * 2 + 1] * 0.95 + y * 0.05;
       }
       Color color = t.inverted ? triangleInverted : triangleNormal;
       out.addLine(color, points);
       if (show.contains("labels")) {
         out.addLabel(color, "" + i, x, y);
       }
       i++;
     }
   }
   super.postProcess(triangles);
 }
Пример #3
0
 public void testMethodKey() throws Exception {
   MethodKey factory = (MethodKey) KeyFactory.create(MethodKey.class);
   Set methodSet = new HashSet();
   methodSet.add(factory.newInstance(Number.class, new Class[] {int.class}));
   assertTrue(methodSet.contains(factory.newInstance(Number.class, new Class[] {int.class})));
   assertTrue(!methodSet.contains(factory.newInstance(Number.class, new Class[] {Integer.class})));
 }
  /**
   * Creates an NL fragment project along with the locale specific properties files.
   *
   * @throws CoreException
   * @throws IOException
   * @throws InvocationTargetException
   * @throws InterruptedException
   */
  private void internationalizePlugins(List plugins, List locales, Map overwrites)
      throws CoreException, IOException, InvocationTargetException, InterruptedException {

    Set created = new HashSet();

    for (Iterator it = plugins.iterator(); it.hasNext(); ) {
      IPluginModelBase plugin = (IPluginModelBase) it.next();

      for (Iterator iter = locales.iterator(); iter.hasNext(); ) {
        Locale locale = (Locale) iter.next();

        IProject project = getNLProject(plugin, locale);
        if (created.contains(project)
            || overwriteWithoutAsking
            || !project.exists()
            || OVERWRITE == overwrites.get(project.getName())) {
          if (!created.contains(project) && project.exists()) {
            project.delete(true, getProgressMonitor());
          }

          if (!created.contains(project)) {
            createNLFragment(plugin, project, locale);
            created.add(project);
            project.getFolder(RESOURCE_FOLDER_PARENT).create(false, true, getProgressMonitor());
          }

          project
              .getFolder(RESOURCE_FOLDER_PARENT)
              .getFolder(locale.toString())
              .create(true, true, getProgressMonitor());
          createLocaleSpecificPropertiesFile(project, plugin, locale);
        }
      }
    }
  }
Пример #5
0
    @NotNull
    @Override
    public GroovyResolveResult[] getCandidates() {
      if (!hasCandidates()) return GroovyResolveResult.EMPTY_ARRAY;
      final GroovyResolveResult[] results =
          ResolveUtil.filterSameSignatureCandidates(getCandidatesInternal());
      List<GroovyResolveResult> list = new ArrayList<GroovyResolveResult>(results.length);
      myPropertyNames.removeAll(myPreferredFieldNames);

      Set<String> usedFields = ContainerUtil.newHashSet();
      for (GroovyResolveResult result : results) {
        final PsiElement element = result.getElement();
        if (element instanceof PsiField) {
          final String name = ((PsiField) element).getName();
          if (myPropertyNames.contains(name)
              || myLocalVars.contains(name)
              || usedFields.contains(name)) {
            continue;
          } else {
            usedFields.add(name);
          }
        }

        list.add(result);
      }
      return list.toArray(new GroovyResolveResult[list.size()]);
    }
Пример #6
0
 public static void updateRepositoryUsingElements(
     final ProvisioningUI ui, final MetadataRepositoryElement[] elements) {
   ui.signalRepositoryOperationStart();
   IMetadataRepositoryManager metaManager = ProvUI.getMetadataRepositoryManager(ui.getSession());
   IArtifactRepositoryManager artManager = ProvUI.getArtifactRepositoryManager(ui.getSession());
   try {
     int visibilityFlags = ui.getRepositoryTracker().getMetadataRepositoryFlags();
     URI[] currentlyEnabled = metaManager.getKnownRepositories(visibilityFlags);
     URI[] currentlyDisabled =
         metaManager.getKnownRepositories(
             IRepositoryManager.REPOSITORIES_DISABLED | visibilityFlags);
     for (int i = 0; i < elements.length; i++) {
       URI location = elements[i].getLocation();
       if (elements[i].isEnabled()) {
         if (containsURI(currentlyDisabled, location))
           // It should be enabled and is not currently
           setColocatedRepositoryEnablement(ui, location, true);
         else if (!containsURI(currentlyEnabled, location)) {
           // It is not known as enabled or disabled.  Add it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
         }
       } else {
         if (containsURI(currentlyEnabled, location))
           // It should be disabled, and is currently enabled
           setColocatedRepositoryEnablement(ui, location, false);
         else if (!containsURI(currentlyDisabled, location)) {
           // It is not known as enabled or disabled.  Add it and then disable it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
           setColocatedRepositoryEnablement(ui, location, false);
         }
       }
       String name = elements[i].getName();
       if (name != null && name.length() > 0) {
         metaManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
         artManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
       }
     }
     // Are there any elements that need to be deleted?  Go over the original state
     // and remove any elements that weren't in the elements we were given
     Set<String> nowKnown = new HashSet<String>();
     for (int i = 0; i < elements.length; i++)
       nowKnown.add(URIUtil.toUnencodedString(elements[i].getLocation()));
     for (int i = 0; i < currentlyEnabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyEnabled[i]))) {
         metaManager.removeRepository(currentlyEnabled[i]);
         artManager.removeRepository(currentlyEnabled[i]);
       }
     }
     for (int i = 0; i < currentlyDisabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyDisabled[i]))) {
         metaManager.removeRepository(currentlyDisabled[i]);
         artManager.removeRepository(currentlyDisabled[i]);
       }
     }
   } finally {
     ui.signalRepositoryOperationComplete(null, true);
   }
 }
 private void extractGrab(Expression init, ConstantExpression ce) {
   if (ce.getValue() instanceof AnnotationNode) {
     AnnotationNode annotation = (AnnotationNode) ce.getValue();
     if ((init != null) && (annotation.getMember("initClass") != null)) {
       annotation.setMember("initClass", init);
     }
     String name = annotation.getClassNode().getName();
     if ((GRAB_CLASS_NAME.equals(name))
         || (allowShortGrab && GRAB_SHORT_NAME.equals(name))
         || (grabAliases.contains(name))) {
       grabAnnotations.add(annotation);
     }
     if ((GRABEXCLUDE_CLASS_NAME.equals(name))
         || (allowShortGrabExcludes && GRABEXCLUDE_SHORT_NAME.equals(name))
         || (grabExcludeAliases.contains(name))) {
       grabExcludeAnnotations.add(annotation);
     }
     if ((GRABCONFIG_CLASS_NAME.equals(name))
         || (allowShortGrabConfig && GRABCONFIG_SHORT_NAME.equals(name))
         || (grabConfigAliases.contains(name))) {
       grabConfigAnnotations.add(annotation);
     }
     if ((GRABRESOLVER_CLASS_NAME.equals(name))
         || (allowShortGrabResolver && GRABRESOLVER_SHORT_NAME.equals(name))
         || (grabResolverAliases.contains(name))) {
       grabResolverAnnotations.add(annotation);
     }
   }
 }
 /**
  * Generate new configuration name basing on descriptor
  *
  * @return the generated configuration name
  */
 private String generateNewConfigurationName() {
   String name = null;
   for (BranchDescriptor d : myBranches) {
     if (d.newBranchName != null) {
       name = d.newBranchName;
       break;
     }
     if (d.existingBranches.contains(d.currentReference)) {
       name = d.currentReference;
     }
   }
   if (name == null) {
     name = "untitled";
   }
   if (myExistingConfigNames.contains(name)) {
     for (int i = 2; i < Integer.MAX_VALUE; i++) {
       String t = name + i;
       if (!myExistingConfigNames.contains(t)) {
         name = t;
         break;
       }
     }
   }
   return name;
 }
  /**
   * Gets a list of all the bundles that can be added as implicit dependencies
   *
   * @return list of possible dependencies
   */
  protected BundleInfo[] getValidBundles() throws CoreException {
    NameVersionDescriptor[] current = getTargetDefinition().getImplicitDependencies();
    Set<String> currentBundles = new HashSet<String>();
    if (current != null) {
      for (int i = 0; i < current.length; i++) {
        if (!currentBundles.contains(current[i].getId())) {
          currentBundles.add(current[i].getId());
        }
      }
    }

    List<BundleInfo> targetBundles = new ArrayList<BundleInfo>();
    TargetBundle[] allTargetBundles = getTargetDefinition().getAllBundles();
    if (allTargetBundles == null || allTargetBundles.length == 0) {
      throw new CoreException(
          new Status(
              IStatus.WARNING,
              PDEPlugin.getPluginId(),
              PDEUIMessages.ImplicitDependenciesSection_0));
    }
    for (int i = 0; i < allTargetBundles.length; i++) {
      BundleInfo bundleInfo = allTargetBundles[i].getBundleInfo();
      if (!currentBundles.contains(bundleInfo.getSymbolicName())) {
        currentBundles.add(bundleInfo.getSymbolicName()); // to avoid duplicate entries
        targetBundles.add(bundleInfo);
      }
    }

    return targetBundles.toArray(new BundleInfo[targetBundles.size()]);
  }
Пример #10
0
    public void verifyEvents(IndexerModelEvent... expectedEvents) {
      if (events.size() != expectedEvents.length) {
        if (events.size() > 0) {
          System.out.println("The events are:");
          for (IndexerModelEvent item : events) {
            System.out.println(item.getType() + " - " + item.getIndexName());
          }
        } else {
          System.out.println("There are no events.");
        }

        assertEquals("Expected number of events", expectedEvents.length, events.size());
      }

      Set<IndexerModelEvent> expectedEventsSet =
          new HashSet<IndexerModelEvent>(Arrays.asList(expectedEvents));

      for (IndexerModelEvent event : expectedEvents) {
        if (!events.contains(event)) {
          fail("Expected event not present among events: " + event);
        }
      }

      for (IndexerModelEvent event : events) {
        if (!expectedEventsSet.contains(event)) {
          fail("Got an event which is not among the expected events: " + event);
        }
      }

      events.clear();
    }
Пример #11
0
 private Word findTrg(Word tg, int pos2, BasicChunk bs) {
   int pos1 = tg.pos;
   if (pos2 - pos1 > 10) {
     return null;
   }
   Chunk c1 = bs.getChunk(pos1);
   Chunk c2 = bs.getChunk(pos2);
   int begin = c1.begin;
   int end = c2.end;
   for (Chunk c : bs.chunkList) {
     if (c.begin >= begin && c.end <= end) {
       for (Word w : c.trigs) {
         if (!validTG.contains(w) && w.pos > pos1) {
           return w;
         } else if (validTG.contains(w) && w.pos > pos1) {
           String key = tg.word + tg.pos_tag;
           Map<String, Counter> ct = sharedTG.get(key);
           if (ct == null) {
             ct = new HashMap<String, Counter>();
             sharedTG.put(key, ct);
           }
           Counter count = ct.get(w.word + w.pos_tag);
           if (count == null) {
             count = new Counter(1);
             ct.put(w.word + w.pos_tag, count);
           } else {
             count.inc();
           }
         }
       }
     }
   }
   return null;
 }
Пример #12
0
 private void countTrg(ChunkAnalyzer ac) {
   Set<BasicChunk> bc = new HashSet<BasicChunk>();
   List<Chunk> verb = new ArrayList<Chunk>();
   Set<Word> used = new HashSet<Word>();
   for (BasicChunk bs : ac.bsList) {
     bc.add(bs);
   }
   for (VerbChunk vc : ac.verbList) {
     bc.add(vc.subject);
     bc.add(vc.object);
     verb.add(vc.verb);
   }
   for (BasicChunk bs : bc) {
     for (Chunk c : bs.chunkList) {
       for (Word w : c.trigs) {
         if (!used.contains(w)) {
           add2Map(w.pos_tag, w.word, "NP");
           used.add(w);
         }
       }
     }
   }
   for (Chunk c : verb) {
     for (Word w : c.trigs) {
       if (!used.contains(w)) {
         add2Map(w.pos_tag, w.word, "VP");
         used.add(w);
       }
     }
   }
 }
Пример #13
0
  /**
   * Evaluates how many words (= terminals) in a collection of trees are covered by the lexicon.
   * First arg is the collection of trees; second through fourth args get the results. Currently
   * unused; this probably only works if train and test at same time so tags and words variables are
   * initialized.
   */
  public double evaluateCoverage(
      Collection<Tree> trees,
      Set<String> missingWords,
      Set<String> missingTags,
      Set<IntTaggedWord> missingTW) {

    List<IntTaggedWord> iTW1 = new ArrayList<IntTaggedWord>();
    for (Tree t : trees) {
      iTW1.addAll(treeToEvents(t));
    }

    int total = 0;
    int unseen = 0;

    for (IntTaggedWord itw : iTW1) {
      total++;
      if (!words.contains(new IntTaggedWord(itw.word(), nullTag))) {
        missingWords.add(wordIndex.get(itw.word()));
      }
      if (!tags.contains(new IntTaggedWord(nullWord, itw.tag()))) {
        missingTags.add(tagIndex.get(itw.tag()));
      }
      // if (!rules.contains(itw)) {
      if (seenCounter.getCount(itw) == 0.0) {
        unseen++;
        missingTW.add(itw);
      }
    }
    return (double) unseen / total;
  }
Пример #14
0
  /**
   * Builds the argument invocation string for calling a constructor
   *
   * @param classVariables The collection of member variables as XMLElements
   * @param constructorArguments The set of names for constructor arguments
   * @param allocatedMemberVariables The set of member variables already allocated
   * @param element The specific 'new' xml element
   */
  private static String buildArguments(
      Vector classVariables,
      Set constructorArguments,
      Set allocatedMemberVariables,
      IXMLElement element)
      throws IOException {
    XMLUtil.checkExpectedNode("new", element);

    boolean comma = false;
    String arguments = "";
    for (Enumeration e = element.enumerateChildren(); e.hasMoreElements(); ) {
      IXMLElement argument = (IXMLElement) e.nextElement();
      String argType = ModelAccessor.getValueType(argument);
      String value = ModelAccessor.getValue(argument);

      /* Exclude cases where we do nothing to the value */
      if (!primitives.contains(argType) && !value.equals("true") && !value.equals("false")) {
        // CASE 0: Translate 'this'
        if (value.equalsIgnoreCase("this")) {
          value = "m_id";
        }

        // CASE 1: It is a singleton member variable which must be mapped to the singleton
        else if (allocatedMemberVariables.contains(value)) {
          String singletonType = getVariableType(classVariables, value);
          if (primitives.contains(singletonType)) {
            value = "(" + singletonType + ") singleton(" + value + ")";
          } else value = "singleton(" + value + ")";
        }

        // CASE 2: It is a constructor argument
        else if (constructorArguments.contains(value)) { // Do nothing, just use the string as is.
        }

        // CASE 3: Test for error - using a member before initializing it
        else if (!allocatedMemberVariables.contains(value) && isMember(classVariables, value)) {
          value = "!ERROR: Cannot use " + value + " without prior initialization.";
        }

        // Otherwise it is a string or enumerataion
        else if (argType.equals("string")
            || // It is an enumeartion of some kind
            ModelAccessor.isEnumeration(argType)
            || argType.equals("symbol")) {
          value = "LabelStr(\"" + XMLUtil.escapeQuotes(value) + "\")";
        }

        // If we fall through to here, there is an error.
        else value = "!ERROR:BAD ASSIGNMENT";
      }

      // CASE 3: It is a true or false value
      if (comma) arguments = arguments + ", ";

      arguments = arguments + value;
      comma = true;
    }

    return arguments;
  }
  @Override
  public void saveConceptRelation(int catId, int conceptId) {
    byte[] key = (prefix + "id2aids").getBytes(ENCODING);
    byte[] hkey = NumberUtils.int2Bytes(catId);
    byte[] value = jedis.hget(key, hkey);
    Set<Integer> ids = NumberUtils.bytes2IntSet(value);

    if (!ids.contains(conceptId)) {
      ids.add(conceptId);
      jedis.hset(key, hkey, NumberUtils.intSet2Bytes(ids));
    }

    // 记录该类别下概念的数量
    incConceptCount(catId, 1);

    // 记录概念所隶属的类别
    key = (prefix + "ctp:catids").getBytes(ENCODING);
    hkey = NumberUtils.int2Bytes(conceptId);
    value = jedis.hget(key, hkey);
    ids = NumberUtils.bytes2IntSet(value);
    if (!ids.contains(catId)) {
      ids.add(catId);
      jedis.hset(key, hkey, NumberUtils.intSet2Bytes(ids));
    }
  }
Пример #16
0
 @Override
 public boolean tick(Tickable ticking, int tickID) {
   if (!super.tick(ticking, tickID)) return false;
   if ((tickID == Tickable.TICKID_MOB) && (invoker() != null) && (affected instanceof MOB)) {
     final MOB mob = (MOB) affected;
     final Set<MOB> invokerGroup = invoker().getGroupMembers(new HashSet<MOB>());
     if (mob != invoker()) {
       if (mob.location() != invoker().location()) unInvoke();
       else {
         if (invokerGroup.contains(mob)) unInvoke();
         else if (mob.isInCombat()) {
           int levels = invoker().charStats().getClassLevel("Templar");
           if (levels < 0) levels = invoker().phyStats().level();
           if (CMLib.dice().rollPercentage() >= levels) {
             final MOB newvictim = mob.location().fetchRandomInhabitant();
             if (newvictim != mob) mob.setVictim(newvictim);
           }
         }
       }
     } else if ((mob.location() != null) && (CMLib.flags().isEvil(invoker()))) {
       for (int m = 0; m < mob.location().numInhabitants(); m++) {
         final MOB M = mob.location().fetchInhabitant(m);
         if ((M != null)
             && (M != invoker())
             && (!invokerGroup.contains(M))
             && (!M.Name().equals(mob.getLiegeID())))
           beneficialAffect(invoker, M, 0, Ability.TICKS_FOREVER);
       }
     }
   }
   return true;
 }
Пример #17
0
  private void buildFullyConnectedGraph(NodeLists listPairs) {

    for (int i = 0; i < listPairs.getList1().size(); i++) {

      // falls Knoten noch nicht erzeugt wurde
      if (!graph.containsVertex(listPairs.getList1().get(i))) {
        graph.addVertex(listPairs.getList1().get(i));
      }
      if (!parents.contains(listPairs.getList1().get(i))) {
        parents.add(listPairs.getList1().get(i));
      }

      // falls Knoten noch nicht erzeugt wurde
      for (int j = 0; j < listPairs.getList2().size(); j++) {

        if (!graph.containsVertex(listPairs.getList2().get(j))) {
          graph.addVertex(listPairs.getList2().get(j));
        }

        if (!children.contains(listPairs.getList2().get(j))) {
          children.add(listPairs.getList2().get(j));
        }

        // Erstelle eine Kante
        graph.addEdge(listPairs.getList1().get(i), listPairs.getList2().get(j));
        System.out.println(listPairs.getList1().get(i) + " -> " + listPairs.getList2().get(j));
      }
    }
  }
 private void handleBranchingInstruction(
     ProblemsHolder holder,
     StandardInstructionVisitor visitor,
     Set<Instruction> trueSet,
     Set<Instruction> falseSet,
     HashSet<PsiElement> reportedAnchors,
     BranchingInstruction instruction,
     final boolean onTheFly) {
   PsiElement psiAnchor = instruction.getPsiAnchor();
   boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor);
   if (instruction instanceof InstanceofInstruction
       && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) {
     if (visitor.canBeNull((BinopInstruction) instruction)) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message("dataflow.message.redundant.instanceof"),
           new RedundantInstanceofFix());
     } else {
       final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true);
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(true)),
           localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix});
     }
   } else if (psiAnchor instanceof PsiSwitchLabelStatement) {
     if (falseSet.contains(instruction)) {
       holder.registerProblem(
           psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label"));
     }
   } else if (psiAnchor != null
       && !reportedAnchors.contains(psiAnchor)
       && !isFlagCheck(psiAnchor)) {
     boolean evaluatesToTrue = trueSet.contains(instruction);
     final PsiElement parent = psiAnchor.getParent();
     if (parent instanceof PsiAssignmentExpression
         && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               "dataflow.message.pointless.assignment.expression",
               Boolean.toString(evaluatesToTrue)),
           createConditionalAssignmentFixes(
               evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly));
     } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) {
       final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue);
       String message =
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(evaluatesToTrue));
       holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix});
     }
     reportedAnchors.add(psiAnchor);
   }
 }
Пример #19
0
  /** Check if the getSubBuilders properly predicts the output. */
  public static void testSubBuilders() throws Exception {
    Workspace ws = Workspace.getWorkspace(new File("test/ws"));
    Project project = ws.getProject("p4-sub");

    Collection<? extends Builder> bs = project.getSubBuilders();
    assertNotNull(bs);
    assertEquals(3, bs.size());
    Set<String> names = new HashSet<String>();
    for (Builder b : bs) {
      names.add(b.getBsn());
    }
    assertTrue(names.contains("p4-sub.a"));
    assertTrue(names.contains("p4-sub.b"));
    assertTrue(names.contains("p4-sub.c"));

    File[] files = project.build();
    assertTrue(project.check());

    System.err.println(Processor.join(project.getErrors(), "\n"));
    System.err.println(Processor.join(project.getWarnings(), "\n"));
    assertEquals(0, project.getErrors().size());
    assertEquals(0, project.getWarnings().size());
    assertNotNull(files);
    assertEquals(3, files.length);
    for (File file : files) {
      Jar jar = new Jar(file);
      Manifest m = jar.getManifest();
      assertTrue(names.contains(m.getMainAttributes().getValue("Bundle-SymbolicName")));
    }
  }
Пример #20
0
 /**
  * Loop through each indivitual parameter. It it does not have a corresponding param tag, try to
  * inherit it.
  */
 private TagletOutput getInheritedTagletOutput(
     boolean isNonTypeParams,
     Doc holder,
     TagletWriter writer,
     Object[] formalParameters,
     Set alreadyDocumented) {
   TagletOutput result = writer.getOutputInstance();
   if ((!alreadyDocumented.contains(null)) && holder instanceof MethodDoc) {
     for (int i = 0; i < formalParameters.length; i++) {
       if (alreadyDocumented.contains(String.valueOf(i))) {
         continue;
       }
       // This parameter does not have any @param documentation.
       // Try to inherit it.
       DocFinder.Output inheritedDoc =
           DocFinder.search(
               new DocFinder.Input((MethodDoc) holder, this, String.valueOf(i), !isNonTypeParams));
       if (inheritedDoc.inlineTags != null && inheritedDoc.inlineTags.length > 0) {
         result.appendOutput(
             processParamTag(
                 isNonTypeParams,
                 writer,
                 (ParamTag) inheritedDoc.holderTag,
                 isNonTypeParams
                     ? ((Parameter) formalParameters[i]).name()
                     : ((TypeVariable) formalParameters[i]).typeName(),
                 alreadyDocumented.size() == 0));
       }
       alreadyDocumented.add(String.valueOf(i));
     }
   }
   return result;
 }
 /**
  * Adds the annotation to the internal target list if a match is found.
  *
  * @param node the AST node we are processing
  */
 public void visitAnnotations(AnnotatedNode node) {
   super.visitAnnotations(node);
   for (AnnotationNode an : node.getAnnotations()) {
     String name = an.getClassNode().getName();
     if ((GRAB_CLASS_NAME.equals(name))
         || (allowShortGrab && GRAB_SHORT_NAME.equals(name))
         || (grabAliases.contains(name))) {
       grabAnnotations.add(an);
     }
     if ((GRABEXCLUDE_CLASS_NAME.equals(name))
         || (allowShortGrabExcludes && GRABEXCLUDE_SHORT_NAME.equals(name))
         || (grabExcludeAliases.contains(name))) {
       grabExcludeAnnotations.add(an);
     }
     if ((GRABCONFIG_CLASS_NAME.equals(name))
         || (allowShortGrabConfig && GRABCONFIG_SHORT_NAME.equals(name))
         || (grabConfigAliases.contains(name))) {
       grabConfigAnnotations.add(an);
     }
     if ((GRAPES_CLASS_NAME.equals(name))
         || (allowShortGrapes && GRAPES_SHORT_NAME.equals(name))
         || (grapesAliases.contains(name))) {
       grapesAnnotations.add(an);
     }
     if ((GRABRESOLVER_CLASS_NAME.equals(name))
         || (allowShortGrabResolver && GRABRESOLVER_SHORT_NAME.equals(name))
         || (grabResolverAliases.contains(name))) {
       grabResolverAnnotations.add(an);
     }
   }
 }
Пример #22
0
  /** Tests getting the list of titles for all guides. */
  public void testGetGuidesTitles() {
    Set titles;

    // Empty set of titles -- not guides
    titles = set.getGuidesTitles();
    assertEquals("Should be not titles.", 0, titles.size());

    // There's one guide in the set
    StandardGuide guide = new StandardGuide();
    guide.setTitle("A");
    set.add(guide);

    titles = set.getGuidesTitles();
    assertEquals("Should be not titles.", 1, titles.size());
    assertEquals("Wrong title", "A", titles.toArray()[0]);

    // There's another guide with the same title
    StandardGuide guide2 = new StandardGuide();
    guide2.setTitle("A");
    set.add(guide2);

    titles = set.getGuidesTitles();
    assertEquals("Should be not titles.", 1, titles.size());
    assertTrue("Wrong title", titles.contains("A"));

    // There's third guide with different title
    StandardGuide guide3 = new StandardGuide();
    guide3.setTitle("B");
    set.add(guide3);

    titles = set.getGuidesTitles();
    assertEquals("Should be not titles.", 2, titles.size());
    assertTrue("Wrong title", titles.contains("A"));
    assertTrue("Wrong title", titles.contains("B"));
  }
  public int longestConsecutive(int[] nums) {
    int maxCount = 1;
    Set<Integer> set = new HashSet<Integer>();

    // form a de-duplicated set of numbers
    for (Integer i : nums) {
      set.add(i);
    }

    for (int i = 0; i < nums.length; i++) {
      int currentCount = 1;

      // look for numbers immediately less the current one
      int current = nums[i] - 1;
      while (set.contains(current)) {
        currentCount++;
        set.remove(current);
        current = current - 1;
      }
      // look for numbers immediately greater the current one
      current = nums[i] + 1;
      while (set.contains(current)) {
        currentCount++;
        set.remove(current);
        current = current + 1;
      }
      // maintain the maximum count
      maxCount = Math.max(maxCount, currentCount);
    }

    return maxCount;
  }
Пример #24
0
 public List<String> wordBreak(String s, Set<String> wordDict) {
   boolean[] dp = new boolean[s.length()];
   List<String> res = new ArrayList<>();
   if (!contains(s, wordDict)) return res;
   Map<Integer, List<String>> paths = new HashMap<>();
   if (s.length() == 0 && wordDict.size() == 0) return res;
   if (s.length() == 0 && wordDict.size() != 0) return res;
   if (wordDict.contains(s.substring(0, 1))) {
     dp[0] = true;
     List<String> elem = new ArrayList<>();
     elem.add(s.substring(0, 1));
     paths.put(0, elem);
   }
   for (int i = 1; i < s.length(); i++) {
     List<String> elem = new ArrayList<>();
     if (wordDict.contains(s.substring(0, i + 1))) {
       dp[i] = true;
       elem.add(s.substring(0, i + 1));
     }
     for (int j = i - 1; j >= 0; j--) {
       if (dp[j] && wordDict.contains(s.substring(j + 1, i + 1))) {
         dp[i] = true;
         for (String x : paths.get(j)) {
           elem.add(x + " " + s.substring(j + 1, i + 1));
         }
       }
     }
     if (dp[i]) paths.put(i, elem);
   }
   if (dp[s.length() - 1]) {
     return paths.get(s.length() - 1);
   }
   return res;
 }
Пример #25
0
  @NotNull
  private static String buildImportListText(
      @NotNull String[] names,
      @NotNull final Set<String> packagesOrClassesToImportOnDemand,
      @NotNull final Set<String> namesToUseSingle,
      @NotNull Set<String> namesToImportStaticly) {
    final Set<String> importedPackagesOrClasses = new THashSet<String>();
    @NonNls final StringBuilder buffer = new StringBuilder();
    for (String name : names) {
      String packageOrClassName = getPackageOrClassName(name);
      final boolean implicitlyImported = JAVA_LANG_PACKAGE.equals(packageOrClassName);
      boolean useOnDemand =
          implicitlyImported || packagesOrClassesToImportOnDemand.contains(packageOrClassName);
      if (useOnDemand && namesToUseSingle.contains(name)) {
        useOnDemand = false;
      }
      if (useOnDemand
          && (importedPackagesOrClasses.contains(packageOrClassName) || implicitlyImported))
        continue;
      buffer.append("import ");
      if (namesToImportStaticly.contains(name)) buffer.append("static ");
      if (useOnDemand) {
        importedPackagesOrClasses.add(packageOrClassName);
        buffer.append(packageOrClassName);
        buffer.append(".*");
      } else {
        buffer.append(name);
      }
      buffer.append(";\n");
    }

    return buffer.toString();
  }
  private void onFinishWebUITests(ITestContext testContext) {
    // List of test results which we will delete later because of duplication or because the test
    // eventually passed
    List<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();

    // collect all id's from passed test
    Set<Integer> passedTestIds = new HashSet<Integer>();
    for (ITestResult passedTest : testContext.getPassedTests().getAllResults()) {
      passedTestIds.add(getTestId(passedTest));
    }

    Set<Integer> failedTestIds = new HashSet<Integer>();
    for (ITestResult failedTest : testContext.getFailedTests().getAllResults()) {

      int failedTestId = getTestId(failedTest);
      // if this test failed before mark as to be deleted
      // or delete this failed test if there is at least one passed version
      if (failedTestIds.contains(failedTestId) || passedTestIds.contains(failedTestId)) {
        testsToBeRemoved.add(failedTest);
      } else {
        failedTestIds.add(failedTestId);
      }
    }
    // finally delete all tests that are marked
    for (Iterator<ITestResult> iterator = testContext.getFailedTests().getAllResults().iterator();
        iterator.hasNext(); ) {
      ITestResult testResult = iterator.next();
      if (testsToBeRemoved.contains(testResult)) {
        iterator.remove();
      }
    }
  }
  private static boolean checkDependants(
      final IdeaPluginDescriptor pluginDescriptor,
      final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor,
      final Condition<PluginId> check,
      final Set<PluginId> processed) {
    processed.add(pluginDescriptor.getPluginId());
    final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
    final Set<PluginId> optionalDependencies =
        new HashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds()));
    for (final PluginId dependentPluginId : dependentPluginIds) {
      if (processed.contains(dependentPluginId)) continue;

      // TODO[yole] should this condition be a parameter?
      if (isModuleDependency(dependentPluginId)
          && (ourAvailableModules.isEmpty()
              || ourAvailableModules.contains(dependentPluginId.getIdString()))) {
        continue;
      }
      if (!optionalDependencies.contains(dependentPluginId)) {
        if (!check.value(dependentPluginId)) {
          return false;
        }
        final IdeaPluginDescriptor dependantPluginDescriptor =
            pluginId2Descriptor.fun(dependentPluginId);
        if (dependantPluginDescriptor != null
            && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) {
          return false;
        }
      }
    }
    return true;
  }
Пример #28
0
  /**
   * Compute the set of all IA32 opcodes that have emit methods in the Assembler. This method uses
   * the stylized form of all emit method names in the Assembler to extract the opcode of each one.
   * It returns a set of all such distinct names, as a set of Strings.
   *
   * @param emitters the set of all emit methods in the Assembler
   * @return the set of all opcodes handled by the Assembler
   */
  private static Set<String> getOpcodes(Method[] emitters) {
    Set<String> s = new HashSet<String>();
    for (int i = 0; i < emitters.length; i++) {
      String name = emitters[i].getName();
      if (DEBUG) System.err.println(name);
      if (name.startsWith("emit")) {
        int posOf_ = name.indexOf('_');
        if (posOf_ != -1) {
          String opcode = name.substring(4, posOf_);
          if (!excludedOpcodes.contains(opcode)) {
            s.add(opcode);
          }
        } else {
          String opcode = name.substring(4);
          // make sure it is an opcode
          if (opcode.equals(opcode.toUpperCase(Locale.getDefault()))) {
            if (!excludedOpcodes.contains(opcode)) {
              s.add(opcode);
            }
          }
        }
      }
    }

    return s;
  }
Пример #29
0
  @Test
  public void testCreateAndDropTable() throws Exception {
    catalog.createDatabase("tmpdb1", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb1"));
    catalog.createDatabase("tmpdb2", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb2"));

    TableDesc table1 = createMockupTable("tmpdb1", "table1");
    catalog.createTable(table1);

    TableDesc table2 = createMockupTable("tmpdb2", "table2");
    catalog.createTable(table2);

    Set<String> tmpdb1 = Sets.newHashSet(catalog.getAllTableNames("tmpdb1"));
    assertEquals(1, tmpdb1.size());
    assertTrue(tmpdb1.contains("table1"));

    Set<String> tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb1");
    assertFalse(catalog.existDatabase("tmpdb1"));

    tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb2");
    assertFalse(catalog.existDatabase("tmpdb2"));
  }
Пример #30
0
 /** generate mention annotations (with entity numbers) based on the ACE entities and mentions. */
 static void addMentionTags(Document doc, AceDocument aceDoc) {
   ArrayList<AceEntity> entities = aceDoc.entities;
   for (int i = 0; i < entities.size(); i++) {
     AceEntity entity = entities.get(i);
     ArrayList<AceEntityMention> mentions = entity.mentions;
     for (int j = 0; j < mentions.size(); j++) {
       AceEntityMention mention = (AceEntityMention) mentions.get(j);
       // we compute a jetSpan not including trailing whitespace
       Span aceSpan = mention.head;
       // skip mentions in ChEnglish APF not aligned to any English text
       if (aceSpan.start() < 0) continue;
       Span jetSpan = new Span(aceSpan.start(), aceSpan.end() + 1);
       FeatureSet features = new FeatureSet("entity", new Integer(i));
       if (flags.contains("types")) {
         features.put("type", entity.type.substring(0, 3));
         if (entity.subtype != null) features.put("subtype", entity.subtype);
       }
       if (flags.contains("extents")) {
         String cleanExtent = mention.text.replaceAll("\n", " ");
         features.put("extent", AceEntityMention.addXmlEscapes(cleanExtent));
       }
       doc.annotate("mention", jetSpan, features);
     }
   }
 }