Ejemplo n.º 1
0
 @Test
 public void testImageDensityFilter() {
   Set<Path> filesToRemove =
       Filters.filterByDensity(candidates, ImmutableSet.of(Density.MDPI), false);
   Predicate<Path> predicate =
       Filters.createImageDensityFilter(candidates, ImmutableSet.of(Density.MDPI), false);
   assertFalse(candidates.isEmpty());
   for (Path candidate : candidates) {
     assertEquals(!filesToRemove.contains(candidate), predicate.apply(candidate));
   }
 }
Ejemplo n.º 2
0
 @Test
 @SuppressWarnings("unchecked")
 public void testXxhdpiFilterRemovesUnneededResources() {
   Set<Path> xxhdpi = Filters.filterByDensity(candidates, ImmutableSet.of(Density.XXHDPI), false);
   Iterable<Path> keepPaths =
       Iterables.concat(
           paths("dmhx.png", XHDPI),
           paths("dmh.png", HDPI),
           paths("dmx.png", XHDPI),
           paths("dhx.png", XHDPI),
           paths("hx.png", XHDPI),
           paths("md.png", MDPI), // drawable-mdpi preferred over drawable.
           paths("l.png", LDPI),
           paths("d.png", DRAWABLE),
           paths("h11.png", HDPI_11),
           paths("2x.png", XXHDPI),
           paths("x2x.png", XXHDPI),
           paths("h3x.png", XXXHDPI),
           paths("dlmhx2x.png", XXHDPI),
           paths("dmhx_rx.png", XHDPI, XHDPI_RO),
           paths("dmhx_fmhx.png", XHDPI, XHDPI_FR),
           paths("lh2x_flh2x.png", XXHDPI, XXHDPI_FR),
           paths("mth11_flth.png", TVDPI, HDPI_11, HDPI_FR),
           paths("fm3x.png", XXXHDPI_FR),
           paths("lx.png", XHDPI),
           paths("nine.9.png", XXHDPI));
   MoreAsserts.assertSetEquals(pathsToRemove(candidates, Lists.newArrayList(keepPaths)), xxhdpi);
 }
Ejemplo n.º 3
0
  static void testServiceChannel(Service<Integer, String> aService) throws InterruptedException {
    Publisher<String> stringPublisher = aService.requestChannel(just(1));
    List<String> strings0 = toList(stringPublisher);
    assertTrue(strings0.equals(Arrays.asList("CHANNEL:1", "CHANNEL(+1):2")));

    Publisher<String> stringPublisher2 = aService.requestChannel(from(1, 2, 3, 4, 5));
    List<String> strings1 = toList(stringPublisher2);
    assertTrue(
        strings1.equals(
            Arrays.asList(
                "CHANNEL:1", "CHANNEL(+1):2",
                "CHANNEL:2", "CHANNEL(+1):3",
                "CHANNEL:3", "CHANNEL(+1):4",
                "CHANNEL:4", "CHANNEL(+1):5",
                "CHANNEL:5", "CHANNEL(+1):6")));

    Publisher<Double> doubles = from(1.0, 2.0, 3.0, 4.0, 5.0);
    Filter<Double, Integer, String, String> filter =
        Filters.fromFunction(x -> (int) (2 * x), str -> "'" + str + "'");
    Publisher<String> apply = filter.requestChannel(doubles, aService);
    List<String> strings2 = toList(apply);
    assertTrue(
        strings2.equals(
            Arrays.asList(
                "'CHANNEL:2'", "'CHANNEL(+1):3'",
                "'CHANNEL:4'", "'CHANNEL(+1):5'",
                "'CHANNEL:6'", "'CHANNEL(+1):7'",
                "'CHANNEL:8'", "'CHANNEL(+1):9'",
                "'CHANNEL:10'", "'CHANNEL(+1):11'")));
  }
Ejemplo n.º 4
0
  private HttpResponse sendRequest(HttpRequest httpRequest) {
    // if HttpRequest was set to null by a filter don't send request
    if (httpRequest != null) {
      String hostHeader = httpRequest.getFirstHeader("Host");
      if (!Strings.isNullOrEmpty(hostHeader)) {
        String[] hostHeaderParts = hostHeader.split(":");

        boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure();
        Integer port = (isSsl ? 443 : 80); // default
        if (hostHeaderParts.length > 1) {
          port = Integer.parseInt(hostHeaderParts[1]); // non-default
        }
        HttpResponse httpResponse =
            filters.applyOnResponseFilters(
                httpRequest,
                httpClient.sendRequest(outboundRequest(hostHeaderParts[0], port, "", httpRequest)));
        if (httpResponse != null) {
          return httpResponse;
        }
      } else {
        logger.error(
            "Host header must be provided for requests being forwarded, the following request does not include the \"Host\" header:"
                + System.getProperty("line.separator")
                + httpRequest);
        throw new IllegalArgumentException(
            "Host header must be provided for requests being forwarded");
      }
    }
    return notFoundResponse();
  }
