Exemplo n.º 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);
     }
   }
 }
Exemplo n.º 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);
      }
    }
  }
Exemplo n.º 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);
 }
Exemplo n.º 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();
 }
Exemplo n.º 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;
 }
Exemplo n.º 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)));
    }
  }
}
Exemplo n.º 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);
     }
   }
 }
Exemplo n.º 10
0
  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();
  }
Exemplo n.º 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;
  }
Exemplo n.º 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);
  }
Exemplo n.º 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);
 }
Exemplo n.º 18
0
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);
  }
}
Exemplo n.º 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;
  }
Exemplo n.º 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()));
      }
    }
  }
Exemplo n.º 22
0
 public SetMultimap<String, String> getTags() {
   if (tags != null) {
     return tags;
   } else {
     return HashMultimap.create();
   }
 }
Exemplo n.º 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;
    }
Exemplo n.º 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);
      }
    }
  }
}
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }