예제 #1
1
 private void scrubCells(
     TransactionManager txManager,
     Multimap<String, Cell> tableNameToCells,
     long scrubTimestamp,
     Transaction.TransactionType transactionType) {
   for (Entry<String, Collection<Cell>> entry : tableNameToCells.asMap().entrySet()) {
     String tableName = entry.getKey();
     if (log.isInfoEnabled()) {
       log.info(
           "Attempting to immediately scrub "
               + entry.getValue().size()
               + " cells from table "
               + tableName);
     }
     for (List<Cell> cells : Iterables.partition(entry.getValue(), batchSizeSupplier.get())) {
       Multimap<Cell, Long> timestampsToDelete =
           HashMultimap.create(
               keyValueService.getAllTimestamps(
                   tableName, ImmutableSet.copyOf(cells), scrubTimestamp));
       for (Cell cell : ImmutableList.copyOf(timestampsToDelete.keySet())) {
         // Don't scrub garbage collection sentinels
         timestampsToDelete.remove(cell, Value.INVALID_VALUE_TIMESTAMP);
       }
       // If transactionType == TransactionType.AGGRESSIVE_HARD_DELETE this might
       // force other transactions to abort or retry
       deleteCellsAtTimestamps(txManager, tableName, timestampsToDelete, transactionType);
     }
     if (log.isInfoEnabled()) {
       log.info(
           "Immediately scrubbed " + entry.getValue().size() + " cells from table " + tableName);
     }
   }
 }
예제 #2
0
  public DaemonicParserState(
      TypeCoercerFactory typeCoercerFactory,
      ConstructorArgMarshaller marshaller,
      int parsingThreads) {
    this.typeCoercerFactory = typeCoercerFactory;
    this.marshaller = marshaller;
    this.allRawNodes = new OptimisticLoadingCache<>(parsingThreads);
    this.targetsCornucopia = HashMultimap.create();
    this.allTargetNodes = new OptimisticLoadingCache<>(parsingThreads);
    this.hasCachedTargetNodeForBuildTargetPredicate =
        new Predicate<BuildTarget>() {
          @Override
          public boolean apply(BuildTarget buildTarget) {
            return hasCachedTargetNodeForBuildTarget(buildTarget);
          }
        };
    this.buildFileTrees =
        CacheBuilder.newBuilder()
            .build(
                new CacheLoader<Cell, BuildFileTree>() {
                  @Override
                  public BuildFileTree load(Cell cell) throws Exception {
                    return new FilesystemBackedBuildFileTree(
                        cell.getFilesystem(), cell.getBuildFileName());
                  }
                });
    this.buildFileDependents = HashMultimap.create();
    this.cachedEnvironment = ImmutableMap.of();
    this.cachedIncludes = new ConcurrentHashMap<>();
    this.knownCells = Collections.synchronizedSet(new HashSet<Cell>());

    this.cachedStateLock = new AutoCloseableReadWriteUpdateLock();
  }
  protected static class Index {
    // This mutable state is only modified under inside the computable
    private final List<JetDeclaration> allDeclarations = Lists.newArrayList();
    private final Multimap<Name, JetNamedFunction> functions = HashMultimap.create();
    private final Multimap<Name, JetProperty> properties = HashMultimap.create();
    private final Multimap<Name, JetClassOrObject> classesAndObjects =
        ArrayListMultimap.create(); // order matters here

    public void putToIndex(@NotNull JetDeclaration declaration) {
      if (declaration instanceof JetClassInitializer) {
        return;
      }
      allDeclarations.add(declaration);
      if (declaration instanceof JetNamedFunction) {
        JetNamedFunction namedFunction = (JetNamedFunction) declaration;
        functions.put(safeNameForLazyResolve(namedFunction), namedFunction);
      } else if (declaration instanceof JetProperty) {
        JetProperty property = (JetProperty) declaration;
        properties.put(safeNameForLazyResolve(property), property);
      } else if (declaration instanceof JetClassOrObject) {
        JetClassOrObject classOrObject = (JetClassOrObject) declaration;
        classesAndObjects.put(safeNameForLazyResolve(classOrObject.getNameAsName()), classOrObject);
      } else if (declaration instanceof JetParameter
          || declaration instanceof JetTypedef
          || declaration instanceof JetMultiDeclaration) {
        // Do nothing, just put it into allDeclarations is enough
      } else {
        throw new IllegalArgumentException("Unknown declaration: " + declaration);
      }
    }
  }