Ejemplo n.º 5
0
 @Test
 @SuppressWarnings("unchecked")
 public void testLdpiMdpiFilterWithDownscale() {
   Set<Path> lmdpi =
       Filters.filterByDensity(candidates, ImmutableSet.of(Density.LDPI, Density.MDPI), true);
   Iterable<Path> keepPaths =
       Iterables.concat(
           paths("dmhx.png", MDPI),
           paths("dmh.png", MDPI),
           paths("dmx.png", MDPI),
           paths("dhx.png", DRAWABLE),
           paths("hx.png", XHDPI), // Downscale XHDPI
           paths("md.png", MDPI),
           paths("l.png", LDPI),
           paths("d.png", DRAWABLE),
           paths("h11.png", HDPI_11),
           paths("2x.png", XXHDPI),
           paths("x2x.png", XXHDPI),
           paths("h3x.png", XXXHDPI), // Downscale XXXHDPI
           paths("dlmhx2x.png", LDPI, MDPI),
           paths("dmhx_rx.png", MDPI, XHDPI_RO),
           paths("dmhx_fmhx.png", MDPI, MDPI_FR),
           paths("lh2x_flh2x.png", LDPI, XXHDPI, LDPI_FR, XXHDPI_FR), // Downscale XXHDPI
           paths("mth11_flth.png", MDPI, HDPI_11, LDPI_FR, HDPI_FR),
           paths("fm3x.png", MDPI_FR),
           paths("lx.png", LDPI, XHDPI),
           paths("nine.9.png", LDPI, XHDPI) /* No downscale */);
   MoreAsserts.assertSetEquals(pathsToRemove(candidates, Lists.newArrayList(keepPaths)), lmdpi);
 }
  public static DescribeServicesResponseType describeService(final DescribeServicesType request) {
    final DescribeServicesResponseType reply = request.getReply();
    Topology.touch(request);
    if (request.getServices().isEmpty()) {
      final ComponentId compId =
          (request.getByServiceType() != null)
              ? ComponentIds.lookup(request.getByServiceType().toLowerCase())
              : Empyrean.INSTANCE;
      final boolean showEventStacks = Boolean.TRUE.equals(request.getShowEventStacks());
      final boolean showEvents = Boolean.TRUE.equals(request.getShowEvents()) || showEventStacks;

      final Function<ServiceConfiguration, ServiceStatusType> transformToStatus =
          ServiceConfigurations.asServiceStatus(showEvents, showEventStacks);
      final List<Predicate<ServiceConfiguration>> filters =
          new ArrayList<Predicate<ServiceConfiguration>>() {
            {
              if (request.getByPartition() != null) {
                Partitions.exists(request.getByPartition());
                this.add(Filters.partition(request.getByPartition()));
              }
              if (request.getByState() != null) {
                final Component.State stateFilter =
                    Component.State.valueOf(request.getByState().toUpperCase());
                this.add(Filters.state(stateFilter));
              }
              if (!request.getServiceNames().isEmpty()) {
                this.add(Filters.name(request.getServiceNames()));
              }
              this.add(Filters.host(request.getByHost()));
              this.add(
                  Filters.listAllOrInternal(
                      request.getListAll(),
                      request.getListUserServices(),
                      request.getListInternal()));
            }
          };
      final Predicate<Component> componentFilter = Filters.componentType(compId);
      final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters);

      List<ServiceConfiguration> replyConfigs = Lists.newArrayList();
      for (final Component comp : Components.list()) {
        if (componentFilter.apply(comp)) {
          Collection<ServiceConfiguration> acceptedConfigs =
              Collections2.filter(comp.services(), configPredicate);
          replyConfigs.addAll(acceptedConfigs);
        }
      }
      ImmutableList<ServiceConfiguration> sortedReplyConfigs =
          ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs);
      final Collection<ServiceStatusType> transformedReplyConfigs =
          Collections2.transform(sortedReplyConfigs, transformToStatus);
      reply.getServiceStatuses().addAll(transformedReplyConfigs);
    } else {
      for (ServiceId s : request.getServices()) {
        reply.getServiceStatuses().add(TypeMappers.transform(s, ServiceStatusType.class));
      }
    }
    return reply;
  }
Ejemplo n.º 7
0
  /**
   * Removes the given file filter.
   *
   * @param filter file filter to remove.
   * @throws IllegalStateException if the scanner hasn't finished processing yet (<code>
   *     isFinished() == true</code>)
   */
  public void removeFilter(FilenameFilter filter) {
    if (isFinished()) {
      throw new IllegalStateException(
          ResourceBundleFactory.getBundle(BUNDLE_NAME).getString("SCANNER_RUNNING" /* NOI18N */));
    }

    _filters.removeFilter(filter);
  }
Ejemplo n.º 8
0
 private void forwardRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) {
   HttpResponse httpResponse =
       sendRequest(
           filters.applyOnRequestFilters(
               httpServletRequestToMockServerRequestDecoder
                   .mapHttpServletRequestToMockServerRequest(request)));
   mockServerResponseToHttpServletResponseEncoder.mapMockServerResponseToHttpServletResponse(
       httpResponse, httpServletResponse);
 }
Ejemplo n.º 9
0
  /**
   * Similar to main method but is not static
   *
   * @param args command line parameters
   * @throws Exception if something fails during the execution
   */
  public void doIt(String[] args) throws Exception {

    Config.loadConfig(
        new File("/Users/jzarzuela/Documents/java-Campus/_Util_DivxCleaner/resources/config.xml"));

    String newName =
        Filters.filterName(
            "Llama A La Comadrona - Temporada 1 [HDTV][Cap.103][Español Castellano]/LlaALComad103 [www.newpct.com]");
    System.out.println(newName);
  }
Ejemplo n.º 10
0
  public static final CapReqBuilder createPackageRequirement(String pkgName, String range) {
    Filter filter;
    SimpleFilter pkgNameFilter = new SimpleFilter(PackageNamespace.PACKAGE_NAMESPACE, pkgName);
    if (range != null)
      filter =
          new AndFilter()
              .addChild(pkgNameFilter)
              .addChild(new LiteralFilter(Filters.fromVersionRange(range)));
    else filter = pkgNameFilter;

    return new CapReqBuilder(PackageNamespace.PACKAGE_NAMESPACE)
        .addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString());
  }
Ejemplo n.º 11
0
  public static Map<String, List<SimplifiedLog>> getPreparedTestData(int msgAmount, Level level) {
    List<SimplifiedLog> allLogs = create(msgAmount, level, false);
    List<SimplifiedLog> host =
        allLogs
            .stream()
            .filter(log -> log.getHostName().equals(HOST1))
            .collect(Collectors.toList());
    List<SimplifiedLog> time =
        host.stream().filter(Validators.isTimestampAround(TIME1)).collect(Collectors.toList());
    List<SimplifiedLog> logger = Filters.filterByLogger(time, LOGGER1);
    List<SimplifiedLog> thread = Filters.filterByThread(time, THREAD1);
    List<SimplifiedLog> loggerThread = Filters.filterByThread(logger, THREAD1);

    Map<String, List<SimplifiedLog>> toReturn = new HashMap<>();
    toReturn.put("all", allLogs);
    toReturn.put("host", host);
    toReturn.put("time", time);
    toReturn.put("logger", logger);
    toReturn.put("thread", thread);
    toReturn.put("logger_thread", loggerThread);
    return toReturn;
  }
