Пример #1
0
  /**
   * Prints an adjacency matrix.
   *
   * @param vertexes the vertexes values.
   * @param adjacencyMatrix the adjacency matrix.
   */
  public static void printAdjacencyMatrix(String[] vertexes, boolean[][] adjacencyMatrix) {
    Preconditions.checkArgument(vertexes != null, "The vertex values must be provided.");
    Preconditions.checkArgument(adjacencyMatrix != null, "The adjacency matrix must be provided.");

    StringBuilder builder = new StringBuilder();
    builder.append("\t");
    for (int i = 0; i < vertexes.length; i++) {
      builder.append(vertexes[i]);
      builder.append("\t");
    }
    builder.append("\n");
    for (int i = 0; i < adjacencyMatrix.length; i++) {
      for (int j = 0; j < adjacencyMatrix.length; j++) {
        if (j == 0) {
          builder.append(vertexes[i]);
          builder.append("\t");
          builder.append(adjacencyMatrix[i][j]);
          builder.append("\t");
        } else {
          builder.append(adjacencyMatrix[i][j]);
          builder.append("\t");
        }
      }
      builder.append("\n");
    }
    System.out.println(builder.toString());
  }
Пример #2
0
 /**
  * Ensures that the given tolerance is a non-negative finite value, i.e. not {@code Float.NaN},
  * {@code Float.POSITIVE_INFINITY}, or negative, including {@code -0.0f}.
  */
 static void checkTolerance(float tolerance) {
   checkArgument(!Float.isNaN(tolerance), "tolerance cannot be NaN");
   checkArgument(tolerance >= 0.0f, "tolerance (%s) cannot be negative", tolerance);
   checkArgument(
       floatToIntBits(tolerance) != NEG_ZERO_BITS, "tolerance (%s) cannot be negative", tolerance);
   checkArgument(tolerance != Float.POSITIVE_INFINITY, "tolerance cannot be POSITIVE_INFINITY");
 }
 @JsonCreator
 public CassandraColumnHandle(
     @JsonProperty("connectorId") String connectorId,
     @JsonProperty("name") String name,
     @JsonProperty("ordinalPosition") int ordinalPosition,
     @JsonProperty("cassandraType") CassandraType cassandraType,
     @Nullable @JsonProperty("typeArguments") List<CassandraType> typeArguments,
     @JsonProperty("partitionKey") boolean partitionKey,
     @JsonProperty("clusteringKey") boolean clusteringKey,
     @JsonProperty("indexed") boolean indexed,
     @JsonProperty("hidden") boolean hidden) {
   this.connectorId = checkNotNull(connectorId, "connectorId is null");
   this.name = checkNotNull(name, "name is null");
   checkArgument(ordinalPosition >= 0, "ordinalPosition is negative");
   this.ordinalPosition = ordinalPosition;
   this.cassandraType = checkNotNull(cassandraType, "cassandraType is null");
   int typeArgsSize = cassandraType.getTypeArgumentSize();
   if (typeArgsSize > 0) {
     this.typeArguments = checkNotNull(typeArguments, "typeArguments is null");
     checkArgument(
         typeArguments.size() == typeArgsSize,
         cassandraType + " must provide " + typeArgsSize + " type arguments");
   } else {
     this.typeArguments = null;
   }
   this.partitionKey = partitionKey;
   this.clusteringKey = clusteringKey;
   this.indexed = indexed;
   this.hidden = hidden;
 }