예제 #4
0
 /** construct deep-copy of other */
 protected Topology(Topology other) {
   dcEndpoints = HashMultimap.create(other.dcEndpoints);
   dcRacks = new HashMap<String, Multimap<String, InetAddress>>();
   for (String dc : other.dcRacks.keySet())
     dcRacks.put(dc, HashMultimap.create(other.dcRacks.get(dc)));
   currentLocations = new HashMap<InetAddress, Pair<String, String>>(other.currentLocations);
 }
예제 #5
0
 DaemonicCellState(Cell cell, int parsingThreads) {
   this.cell = cell;
   this.parsingThreads = parsingThreads;
   this.cellRoot = cell.getRoot();
   this.buildFileDependents = HashMultimap.create();
   this.targetsCornucopia = HashMultimap.create();
   this.buildFileConfigs = new HashMap<>();
   this.allRawNodes = new ConcurrentMapCache<>(parsingThreads);
   this.typedNodeCaches = Maps.newConcurrentMap();
   this.rawAndComputedNodesLock = new AutoCloseableReadWriteUpdateLock();
 }
예제 #6
0
 /**
  * Returns a multimap of propertyKey -> values
  *
  * @param results The AQL properties search result
  */
 public static HashMultimap<String, String> propsToMap(AqlEagerResult<AqlProperty> results) {
   HashMultimap<String, String> map = HashMultimap.create();
   for (AqlProperty property : results.getResults()) {
     map.put(property.getKey(), property.getValue());
   }
   return map;
 }
예제 #7
0
  public void checkRedeclarationsInInnerClassNames(@NotNull TopDownAnalysisContext c) {
    for (ClassDescriptorWithResolutionScopes classDescriptor : c.getDeclaredClasses().values()) {
      if (classDescriptor.getKind() == ClassKind.CLASS_OBJECT) {
        // Class objects should be considered during analysing redeclarations in classes
        continue;
      }

      Collection<DeclarationDescriptor> allDescriptors =
          classDescriptor.getScopeForMemberLookup().getOwnDeclaredDescriptors();

      ClassDescriptorWithResolutionScopes classObj = classDescriptor.getClassObjectDescriptor();
      if (classObj != null) {
        Collection<DeclarationDescriptor> classObjDescriptors =
            classObj.getScopeForMemberLookup().getOwnDeclaredDescriptors();
        if (!classObjDescriptors.isEmpty()) {
          allDescriptors = Lists.newArrayList(allDescriptors);
          allDescriptors.addAll(classObjDescriptors);
        }
      }

      Multimap<Name, DeclarationDescriptor> descriptorMap = HashMultimap.create();
      for (DeclarationDescriptor desc : allDescriptors) {
        if (desc instanceof ClassDescriptor || desc instanceof PropertyDescriptor) {
          descriptorMap.put(desc.getName(), desc);
        }
      }

      reportRedeclarations(descriptorMap);
    }
  }
public class DaitchMokotoffSoundexTest {

  private static final Multimap<String, String> testCases = HashMultimap.create();

  @BeforeClass
  public static void setUp() throws IOException {
    InputStream dataFileInputStream =
        NaraSoundexTest.class.getResourceAsStream("DaitchMokotoffSoundexTest.data");
    List<String> lines = CharStreams.readLines(new InputStreamReader(dataFileInputStream));

    for (String currentLine : lines) {
      if (!currentLine.startsWith(";")) {
        Iterable<String> components = Splitter.on("->").trimResults().split(currentLine);
        Iterable<String> expectedValues =
            Splitter.on(",").trimResults().split(Iterables.get(components, 1));
        testCases.putAll(Iterables.get(components, 0), expectedValues);
      }
    }
  }