Ejemplo n.º 12
0
  public static CapReqBuilder createSimpleRequirement(String ns, String name, String range) {
    Filter filter;
    SimpleFilter bsnFilter = new SimpleFilter(ns, name);
    if (range != null)
      filter =
          new AndFilter()
              .addChild(bsnFilter)
              .addChild(new LiteralFilter(Filters.fromVersionRange(range)));
    else filter = bsnFilter;

    return new CapReqBuilder(ns)
        .addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString());
  }
Ejemplo n.º 13
0
  public static CapReqBuilder createBundleRequirement(String bsn, String range) {
    Filter filter;
    SimpleFilter bsnFilter = new SimpleFilter(IdentityNamespace.IDENTITY_NAMESPACE, bsn);
    if (range != null)
      filter =
          new AndFilter()
              .addChild(bsnFilter)
              .addChild(new LiteralFilter(Filters.fromVersionRange(range)));
    else filter = bsnFilter;

    return new CapReqBuilder(IdentityNamespace.IDENTITY_NAMESPACE)
        .addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString());
  }
Ejemplo n.º 14
0
  /**
   * Create an 'empty' BootDashViewModel with no run targets. Targets can be added by adding them to
   * the runTarget's LiveSet.
   */
  public BootDashViewModel(BootDashModelContext context, RunTargetType... runTargetTypes) {
    runTargets = new LiveSet<RunTarget>(new LinkedHashSet<RunTarget>());
    models = new BootDashModelManager(context, runTargets);

    manager = new RunTargetPropertiesManager(context, runTargetTypes);
    List<RunTarget> existingtargets = manager.getStoredTargets();
    runTargets.addAll(existingtargets);
    runTargets.addListener(manager);

    this.runTargetTypes = new LinkedHashSet<RunTargetType>(Arrays.asList(runTargetTypes));
    filterBox = new TagFilterBoxModel();
    toggleFiltersModel = new ToggleFiltersModel();
    filter = Filters.compose(filterBox.getFilter(), toggleFiltersModel.getFilter());
    devtoolsProcessTracker = DevtoolsUtil.createProcessTracker(this);
  }
Ejemplo n.º 15
0
  /**
   * Single joystick to control robot drive
   *
   * @param controlStickX magnitude of turning axis
   * @param controlStickY magnitude of driving axis
   */
  public void ArcadeDrive(double controlStickX, double controlStickY) {
    double xRotation = controlStickX;
    double yDrive = controlStickY;

    xRotation = Filters.powerCurving(controlStickX, 0.75); // filter rotational values

    if (Math.abs(yDrive) >= speedLimit) {
      yDrive = (Math.abs(yDrive) / yDrive) * speedLimit;
    }
    if (Math.abs(xRotation) >= speedLimit) {
      xRotation = (Math.abs(xRotation) / xRotation) * speedLimit;
    }

    drive.arcadeDrive(-yDrive, -(xRotation));
  }
  private static void validateLegacyFilter(
      final KernelServices kernelServices,
      final ModelVersion modelVersion,
      final ModelNode address,
      final String filterExpression)
      throws OperationFailedException {
    ModelNode op = Operations.createReadResourceOperation(address);
    ModelNode result = executeTransformOperation(kernelServices, modelVersion, op);
    // No filter-spec should be there
    Assert.assertFalse(
        "filter-spec found at: " + address.asString(),
        result.has(CommonAttributes.FILTER_SPEC.getName()));

    op = Operations.createReadAttributeOperation(address, CommonAttributes.FILTER);
    result = executeTransformOperation(kernelServices, modelVersion, op);
    Assert.assertEquals(
        "Transformed spec does not match filter expression.",
        Filters.filterToFilterSpec(Operations.readResult(result)),
        filterExpression);
  }
Ejemplo n.º 17
0
    public DescribeServicesResponseType user(final DescribeServicesType request) {
      final DescribeServicesResponseType reply = request.getReply();
      /**
       * Only show public services to normal users. Allow for filtering by component and state w/in
       * that set.
       */
      final List<Predicate<ServiceConfiguration>> filters =
          new ArrayList<Predicate<ServiceConfiguration>>() {
            {
              this.add(Filters.publicService());
              if (request.getByPartition() != null) {
                this.add(Filters.partition(request.getByPartition()));
              }
              if (request.getByState() != null) {
                this.add(
                    Filters.state(Component.State.valueOf(request.getByState().toUpperCase())));
              }
            }
          };
      final Predicate<Component> componentFilter =
          (Predicate<Component>)
              (request.getByServiceType() != null
                  ? Filters.componentType(
                      ComponentIds.lookup(request.getByServiceType().toLowerCase()))
                  : Predicates.alwaysTrue());
      final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters);

      final Collection<ServiceConfiguration> replyConfigs = Lists.newArrayList();
      for (final Component comp : Iterables.filter(Components.list(), componentFilter)) {
        replyConfigs.addAll(Collections2.filter(comp.services(), configPredicate));
      }
      final ImmutableList<ServiceConfiguration> sortedReplyConfigs =
          ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs);
      final Collection<ServiceStatusType> replyStatuses =
          Collections2.transform(
              sortedReplyConfigs, ServiceConfigurations.asServiceStatus(false, false));
      reply.getServiceStatuses().addAll(replyStatuses);
      return reply;
    }