Пример #4
0
  /**
   * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.
   *
   * @param hostPortString the full bracketed host-port specification. Post might not be specified.
   * @return an array with 2 strings: host and port, in that order.
   * @throws IllegalArgumentException if parsing the bracketed host-port string fails.
   */
  private static String[] getHostAndPortFromBracketedHost(String hostPortString) {
    int colonIndex = 0;
    int closeBracketIndex = 0;
    checkArgument(
        hostPortString.charAt(0) == '[',
        "Bracketed host-port string must start with a bracket: %s",
        hostPortString);
    colonIndex = hostPortString.indexOf(':');
    closeBracketIndex = hostPortString.lastIndexOf(']');
    checkArgument(
        colonIndex > -1 && closeBracketIndex > colonIndex,
        "Invalid bracketed host/port: %s",
        hostPortString);

    String host = hostPortString.substring(1, closeBracketIndex);
    if (closeBracketIndex + 1 == hostPortString.length()) {
      return new String[] {host, ""};
    } else {
      checkArgument(
          hostPortString.charAt(closeBracketIndex + 1) == ':',
          "Only a colon may follow a close bracket: %s",
          hostPortString);
      for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) {
        checkArgument(
            Character.isDigit(hostPortString.charAt(i)),
            "Port must be numeric: %s",
            hostPortString);
      }
      return new String[] {host, hostPortString.substring(closeBracketIndex + 2)};
    }
  }
 public InterestRateSwapSecurity(
     final ExternalIdBundle id,
     final String name,
     final LocalDate effectiveDate,
     final LocalDate unAdjustedMaturityDate,
     final Collection<InterestRateSwapLeg> legs) {
   super(SECURITY_TYPE);
   setExternalIdBundle(id);
   setName(name);
   setEffectiveDate(effectiveDate);
   setUnadjustedMaturityDate(unAdjustedMaturityDate);
   setLegs(Lists.newArrayList(legs));
   Preconditions.checkArgument(
       getPayLeg().getEffectiveDate() == null,
       "Pay leg effective date conflict: If effective date is set on the swap, then it must not be set on the legs");
   Preconditions.checkArgument(
       getReceiveLeg().getEffectiveDate() == null,
       "Rec leg effective date conflict: If effective date is set on the swap, then it must not be set on the legs");
   Preconditions.checkArgument(
       getPayLeg().getUnadjustedMaturityDate() == null,
       "Pay leg termination date conflict: If termination date is set on the swap, then it must not be set on the legs");
   Preconditions.checkArgument(
       getReceiveLeg().getUnadjustedMaturityDate() == null,
       "Rec leg termination date conflict: If termination date is set on the swap, then it must not be set on the legs");
 }
Пример #6
0
 /**
  * Use provided JAXWSEnvironment. Service endpoints are published relative to the provided
  * servletPath.
  *
  * @param servletPath Root path for service endpoints. Leading slash is required.
  * @param jaxwsEnvironment Valid JAXWSEnvironment.
  */
 public JAXWSBundle(String servletPath, JAXWSEnvironment jaxwsEnvironment) {
   checkArgument(servletPath != null, "Servlet path is null");
   checkArgument(servletPath.startsWith("/"), "%s is not an absolute path", servletPath);
   checkArgument(jaxwsEnvironment != null, "jaxwsEnvironment is null");
   this.servletPath = servletPath.endsWith("/") ? servletPath + "*" : servletPath + "/*";
   this.jaxwsEnvironment = jaxwsEnvironment;
 }
Пример #7
0
  @Override
  public HashMap<Long, Long> getIntervals(
      long lowWatermarkValue, long highWatermarkValue, long partitionInterval, int maxIntervals) {
    Preconditions.checkArgument(
        partitionInterval >= 1, "Invalid value for partitionInterval, value should be at least 1.");
    Preconditions.checkArgument(
        maxIntervals > 0, "Invalid value for maxIntervals, positive value expected.");

    HashMap<Long, Long> intervalMap = new HashMap<Long, Long>();
    long nextNum;
    long interval =
        this.getInterval(lowWatermarkValue, highWatermarkValue, partitionInterval, maxIntervals);
    LOG.info("Recalculated partition interval:" + interval);
    if (interval == 0) {
      return intervalMap;
    }

    long startNum = lowWatermarkValue;
    long endNum = highWatermarkValue;
    boolean longOverflow = false;
    while (startNum <= endNum && !longOverflow) {
      longOverflow = (Long.MAX_VALUE - interval < startNum);
      nextNum = longOverflow ? Long.MAX_VALUE : startNum + interval;
      intervalMap.put(startNum, (nextNum <= endNum ? nextNum : endNum));
      startNum = nextNum + deltaForNextWatermark;
    }
    return intervalMap;
  }
  /**
   * Skip a specified number of entries and return the resulting position.
   *
   * @param startPosition the current position
   * @param entriesToSkip the numbers of entries to skip
   * @return the new position
   */
  protected synchronized Position skipEntries(Position startPosition, int entriesToSkip) {
    log.debug("[{}] Skipping {} entries from position {}", va(name, entriesToSkip, startPosition));
    long ledgerId = startPosition.getLedgerId();
    entriesToSkip += startPosition.getEntryId();

    while (entriesToSkip > 0) {
      if (currentLedger != null && ledgerId == currentLedger.getId()) {
        checkArgument(entriesToSkip <= (currentLedger.getLastAddConfirmed() + 1));
        return new Position(ledgerId, entriesToSkip);
      } else {
        LedgerStat ledger = ledgers.get(ledgerId);
        if (ledger == null) {
          checkArgument(!ledgers.isEmpty());
          ledgerId = ledgers.ceilingKey(ledgerId);
          continue;
        }

        if (entriesToSkip < ledger.getEntriesCount()) {
          return new Position(ledgerId, entriesToSkip);
        } else {
          // Move to next ledger
          entriesToSkip -= ledger.getEntriesCount();
          ledgerId = ledgers.ceilingKey(ledgerId + 1);
        }
      }
    }

    return new Position(ledgerId, 0);
  }