  @Test
  public void testComputeNaraSoundexCode() {
    for (String input : testCases.keySet()) {
      Set<String> expectedOutput = Sets.newHashSet(testCases.get(input));
      assertThat(
          "\n   input: " + input,
          StringSimilarityUtils.computeDaitchMokotoffSoundexCode(input),
          is(equalTo(expectedOutput)));
    }
  }
}
예제 #9
0
 static void update() {
   final Multimap<String, String> partitionVolumeMap = HashMultimap.create();
   final EntityTransaction db = Entities.get(Volume.class);
   try {
     for (final Volume v : Entities.query(Volume.named(null, null))) {
       partitionVolumeMap.put(v.getPartition(), v.getDisplayName());
     }
     db.rollback();
   } catch (final Exception ex) {
     Logs.extreme().error(ex, ex);
     db.rollback();
   }
   Logs.extreme()
       .debug("Volume state update: " + Joiner.on("\n").join(partitionVolumeMap.entries()));
   for (final String partition : partitionVolumeMap.keySet()) {
     try {
       final Map<String, StorageVolume> idStorageVolumeMap =
           updateVolumesInPartition(partition); // TODO:GRZE: restoring volume state
       for (final String v : partitionVolumeMap.get(partition)) {
         try {
           final StorageVolume storageVolume = idStorageVolumeMap.get(v);
           volumeStateUpdate(v, storageVolume);
         } catch (final Exception ex) {
           LOG.error(ex);
           Logs.extreme().error(ex, ex);
         }
       }
     } catch (final Exception ex) {
       LOG.error(ex);
       Logs.extreme().error(ex, ex);
     }
   }
 }
예제 #10
0
파일: Gsons.java 프로젝트: akune/immutables
  public Iterable<TypeAdapterTypes> typeAdapters() {
    Multimap<AbstractDeclaring, ValueType> byDeclaring = HashMultimap.create();
    for (ValueType value : values().values()) {
      Protoclass protoclass = value.constitution.protoclass();
      if (protoclass.kind().isValue()) {
        Optional<AbstractDeclaring> typeAdaptersProvider = protoclass.typeAdaptersProvider();
        if (typeAdaptersProvider.isPresent()) {
          byDeclaring.put(typeAdaptersProvider.get(), value);
        } else if (protoclass.gsonTypeAdapters().isPresent()
            && protoclass.declaringType().isPresent()) {
          DeclaringType topLevel = protoclass.declaringType().get().associatedTopLevel();
          byDeclaring.put(topLevel, value);
        }
      }
    }

    ImmutableList.Builder<TypeAdapterTypes> builder = ImmutableList.builder();
    for (Entry<AbstractDeclaring, Collection<ValueType>> entry : byDeclaring.asMap().entrySet()) {
      builder.add(
          ImmutableTypeAdapterTypes.builder()
              .definedBy(entry.getKey())
              .addAllTypes(entry.getValue())
              .build());
    }

    return builder.build();
  }
