Exemple #1
0
 // IndexOutOfBoundsException is raised when the instance is equal to ROOT
 ResourceId parent() {
   if (components.size() == 1) {
     return ROOT;
   } else {
     return new ResourceId(components.subList(0, components.size() - 1));
   }
 }
Exemple #2
0
  SummaryRuleFamily(ListMultimap<RuleType, RuleDocumentation> ruleTypeMap, String name) {
    this.name = name;
    this.binaryRules = ImmutableList.copyOf(ruleTypeMap.get(RuleType.BINARY));
    this.libraryRules = ImmutableList.copyOf(ruleTypeMap.get(RuleType.LIBRARY));
    this.testRules = ImmutableList.copyOf(ruleTypeMap.get(RuleType.TEST));

    final ImmutableList<RuleDocumentation> otherRules =
        ImmutableList.copyOf(ruleTypeMap.get(RuleType.OTHER));
    if (otherRules.size() >= 4) {
      this.otherRules1 = ImmutableList.copyOf(otherRules.subList(0, otherRules.size() / 2));
      this.otherRules2 =
          ImmutableList.copyOf(otherRules.subList(otherRules.size() / 2, otherRules.size()));
    } else {
      this.otherRules1 = otherRules;
      this.otherRules2 = ImmutableList.of();
    }
  }
Exemple #3
0
 public static int parseAndWriteBuckCompatibleDepfile(
     ExecutionContext context,
     ProjectFilesystem filesystem,
     HeaderPathNormalizer headerPathNormalizer,
     HeaderVerification headerVerification,
     Path sourceDepFile,
     Path destDepFile,
     Path inputPath,
     Path outputPath)
     throws IOException {
   // Process the dependency file, fixing up the paths, and write it out to it's final location.
   // The paths of the headers written out to the depfile are the paths to the symlinks from the
   // root of the repo if the compilation included them from the header search paths pointing to
   // the symlink trees, or paths to headers relative to the source file if the compilation
   // included them using source relative include paths. To handle both cases we check for the
   // prerequisites both in the values and the keys of the replacement map.
   Logger.get(Depfiles.class).debug("Processing dependency file %s as Makefile", sourceDepFile);
   ImmutableMap<String, Object> params =
       ImmutableMap.<String, Object>of("input", inputPath, "output", outputPath);
   try (InputStream input = filesystem.newFileInputStream(sourceDepFile);
       BufferedReader reader = new BufferedReader(new InputStreamReader(input));
       OutputStream output = filesystem.newFileOutputStream(destDepFile);
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
       SimplePerfEvent.Scope perfEvent =
           SimplePerfEvent.scope(
               context.getBuckEventBus(), PerfEventId.of("depfile-parse"), params)) {
     ImmutableList<String> prereqs = Depfiles.parseDepfile(reader).getPrereqs();
     // Skip the first prereq, as it's the input source file.
     Preconditions.checkState(inputPath.toString().equals(prereqs.get(0)));
     ImmutableList<String> headers = prereqs.subList(1, prereqs.size());
     for (String rawHeader : headers) {
       Path header = Paths.get(rawHeader).normalize();
       Optional<Path> absolutePath =
           headerPathNormalizer.getAbsolutePathForUnnormalizedPath(header);
       if (absolutePath.isPresent()) {
         Preconditions.checkState(absolutePath.get().isAbsolute());
         writer.write(absolutePath.get().toString());
         writer.newLine();
       } else if (headerVerification.getMode() != HeaderVerification.Mode.IGNORE
           && !headerVerification.isWhitelisted(header.toString())) {
         context
             .getBuckEventBus()
             .post(
                 ConsoleEvent.create(
                     headerVerification.getMode() == HeaderVerification.Mode.ERROR
                         ? Level.SEVERE
                         : Level.WARNING,
                     "%s: included an untracked header \"%s\"",
                     inputPath,
                     header));
         if (headerVerification.getMode() == HeaderVerification.Mode.ERROR) {
           return 1;
         }
       }
     }
   }
   return 0;
 }
 private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) {
   if (fromIndex == 0 && toIndex == size()) {
     return this;
   } else if (fromIndex == toIndex) {
     return emptyMap(comparator());
   } else {
     return from(keySet.getSubSet(fromIndex, toIndex), valueList.subList(fromIndex, toIndex));
   }
 }
  // -------------------------------------------------------------------------
  public void test_cashFlowEquivalentAndSensitivity() {
    Swap swap = Swap.builder().legs(IBOR_LEG, FIXED_LEG).build();
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedFull =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivitySwap(swap.expand(), PROVIDER);
    ImmutableList<NotionalExchange> keyComputedFull = computedFull.keySet().asList();
    ImmutableList<PointSensitivityBuilder> valueComputedFull = computedFull.values().asList();
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedIborLeg =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivityIborLeg(
            IBOR_LEG.expand(), PROVIDER);
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedFixedLeg =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivityFixedLeg(
            FIXED_LEG.expand(), PROVIDER);
    assertEquals(computedFixedLeg.keySet().asList(), keyComputedFull.subList(0, 2));
    assertEquals(computedIborLeg.keySet().asList(), keyComputedFull.subList(2, 6));
    assertEquals(computedFixedLeg.values().asList(), valueComputedFull.subList(0, 2));
    assertEquals(computedIborLeg.values().asList(), valueComputedFull.subList(2, 6));

    double eps = 1.0e-7;
    RatesFiniteDifferenceSensitivityCalculator calc =
        new RatesFiniteDifferenceSensitivityCalculator(eps);
    int size = keyComputedFull.size();
    for (int i = 0; i < size; ++i) {
      final int index = i;
      CurveCurrencyParameterSensitivities expected =
          calc.sensitivity(
              PROVIDER,
              p ->
                  ((NotionalExchange)
                          CashFlowEquivalentCalculator.cashFlowEquivalentSwap(swap.expand(), p)
                              .getPaymentEvents()
                              .get(index))
                      .getPaymentAmount());
      PointSensitivityBuilder point =
          computedFull.get(
              CashFlowEquivalentCalculator.cashFlowEquivalentSwap(swap.expand(), PROVIDER)
                  .getPaymentEvents()
                  .get(index));
      CurveCurrencyParameterSensitivities computed =
          PROVIDER.curveParameterSensitivity(point.build());
      assertTrue(computed.equalWithTolerance(expected, eps * NOTIONAL));
    }
  }