Пример #9
0
 public static final By elementWithAttribute(
     String element, String attributeName, String attributeValue) {
   Preconditions.checkArgument(!Strings.isNullOrEmpty(element));
   Preconditions.checkArgument(!Strings.isNullOrEmpty(attributeName));
   Preconditions.checkArgument(!Strings.isNullOrEmpty(attributeValue));
   return By.xpath(String.format(".//%s[@%s='%s']", element, attributeName, attributeValue));
 }
 private static Class<?> getPrimitiveType(ByteCodeExpression expression, String name) {
   requireNonNull(expression, name + " is null");
   Class<?> leftType = expression.getType().getPrimitiveType();
   checkArgument(leftType != null, name + " is not a primitive");
   checkArgument(leftType != void.class, name + " is void");
   return leftType;
 }
Пример #11
0
 protected Payload doSlice(byte[] content, long offset, long length) {
   Payload returnVal;
   checkArgument(offset <= Integer.MAX_VALUE, "offset is too big for an array");
   checkArgument(length <= Integer.MAX_VALUE, "length is too big for an array");
   returnVal = new InputStreamSupplierPayload(ByteSource.wrap(content).slice(offset, length));
   return returnVal;
 }
Пример #12
0
 public DocEventFrameReference asEventFrameReference(ResponseSet rs) {
   checkArgument(responseSets().contains(rs), "Response set not found in linking");
   checkArgument(
       responseSetIds().isPresent(),
       "Cannot create event frame references without " + "response IDs");
   return DocEventFrameReference.of(docID(), responseSetIds().get().inverse().get(rs));
 }
Пример #13
0
 @Value.Check
 protected void checkValidity() {
   // no incomplete response may appear in any response set
   final ImmutableSet<Response> allResponsesInSets = ImmutableSet.copyOf(concat(responseSets()));
   for (final Response incompleteResponse : incompleteResponses()) {
     checkArgument(
         !allResponsesInSets.contains(incompleteResponse),
         "A response may not be both completed and incomplete");
   }
   if (responseSetIds().isPresent()) {
     for (final String id : responseSetIds().get().keySet()) {
       checkArgument(!id.contains("-"), "Event frame IDs may not contain -s");
       checkArgument(!id.contains("\t"), "Event frame IDs may not contain tabs");
     }
     // we can have an empty output file, verify that all the responseSets have an id
     checkArgument(
         responseSets().size() == responseSetIds().get().size(), "Response set IDs are missing");
     checkArgument(
         responseSetIds().get().keySet().size() == responseSets().size(),
         "All response set IDs must be unique");
     CollectionUtils.assertSameElementsOrIllegalArgument(
         responseSets(),
         responseSetIds().get().values(),
         "Response sets did not match IDs",
         "Response sets in list",
         "Response sets in ID map");
   }
 }