예제 #11
0
  @NotNull
  private static Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>>
      getSuperclassToFunctionsMultimap(
          @NotNull PsiMethodWrapper method,
          @NotNull BindingContext bindingContext,
          @NotNull ClassDescriptor containingClass) {
    Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> result = HashMultimap.create();

    Name functionName = Name.identifier(method.getName());
    int parameterCount = method.getParameters().size();

    for (JetType supertype : TypeUtils.getAllSupertypes(containingClass.getDefaultType())) {
      ClassifierDescriptor klass = supertype.getConstructor().getDeclarationDescriptor();
      assert klass != null;
      FqName fqName = DescriptorUtils.getFQName(klass).toSafe();

      for (FunctionDescriptor fun :
          klass.getDefaultType().getMemberScope().getFunctions(functionName)) {
        if (fun.getKind().isReal() && fun.getValueParameters().size() == parameterCount) {
          PsiElement declaration = BindingContextUtils.descriptorToDeclaration(bindingContext, fun);
          if (declaration instanceof PsiMethod) {
            result.put(fqName, Pair.create(fun, (PsiMethod) declaration));
          } // else declaration is null or JetNamedFunction: both cases are processed later
        }
      }
    }
    return result;
  }
  /**
   * 将原始数据切割后装入ThreadInfo,并以Key=WaitID,Value= ThreadInfo实体放入到Multimap<String, ThreadInfo>集合中
   * ps:Multimap 类似于Map<key,collection>, key:value-> 1:n
   *
   * @param rawDatas
   * @return
   */
  public Multimap<String, ThreadInfo> getThreadInfo(List<String[]> rawDatas) {
    Multimap<String, ThreadInfo> w_IdMap = HashMultimap.create();
    List<ThreadInfo> threadsList = Lists.newArrayList();
    for (String[] rawData : rawDatas) {
      ThreadInfo threadInfo = new ThreadInfo();
      Pattern t_id = Pattern.compile("tid=(0x[\\d\\w]+)");
      Pattern t_name = Pattern.compile("\"([\\d\\D]*)\"");
      Pattern w_Id = Pattern.compile("\\[(0x[\\d\\w]+)\\]");
      Matcher tIdMatcher = t_id.matcher(rawData[0]);
      Matcher nameMatcher = t_name.matcher(rawData[0]);
      Matcher w_IdMatcher = w_Id.matcher(rawData[0]);
      if (tIdMatcher.find()) {
        threadInfo.setThreadId(tIdMatcher.group(1));
      }

      if (nameMatcher.find()) {
        threadInfo.setThreadName(nameMatcher.group(1));
      }

      if (w_IdMatcher.find()) {
        threadInfo.setWaitThreadId(w_IdMatcher.group(1));
      }
      threadInfo.setThreadCondition(rawData[1]);
      w_IdMap.put(threadInfo.getWaitThreadId(), threadInfo);
    }
    return w_IdMap;
  }
  boolean areAbstractSuccessors(
      AbstractState pElement,
      CFAEdge pCfaEdge,
      Collection<? extends AbstractState> pSuccessors,
      ProofChecker wrappedProofChecker)
      throws CPATransferException, InterruptedException {
    ARGState element = (ARGState) pElement;

    assert Iterables.elementsEqual(element.getChildren(), pSuccessors);

    AbstractState wrappedState = element.getWrappedState();
    Multimap<CFAEdge, AbstractState> wrappedSuccessors = HashMultimap.create();
    for (AbstractState absElement : pSuccessors) {
      ARGState successorElem = (ARGState) absElement;
      wrappedSuccessors.put(element.getEdgeToChild(successorElem), successorElem.getWrappedState());
    }

    if (pCfaEdge != null) {
      return wrappedProofChecker.areAbstractSuccessors(
          wrappedState, pCfaEdge, wrappedSuccessors.get(pCfaEdge));
    }

    CFANode loc = AbstractStates.extractLocation(element);
    for (CFAEdge edge : leavingEdges(loc)) {
      if (!wrappedProofChecker.areAbstractSuccessors(
          wrappedState, edge, wrappedSuccessors.get(edge))) {
        return false;
      }
    }
    return true;
  }
예제 #14
0
  private Multimap<Cell, Long> getCellTsPairsToSweep(
      Multimap<Cell, Long> cellTsMappings,
      PeekingIterator<RowResult<Value>> values,
      long sweepTimestamp,
      SweepStrategy sweepStrategy,
      @Output Set<Cell> sentinelsToAdd) {
    Multimap<Cell, Long> cellTsMappingsToSweep = HashMultimap.create();

    Map<Long, Long> startTsToCommitTs = transactionService.get(cellTsMappings.values());
    for (Map.Entry<Cell, Collection<Long>> entry : cellTsMappings.asMap().entrySet()) {
      Cell cell = entry.getKey();
      Collection<Long> timestamps = entry.getValue();
      boolean sweepLastCommitted = isLatestValueEmpty(cell, values);
      Iterable<? extends Long> timestampsToSweep =
          getTimestampsToSweep(
              cell,
              timestamps,
              startTsToCommitTs,
              sentinelsToAdd,
              sweepTimestamp,
              sweepLastCommitted,
              sweepStrategy);
      cellTsMappingsToSweep.putAll(entry.getKey(), timestampsToSweep);
    }
    return cellTsMappingsToSweep;
  }
  public void testAllOptions() throws IOException {

    String expected =
        Strings2.toStringAndClose(
            getClass().getResourceAsStream("/InstantiateVAppTemplateParams-options-test.xml"));
    Multimap<String, String> headers =
        Multimaps.synchronizedMultimap(HashMultimap.<String, String>create());
    GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
    expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
    expect(request.getArgs())
        .andReturn(
            ImmutableList.<Object>of(
                InstantiateVAppTemplateOptions.Builder.processorCount(2)
                    .memory(512)
                    .inGroup("group")
                    .withPassword("password")
                    .inRow("row")
                    .addNetworkConfig(new NetworkConfig(URI.create("http://network")))))
        .atLeastOnce();
    expect(request.getFirstHeaderOrNull("Content-Type"))
        .andReturn("application/unknown")
        .atLeastOnce();
    expect(request.getHeaders()).andReturn(headers).atLeastOnce();
    request.setPayload(expected);
    replay(request);

    BindInstantiateVAppTemplateParamsToXmlPayload binder =
        injector.getInstance(BindInstantiateVAppTemplateParamsToXmlPayload.class);

    Map<String, String> map = Maps.newHashMap();
    map.put("name", "name");
    map.put("template", "https://vcloud/vAppTemplate/3");
    binder.bindToRequest(request, map);
  }