Ejemplo n.º 18
0
 /**
  * Sets the hint to the given value. If the key corresponds to a known key, then that value is set
  * via the setter method. Otherwise it is put into opaque hints map. <br>
  * In either case, the original value is put in the hints map. So essential difference between
  * setting a value directly by a setter and via a hint is the memory of this original value. <br>
  * The other important difference is setting lock levels. Setting of lock level via setter method
  * needs active transaction. But setting via hint does not.
  *
  * @param key a hint key. If it is one of the statically registered hint key then the setter is
  *     called.
  * @param value to be set. The given value type must match the argument type of the setter, if one
  *     exists.
  * @param original value as specified by the caller. This value is put in the hints map.
  * @exception IllegalArgumentException if the given value is not acceptable by the setter method,
  *     if one exists corresponds the given hint key.
  */
 public void setHint(String key, Object value, Object original) {
   if (key == null) return;
   if (_hintSetters.containsKey(key)) {
     Method setter = _hintSetters.get(key);
     String methodName = setter.getName();
     try {
       if ("setReadLockLevel".equals(methodName) && !isActiveTransaction()) {
         _state.readLockLevel = (Integer) value;
       } else if ("setWriteLockLevel".equals(methodName) && !isActiveTransaction()) {
         _state.writeLockLevel = (Integer) value;
       } else {
         setter.invoke(this, Filters.convertToMatchMethodArgument(value, setter));
       }
     } catch (Exception e) {
       String message =
           _loc.get("bad-hint-value", key, toString(value), toString(original)).getMessage();
       if (e instanceof IllegalArgumentException) {
         throw new IllegalArgumentException(message);
       }
       throw new IllegalArgumentException(message, e);
     }
   }
   addHint(key, original);
 }
Ejemplo n.º 19
0
  /**
   * Codebook Search Quantification (Split Shape).
   *
   * @param target target vector
   * @param ak LPCs for this subframe
   * @param awk1 Weighted LPCs for this subframe
   * @param awk2 Weighted LPCs for this subframe
   * @param p number of LPC coeffs
   * @param nsf number of samples in subframe
   * @param exc excitation array.
   * @param es position in excitation array.
   * @param r
   * @param bits Speex bits buffer.
   * @param complexity
   */
  public final void quant(
      float[] target,
      float[] ak,
      float[] awk1,
      float[] awk2,
      int p,
      int nsf,
      float[] exc,
      int es,
      float[] r,
      @NotNull Bits bits,
      int complexity) {
    int i, j, k, m, n, q;
    float[] resp;
    float[] ndist, odist;
    int[] best_index;
    float[] best_dist;

    int N = complexity;
    if (N > 10) N = 10;

    resp = new float[shape_cb_size * subvect_size];

    best_index = new int[N];
    best_dist = new float[N];
    ndist = new float[N];
    odist = new float[N];

    for (i = 0; i < N; i++) {
      for (j = 0; j < nb_subvect; j++) nind[i][j] = oind[i][j] = -1;
    }

    for (j = 0; j < N; j++) for (i = 0; i < nsf; i++) ot[j][i] = target[i];

    //    System.arraycopy(target, 0, t, 0, nsf);

    /* Pre-compute codewords response and energy */
    for (i = 0; i < shape_cb_size; i++) {
      int res;
      int shape;

      res = i * subvect_size;
      shape = i * subvect_size;

      /* Compute codeword response using convolution with impulse response */
      for (j = 0; j < subvect_size; j++) {
        resp[res + j] = 0;
        for (k = 0; k <= j; k++) resp[res + j] += 0.03125f * shape_cb[shape + k] * r[j - k];
      }

      /* Compute codeword energy */
      E[i] = 0;
      for (j = 0; j < subvect_size; j++) E[i] += resp[res + j] * resp[res + j];
    }

    for (j = 0; j < N; j++) odist[j] = 0;
    /*For all subvectors*/
    for (i = 0; i < nb_subvect; i++) {
      int offset = i * subvect_size;
      /*"erase" nbest list*/
      for (j = 0; j < N; j++) ndist[j] = -1;

      /*For all n-bests of previous subvector*/
      for (j = 0; j < N; j++) {
        /*Find new n-best based on previous n-best j*/
        if (have_sign != 0)
          VQ.nbest_sign(
              ot[j], offset, resp, subvect_size, shape_cb_size, E, N, best_index, best_dist);
        else
          VQ.nbest(ot[j], offset, resp, subvect_size, shape_cb_size, E, N, best_index, best_dist);

        /*For all new n-bests*/
        for (k = 0; k < N; k++) {
          float[] ct;
          float err = 0;
          ct = ot[j];
          /*update target*/

          /*previous target*/
          for (m = offset; m < offset + subvect_size; m++) t[m] = ct[m];

          /* New code: update only enough of the target to calculate error*/
          {
            int rind;
            int res;
            float sign = 1;
            rind = best_index[k];
            if (rind >= shape_cb_size) {
              sign = -1;
              rind -= shape_cb_size;
            }
            res = rind * subvect_size;
            if (sign > 0) for (m = 0; m < subvect_size; m++) t[offset + m] -= resp[res + m];
            else for (m = 0; m < subvect_size; m++) t[offset + m] += resp[res + m];
          }

          /*compute error (distance)*/
          err = odist[j];
          for (m = offset; m < offset + subvect_size; m++) err += t[m] * t[m];
          /*update n-best list*/
          if (err < ndist[N - 1] || ndist[N - 1] < -0.5f) {

            /*previous target (we don't care what happened before*/
            for (m = offset + subvect_size; m < nsf; m++) t[m] = ct[m];
            /* New code: update the rest of the target only if it's worth it */
            for (m = 0; m < subvect_size; m++) {
              float g;
              int rind;
              float sign = 1;
              rind = best_index[k];
              if (rind >= shape_cb_size) {
                sign = -1;
                rind -= shape_cb_size;
              }

              g = sign * 0.03125f * shape_cb[rind * subvect_size + m];
              q = subvect_size - m;
              for (n = offset + subvect_size; n < nsf; n++, q++) t[n] -= g * r[q];
            }

            for (m = 0; m < N; m++) {
              if (err < ndist[m] || ndist[m] < -0.5f) {
                for (n = N - 1; n > m; n--) {
                  for (q = offset + subvect_size; q < nsf; q++) nt[n][q] = nt[n - 1][q];
                  for (q = 0; q < nb_subvect; q++) nind[n][q] = nind[n - 1][q];
                  ndist[n] = ndist[n - 1];
                }
                for (q = offset + subvect_size; q < nsf; q++) nt[m][q] = t[q];
                for (q = 0; q < nb_subvect; q++) nind[m][q] = oind[j][q];
                nind[m][i] = best_index[k];
                ndist[m] = err;
                break;
              }
            }
          }
        }
        if (i == 0) break;
      }

      /*update old-new data*/
      /* just swap pointers instead of a long copy */
      {
        float[][] tmp2;
        tmp2 = ot;
        ot = nt;
        nt = tmp2;
      }
      for (j = 0; j < N; j++) for (m = 0; m < nb_subvect; m++) oind[j][m] = nind[j][m];
      for (j = 0; j < N; j++) odist[j] = ndist[j];
    }

    /*save indices*/
    for (i = 0; i < nb_subvect; i++) {
      ind[i] = nind[0][i];
      bits.pack(ind[i], shape_bits + have_sign);
    }

    /* Put everything back together */
    for (i = 0; i < nb_subvect; i++) {
      int rind;
      float sign = 1;
      rind = ind[i];
      if (rind >= shape_cb_size) {
        sign = -1;
        rind -= shape_cb_size;
      }

      for (j = 0; j < subvect_size; j++)
        e[subvect_size * i + j] = sign * 0.03125f * shape_cb[rind * subvect_size + j];
    }
    /* Update excitation */
    for (j = 0; j < nsf; j++) exc[es + j] += e[j];

    /* Update target */
    Filters.syn_percep_zero(e, 0, ak, awk1, awk2, r2, nsf, p);
    for (j = 0; j < nsf; j++) target[j] -= r2[j];
  }
Ejemplo n.º 20
0
 /**
  * Add filter for HTTP response, each filter get called after each request has been proxied
  *
  * @param httpRequest the request to match against for this filter
  * @param filter the filter that is executed after this request has been proxied
  */
 public ProxyServlet withFilter(HttpRequest httpRequest, ResponseFilter filter) {
   filters.withFilter(httpRequest, filter);
   return this;
 }
Ejemplo n.º 21
0
 /**
  * Sets the filter policy to use.
  *
  * @param policy valid filter policy.
  */
 public void setFilterPolicy(int policy) {
   if (_filters != null) {
     _filters.setPolicy(policy);
   }
 }
Ejemplo n.º 22
0
 public ProxyServlet() {
   filters.withFilter(new HttpRequest(), new HopByHopHeaderFilter());
   filters.withFilter(new HttpRequest(), requestLogFilter);
   filters.withFilter(new HttpRequest(), requestResponseLogFilter);
 }
Ejemplo n.º 23
0
 /**
  * Creates an interpolator using a simple fir1 16th order low pass filter.
  *
  * @param factor upsample factor
  * @throws IllegalArgumentException if the upsample factor is not supported
  * @see Filters#createFir1_16thOrderLowpass(int)
  */
 public Interpolator(final int factor) {
   this(Filters.createFir1_16thOrderLowpass(factor).getCoefficients(), factor);
 }