Пример #14
0
  /**
   * A wrapper for the function {@code execute(HttpRequestBase request)}. It retries using
   * exponential retry strategy with the following intervals:<br>
   * {@code baseIntervalSeconds, baseIntervalSeconds * 2, baseIntervalSeconds * 2^2,
   * baseIntervalSeconds * 2^3 ...}
   *
   * @param request {@link HttpRequestBase} specifies the HTTP request expected to execute.
   * @param maxRetries specifies the maximum number of retries.
   * @param baseIntervalSeconds specifies the interval base for the exponential retry strategy
   * @return the {@link HttpResponse} if the execution is successful with maximum number of retries.
   * @throws IOException
   */
  public HttpResponse executeWithRetries(
      HttpRequestBase request, int maxRetries, long baseIntervalSeconds) throws IOException {
    Preconditions.checkArgument(maxRetries > 0, "maxRetries must be > 1");
    Preconditions.checkArgument(baseIntervalSeconds > 0, "baseIntervalSeconds must be > 0");

    HttpResponse response = null;
    IOException exception = null;
    long sleepMillis = TimeUnit.SECONDS.toMillis(baseIntervalSeconds);
    for (int i = 0; i < maxRetries; ++i) {
      try {
        response = _httpClient.execute(request);
      } catch (IOException e) {
        exception = e;
        response = null;
        try {
          Thread.sleep(sleepMillis);
          sleepMillis *= 2;
        } catch (InterruptedException ie) {
          // no-op
        }
      }
      if (null != response) {
        return response;
      }
    }
    // If it can not get any response after several retries, re-throw the the exception.
    throw new IOException(exception);
  }
Пример #15
0
  private GeneralRange(
      Comparator<? super T> comparator,
      boolean hasLowerBound,
      @Nullable T lowerEndpoint,
      BoundType lowerBoundType,
      boolean hasUpperBound,
      @Nullable T upperEndpoint,
      BoundType upperBoundType) {
    this.comparator = checkNotNull(comparator);
    this.hasLowerBound = hasLowerBound;
    this.hasUpperBound = hasUpperBound;
    this.lowerEndpoint = lowerEndpoint;
    this.lowerBoundType = checkNotNull(lowerBoundType);
    this.upperEndpoint = upperEndpoint;
    this.upperBoundType = checkNotNull(upperBoundType);

    if (hasLowerBound) {
      comparator.compare(lowerEndpoint, lowerEndpoint);
    }
    if (hasUpperBound) {
      comparator.compare(upperEndpoint, upperEndpoint);
    }
    if (hasLowerBound && hasUpperBound) {
      int cmp = comparator.compare(lowerEndpoint, upperEndpoint);
      // be consistent with Range
      checkArgument(
          cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint);
      if (cmp == 0) {
        checkArgument(lowerBoundType != OPEN | upperBoundType != OPEN);
      }
    }
  }
Пример #16
0
  /**
   * Creates a new instance of a monotone solver.
   *
   * @param graph Graph that is being worked on.
   * @param lattice Lattice structure that provides the method to merge states.
   * @param startVector Initial state vector.
   * @param transformationProvider Transforms the state vector during each step of the algorithm.
   * @param walker Specifies how to walk through the graph.
   * @param debugger Optional debugger that receives debugging information while the monotone
   *     framework is running.
   */
  public MonotoneSolver(
      final ILatticeGraph<GraphNode> graph,
      final Lattice lattice,
      final IStateVector<GraphNode, LatticeElement> startVector,
      final ITransformationProvider<GraphNode, LatticeElement> transformationProvider,
      final IGraphWalker<GraphNode, ObjectType> walker,
      final IMonotoneDebugger debugger) {
    Preconditions.checkNotNull(graph, "Error: Graph argument can not be null");
    Preconditions.checkNotNull(lattice, "Error: Lattice argument can not be null");
    Preconditions.checkNotNull(startVector, "Error: Start vector argument can not be null");
    Preconditions.checkNotNull(
        transformationProvider, "Error: Transformation list argument can not be null");

    final List<GraphNode> nodes = graph.getNodes();

    Preconditions.checkArgument(
        nodes.size() == startVector.size(),
        String.format(
            "Error: Invalid start vector (%d states for %d nodes)",
            startVector.size(), nodes.size()));

    for (final GraphNode node : nodes) {
      Preconditions.checkArgument(
          startVector.hasState(node),
          "Error: Node " + node + " does not have a state in the initial state vector");
    }

    this.graph = graph;
    this.lattice = lattice;
    this.state = startVector;
    this.transformationList = transformationProvider;
    this.walker = walker;
    this.debugger = debugger;
  }