Exemple #6
0
 public static String removeParent(final String parentPath, final String childPath) {
   checkArgument(isChild(parentPath, childPath));
   ImmutableList<String> parent = split(parentPath);
   ImmutableList<String> child = split(childPath);
   child = child.subList(parent.size(), child.size());
   String strippedChildPath = child.get(0);
   for (int i = 1; i < child.size(); i++) {
     appendChild(strippedChildPath, child.get(i));
   }
   return strippedChildPath;
 }
 public void testCreatedErrors_03() {
   maxCallCount = 0;
   ImmutableList<ENamedElement> elements =
       ImmutableList.of(createEClass(), createEDataType(), createEPackage());
   for (ENamedElement classifier : elements) {
     classifier.setName("Same");
   }
   expected.addAll(elements.subList(0, 2));
   helper.checkUniqueNames(Scopes.scopedElementsFor(elements), this, this);
   assertEquals(elements.size(), callCount);
   assertTrue(expected.isEmpty());
 }
  @Override
  public Pagination<PaymentMethodPlugin> searchPaymentMethods(
      final String searchKey,
      final Long offset,
      final Long limit,
      final TenantContext tenantContext)
      throws PaymentPluginApiException {
    final ImmutableList<PaymentMethodPlugin> allResults =
        ImmutableList.<PaymentMethodPlugin>copyOf(
            Iterables.<PaymentMethodPlugin>filter(
                Iterables.<PaymentMethodPlugin>concat(paymentMethods.values()),
                new Predicate<PaymentMethodPlugin>() {
                  @Override
                  public boolean apply(final PaymentMethodPlugin input) {
                    return (input.getAddress1() != null && input.getAddress1().contains(searchKey))
                        || (input.getAddress2() != null && input.getAddress2().contains(searchKey))
                        || (input.getCCLast4() != null && input.getCCLast4().contains(searchKey))
                        || (input.getCCName() != null && input.getCCName().contains(searchKey))
                        || (input.getCity() != null && input.getCity().contains(searchKey))
                        || (input.getState() != null && input.getState().contains(searchKey))
                        || (input.getCountry() != null && input.getCountry().contains(searchKey));
                  }
                }));

    final List<PaymentMethodPlugin> results;
    if (offset >= allResults.size()) {
      results = ImmutableList.<PaymentMethodPlugin>of();
    } else if (offset + limit > allResults.size()) {
      results = allResults.subList(offset.intValue(), allResults.size());
    } else {
      results = allResults.subList(offset.intValue(), offset.intValue() + limit.intValue());
    }

    return new DefaultPagination<PaymentMethodPlugin>(
        offset,
        limit,
        (long) results.size(),
        (long) paymentMethods.values().size(),
        results.iterator());
  }
Exemple #9
0
 public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() {
   ImmutableList<Integer> allElements =
       ImmutableList.of(
           4233352, 3284593, 3794208, 3849533, 4013967, 2902658, 1886275, 2131109, 985872,
           1843868);
   for (int i = 0; i < allElements.size(); i++) {
     Set<Integer> elements = newHashSet(allElements.subList(0, i));
     Set<Set<Integer>> powerSet1 = powerSet(elements);
     Set<Set<Integer>> powerSet2 = powerSet(elements);
     new EqualsTester()
         .addEqualityGroup(powerSet1, powerSet2, toHashSets(powerSet1))
         .addEqualityGroup(ImmutableSet.of())
         .addEqualityGroup(ImmutableSet.of(9999999))
         .addEqualityGroup("notASet")
         .testEquals();
     assertEquals(toHashSets(powerSet1).hashCode(), powerSet1.hashCode());
   }
 }
 private BigInteger derivePrivateKeyDownwards(
     DeterministicKey cursor, byte[] parentalPrivateKeyBytes) {
   DeterministicKey downCursor =
       new DeterministicKey(
           cursor.childNumberPath,
           cursor.chainCode,
           cursor.pub,
           new BigInteger(1, parentalPrivateKeyBytes),
           cursor.parent);
   // Now we have to rederive the keys along the path back to ourselves. That path can be found by
   // just truncating
   // our path with the length of the parents path.
   ImmutableList<ChildNumber> path =
       childNumberPath.subList(cursor.getPath().size(), childNumberPath.size());
   for (ChildNumber num : path) {
     downCursor = HDKeyDerivation.deriveChildKey(downCursor, num);
   }
   // downCursor is now the same key as us, but with private key bytes.
   checkState(downCursor.pub.equals(pub));
   return checkNotNull(downCursor.priv);
 }
  public static <T, TOKEN> TokenBackedBasicResultsPage<T, TOKEN> getFirstPage(
      BatchingVisitable<T> v, int numToVisitArg, Function<T, TOKEN> tokenExtractor) {
    Preconditions.checkArgument(
        numToVisitArg >= 0, "numToVisit cannot be negative.  Value was: " + numToVisitArg);

    if (numToVisitArg == Integer.MAX_VALUE) {
      // prevent issue with overflow
      numToVisitArg--;
    }

    final int numToVisit = numToVisitArg + 1;
    ImmutableList<T> list = BatchingVisitableView.of(v).limit(numToVisit).immutableCopy();

    Preconditions.checkState(list.size() <= numToVisit);
    if (list.size() >= numToVisit) {
      TOKEN token = tokenExtractor.apply(list.get(list.size() - 1));
      list = list.subList(0, numToVisit - 1);
      return new SimpleTokenBackedResultsPage<T, TOKEN>(token, list, true);
    }

    return new SimpleTokenBackedResultsPage<T, TOKEN>(null, list, false);
  }
Exemple #12
0
 @Override
 public ImmutableList<E> subList(int fromIndex, int toIndex) {
   checkPositionIndexes(fromIndex, toIndex, size());
   return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
 }
 /**
  * Получить все теги сообщения по идентификационному номеру сообщения. Ограничение по числу тегов
  * для показа в заголовке в таблице
  *
  * @param msgId идентификационный номер сообщения
  * @return все теги сообщения
  */
 @Nonnull
 public ImmutableList<String> getMessageTagsForTitle(int msgId) {
   ImmutableList<String> tags = topicTagDao.getTags(msgId);
   return tags.subList(0, Math.min(tags.size(), MAX_TAGS_IN_TITLE));
 }