Ejemplo n.º 24
0
  /**
   * Encode the given input signal.
   *
   * @param bits - Speex bits buffer.
   * @param in - the raw mono audio frame to encode.
   * @return 1 if successful.
   */
  public int encode(final Bits bits, final float[] in) {
    int i;
    float[] mem, innov, syn_resp;
    float[] low_pi_gain, low_exc, low_innov;
    int dtx;

    /* Compute the two sub-bands by filtering with h0 and h1*/
    Filters.qmf_decomp(in, h0, x0d, x1d, fullFrameSize, QMF_ORDER, h0_mem);
    /* Encode the narrowband part*/
    lowenc.encode(bits, x0d);

    /* High-band buffering / sync with low band */
    for (i = 0; i < windowSize - frameSize; i++) high[i] = high[frameSize + i];
    for (i = 0; i < frameSize; i++) high[windowSize - frameSize + i] = x1d[i];

    System.arraycopy(excBuf, frameSize, excBuf, 0, bufSize - frameSize);

    low_pi_gain = lowenc.getPiGain();
    low_exc = lowenc.getExc();
    low_innov = lowenc.getInnov();

    int low_mode = lowenc.getMode();
    if (low_mode == 0) dtx = 1;
    else dtx = 0;

    /* Start encoding the high-band */
    for (i = 0; i < windowSize; i++) buf[i] = high[i] * window[i];

    /* Compute auto-correlation */
    Lpc.autocorr(buf, autocorr, lpcSize + 1, windowSize);

    autocorr[0] += 1; /* prevents NANs */
    autocorr[0] *= lpc_floor; /* Noise floor in auto-correlation domain */
    /* Lag windowing: equivalent to filtering in the power-spectrum domain */
    for (i = 0; i < lpcSize + 1; i++) autocorr[i] *= lagWindow[i];

    /* Levinson-Durbin */
    Lpc.wld(lpc, autocorr, rc, lpcSize); // tmperr
    System.arraycopy(lpc, 0, lpc, 1, lpcSize);
    lpc[0] = 1;

    /* LPC to LSPs (x-domain) transform */
    int roots = Lsp.lpc2lsp(lpc, lpcSize, lsp, 15, 0.2f);
    if (roots != lpcSize) {
      roots = Lsp.lpc2lsp(lpc, lpcSize, lsp, 11, 0.02f);
      if (roots != lpcSize) {
        /*If we can't find all LSP's, do some damage control and use a flat filter*/
        for (i = 0; i < lpcSize; i++) {
          lsp[i] = (float) Math.cos(Math.PI * ((float) (i + 1)) / (lpcSize + 1));
        }
      }
    }

    /* x-domain to angle domain*/
    for (i = 0; i < lpcSize; i++) lsp[i] = (float) Math.acos(lsp[i]);

    float lsp_dist = 0;
    for (i = 0; i < lpcSize; i++) lsp_dist += (old_lsp[i] - lsp[i]) * (old_lsp[i] - lsp[i]);

    /*VBR stuff*/
    if ((vbr_enabled != 0 || vad_enabled != 0) && dtx == 0) {
      float e_low = 0, e_high = 0;
      float ratio;
      if (abr_enabled != 0) {
        float qual_change = 0;
        if (abr_drift2 * abr_drift > 0) {
          /* Only adapt if long-term and short-term drift are the same sign */
          qual_change = -.00001f * abr_drift / (1 + abr_count);
          if (qual_change > .1f) qual_change = .1f;
          if (qual_change < -.1f) qual_change = -.1f;
        }
        vbr_quality += qual_change;
        if (vbr_quality > 10) vbr_quality = 10;
        if (vbr_quality < 0) vbr_quality = 0;
      }

      for (i = 0; i < frameSize; i++) {
        e_low += x0d[i] * x0d[i];
        e_high += high[i] * high[i];
      }
      ratio = (float) Math.log((1 + e_high) / (1 + e_low));
      relative_quality = lowenc.getRelativeQuality();

      if (ratio < -4) ratio = -4;
      if (ratio > 2) ratio = 2;
      /*if (ratio>-2)*/
      if (vbr_enabled != 0) {
        int modeid;
        modeid = nb_modes - 1;
        relative_quality += 1.0 * (ratio + 2);
        if (relative_quality < -1) {
          relative_quality = -1;
        }
        while (modeid != 0) {
          int v1;
          float thresh;
          v1 = (int) Math.floor(vbr_quality);
          if (v1 == 10) thresh = Vbr.hb_thresh[modeid][v1];
          else
            thresh =
                (vbr_quality - v1) * Vbr.hb_thresh[modeid][v1 + 1]
                    + (1 + v1 - vbr_quality) * Vbr.hb_thresh[modeid][v1];
          if (relative_quality >= thresh) break;
          modeid--;
        }
        setMode(modeid);
        if (abr_enabled != 0) {
          int bitrate;
          bitrate = getBitRate();
          abr_drift += (bitrate - abr_enabled);
          abr_drift2 = .95f * abr_drift2 + .05f * (bitrate - abr_enabled);
          abr_count += 1.0;
        }
      } else {
        /* VAD only */
        int modeid;
        if (relative_quality < 2.0) modeid = 1;
        else modeid = submodeSelect;
        /*speex_encoder_ctl(state, SPEEX_SET_MODE, &mode);*/
        submodeID = modeid;
      }
      /*fprintf (stderr, "%f %f\n", ratio, low_qual);*/
    }

    bits.pack(1, 1);
    if (dtx != 0) bits.pack(0, SB_SUBMODE_BITS);
    else bits.pack(submodeID, SB_SUBMODE_BITS);

    /* If null mode (no transmission), just set a couple things to zero*/
    if (dtx != 0 || submodes[submodeID] == null) {
      for (i = 0; i < frameSize; i++) excBuf[excIdx + i] = swBuf[i] = VERY_SMALL;

      for (i = 0; i < lpcSize; i++) mem_sw[i] = 0;
      first = 1;

      /* Final signal synthesis from excitation */
      Filters.iir_mem2(excBuf, excIdx, interp_qlpc, high, 0, subframeSize, lpcSize, mem_sp);

      /* Reconstruct the original */
      filters.fir_mem_up(x0d, h0, y0, fullFrameSize, QMF_ORDER, g0_mem);
      filters.fir_mem_up(high, h1, y1, fullFrameSize, QMF_ORDER, g1_mem);

      for (i = 0; i < fullFrameSize; i++) in[i] = 2 * (y0[i] - y1[i]);

      if (dtx != 0) return 0;
      else return 1;
    }

    /* LSP quantization */
    submodes[submodeID].lsqQuant.quant(lsp, qlsp, lpcSize, bits);

    if (first != 0) {
      for (i = 0; i < lpcSize; i++) old_lsp[i] = lsp[i];
      for (i = 0; i < lpcSize; i++) old_qlsp[i] = qlsp[i];
    }

    mem = new float[lpcSize];
    syn_resp = new float[subframeSize];
    innov = new float[subframeSize];

    for (int sub = 0; sub < nbSubframes; sub++) {
      float tmp, filter_ratio;
      int exc, sp, sw, resp;
      int offset;
      float rl, rh, eh = 0, el = 0;
      int fold;

      offset = subframeSize * sub;
      sp = offset;
      exc = excIdx + offset;
      resp = offset;
      sw = offset;

      /* LSP interpolation (quantized and unquantized) */
      tmp = (1.0f + sub) / nbSubframes;
      for (i = 0; i < lpcSize; i++) interp_lsp[i] = (1 - tmp) * old_lsp[i] + tmp * lsp[i];
      for (i = 0; i < lpcSize; i++) interp_qlsp[i] = (1 - tmp) * old_qlsp[i] + tmp * qlsp[i];

      Lsp.enforce_margin(interp_lsp, lpcSize, .05f);
      Lsp.enforce_margin(interp_qlsp, lpcSize, .05f);

      /* Compute interpolated LPCs (quantized and unquantized) */
      for (i = 0; i < lpcSize; i++) interp_lsp[i] = (float) Math.cos(interp_lsp[i]);
      for (i = 0; i < lpcSize; i++) interp_qlsp[i] = (float) Math.cos(interp_qlsp[i]);

      m_lsp.lsp2lpc(interp_lsp, interp_lpc, lpcSize);
      m_lsp.lsp2lpc(interp_qlsp, interp_qlpc, lpcSize);

      Filters.bw_lpc(gamma1, interp_lpc, bw_lpc1, lpcSize);
      Filters.bw_lpc(gamma2, interp_lpc, bw_lpc2, lpcSize);

      /* Compute mid-band (4000 Hz for wideband) response of low-band and high-band
      filters */
      rl = rh = 0;
      tmp = 1;
      pi_gain[sub] = 0;
      for (i = 0; i <= lpcSize; i++) {
        rh += tmp * interp_qlpc[i];
        tmp = -tmp;
        pi_gain[sub] += interp_qlpc[i];
      }
      rl = low_pi_gain[sub];
      rl = 1 / (Math.abs(rl) + .01f);
      rh = 1 / (Math.abs(rh) + .01f);
      /* Compute ratio, will help predict the gain */
      filter_ratio = Math.abs(.01f + rh) / (.01f + Math.abs(rl));

      fold = filter_ratio < 5 ? 1 : 0;
      /*printf ("filter_ratio %f\n", filter_ratio);*/
      fold = 0;

      /* Compute "real excitation" */
      Filters.fir_mem2(high, sp, interp_qlpc, excBuf, exc, subframeSize, lpcSize, mem_sp2);
      /* Compute energy of low-band and high-band excitation */
      for (i = 0; i < subframeSize; i++) eh += excBuf[exc + i] * excBuf[exc + i];

      if (submodes[submodeID].innovation == null) {
          /* 1 for spectral folding excitation, 0 for stochastic */
        float g;
        /*speex_bits_pack(bits, 1, 1);*/
        for (i = 0; i < subframeSize; i++) el += low_innov[offset + i] * low_innov[offset + i];

        /* Gain to use if we want to use the low-band excitation for high-band */
        g = eh / (.01f + el);
        g = (float) Math.sqrt(g);

        g *= filter_ratio;
        /*print_vec(&g, 1, "gain factor");*/
        /* Gain quantization */
        {
          int quant = (int) Math.floor(.5 + 10 + 8.0 * Math.log((g + .0001)));
          /*speex_warning_int("tata", quant);*/
          if (quant < 0) quant = 0;
          if (quant > 31) quant = 31;
          bits.pack(quant, 5);
          g = (float) (.1 * Math.exp(quant / 9.4));
        }
        /*printf ("folding gain: %f\n", g);*/
        g /= filter_ratio;

      } else {
        float gc, scale, scale_1;

        for (i = 0; i < subframeSize; i++) el += low_exc[offset + i] * low_exc[offset + i];
        /*speex_bits_pack(bits, 0, 1);*/

        gc = (float) (Math.sqrt(1 + eh) * filter_ratio / Math.sqrt((1 + el) * subframeSize));
        {
          int qgc = (int) Math.floor(.5 + 3.7 * (Math.log(gc) + 2));
          if (qgc < 0) qgc = 0;
          if (qgc > 15) qgc = 15;
          bits.pack(qgc, 4);
          gc = (float) Math.exp((1 / 3.7) * qgc - 2);
        }

        scale = gc * (float) Math.sqrt(1 + el) / filter_ratio;
        scale_1 = 1 / scale;

        for (i = 0; i < subframeSize; i++) excBuf[exc + i] = 0;
        excBuf[exc] = 1;
        Filters.syn_percep_zero(
            excBuf, exc, interp_qlpc, bw_lpc1, bw_lpc2, syn_resp, subframeSize, lpcSize);

        /* Reset excitation */
        for (i = 0; i < subframeSize; i++) excBuf[exc + i] = 0;

        /* Compute zero response (ringing) of A(z/g1) / ( A(z/g2) * Aq(z) ) */
        for (i = 0; i < lpcSize; i++) mem[i] = mem_sp[i];
        Filters.iir_mem2(excBuf, exc, interp_qlpc, excBuf, exc, subframeSize, lpcSize, mem);

        for (i = 0; i < lpcSize; i++) mem[i] = mem_sw[i];
        Filters.filter_mem2(
            excBuf, exc, bw_lpc1, bw_lpc2, res, resp, subframeSize, lpcSize, mem, 0);

        /* Compute weighted signal */
        for (i = 0; i < lpcSize; i++) mem[i] = mem_sw[i];
        Filters.filter_mem2(high, sp, bw_lpc1, bw_lpc2, swBuf, sw, subframeSize, lpcSize, mem, 0);

        /* Compute target signal */
        for (i = 0; i < subframeSize; i++) target[i] = swBuf[sw + i] - res[resp + i];

        for (i = 0; i < subframeSize; i++) excBuf[exc + i] = 0;

        for (i = 0; i < subframeSize; i++) target[i] *= scale_1;

        /* Reset excitation */
        for (i = 0; i < subframeSize; i++) innov[i] = 0;

        /*print_vec(target, st->subframeSize, "\ntarget");*/
        submodes[submodeID].innovation.quant(
            target,
            interp_qlpc,
            bw_lpc1,
            bw_lpc2,
            lpcSize,
            subframeSize,
            innov,
            0,
            syn_resp,
            bits,
            (complexity + 1) >> 1);
        /*print_vec(target, st->subframeSize, "after");*/

        for (i = 0; i < subframeSize; i++) excBuf[exc + i] += innov[i] * scale;

        if (submodes[submodeID].double_codebook != 0) {
          float[] innov2 = new float[subframeSize];
          for (i = 0; i < subframeSize; i++) innov2[i] = 0;
          for (i = 0; i < subframeSize; i++) target[i] *= 2.5;
          submodes[submodeID].innovation.quant(
              target,
              interp_qlpc,
              bw_lpc1,
              bw_lpc2,
              lpcSize,
              subframeSize,
              innov2,
              0,
              syn_resp,
              bits,
              (complexity + 1) >> 1);
          for (i = 0; i < subframeSize; i++) innov2[i] *= scale * (1 / 2.5);
          for (i = 0; i < subframeSize; i++) excBuf[exc + i] += innov2[i];
        }
      }

      /*Keep the previous memory*/
      for (i = 0; i < lpcSize; i++) mem[i] = mem_sp[i];
      /* Final signal synthesis from excitation */
      Filters.iir_mem2(excBuf, exc, interp_qlpc, high, sp, subframeSize, lpcSize, mem_sp);

      /* Compute weighted signal again, from synthesized speech (not sure it's the right thing) */
      Filters.filter_mem2(high, sp, bw_lpc1, bw_lpc2, swBuf, sw, subframeSize, lpcSize, mem_sw, 0);
    }

    // #ifndef RELEASE
    /* Reconstruct the original */
    filters.fir_mem_up(x0d, h0, y0, fullFrameSize, QMF_ORDER, g0_mem);
    filters.fir_mem_up(high, h1, y1, fullFrameSize, QMF_ORDER, g1_mem);

    for (i = 0; i < fullFrameSize; i++) in[i] = 2 * (y0[i] - y1[i]);
    // #endif
    for (i = 0; i < lpcSize; i++) old_lsp[i] = lsp[i];
    for (i = 0; i < lpcSize; i++) old_qlsp[i] = qlsp[i];
    first = 0;
    return 1;
  }