Пример #17
0
  public T build() {
    Preconditions.checkArgument(null != serviceType, "ServiceType cannot be null.");
    Preconditions.checkArgument(null != clazz, "Service interface cannot be null.");
    Preconditions.checkArgument(clazz.isInterface(), "Service interface must be an interface.");
    if (null == factory) {
      if (null == strategy) {
        strategy = Strategy.RANDOM;
      }
      factory = LoadBalancerSupport.newFactory(strategy);
    }
    ServiceProxyFactory proxyFactory;
    switch (serviceType) {
      case THRIFT:
        proxyFactory = ThriftServiceProxyFactory.getInstance();
        break;
      default:
        throw new IllegalArgumentException("Not supported ServiceType: " + serviceType);
    }
    if (StringUtils.isEmpty(serviceName)) {
      serviceName = ServiceConfigHelper.buildDefaultServiceName(serviceType, clazz);
    }
    if (Strings.isNullOrEmpty(serviceGroup)) {
      serviceGroup = ZookeeperConfig.getServiceGroup(serviceName);
    }
    if (!Strings.isNullOrEmpty(user)) {}

    return proxyFactory.getService(serviceGroup, serviceName, factory, clazz);
  }
Пример #18
0
  /**
   * Creates a command that filters a specified set of directories.
   *
   * @param inResDirToOutResDirMap set of {@code res} directories to filter
   * @param filterDrawables whether to filter drawables (images)
   * @param enableStringWhitelisting whether to filter strings based on a whitelist
   * @param whitelistedStringDirs set of directories containing string resource files that must not
   *     be filtered out.
   * @param locales set of locales that the localized strings.xml files within {@code values-*}
   *     directories should be filtered by. This is useful if there are multiple apps that support a
   *     different set of locales that share a module. If empty, no filtering is performed.
   * @param filteredDirectoryCopier refer {@link FilteredDirectoryCopier}
   * @param targetDensities densities we're interested in keeping (e.g. {@code mdpi}, {@code hdpi}
   *     etc.) Only applicable if filterDrawables is true
   * @param drawableFinder refer {@link DrawableFinder}. Only applicable if filterDrawables is true.
   * @param imageScaler if not null, use the {@link ImageScaler} to downscale higher-density
   *     drawables for which we weren't able to find an image file of the proper density (as opposed
   *     to allowing Android to do it at runtime). Only applicable if filterDrawables. is true.
   */
  @VisibleForTesting
  FilterResourcesStep(
      ProjectFilesystem filesystem,
      ImmutableBiMap<Path, Path> inResDirToOutResDirMap,
      boolean filterDrawables,
      boolean enableStringWhitelisting,
      ImmutableSet<Path> whitelistedStringDirs,
      ImmutableSet<String> locales,
      FilteredDirectoryCopier filteredDirectoryCopier,
      @Nullable Set<ResourceFilters.Density> targetDensities,
      @Nullable DrawableFinder drawableFinder,
      @Nullable ImageScaler imageScaler) {

    Preconditions.checkArgument(filterDrawables || enableStringWhitelisting || !locales.isEmpty());
    Preconditions.checkArgument(
        !filterDrawables || (targetDensities != null && drawableFinder != null));

    this.filesystem = filesystem;
    this.inResDirToOutResDirMap = inResDirToOutResDirMap;
    this.filterDrawables = filterDrawables;
    this.enableStringWhitelisting = enableStringWhitelisting;
    this.whitelistedStringDirs = whitelistedStringDirs;
    this.locales = locales;
    this.filteredDirectoryCopier = filteredDirectoryCopier;
    this.targetDensities = targetDensities;
    this.drawableFinder = drawableFinder;
    this.imageScaler = imageScaler;
  }
Пример #19
0
  private void finishCompactionOutputFile(CompactionState compactionState) throws IOException {
    Preconditions.checkNotNull(compactionState, "compactionState is null");
    Preconditions.checkArgument(compactionState.outfile != null);
    Preconditions.checkArgument(compactionState.builder != null);

    long outputNumber = compactionState.currentFileNumber;
    Preconditions.checkArgument(outputNumber != 0);

    long currentEntries = compactionState.builder.getEntryCount();
    compactionState.builder.finish();

    long currentBytes = compactionState.builder.getFileSize();
    compactionState.currentFileSize = currentBytes;
    compactionState.totalBytes += currentBytes;

    FileMetaData currentFileMetaData =
        new FileMetaData(
            compactionState.currentFileNumber,
            compactionState.currentFileSize,
            compactionState.currentSmallest,
            compactionState.currentLargest);
    compactionState.outputs.add(currentFileMetaData);

    compactionState.builder = null;

    compactionState.outfile.force(true);
    compactionState.outfile.close();
    compactionState.outfile = null;

    if (currentEntries > 0) {
      // Verify that the table is usable
      tableCache.newIterator(outputNumber);
    }
  }