예제 #16
0
  static Set<String> sanityCheckDatacenters(
      Cassandra.Client client, int desiredRf, boolean safetyDisabled)
      throws InvalidRequestException, TException {
    ensureTestKeyspaceExists(client);
    Multimap<String, String> dataCenterToRack = HashMultimap.create();
    List<TokenRange> ring = client.describe_ring(CassandraConstants.SIMPLE_RF_TEST_KEYSPACE);
    for (TokenRange tokenRange : ring) {
      for (EndpointDetails details : tokenRange.getEndpoint_details()) {
        dataCenterToRack.put(details.datacenter, details.rack);
      }
    }

    if (dataCenterToRack.size() == 1) {
      String dc = dataCenterToRack.keySet().iterator().next();
      String rack = dataCenterToRack.values().iterator().next();
      if (dc.equals(CassandraConstants.DEFAULT_DC)
          && rack.equals(CassandraConstants.DEFAULT_RACK)
          && desiredRf > 1) {
        // We don't allow greater than RF=1 because they didn't set up their network.
        logErrorOrThrow(
            "The cassandra cluster is not set up to be datacenter and rack aware.  "
                + "Please set this up before running with a replication factor higher than 1.",
            safetyDisabled);
      }
    }

    return dataCenterToRack.keySet();
  }
 public static String paramsListToString(Map<String, String> params) {
   Multimap<String, String> multimap = HashMultimap.create(params.size(), 1);
   for (String key : params.keySet()) {
     multimap.put(key, params.get(key));
   }
   return paramsListToString(multimap);
 }
예제 #18
0
파일: Main.java 프로젝트: ruminski/looksok
public class Main {

  private static Map<String, List<Integer>> playerScoresMap = new HashMap<String, List<Integer>>();
  private static Multimap<String, Integer> playerScoresMultimap = HashMultimap.create();

  public static void main(String[] args) {
    System.out.println("Multimap demo!");

    addToOldStyleMultimap("Bob", 10);
    addToOldStyleMultimap("Bob", 20);
    addToOldStyleMultimap("Bob", 30);
    addToOldStyleMultimap("Kate", 130);
    System.out.println("Old style multimap result: " + playerScoresMap);

    addToGuavaMultimap("Alan", 2);
    addToGuavaMultimap("Alan", 4);
    addToGuavaMultimap("Alan", 6);
    addToGuavaMultimap("Paul", 87);
    System.out.println("Guava multimap result: " + playerScoresMultimap);
  }

  private static void addToOldStyleMultimap(String playerName, int scoreToAdd) {
    List<Integer> scoresList = new ArrayList<Integer>();
    if (playerScoresMap.containsKey(playerName)) {
      scoresList = playerScoresMap.get(playerName);
    }

    scoresList.add(scoreToAdd);
    playerScoresMap.put(playerName, scoresList);
  }