Exemple #14
0
  /**
   * Process the caller-provided arguments into an array suitable for the callee (this function).
   */
  public Object[] processArguments(
      List<Object> args, @Nullable Map<String, Object> kwargs, @Nullable Location loc)
      throws EvalException {

    Object[] arguments = new Object[getArgArraySize()];

    // extract function signature
    FunctionSignature sig = signature.getSignature();
    FunctionSignature.Shape shape = sig.getShape();
    ImmutableList<String> names = sig.getNames();
    List<Object> defaultValues = signature.getDefaultValues();

    // Note that this variable will be adjusted down if there are extra positionals,
    // after these extra positionals are dumped into starParam.
    int numPositionalArgs = args.size();

    int numMandatoryPositionalParams = shape.getMandatoryPositionals();
    int numOptionalPositionalParams = shape.getOptionalPositionals();
    int numMandatoryNamedOnlyParams = shape.getMandatoryNamedOnly();
    int numOptionalNamedOnlyParams = shape.getOptionalNamedOnly();
    boolean hasStarParam = shape.hasStarArg();
    boolean hasKwParam = shape.hasKwArg();
    int numPositionalParams = numMandatoryPositionalParams + numOptionalPositionalParams;
    int numNamedOnlyParams = numMandatoryNamedOnlyParams + numOptionalNamedOnlyParams;
    int numNamedParams = numPositionalParams + numNamedOnlyParams;
    int kwParamIndex = names.size() - 1; // only valid if hasKwParam

    // (1) handle positional arguments
    if (hasStarParam) {
      // Nota Bene: we collect extra positional arguments in a (tuple,) rather than a [list],
      // and this is actually the same as in Python.
      int starParamIndex = numNamedParams;
      if (numPositionalArgs > numPositionalParams) {
        arguments[starParamIndex] =
            Tuple.copyOf(args.subList(numPositionalParams, numPositionalArgs));
        numPositionalArgs = numPositionalParams; // clip numPositionalArgs
      } else {
        arguments[starParamIndex] = Tuple.EMPTY;
      }
    } else if (numPositionalArgs > numPositionalParams) {
      throw new EvalException(
          loc,
          numPositionalParams > 0
              ? "too many (" + numPositionalArgs + ") positional arguments in call to " + this
              : this + " does not accept positional arguments, but got " + numPositionalArgs);
    }

    for (int i = 0; i < numPositionalArgs; i++) {
      arguments[i] = args.get(i);
    }

    // (2) handle keyword arguments
    if (kwargs == null || kwargs.isEmpty()) {
      // Easy case (2a): there are no keyword arguments.
      // All arguments were positional, so check we had enough to fill all mandatory positionals.
      if (numPositionalArgs < numMandatoryPositionalParams) {
        throw new EvalException(
            loc,
            String.format(
                "insufficient arguments received by %s (got %s, expected at least %s)",
                this, numPositionalArgs, numMandatoryPositionalParams));
      }
      // We had no named argument, so fail if there were mandatory named-only parameters
      if (numMandatoryNamedOnlyParams > 0) {
        throw new EvalException(
            loc, String.format("missing mandatory keyword arguments in call to %s", this));
      }
      // Fill in defaults for missing optional parameters, that were conveniently grouped together,
      // thanks to the absence of mandatory named-only parameters as checked above.
      if (defaultValues != null) {
        int j = numPositionalArgs - numMandatoryPositionalParams;
        int endOptionalParams = numPositionalParams + numOptionalNamedOnlyParams;
        for (int i = numPositionalArgs; i < endOptionalParams; i++) {
          arguments[i] = defaultValues.get(j++);
        }
      }
      // If there's a kwParam, it's empty.
      if (hasKwParam) {
        // TODO(bazel-team): create a fresh mutable dict, like Python does
        arguments[kwParamIndex] = ImmutableMap.<String, Object>of();
      }
    } else if (hasKwParam && numNamedParams == 0) {
      // Easy case (2b): there are no named parameters, but there is a **kwParam.
      // Therefore all keyword arguments go directly to the kwParam.
      // Note that *starParam and **kwParam themselves don't count as named.
      // Also note that no named parameters means no mandatory parameters that weren't passed,
      // and no missing optional parameters for which to use a default. Thus, no loops.
      // TODO(bazel-team): create a fresh mutable dict, like Python does
      arguments[kwParamIndex] = kwargs; // NB: not 2a means kwarg isn't null
    } else {
      // Hard general case (2c): some keyword arguments may correspond to named parameters
      HashMap<String, Object> kwArg = hasKwParam ? new HashMap<String, Object>() : null;

      // For nicer stabler error messages, start by checking against
      // an argument being provided both as positional argument and as keyword argument.
      ArrayList<String> bothPosKey = new ArrayList<>();
      for (int i = 0; i < numPositionalArgs; i++) {
        String name = names.get(i);
        if (kwargs.containsKey(name)) {
          bothPosKey.add(name);
        }
      }
      if (!bothPosKey.isEmpty()) {
        throw new EvalException(
            loc,
            String.format(
                "argument%s '%s' passed both by position and by name in call to %s",
                (bothPosKey.size() > 1 ? "s" : ""), Joiner.on("', '").join(bothPosKey), this));
      }

      // Accept the arguments that were passed.
      for (Map.Entry<String, Object> entry : kwargs.entrySet()) {
        String keyword = entry.getKey();
        Object value = entry.getValue();
        int pos = names.indexOf(keyword); // the list should be short, so linear scan is OK.
        if (0 <= pos && pos < numNamedParams) {
          arguments[pos] = value;
        } else {
          if (!hasKwParam) {
            List<String> unexpected =
                Ordering.natural()
                    .sortedCopy(
                        Sets.difference(
                            kwargs.keySet(),
                            ImmutableSet.copyOf(names.subList(0, numNamedParams))));
            throw new EvalException(
                loc,
                String.format(
                    "unexpected keyword%s '%s' in call to %s",
                    unexpected.size() > 1 ? "s" : "", Joiner.on("', '").join(unexpected), this));
          }
          if (kwArg.containsKey(keyword)) {
            throw new EvalException(
                loc,
                String.format("%s got multiple values for keyword argument '%s'", this, keyword));
          }
          kwArg.put(keyword, value);
        }
      }
      if (hasKwParam) {
        // TODO(bazel-team): create a fresh mutable dict, like Python does
        arguments[kwParamIndex] = ImmutableMap.copyOf(kwArg);
      }

      // Check that all mandatory parameters were filled in general case 2c.
      // Note: it's possible that numPositionalArgs > numMandatoryPositionalParams but that's OK.
      for (int i = numPositionalArgs; i < numMandatoryPositionalParams; i++) {
        if (arguments[i] == null) {
          throw new EvalException(
              loc,
              String.format(
                  "missing mandatory positional argument '%s' while calling %s",
                  names.get(i), this));
        }
      }

      int endMandatoryNamedOnlyParams = numPositionalParams + numMandatoryNamedOnlyParams;
      for (int i = numPositionalParams; i < endMandatoryNamedOnlyParams; i++) {
        if (arguments[i] == null) {
          throw new EvalException(
              loc,
              String.format(
                  "missing mandatory named-only argument '%s' while calling %s",
                  names.get(i), this));
        }
      }

      // Get defaults for those parameters that weren't passed.
      if (defaultValues != null) {
        for (int i = Math.max(numPositionalArgs, numMandatoryPositionalParams);
            i < numPositionalParams;
            i++) {
          if (arguments[i] == null) {
            arguments[i] = defaultValues.get(i - numMandatoryPositionalParams);
          }
        }
        int numMandatoryParams = numMandatoryPositionalParams + numMandatoryNamedOnlyParams;
        for (int i = numMandatoryParams + numOptionalPositionalParams; i < numNamedParams; i++) {
          if (arguments[i] == null) {
            arguments[i] = defaultValues.get(i - numMandatoryParams);
          }
        }
      }
    } // End of general case 2c for argument passing.

    return arguments;
  }