Ejemplo n.º 25
0
 /**
  * Find the appropriate filter for the given up/down compbination.
  *
  * @param upFactor up sampling factor
  * @param downFactor down sampling factor
  * @return filter
  */
 private static Filters.FIRFilter createFilter(final int upFactor, final int downFactor) {
   final int gcd = greatestCommonDivisor(upFactor, downFactor);
   return Filters.createFir1_16thOrderLowpass(Math.max(upFactor / gcd, downFactor / gcd));
 }
  /**
   * Creates a locale specific properties file within the fragment project based on the content of
   * the host plug-in's properties file.
   *
   * @param fragmentProject
   * @param locale
   * @throws CoreException
   * @throws IOException
   */
  private void createLocaleSpecificPropertiesFile(
      final IProject fragmentProject, IPluginModelBase plugin, final Locale locale)
      throws CoreException, IOException {
    final IFolder localeResourceFolder =
        fragmentProject.getFolder(RESOURCE_FOLDER_PARENT).getFolder(locale.toString());

    // Case 1: External plug-in
    if (plugin instanceof ExternalPluginModelBase) {
      final String installLocation = plugin.getInstallLocation();
      // Case 1a: External plug-in is a jar file
      if (new File(installLocation).isFile()) {
        ZipFile zf = new ZipFile(installLocation);
        for (Enumeration e = zf.entries(); e.hasMoreElements(); ) {
          worked();

          ZipEntry zfe = (ZipEntry) e.nextElement();
          String name = zfe.getName();

          String[] segments = name.split(SLASH);
          IPath path = Path.fromPortableString(join(SLASH, segments, 0, segments.length - 1));
          String resourceName = segments[segments.length - 1];
          String localizedResourceName = localeSpecificName(resourceName, locale);
          if (propertiesFilter.include(name)) {

            createParents(fragmentProject, path);
            IFile file = fragmentProject.getFile(path.append(localizedResourceName));
            InputStream is = zf.getInputStream(zfe);
            file.create(is, false, getProgressMonitor());
          } else if (resourceFilter.include(name)) {
            IPath target = localeResourceFolder.getFullPath().append(path).append(resourceName);
            createParents(fragmentProject, target.removeLastSegments(1).removeFirstSegments(1));
            IFile file = fragmentProject.getFile(target.removeFirstSegments(1));
            file.create(zf.getInputStream(zfe), false, getProgressMonitor());
          }
        }
      }
      // Case 1b: External plug-in has a folder structure
      else {
        Visitor visitor =
            new Visitor() {
              public void visit(File file) throws CoreException, FileNotFoundException {
                worked();

                String relativePath =
                    file.getAbsolutePath()
                        .substring(installLocation.length())
                        .replaceAll(File.separator, SLASH);
                String[] segments = relativePath.split(SLASH);
                IPath path = Path.fromPortableString(join(SLASH, segments, 0, segments.length - 1));
                String resourceName = segments[segments.length - 1];
                String localizedResourceName = localeSpecificName(resourceName, locale);

                if (propertiesFilter.include(
                    relativePath + (file.isDirectory() ? SLASH : EMPTY_STRING))) {
                  createParents(fragmentProject, path);
                  IFile iFile = fragmentProject.getFile(path.append(localizedResourceName));
                  iFile.create(new FileInputStream(file), false, getProgressMonitor());
                } else if (resourceFilter.include(
                    relativePath + (file.isDirectory() ? SLASH : EMPTY_STRING))) {
                  IPath target = localeResourceFolder.getFullPath().append(relativePath);
                  createParents(
                      fragmentProject, target.removeLastSegments(1).removeFirstSegments(1));
                  IFile iFile = fragmentProject.getFile(target.removeFirstSegments(1));
                  iFile.create(new FileInputStream(file), false, getProgressMonitor());
                }

                if (file.isDirectory()) {
                  File[] children = file.listFiles();
                  for (int i = 0; i < children.length; i++) {
                    visit(children[i]);
                  }
                }
              }
            };

        visitor.visit(new File(installLocation));
      }
    }
    // Case 2: Workspace plug-in
    else {
      final IProject project = plugin.getUnderlyingResource().getProject();

      project.accept(
          new IResourceVisitor() {
            public boolean visit(IResource resource) throws CoreException {
              worked();

              IPath parent = resource.getFullPath().removeLastSegments(1).removeFirstSegments(1);
              if (propertiesFilter.include(resource)) {
                String segment = localeSpecificName(resource.getFullPath().lastSegment(), locale);
                IPath fragmentResource =
                    fragmentProject.getFullPath().append(parent).append(segment);

                createParents(fragmentProject, parent);
                resource.copy(fragmentResource, true, getProgressMonitor());
              } else if (resourceFilter.include(resource)) {
                IPath target =
                    localeResourceFolder
                        .getFullPath()
                        .append(parent)
                        .append(resource.getFullPath().lastSegment());
                createParents(fragmentProject, target.removeLastSegments(1).removeFirstSegments(1));
                resource.copy(target, true, getProgressMonitor());
              }
              return true;
            }
          });
    }
  }
Ejemplo n.º 27
0
 /**
  * Creates a decimator using a simple fir1 16th order low pass filter.
  *
  * @param factor nth frame to keep (factor)
  * @throws IllegalArgumentException if the decimation factor is not supported
  * @see Filters#createFir1_16thOrderLowpass(int)
  */
 public Decimator(final int factor) throws IllegalArgumentException {
   super(Filters.createFir1_16thOrderLowpass(factor).getCoefficients());
   this.factor = factor;
 }