  private static void addToGuavaMultimap(String playerName, Integer scoreToAdd) {
    playerScoresMultimap.put(playerName, scoreToAdd);
  }
}
예제 #19
0
  protected void updateSuperProjects(ReviewDb db, Set<Branch.NameKey> updatedBranches)
      throws SubmoduleException {
    try {
      // These (repo/branch) will be updated later with all the given
      // individual submodule subscriptions
      Multimap<Branch.NameKey, SubmoduleSubscription> targets = HashMultimap.create();

      for (Branch.NameKey updatedBranch : updatedBranches) {
        for (SubmoduleSubscription sub : db.submoduleSubscriptions().bySubmodule(updatedBranch)) {
          targets.put(sub.getSuperProject(), sub);
        }
      }
      updatedSubscribers.addAll(updatedBranches);
      // Update subscribers.
      for (Branch.NameKey dest : targets.keySet()) {
        try {
          if (!updatedSubscribers.add(dest)) {
            log.error("Possible circular subscription involving " + dest);
          } else {
            updateGitlinks(db, dest, targets.get(dest));
          }
        } catch (SubmoduleException e) {
          log.warn("Cannot update gitlinks for " + dest, e);
        }
      }
    } catch (OrmException e) {
      logAndThrowSubmoduleException("Cannot read subscription records", e);
    }
  }
  /**
   * Gets the feed mapping for a feed.
   *
   * @return a multimap from feed attribute ID to the set of field IDs mapped to the attribute
   */
  private static Multimap<Long, Integer> getFeedMapping(
      AdWordsServices adWordsServices, AdWordsSession session, Feed feed, long placeholderType)
      throws Exception {
    // Get the FeedMappingService.
    FeedMappingServiceInterface feedMappingService =
        adWordsServices.get(session, FeedMappingServiceInterface.class);
    String query =
        String.format(
            "SELECT FeedMappingId, AttributeFieldMappings WHERE FeedId = %d and PlaceholderType = %d "
                + "AND Status = 'ENABLED'",
            feed.getId(), placeholderType);

    Multimap<Long, Integer> attributeMappings = HashMultimap.create();
    int offset = 0;
    FeedMappingPage feedMappingPage;

    do {
      String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
      feedMappingPage = feedMappingService.query(pageQuery);
      if (feedMappingPage.getEntries() != null) {
        // Normally, a feed attribute is mapped only to one field. However, you may map it to more
        // than one field if needed.
        for (FeedMapping feedMapping : feedMappingPage.getEntries()) {
          for (AttributeFieldMapping attributeMapping : feedMapping.getAttributeFieldMappings()) {
            attributeMappings.put(
                attributeMapping.getFeedAttributeId(), attributeMapping.getFieldId());
          }
        }
      }
      offset += PAGE_SIZE;
    } while (offset < feedMappingPage.getTotalNumEntries());

    return attributeMappings;
  }
예제 #21
0
  public ReverseCFATransformerFactory(Set<CFAEdge> cfa) {
    reverseCFA = HashMultimap.create();
    Set<Location> nonSinks = new HashSet<Location>();
    for (CFAEdge e : cfa) {
      reverseCFA.put(e.getTarget(), e);
      nonSinks.add(e.getSource());
    }

    FastSet<Location> sinks = new FastSet<Location>();
    for (Location l : reverseCFA.keySet()) {
      if (!nonSinks.contains(l)) {
        sinks.add(l);
      }
    }

    if (sinks.size() == 1) {
      sink = sinks.pick();
    } else if (sinks.size() == 0) {
      throw new RuntimeException("CFA has no sink!");
    } else {
      // Generate artificial exit node
      sink = new Location(new AbsoluteAddress(0xFFFFFF01L));
      for (Location l : sinks) {
        reverseCFA.put(sink, new CFAEdge(l, sink, new RTLSkip()));
      }
    }
  }
예제 #22
0
 public SetMultimap<String, String> getTags() {
   if (tags != null) {
     return tags;
   } else {
     return HashMultimap.create();
   }
 }