Пример #20
0
  InlineFunctions(
      AbstractCompiler compiler,
      Supplier<String> safeNameIdSupplier,
      boolean inlineGlobalFunctions,
      boolean inlineLocalFunctions,
      boolean blockFunctionInliningEnabled,
      boolean assumeStrictThis,
      boolean assumeMinimumCapture,
      int maxSizeAfterInlining) {
    Preconditions.checkArgument(compiler != null);
    Preconditions.checkArgument(safeNameIdSupplier != null);
    this.compiler = compiler;

    this.inlineGlobalFunctions = inlineGlobalFunctions;
    this.inlineLocalFunctions = inlineLocalFunctions;
    this.blockFunctionInliningEnabled = blockFunctionInliningEnabled;
    this.assumeMinimumCapture = assumeMinimumCapture;

    this.maxSizeAfterInlining = maxSizeAfterInlining;
    this.enforceMaxSizeAfterInlining =
        (maxSizeAfterInlining == CompilerOptions.UNLIMITED_FUN_SIZE_AFTER_INLINING) ? false : true;

    this.injector =
        new FunctionInjector(
            compiler, safeNameIdSupplier, true, assumeStrictThis, assumeMinimumCapture);
  }
  /**
   * Appends the given deltas to the deltas already stored. Updates the latest snapshot and latest
   * version as well. This method will make a copy of the snapshot.
   *
   * @param updatedSnapshot the snapshot after deltas have been applied
   * @param newDeltas the deltas that have been applied since the last call to appendDeltas.
   */
  public void appendDeltas(ReadableWaveletData updatedSnapshot, DeltaSequence newDeltas) {
    HashedVersion newEndVersion = newDeltas.getEndVersion();
    Preconditions.checkArgument(
        !newDeltas.isEmpty(), "There were no new deltas passed to appendDeltas");
    Preconditions.checkArgument(
        updatedSnapshot.getVersion() == newEndVersion.getVersion(),
        String.format(
            "Version of snapshot %s doesn't match the HashedVersion %s",
            updatedSnapshot.getVersion(), newEndVersion));
    Preconditions.checkArgument(
        areContiguousToCurrentVersion(newDeltas),
        String.format(
            "Deltas are not contiguous to the current version(%s) %s",
            getVersionAfterDeltas(), deltas));
    WaveletName updatedWaveletName = WaveletDataUtil.waveletNameOf(updatedSnapshot);
    Preconditions.checkArgument(
        updatedWaveletName.equals(waveletName),
        String.format(
            "Updated wavelet doesn't have the same name as with which this class has been "
                + "instantiated. %s != %s",
            updatedWaveletName, waveletName));

    // TODO(ljvderijk): This should actually be applying the deltas, however
    // they do not contain a timestamp at this time.
    snapshotAfterDeltas = WaveletDataUtil.copyWavelet(updatedSnapshot);
    deltas = DeltaSequence.join(deltas, newDeltas);
  }
Пример #22
0
  @JsonCreator
  public TopNNode(
      @JsonProperty("id") PlanNodeId id,
      @JsonProperty("source") PlanNode source,
      @JsonProperty("count") long count,
      @JsonProperty("orderBy") List<Symbol> orderBy,
      @JsonProperty("orderings") Map<Symbol, SortOrder> orderings,
      @JsonProperty("partial") boolean partial,
      @JsonProperty("sampleWeight") Optional<Symbol> sampleWeight) {
    super(id);

    Preconditions.checkNotNull(source, "source is null");
    Preconditions.checkArgument(count > 0, "count must be positive");
    Preconditions.checkNotNull(orderBy, "orderBy is null");
    Preconditions.checkArgument(!orderBy.isEmpty(), "orderBy is empty");
    Preconditions.checkArgument(
        orderings.size() == orderBy.size(), "orderBy and orderings sizes don't match");
    Preconditions.checkNotNull(sampleWeight, "sampleWeight is null");
    if (sampleWeight.isPresent()) {
      Preconditions.checkArgument(
          source.getOutputSymbols().contains(sampleWeight.get()),
          "source does not output sample weight");
    }

    this.source = source;
    this.count = count;
    this.orderBy = ImmutableList.copyOf(orderBy);
    this.orderings = ImmutableMap.copyOf(orderings);
    this.partial = partial;
    this.sampleWeight = sampleWeight;
  }