예제 #23
0
    public Multimap<Node, Split> computeAssignments(Set<Split> splits) {
      Multimap<Node, Split> assignment = HashMultimap.create();

      for (Split split : splits) {
        List<Node> candidateNodes;
        if (locationAwareScheduling) {
          candidateNodes = selectCandidateNodes(nodeMap.get().get(), split);
        } else {
          candidateNodes = selectRandomNodes(minCandidates);
        }
        checkCondition(
            !candidateNodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query");

        Node chosen = null;
        int min = Integer.MAX_VALUE;
        for (Node node : candidateNodes) {
          RemoteTask task = taskMap.get(node);
          int currentSplits = (task == null) ? 0 : task.getQueuedSplits();
          int assignedSplits = currentSplits + assignment.get(node).size();
          if (assignedSplits < min && assignedSplits < maxPendingSplitsPerTask) {
            chosen = node;
            min = assignedSplits;
          }
        }
        if (chosen != null) {
          assignment.put(chosen, split);
        }
      }
      return assignment;
    }
예제 #24
0
 @Override
 public SetMultimap<Object, String> getContentAnchorages() {
   SetMultimap<Object, String> anchorages = HashMultimap.create();
   anchorages.put(getContent().getSource(), "START");
   anchorages.put(getContent().getTarget(), "END");
   return anchorages;
 }
public class ClassDependencies {

  private final SetMultimap<ClassName, ClassName> _classToReferencedClassesMap =
      HashMultimap.create();

  public Set<ClassName> getAllClasses() {
    return Collections.unmodifiableSet(_classToReferencedClassesMap.keySet());
  }

  public Set<ClassName> getReferencedClasses(ClassName className) {
    return Collections.unmodifiableSet(_classToReferencedClassesMap.get(className));
  }

  public void add(ClassName className, Collection<ClassName> referencedClasses) {
    _classToReferencedClassesMap.putAll(className, referencedClasses);
    _classToReferencedClassesMap.remove(className, className);
  }

  public Set<ClassName> getTransitiveClosure(Collection<ClassName> classNames) {
    Set<ClassName> transitiveClosure = Sets.newHashSet();
    for (ClassName className : classNames) {
      collectTransitiveClosure(className, transitiveClosure);
    }
    return transitiveClosure;
  }

  private void collectTransitiveClosure(ClassName className, Set<ClassName> transitiveClosure) {
    if (transitiveClosure.add(className)) {
      for (ClassName referencedClass : _classToReferencedClassesMap.get(className)) {
        collectTransitiveClosure(referencedClass, transitiveClosure);
      }
    }
  }
}
예제 #26
0
 @Override
 public Multimap getItemAttributeModifiers() {
   Multimap multimap = HashMultimap.create();
   multimap.put(
       SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(),
       new AttributeModifier(field_111210_e, "Tool modifier", this.damageVsEntity, 0));
   return multimap;
 }
예제 #27
0
 private static <T> SetMultimap<Set<T>, Set<T>> createStrataDependencyGraph(
     Multimap<T, T> dependencyGraph) {
   SetMultimap<Set<T>, Set<T>> strataDependencyGraph = HashMultimap.create();
   for (Entry<T, T> entry : dependencyGraph.entries()) {
     strataDependencyGraph.put(ImmutableSet.of(entry.getKey()), ImmutableSet.of(entry.getValue()));
   }
   return strataDependencyGraph;
 }
예제 #28
0
 private synchronized Multimap<Range, InetAddress> getPendingRangesMM(String table) {
   Multimap<Range, InetAddress> map = pendingRanges.get(table);
   if (map == null) {
     map = HashMultimap.create();
     pendingRanges.put(table, map);
   }
   return map;
 }
예제 #29
0
 @Override
 public Multimap getItemAttributeModifiers() {
   Multimap multimap = HashMultimap.create();
   multimap.put(
       SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(),
       new AttributeModifier(field_111210_e, "Weapon modifier", (double) this.weaponDamage, 0));
   return multimap;
 }
예제 #30
0
 /**
  * Constructor taking String matcher.
  *
  * @param path The mandatory argument is the path which will be listened on
  */
 public ClientDriverRequest(Matcher<? extends String> path) {
   this.path = path;
   method = Method.GET;
   params = HashMultimap.create();
   headers = new HashMap<String, Matcher<? extends String>>();
   excludedHeaders = new HashSet<String>();
   anyParams = false;
 }