Пример #23
0
 private void handleVertexStateUpdate(VertexStateUpdate stateUpdate) {
   Preconditions.checkArgument(
       stateUpdate.getVertexState() == VertexState.CONFIGURED,
       "Received incorrect state notification : "
           + stateUpdate.getVertexState()
           + " for vertex: "
           + stateUpdate.getVertexName()
           + " in vertex: "
           + getContext().getVertexName());
   Preconditions.checkArgument(
       srcVertexInfo.containsKey(stateUpdate.getVertexName()),
       "Received incorrect vertex notification : "
           + stateUpdate.getVertexState()
           + " for vertex: "
           + stateUpdate.getVertexName()
           + " in vertex: "
           + getContext().getVertexName());
   SourceVertexInfo vInfo = srcVertexInfo.get(stateUpdate.getVertexName());
   Preconditions.checkState(vInfo.vertexIsConfigured == false);
   vInfo.vertexIsConfigured = true;
   LOG.info(
       "Received configured notification : "
           + stateUpdate.getVertexState()
           + " for vertex: "
           + stateUpdate.getVertexName()
           + " in vertex: "
           + getContext().getVertexName());
   schedulePendingTasks();
 }
Пример #24
0
  /**
   * @param id A unique id for this message (same across all translations).
   * @param altId An alternate unique id for this message, or -1L if not applicable.
   * @param localeString The language/locale string, or null if unknown. Should only be null for
   *     messages newly extracted from source files. Should always be set for messages parsed from
   *     message files/resources.
   * @param meaning The meaning string, or null if not necessary (usually null). This is a string to
   *     create unique messages for two otherwise identical messages. This is usually done for
   *     messages used in different contexts. (For example, the same word can be used as a noun in
   *     one location and as a verb in another location, and the message texts would be the same but
   *     the messages would have meanings of "noun" and "verb".). May not be applicable to all
   *     message plugins.
   * @param desc The description for translators.
   * @param isHidden Whether this message should be hidden. May not be applicable to all message
   *     plugins.
   * @param contentType Content type of the document that this message will appear in (e.g. "{@code
   *     text/html}"). May not be applicable to all message plugins.
   * @param sourceLocation Location of a source file that this message comes from. More sources can
   *     be added using {@code addSourceLocation()}. May not be applicable to all message plugins.
   * @param isPlrselMsg Whether this is a plural/select message.
   * @param parts The parts that make up the message content.
   */
  public SoyMsg(
      long id,
      long altId,
      @Nullable String localeString,
      @Nullable String meaning,
      @Nullable String desc,
      boolean isHidden,
      @Nullable String contentType,
      @Nullable SourceLocation sourceLocation,
      boolean isPlrselMsg,
      Iterable<? extends SoyMsgPart> parts) {

    checkArgument(id >= 0L);
    checkArgument(altId >= -1L);
    this.id = id;
    this.altId = altId;
    this.localeString = localeString;
    this.meaning = meaning;
    this.desc = desc;
    this.isHidden = isHidden;
    this.contentType = contentType;
    this.sourceLocations = ImmutableSet.of();
    if (sourceLocation != null) {
      addSourceLocation(sourceLocation);
    }
    this.isPlrselMsg = isPlrselMsg;
    this.parts = ImmutableList.copyOf(parts);
  }
Пример #25
0
 private ImmutableList<Path> conditionallyCopy(ImmutableList<Path> roots) throws IOException {
   final Builder<Path> builder = ImmutableList.builder();
   for (Path root : roots) {
     Preconditions.checkArgument(
         root.startsWith(workingDirectory),
         root + " must start with root " + workingDirectory + " from " + roots);
     Preconditions.checkArgument(
         !root.equals(workingDirectory),
         "Cannot deduplicate root directory: " + root + " from " + roots);
     if (!seen.containsKey(root)) {
       seen.put(root, null);
       final Path newRoot = out.resolve(workingDirectory.relativize(root));
       Files.walkFileTree(
           root,
           ImmutableSet.of(FileVisitOption.FOLLOW_LINKS),
           Integer.MAX_VALUE,
           new ConditionalCopyVisitor(newRoot, root, seen, hashFunction));
       builder.add(newRoot);
     } else {
       // Duplicated directories are ok -- multiple files from different libraries
       // can reside in the same directory, but duplicate files should not be seen mulitple times.
     }
   }
   return builder.build();
 }
Пример #26
0
		@Override
		public void onCommand(CommandSender sender, String[] args, boolean confirmedCmd)
				throws IllegalArgumentException {
			final ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]);
			final String reason = Utils.getFinalArg(args, 1);
			if(target == null){
				if(!confirmedCmd && Core.getPlayerIP(args[0]).equals("0.0.0.0")){
					mustConfirmCommand(sender, getName() + " " + Joiner.on(' ').join(args),
							_("operationUnknownPlayer", new String[] {args[0]}));
					return;
				}
			}
			
			if(sender instanceof ProxiedPlayer){
				checkArgument(PermissionManager.canExecuteAction(Action.WARN , sender, ((ProxiedPlayer)sender).getServer().getInfo().getName()),
						_("noPerm"));
			}
	          checkArgument(comment.hasLastcommentCooledDown(args[0]), _("cooldownUnfinished"));
			comment.insertComment(args[0], reason, Type.WARNING, sender.getName());
			if(target != null){
			  target.sendMessage(__("wasWarnedNotif", new String[] {reason}));
			}
			  
			BAT.broadcast(_("warnBroadcast", new String[]{args[0], sender.getName(), reason}), Action.WARN_BROADCAST.getPermission());
			return;
		}
Пример #27
0
 public void setPhase(@Nonnull EventPriority value) {
   Preconditions.checkArgument(value != null, "setPhase argument must not be null");
   int prev = phase == null ? -1 : phase.ordinal();
   Preconditions.checkArgument(
       prev < value.ordinal(), "Attempted to set event phase to %s when already %s", value, phase);
   phase = value;
 }
Пример #28
0
  private static void parseScriptLine(
      String line,
      ArrayList<Long> duration,
      ArrayList<Double> readProb,
      ArrayList<Double> writeProb) {
    String[] a = line.split("\\s");

    if (a.length != 3) {
      throw new IllegalArgumentException("Incorrect number of parameters: " + line);
    }

    try {
      long d = Long.parseLong(a[0]);
      double r = Double.parseDouble(a[1]);
      double w = Double.parseDouble(a[2]);

      Preconditions.checkArgument(d >= 0, "Invalid duration: " + d);
      Preconditions.checkArgument(0 <= r && r <= 1.0, "The read probability must be [0, 1]: " + r);
      Preconditions.checkArgument(0 <= w && w <= 1.0, "The read probability must be [0, 1]: " + w);

      readProb.add(r);
      duration.add(d);
      writeProb.add(w);
    } catch (NumberFormatException nfe) {
      throw new IllegalArgumentException("Cannot parse: " + line);
    }
  }
 @Override
 public void addValue(final int index, final FeatureValue fvalue) {
   Preconditions.checkArgument(fvalue != null, "fvalue is null");
   Preconditions.checkArgument(
       index <= values.size() && index >= 0, "index is not in range of: 0 and " + values.size());
   values.add(index, fvalue);
 }
Пример #30
0
 @VisibleForTesting
 static <T> BloomFilter<T> create(
     Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) {
   checkNotNull(funnel);
   checkArgument(
       expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions);
   checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
   checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
   checkNotNull(strategy);
   if (expectedInsertions == 0) {
     expectedInsertions = 1;
   }
   /*
    * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size
    * is proportional to -log(p), but there is not much of a point after all, e.g.
    * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares!
    */
   long numBits = optimalNumOfBits(expectedInsertions, fpp);
   int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
   try {
     return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, strategy);
   } catch (IllegalArgumentException e) {
     throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
   }
 }