text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/monitoring/v3/metric_service.proto

namespace Google\Cloud\Monitoring\V3;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The `ListTimeSeries` request.
 *
 * Generated from protobuf message google.monitoring.v3.ListTimeSeriesRequest
 */
class ListTimeSeriesRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The project on which to execute the request. The format is:
     *     projects/[PROJECT_ID_OR_NUMBER]
     *
     * Generated from protobuf field string name = 10 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';
    /**
     * Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters)
     * that specifies which time series should be returned.  The filter must
     * specify a single metric type, and can additionally specify metric labels
     * and other information. For example:
     *     metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND
     *         metric.labels.instance_name = "my-instance-name"
     *
     * Generated from protobuf field string filter = 2 [(.google.api.field_behavior) = REQUIRED];
     */
    private $filter = '';
    /**
     * Required. The time interval for which results should be returned. Only time series
     * that contain data points in the specified interval are included
     * in the response.
     *
     * Generated from protobuf field .google.monitoring.v3.TimeInterval interval = 4 [(.google.api.field_behavior) = REQUIRED];
     */
    private $interval = null;
    /**
     * Specifies the alignment of data points in individual time series as
     * well as how to combine the retrieved time series across specified labels.
     * By default (if no `aggregation` is explicitly specified), the raw time
     * series data is returned.
     *
     * Generated from protobuf field .google.monitoring.v3.Aggregation aggregation = 5;
     */
    private $aggregation = null;
    /**
     * Unsupported: must be left blank. The points in each time series are
     * currently returned in reverse time order (most recent to oldest).
     *
     * Generated from protobuf field string order_by = 6;
     */
    private $order_by = '';
    /**
     * Required. Specifies which information is returned about the time series.
     *
     * Generated from protobuf field .google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView view = 7 [(.google.api.field_behavior) = REQUIRED];
     */
    private $view = 0;
    /**
     * A positive number that is the maximum number of results to return. If
     * `page_size` is empty or more than 100,000 results, the effective
     * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the
     * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is
     * the maximum number of `TimeSeries` returned.
     *
     * Generated from protobuf field int32 page_size = 8;
     */
    private $page_size = 0;
    /**
     * If this field is not empty then it must contain the `nextPageToken` value
     * returned by a previous call to this method.  Using this field causes the
     * method to return additional results from the previous method call.
     *
     * Generated from protobuf field string page_token = 9;
     */
    private $page_token = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The project on which to execute the request. The format is:
     *               projects/[PROJECT_ID_OR_NUMBER]
     *     @type string $filter
     *           Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters)
     *           that specifies which time series should be returned.  The filter must
     *           specify a single metric type, and can additionally specify metric labels
     *           and other information. For example:
     *               metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND
     *                   metric.labels.instance_name = "my-instance-name"
     *     @type \Google\Cloud\Monitoring\V3\TimeInterval $interval
     *           Required. The time interval for which results should be returned. Only time series
     *           that contain data points in the specified interval are included
     *           in the response.
     *     @type \Google\Cloud\Monitoring\V3\Aggregation $aggregation
     *           Specifies the alignment of data points in individual time series as
     *           well as how to combine the retrieved time series across specified labels.
     *           By default (if no `aggregation` is explicitly specified), the raw time
     *           series data is returned.
     *     @type string $order_by
     *           Unsupported: must be left blank. The points in each time series are
     *           currently returned in reverse time order (most recent to oldest).
     *     @type int $view
     *           Required. Specifies which information is returned about the time series.
     *     @type int $page_size
     *           A positive number that is the maximum number of results to return. If
     *           `page_size` is empty or more than 100,000 results, the effective
     *           `page_size` is 100,000 results. If `view` is set to `FULL`, this is the
     *           maximum number of `Points` returned. If `view` is set to `HEADERS`, this is
     *           the maximum number of `TimeSeries` returned.
     *     @type string $page_token
     *           If this field is not empty then it must contain the `nextPageToken` value
     *           returned by a previous call to this method.  Using this field causes the
     *           method to return additional results from the previous method call.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Monitoring\V3\MetricService::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The project on which to execute the request. The format is:
     *     projects/[PROJECT_ID_OR_NUMBER]
     *
     * Generated from protobuf field string name = 10 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The project on which to execute the request. The format is:
     *     projects/[PROJECT_ID_OR_NUMBER]
     *
     * Generated from protobuf field string name = 10 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters)
     * that specifies which time series should be returned.  The filter must
     * specify a single metric type, and can additionally specify metric labels
     * and other information. For example:
     *     metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND
     *         metric.labels.instance_name = "my-instance-name"
     *
     * Generated from protobuf field string filter = 2 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getFilter()
    {
        return $this->filter;
    }

    /**
     * Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters)
     * that specifies which time series should be returned.  The filter must
     * specify a single metric type, and can additionally specify metric labels
     * and other information. For example:
     *     metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND
     *         metric.labels.instance_name = "my-instance-name"
     *
     * Generated from protobuf field string filter = 2 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setFilter($var)
    {
        GPBUtil::checkString($var, True);
        $this->filter = $var;

        return $this;
    }

    /**
     * Required. The time interval for which results should be returned. Only time series
     * that contain data points in the specified interval are included
     * in the response.
     *
     * Generated from protobuf field .google.monitoring.v3.TimeInterval interval = 4 [(.google.api.field_behavior) = REQUIRED];
     * @return \Google\Cloud\Monitoring\V3\TimeInterval
     */
    public function getInterval()
    {
        return $this->interval;
    }

    /**
     * Required. The time interval for which results should be returned. Only time series
     * that contain data points in the specified interval are included
     * in the response.
     *
     * Generated from protobuf field .google.monitoring.v3.TimeInterval interval = 4 [(.google.api.field_behavior) = REQUIRED];
     * @param \Google\Cloud\Monitoring\V3\TimeInterval $var
     * @return $this
     */
    public function setInterval($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\TimeInterval::class);
        $this->interval = $var;

        return $this;
    }

    /**
     * Specifies the alignment of data points in individual time series as
     * well as how to combine the retrieved time series across specified labels.
     * By default (if no `aggregation` is explicitly specified), the raw time
     * series data is returned.
     *
     * Generated from protobuf field .google.monitoring.v3.Aggregation aggregation = 5;
     * @return \Google\Cloud\Monitoring\V3\Aggregation
     */
    public function getAggregation()
    {
        return $this->aggregation;
    }

    /**
     * Specifies the alignment of data points in individual time series as
     * well as how to combine the retrieved time series across specified labels.
     * By default (if no `aggregation` is explicitly specified), the raw time
     * series data is returned.
     *
     * Generated from protobuf field .google.monitoring.v3.Aggregation aggregation = 5;
     * @param \Google\Cloud\Monitoring\V3\Aggregation $var
     * @return $this
     */
    public function setAggregation($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\Aggregation::class);
        $this->aggregation = $var;

        return $this;
    }

    /**
     * Unsupported: must be left blank. The points in each time series are
     * currently returned in reverse time order (most recent to oldest).
     *
     * Generated from protobuf field string order_by = 6;
     * @return string
     */
    public function getOrderBy()
    {
        return $this->order_by;
    }

    /**
     * Unsupported: must be left blank. The points in each time series are
     * currently returned in reverse time order (most recent to oldest).
     *
     * Generated from protobuf field string order_by = 6;
     * @param string $var
     * @return $this
     */
    public function setOrderBy($var)
    {
        GPBUtil::checkString($var, True);
        $this->order_by = $var;

        return $this;
    }

    /**
     * Required. Specifies which information is returned about the time series.
     *
     * Generated from protobuf field .google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView view = 7 [(.google.api.field_behavior) = REQUIRED];
     * @return int
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * Required. Specifies which information is returned about the time series.
     *
     * Generated from protobuf field .google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView view = 7 [(.google.api.field_behavior) = REQUIRED];
     * @param int $var
     * @return $this
     */
    public function setView($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView::class);
        $this->view = $var;

        return $this;
    }

    /**
     * A positive number that is the maximum number of results to return. If
     * `page_size` is empty or more than 100,000 results, the effective
     * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the
     * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is
     * the maximum number of `TimeSeries` returned.
     *
     * Generated from protobuf field int32 page_size = 8;
     * @return int
     */
    public function getPageSize()
    {
        return $this->page_size;
    }

    /**
     * A positive number that is the maximum number of results to return. If
     * `page_size` is empty or more than 100,000 results, the effective
     * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the
     * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is
     * the maximum number of `TimeSeries` returned.
     *
     * Generated from protobuf field int32 page_size = 8;
     * @param int $var
     * @return $this
     */
    public function setPageSize($var)
    {
        GPBUtil::checkInt32($var);
        $this->page_size = $var;

        return $this;
    }

    /**
     * If this field is not empty then it must contain the `nextPageToken` value
     * returned by a previous call to this method.  Using this field causes the
     * method to return additional results from the previous method call.
     *
     * Generated from protobuf field string page_token = 9;
     * @return string
     */
    public function getPageToken()
    {
        return $this->page_token;
    }

    /**
     * If this field is not empty then it must contain the `nextPageToken` value
     * returned by a previous call to this method.  Using this field causes the
     * method to return additional results from the previous method call.
     *
     * Generated from protobuf field string page_token = 9;
     * @param string $var
     * @return $this
     */
    public function setPageToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->page_token = $var;

        return $this;
    }

}


text:
homebrew-tools
===============

Homebrew formula for recime-cli.

## Usage

To install the latest release:

    $ brew tap recime/tools
    $ brew install / upgrade recime-cli

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.karaf.cellar.utils.ping.internal.osgi;

import org.apache.karaf.cellar.core.ClusterManager;
import org.apache.karaf.cellar.core.command.CommandStore;
import org.apache.karaf.cellar.core.event.EventHandler;
import org.apache.karaf.cellar.core.event.EventProducer;
import org.apache.karaf.cellar.utils.ping.PingHandler;
import org.apache.karaf.cellar.utils.ping.PongHandler;
import org.apache.karaf.util.tracker.BaseActivator;
import org.apache.karaf.util.tracker.annotation.ProvideService;
import org.apache.karaf.util.tracker.annotation.RequireService;
import org.apache.karaf.util.tracker.annotation.Services;
import org.osgi.service.cm.ConfigurationAdmin;

@Services(
        requires = { @RequireService(ClusterManager.class), @RequireService(CommandStore.class), @RequireService(EventProducer.class), @RequireService(ConfigurationAdmin.class)},
        provides = { @ProvideService(EventHandler.class)}
)
public class Activator extends BaseActivator {

    @Override
    public void doStart() throws Exception {
        // retrieving services
        ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
        if (configurationAdmin == null)
            return;
        ClusterManager clusterManager = getTrackedService(ClusterManager.class);
        if (clusterManager == null)
            return;
        EventProducer eventProducer = getTrackedService(EventProducer.class);
        if (eventProducer == null)
            return;
        CommandStore commandStore = getTrackedService(CommandStore.class);
        if (commandStore == null)
            return;

        // registering ping event handler
        PingHandler pingHandler = new PingHandler();
        pingHandler.setClusterManager(clusterManager);
        pingHandler.setConfigurationAdmin(configurationAdmin);
        pingHandler.setProducer(eventProducer);
        register(EventHandler.class, pingHandler);

        // registering pong event handler
        PongHandler pongHandler = new PongHandler();
        pongHandler.setCommandStore(commandStore);
        register(EventHandler.class, pongHandler);
    }

    @Override
    public void doStop() {
        super.doStop();
    }

}


text:
/* cowjac © 2012 David Given
 * This file is licensed under the Simplified BSD license. Please see
 * COPYING.cowjac for the full text.
 */

package com.cowlark.luje.harmony;

import java.util.Locale;

public class UCharacter
{
	public static String toLowerCase(Locale locale, String s)
	{
		char[] chars = s.toCharArray();
		for (int i = 0; i < chars.length; i++)
			chars[i] = Character.toLowerCase(chars[i]);
		return new String(chars);
	}
}


text:
package org.springframework.data.jpa.repository.support;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.mysema.query.dml.DeleteClause;
import com.mysema.query.dml.UpdateClause;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPADeleteClause;
import com.mysema.query.jpa.impl.JPAUpdateClause;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.path.PathBuilder;
import com.mysema.query.types.path.PathBuilderFactory;

/**
 * Base class for implementing repositories using QueryDsl library.
 *
 * @author Oliver Gierke
 */
@Repository
public abstract class QueryDslRepositorySupport {

	private final PathBuilder<?> builder;

	private EntityManager entityManager;
	private Querydsl querydsl;

	/**
	 * Creates a new {@link QueryDslRepositorySupport} instance for the given domain type.
	 *
	 * @param domainClass must not be {@literal null}.
	 */
	public QueryDslRepositorySupport(Class<?> domainClass) {
		Assert.notNull(domainClass);
		this.builder = new PathBuilderFactory().create(domainClass);
	}

	/**
	 * Setter to inject {@link EntityManager}.
	 *
	 * @param entityManager must not be {@literal null}
	 */
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {

		Assert.notNull(entityManager);
		this.querydsl = new Querydsl(entityManager, builder);
		this.entityManager = entityManager;
	}

	/**
	 * Callback to verify configuration. Used by containers.
	 */
	@PostConstruct
	public void validate() {
		Assert.notNull(entityManager, "EntityManager must not be null!");
		Assert.notNull(querydsl, "Querydsl must not be null!");
	}

	/**
	 * Returns the {@link EntityManager}.
	 *
	 * @return the entityManager
	 */
	protected EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * Returns a fresh {@link JPQLQuery}.
	 *
	 * @return the Querydsl {@link JPQLQuery}.
	 */
	protected JPQLQuery from(EntityPath<?>... paths) {
		return querydsl.createQuery(paths);
	}

	/**
	 * Returns a fresh {@link DeleteClause}.
	 *
	 * @param path
	 * @return the Querydsl {@link DeleteClause}.
	 */
	protected DeleteClause<JPADeleteClause> delete(EntityPath<?> path) {
		return new JPADeleteClause(entityManager, path);
	}

	/**
	 * Returns a fresh {@link UpdateClause}.
	 *
	 * @param path
	 * @return the Querydsl {@link UpdateClause}.
	 */
	protected UpdateClause<JPAUpdateClause> update(EntityPath<?> path) {
		return new JPAUpdateClause(entityManager, path);
	}

	/**
	 * Returns a {@link PathBuilder} for the configured domain type.
	 *
	 * @param <T>
	 * @return the Querdsl {@link PathBuilder}.
	 */
	@SuppressWarnings("unchecked")
	protected <T> PathBuilder<T> getBuilder() {
		return (PathBuilder<T>) builder;
	}

	/**
	 * Returns the underlying Querydsl helper instance.
	 *
	 * @return
	 */
	protected Querydsl getQuerydsl() {
		return this.querydsl;
	}
}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.exec;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.DigestOfDirectoryException;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.MetadataProvider;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Symlinks;
import java.io.IOException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;

/**
 * An in-memory cache to ensure we do I/O for source files only once during a single build.
 *
 * <p>Simply maintains a cached mapping from filename to metadata that may be populated only once.
 */
@ThreadSafe
public class SingleBuildFileCache implements MetadataProvider {

  private final Path execRoot;

  // If we can't get the digest, we store the exception. This avoids extra file IO for files
  // that are allowed to be missing, as we first check a likely non-existent content file
  // first.  Further we won't need to unwrap the exception in getDigest().
  private final Cache<String, ActionInputMetadata> pathToMetadata =
      Caffeine.newBuilder()
          // Even small-ish builds, as of 11/21/2011 typically have over 10k artifacts, so it's
          // unlikely that this default will adversely affect memory in most cases.
          .initialCapacity(10000)
          .build();

  public SingleBuildFileCache(String cwd, FileSystem fs) {
    this.execRoot = fs.getPath(cwd);
  }

  @Override
  public FileArtifactValue getMetadata(ActionInput input) throws IOException {
    return pathToMetadata
        .get(
            input.getExecPathString(),
            execPath -> {
              Path path = ActionInputHelper.toInputPath(input, execRoot);
              FileArtifactValue metadata;
              try {
                metadata = FileArtifactValue.createFromStat(path, path.stat(Symlinks.FOLLOW), true);
              } catch (IOException e) {
                return new ActionInputMetadata(input, e);
              }
              if (metadata.getType().isDirectory()) {
                return new ActionInputMetadata(
                    input, new DigestOfDirectoryException("Input is a directory: " + execPath));
              }
              return new ActionInputMetadata(input, metadata);
            })
        .getMetadata();
  }

  @Override
  @Nullable
  public ActionInput getInput(String execPath) {
    ActionInputMetadata metadata = pathToMetadata.getIfPresent(execPath);
    if (metadata == null) {
      return null;
    }
    return metadata.getInput();
  }

  /** Container class for caching I/O around ActionInputs. */
  private static class ActionInputMetadata {
    private final ActionInput input;
    private final FileArtifactValue metadata;
    private final IOException exceptionOnAccess;

    /** Constructor for a successful lookup. */
    ActionInputMetadata(ActionInput input, FileArtifactValue metadata) {
      this.input = input;
      this.metadata = metadata;
      this.exceptionOnAccess = null;
    }

    /** Constructor for a failed lookup, size will be 0. */
    ActionInputMetadata(ActionInput input, IOException exceptionOnAccess) {
      this.input = input;
      this.exceptionOnAccess = exceptionOnAccess;
      this.metadata = null;
    }

    FileArtifactValue getMetadata() throws IOException {
      maybeRaiseException();
      return metadata;
    }

    ActionInput getInput() {
      return input;
    }

    private void maybeRaiseException() throws IOException {
      if (exceptionOnAccess != null) {
        throw exceptionOnAccess;
      }
    }
  }
}


text:
package resources

//fabric resources used for ACL checks. Note that some of the checks
//such as LSCC_INSTALL are "peer wide" (current access checks in peer are
//based on local MSP). These are not currently covered by RSCC or defaultProvider
const (
	PROPOSE = "PROPOSE"

	//LSCC resources
	LSCC_INSTALL                = "LSCC.INSTALL"
	LSCC_DEPLOY                 = "LSCC.DEPLOY"
	LSCC_UPGRADE                = "LSCC.UPGRADE"
	LSCC_GETCCINFO              = "LSCC.GETCCINFO"
	LSCC_GETDEPSPEC             = "LSCC.GETDEPSPEC"
	LSCC_GETCCDATA              = "LSCC.GETCCDATA"
	LSCC_GETCHAINCODES          = "LSCC.GETCHAINCODES"
	LSCC_GETINSTALLEDCHAINCODES = "LSCC.GETINSTALLEDCHAINCODES"

	//QSCC resources
	QSCC_GetChainInfo       = "QSCC.GetChainInfo"
	QSCC_GetBlockByNumber   = "QSCC.GetBlockByNumber"
	QSCC_GetBlockByHash     = "QSCC.GetBlockByHash"
	QSCC_GetTransactionByID = "QSCC.GetTransactionByID"
	QSCC_GetBlockByTxID     = "QSCC.GetBlockByTxID"

	//CSCC resources
	CSCC_JoinChain                = "CSCC.JoinChain"
	CSCC_GetConfigBlock           = "CSCC.GetConfigBlock"
	CSCC_GetChannels              = "CSCC.GetChannels"
	CSCC_GetConfigTree            = "CSCC.GetConfigTree"
	CSCC_SimulateConfigTreeUpdate = "CSCC.SimulateConfigTreeUpdate"

	//Chaincode-to-Chaincode call
	CC2CC = "CC2CC"

	//Events
	BLOCKEVENT         = "BLOCKEVENT"
	FILTEREDBLOCKEVENT = "FILTEREDBLOCKEVENT"
)


text:
Sharpen
=======

Usage: `sharpen(sharpen\_amount,sharpen\_radius,luminance\_only)`

Description
-----------

This filter enhances apparent sharpness of the image. It's heavily based
on Marco Rossini's excellent Wavelet sharpen GIMP plugin. Check
`<http://registry.gimp.org/node/9836>`_ for details about how it work.

Arguments
---------

-  ``sharpen_amount`` - Sharpen amount. Typical values are between :math:`0.0` and
   :math:`10.0`.
-  ``sharpen_radius`` - Sharpen radius. Typical values are between :math:`0.0` and
   :math:`2.0`.
-  ``luminance_only`` - Sharpen only luminance channel. Values can be
   ``true`` or ``false``.

Example 1
---------

.. image:: images/man_before_sharpen.png
    :alt: Picture before the sharpen filter

::

    http://localhost:8888/unsafe/filters:sharpen(2,1.0,true)/http://videoprocessing.ucsd.edu/~stanleychan/research/pix/Blurred_foreman_0005.png

.. image:: images/man_after_sharpen.png
    :alt: Picture after the sharpen filter

Example 2
---------

.. image:: images/eagle_before_sharpen.jpg
    :alt: Picture before the sharpen filter

::

    http://localhost:8888/unsafe/filters:sharpen(1.5,0.5,true)/http://images.cambridgeincolour.com/tutorials/sharpening_eagle2-original.jpg

.. image:: images/eagle_after_sharpen.jpg
    :alt: Picture after the sharpen filter


text:
/**
 * Created by c13lbm on 4/27/16.
 */

var TeacherRecordVideo = React.createClass({
    formDataBuilder: function (blob, fileName) {
            var fd = new FormData();
            var id_array = this.props.idArray;
            var student = this.props.studentArray;

            fd.append("feedbackVideo", blob);
            return fd;
       },
    playVideo: function (fName) {
    },
    render: function () {
        var id_array = this.props.idArray;
        var student = this.props.studentArray;
        var submissionURL = "assignments/" + id_array[0].assignmentID + "/submissions/" + student[0].studentID + "/feedbackvideo/";
        return (

                        <Recorder playCallback={this.playVideo}
                                  postURL={submissionURL}
                                  formDataBuilder={this.formDataBuilder}
                                  recButtonID="teacherRecordButton"
                                  stopButtonID="teacherStopButton"
                                  fileName="feedback.webm" replay="true"
                                  siteView="feedback" camOnLoad="true"
                                  contID="teacherRecorder"
                        />

                        <button id="teacherRecordButton" className="recControls">Record</button>
                        <button id="teacherStopButton" className="recControls" >Stop</button>

        );
    }
});

window.TeacherRecordVideo = TeacherRecordVideo;


text:
<?php

// no direct access
defined('_JEXEC') or die;
$doc    = JFactory::getDocument();

$lists  = $this -> itemMore;
// Create shortcuts to some parameters.
$params		= $this->item->params;
$tmpl       = null;
if($params -> get('tz_use_lightbox') == 1){
    $tmpl   = '&tmpl=component';
}
if($lists):
    if($params -> get('show_related_article',1)):
?>

    <?php if($params -> get('show_related_heading',1)):?>
        <?php
            $title    = JText::_('COM_TZ_PORTFOLIO_RELATED_ARTICLE');
            if($params -> get('related_heading')){
                $title  = $params -> get('related_heading');
            }
        ?>

<?php echo $title;?>

    <?php endif;?>

    <?php $media      = JModelLegacy::getInstance('Media','TZ_PortfolioModel');?>
    <?php foreach($lists as $i => $item):?>
        <?php

            $tzRedirect = $params -> get('tz_portfolio_redirect','p_article'); //Set params for $tzRedirect
            $itemParams = new JRegistry($item -> attribs); //Get Article's Params
            //Check redirect to view article
            if($itemParams -> get('tz_portfolio_redirect')){
                $tzRedirect = $itemParams -> get('tz_portfolio_redirect');
            }
            if($tzRedirect == 'article'){
                $item -> _link = JRoute::_(TZ_PortfolioHelperRoute::getArticleRoute($item -> slug, $item -> catid).$tmpl);
            }
            else{
                $item -> _link = JRoute::_(TZ_PortfolioHelperRoute::getPortfolioArticleRoute($item -> slug, $item -> catid).$tmpl);
            }

            $listMedia      = $media -> getMedia($item -> id);
            $src    = null;
            if($listMedia){
                if($listMedia[0] -> type == 'video'){
                    $src    = $listMedia[0] -> thumb;
                }
                else{
                    $src    = $listMedia[0] -> images;
                }
            }
        ?>
    <?php if(($params -> get('show_related_type','title_image') == 'image' AND $src)
             OR $params -> get('show_related_type','title_image') == 'title'
            OR $params -> get('show_related_type','title_image') == 'title_image'):?>
    <li class="TzItem<?php if($i == 0) echo ' first'; if($i == count($lists) - 1) echo ' last';?>">
    <?php endif;?>
        <?php if($params -> get('show_related_type','title_image') == 'image'
                 OR $params -> get('show_related_type','title_image') == 'title_image'):?>
            <?php

                if($src):
                    $size   = $params -> get('related_image_size','S');
                    $src    = str_replace('.'.JFile::getExt($src),'_'.$size.'.'.JFile::getExt($src),$src);
            ?>

                <a<?php if($params -> get('tz_use_lightbox',1) == 1){echo ' class="fancybox fancybox.iframe"';}?>
                        href="<?php echo $item -> _link;?>">
                    <img src="<?php echo $src;?>" alt="<?php echo $item -> title?>" title="<?php echo $item -> title;?>"/>

            <?php endif;?>
        <?php endif;?>
        <?php if($params -> get('show_related_type','title_image') == 'title'
                 OR($params -> get('show_related_type','title_image') == 'title_image')):?>
        <a<?php if($params -> get('tz_use_lightbox',1) == 1){echo ' class="fancybox fancybox.iframe"';}?>
                href="<?php echo $item -> _link;?>" class="TzTitle">
            <?php echo $item -> title;?>

        <?php endif;?>
    <?php if(($params -> get('show_related_type','title_image') == 'image' AND $src)
             OR $params -> get('show_related_type','title_image') == 'title'
            OR $params -> get('show_related_type','title_image') == 'title_image'):?>

    <?php endif;?>

    <?php endforeach;?>

    <?php endif;?>
<?php endif;?>


text:
const proxy = require('http-proxy-middleware')

module.exports = app => {
  app.use(proxy('/api', { target: 'http://localhost:3001/' }))
  app.use(
    proxy('/socket.io', { target: 'ws://localhost:3001/socket.io', ws: true }),
  )
}


text:
#ifndef CV_MATELEMCN_INCLUDED
#define CV_MATELEMCN_INCLUDED

#define CV_MAT_ELEM_CN( mat, elemtype, row, chcol ) \
    (*(elemtype*)((mat).data.ptr + (size_t)(mat).step*(row) + sizeof(elemtype)*(chcol)))

#endif


text:
import * as winston from 'winston';

// set up the logger with a transport
const _logger = winston.add(new winston.transports.Console({
  format: (winston as any).format.simple(),
}));

export const logger = _logger;


text:
package com.arjuna.databroker.plugins.test;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import com.arjuna.databroker.data.DataConsumer;
import com.arjuna.databroker.data.DataFlow;
import com.arjuna.databroker.data.DataProvider;
import com.arjuna.databroker.data.DataSource;
import com.arjuna.databroker.data.jee.annotation.DataConsumerInjection;
import com.arjuna.databroker.data.jee.annotation.DataProviderInjection;

public class JSONRandomDataSource implements DataSource
{
    private static final Logger logger = Logger.getLogger(JSONRandomDataSource.class.getName());

    private class Worker extends Thread
    {
        public void run()
        {
            try
            {
                while (true)
                {
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("Key1", UUID.randomUUID().toString());
                    jsonObject.put("Key2", UUID.randomUUID().toString());
                    jsonObject.put("Key3", UUID.randomUUID().toString());
                    jsonObject.put("Key4", UUID.randomUUID().toString());

                    _dataProvider.produce(jsonObject);

                    Thread.sleep(Long.parseLong(_properties.get(TIMEINTERVAL_PROPERTYNAME)));
                }
            }
            catch (Throwable throwable)
            {
                logger.log(Level.WARNING, "Problem in JSONRandomDataSource.Worker", throwable);
            }
        }
    }

    public static final String TIMEINTERVAL_PROPERTYNAME = "Time Interval";

    public JSONRandomDataSource(String name, Map<String, String> properties)
    {
        logger.info("JSONRandomDataSource: " + name + ", " + properties);

        _name       = name;
        _properties = properties;
        _dataFlow   = null;

        (new Worker()).start();
    }

    @Override
    public String getName()
    {
        return _name;
    }

    @Override
    public void setName(String name)
    {
        _name = name;
    }

    @Override
    public Map<String, String> getProperties()
    {
        return Collections.unmodifiableMap(_properties);
    }

    @Override
    public void setProperties(Map<String, String> properties)
    {
        _properties = properties;
    }

    @Override
    public DataFlow getDataFlow()
    {
        return _dataFlow;
    }

    @Override
    public void setDataFlow(DataFlow dataFlow)
    {
        _dataFlow = dataFlow;
    }

    @Override
    public Collection<Class<?>> getDataProviderDataClasses()
    {
        Set<Class<?>> dataProviderDataClasses = new HashSet<Class<?>>();

        dataProviderDataClasses.add(JSONObject.class);

        return dataProviderDataClasses;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> DataProvider<T> getDataProvider(Class<T> dataClass)
    {
        if (dataClass == JSONObject.class)
            return (DataProvider<T>) _dataProvider;
        else
            return null;
    }

    private String                   _name;
    private Map<String, String>      _properties;
    private DataFlow                 _dataFlow;
    @DataProviderInjection
    private DataProvider<JSONObject> _dataProvider;
}


text:
@interface PodsDummy_Pods_Visionary : NSObject
@end
@implementation PodsDummy_Pods_Visionary
@end


text:
//
//  TLYAllViewController.m
//  百思不得姐
//
//  Created by jack_tang on 17/4/14.
//  Copyright © 2017年 jack_tang. All rights reserved.
//

#import "TLYAllViewController.h"
#import "TLYTopicViewCell.h"
#import <AFNetworking/AFNetworking.h>
#import "TLYTopicItem.h"
#import <MJExtension/MJExtension.h>
#import "TLYTopicItem.h"
#import <MJRefresh/MJRefresh.h>
static NSString * const ID = @"cell";
@interface TLYAllViewController ()

@property (nonatomic,strong)  AFHTTPSessionManager *manager;
@property (nonatomic,strong) NSMutableArray<TLYTopicItem *> *cellData;
/** 当前最后一条帖子数据的描述信息,专门用来加载下一页数据 */
@property (nonatomic, copy) NSString *maxtime;
@end

@implementation TLYAllViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = TLYRandomColor;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
    self.tableView.contentInset = UIEdgeInsetsMake(TLYNavMaxY+TLYTitleViewH, 0, TLYTabBarH, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.estimatedRowHeight = 200;
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([TLYTopicViewCell class]) bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:ID];

    //监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabClick) name:UITabClickNotification object:nil];
    //监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleClick) name:UITitleClickNotification object:nil];

    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
}

-(AFHTTPSessionManager *)manager{
    if(_manager ==nil){
        AFHTTPSessionManager *manager =  [AFHTTPSessionManager manager];
        _manager =manager;
    }
    return _manager;
}

/**
 加载数据
 **/
-(void)loadData{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(self.tabType);
    [self.manager GET:TLYCommonURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {

      self.cellData = [TLYTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
      [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self.tableView.mj_header endRefreshing];

    }];
}

/**
 加载数据
 **/
-(void)loadMoreData{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(self.tabType);
    parameters[@"maxtime"] = self.maxtime;

    [self.manager GET:TLYCommonURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        // 存储maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        [self.cellData addObjectsFromArray:[TLYTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];

}

-(void)titleClick{
    [self tabClick];

}

/**
 重新刷新的通知
 */
-(void)tabClick{
    if(self.view.window==nil)return ;
    if(self.tableView.scrollsToTop == NO)return;//是否是点击的当前view刷新
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellData.count;
}

/**
 计算每个cell 内容的高度
 **/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    TLYTopicItem *item = self.cellData[indexPath.item];
    return item.cellHeight;
}

/**
 移除接受通知
 */
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TLYTopicViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.item = self.cellData[indexPath.item];
    return cell;
}

@end


text:
'use strict';

var Component = require('./Component');
var $$ = Component.$$;
var $ = require('../util/jquery');

/**
  A simple container holding editing tools.

  @class
  @component

  @example

  ```js
  $$(Toolbar).append(
    $$(Toolbar.Group).append(
      $$(UndoTool).append($$(Icon, {icon: 'fa-undo'}))
    )
  )
  ```
*/

function Toolbar() {
  Component.apply(this, arguments);
}

Toolbar.Prototype = function() {
  this.render = function() {
    var el = $$("div").addClass("sc-toolbar");
    el.append(this.props.children);
    return el;
  };
};

Component.extend(Toolbar);

/**
  @class Toolbar.Dropdown
  @component

  @prop {ui/VirtualDOMElement} name unique editor name
  @example

  ```
  $$(Toolbar.Dropdown, {label: $$(Icon, {icon: 'fa-image'}),}).append(
    $$(InsertFigureTool).append(this.i18n.t('insert'))
  )
  ```
*/

function Dropdown() {
  Component.apply(this, arguments);
}

Dropdown.Prototype = function() {

  this.getInitialState = function() {
    return {
      open: false
    };
  };

  // Note: It's important that all children tools are rendered (even if not shown)
  // because only that way we can keep the disabled states accurate
  this.render = function() {
    var el = $$('div').addClass('se-toolbar-dropdown');
    if (this.state.open) {
      el.addClass('sm-open');
    }
    el.append(
      $$('button').ref('toggle')
        .addClass('se-toggle')
        .attr('title', this.props.title)
        .append(this.props.label)
        .on('click', this.handleDropdownToggle),
      $$('div').ref('options')
        .addClass('se-options')
        .append(this.props.children)
    );
    return el;
  };

  // Prevent click behavior as we want to preserve the text selection in the doc
  this.handleClick = function(e) {
    e.preventDefault();
  };

  this.handleDropdownToggle = function(e) {
    e.preventDefault();
    var open = this.state.open;
    var ctx = this;
    if (open) return;
    this.setState({open: !this.state.open});
    setTimeout(function() {
      $(window).one('click', function(e) {
        /*jshint unused: false */
        ctx.close();
      });
    }, 0);
  };

  this.close = function() {
    this.setState({
      open: false
    });
  };
};

Component.extend(Dropdown);

/**
  @class Toolbar.Group
  @component

  @prop {ui/VirtualDOMElement} name unique editor name

  @example

  ```js
  $$(Toolbar.Group).append(
    $$(StrongTool).append($$(Icon, {icon: 'fa-bold'}))
  )
  ```
*/

function Group() {
  Component.apply(this, arguments);
}

Group.Prototype = function() {
  this.render = function() {
    var el = $$('div').addClass('se-toolbar-group');
    el.append(this.props.children);
    return el;
  };
};

Component.extend(Group);

Toolbar.Group = Group;
Toolbar.Dropdown = Dropdown;

module.exports = Toolbar;


text:
Write a program that reads three integer numbers `N`, `K` and `S` and an array of `N` elements from the console.
- Find in the array a subset of `K` elements that have sum `S` or indicate about its absence.

_You do not have to submit anything for this problem._


text:
'use strict'

//----------------------------------------------------------
// modules
//----------------------------------------------------------
// node
const p = require('path')

// npm
const mdi = require('markdown-it')({html: true})
  .use(require('markdown-it-highlightjs'))

//----------------------------------------------------------
// transformers
//----------------------------------------------------------
/**
  Set default template for data objects that have no template specified.

  @param {String} template - default template
  @returns {Function} curried function that mutates data object
 */
const defaultTemplate = template => ob =>
  ob.template ? ob : Object.assign(ob, {template})

/**
  Inject post data into content that will use a template requiring post data.

  @param {String[]} need - templates that require post data
  @param {Object[]} content - content data objects
  @param {Object[]} posts - post data objects
  @returns {Object[]} content data objects with post data conditionally injected
 */
const injectPostData = (need, content, posts) =>
  content.map(ob =>
    need.indexOf(ob.template) > -1
      ? Object.assign({}, ob, {posts})
      : ob
  )

/**
  Render markdown to html with markdown-it.

  @param {Object} data - object with markdown to render
  @returns {Object} object with markdown rendered to html
  */
const markdown = data => {
  ['preview', 'content'].map(k => {
    if (data[k]) data[k] = mdi.render(data[k]).trim()
  })
  return data
}

/**
  Calculate the estimated reading time of a string.

  @param {String} str - string
  @param {Number} wpm - average word per minute to use in calculation
  @returns {Number} estimated reading time in minutes
 */
const ertCalc = (str, wpm) => Math.ceil(str.split(' ').length / wpm)

/**
  Curried fn to calculate the reading time of obj.content.

  @param {Number} wpm - average word per minute to use in calculation
  @returns {Function} fn that accepts an object and returns a mutated object
 */
const ert = wpm => obj => Object.assign(obj, {ert: ertCalc(obj.content, wpm)})

/**
  Make canonical link from hostname and slug.

  @param {String} host - hostname (e.g. http://example.com)
  @param {String} slug - slug (e.g. about)
  @returns {String} canonical link
 */
const makeCanonical = (host, slug) => slug === '/'
  ? host
  : `${host}${slug}`

/**
  Attach generated canonical link to Object.canonical.

  @param {String} host - hostname
  @returns {Function} pure curriend function that returns object
 */
const addCanonical = host => ob =>
  Object.assign({}, ob, {canonical: makeCanonical(host, ob.slug)})

// TODO jsdoc
const addDateOb = ob => Object.assign({}, ob, {dateOb: new Date(ob.posted)})

// TODO jsdoc
const parseDate = d => `${d.getMonth() + 1}/${d.getDate()}/${d.getFullYear()}`

// TODO jsdoc
const addDate = ob => Object.assign({}, ob, {date: parseDate(ob.dateOb)})

// TODO jsdoc
const addDateNum = ob => Object.assign(ob, {dateNum: ob.dateOb.valueOf()})

// TODO jsdoc
const byReverseDate = (a, b) => b.dateNum - a.dateNum

/**
  Attach generated path to Object.path.

  @param {String} dist - base dist dir to write to
  @returns {Function} curried function that mutates data object
 */
const addPath = dist => ob =>
  Object.assign(ob, {path: p.join(dist, ob.slug, 'index.html')})

/**
  Assign split string to object.preview and object.content.

  @param {String[]} strs - array of two strings
  @param {Object} ob - object to mutate
  @returns {Object} mutated object
 */
const assignSplits = (strs, ob) => Object.assign(ob
  , {preview: strs[0]}
  , {content: strs[1]}
)

/**
  Split object.content by preview delimiter.

  @param {String} delim - delimiter to split around
  @returns {Function} curried fn that mutates object with assignSplits if delim
    is found
 */
const splitPreview = delim => ob => {
  const content = ob.content.toString()
  return content.includes(delim)
    ? assignSplits(content.split(delim), ob)
    : Object.assign(ob, {content})
}

/**
  Add author data to objects with unspecified author.

  @param {Object} author - default author
  @returns {Function} pure curried function that returns object
 */
const addAuthor = author => ob =>
  ob.author ? ob : Object.assign({}, ob, {author})

/**
  Add nav data to object.

  @param {Object} nav - links to include in site nav; each link must be an
    object with `text` and `link` entries
  @returns {Function} pure curried function that returns object
 */
const addNav = nav => ob => Object.assign({}, ob, {nav})

/**
  Render all content with templates.

  @param {Object[]} content - ar of data objects
  @param {Object} templates - templates to render with
  @returns {Array[]} 2D array of pairs with the following values:
    value 1: path to write to
    value 2: rendered HTML
 */
const render = (content, templates) =>
  content.map(data => [data.path, templates[data.template](data)])

//----------------------------------------------------------
// exports
//----------------------------------------------------------
module.exports =
  { addAuthor
  , addCanonical
  , addDate
  , addDateOb
  , addDateNum
  , addNav
  , addPath
  , assignSplits
  , byReverseDate
  , defaultTemplate
  , ert
  , ertCalc
  , injectPostData
  , makeCanonical
  , markdown
  , parseDate
  , render
  , splitPreview
  }


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace CalypsoWeb.Controllers
{
    public class ConfigSetsController : ApiController
    {
        // GET api/configsets
        public IQueryable<ConfigSet> Get()
        {
            DataClassesDataContext db = new DataClassesDataContext();

            var ConfigSets = from cs in db.ConfigSets
                             //where cs.Status == "ACTIVE"
                             select cs;

            return ConfigSets;
        }

        // GET api/configsets/1
        public IQueryable<ConfigSet> Get(int id)
        {
            DataClassesDataContext db = new DataClassesDataContext();

            var ConfigSets = from cs in db.ConfigSets
                             where cs.ConfigSetId == id
                             select cs;

            return ConfigSets;
        }
    }
}


text:
/*
 * ffmpeg filter configuration
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "ffmpeg.h"

#include "libavfilter/avfilter.h"
#include "libavfilter/buffersink.h"

#include "libavresample/avresample.h"

#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/channel_layout.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavutil/pixfmt.h"
#include "libavutil/imgutils.h"
#include "libavutil/samplefmt.h"

enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum AVPixelFormat target)
{
    if (codec && codec->pix_fmts) {
        const enum AVPixelFormat *p = codec->pix_fmts;
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
        int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
        enum AVPixelFormat best= AV_PIX_FMT_NONE;
        if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
            if (st->codec->codec_id == AV_CODEC_ID_MJPEG) {
                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
            } else if (st->codec->codec_id == AV_CODEC_ID_LJPEG) {
                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
                                                 AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
            }
        }
        for (; *p != AV_PIX_FMT_NONE; p++) {
            best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
            if (*p == target)
                break;
        }
        if (*p == AV_PIX_FMT_NONE) {
            if (target != AV_PIX_FMT_NONE)
                av_log(NULL, AV_LOG_WARNING,
                       "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
                       av_get_pix_fmt_name(target),
                       codec->name,
                       av_get_pix_fmt_name(best));
            return best;
        }
    }
    return target;
}

void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if (codec && codec->sample_fmts) {
        const enum AVSampleFormat *p = codec->sample_fmts;
        for (; *p != -1; p++) {
            if (*p == st->codec->sample_fmt)
                break;
        }
        if (*p == -1) {
            if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
                av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
            if(av_get_sample_fmt_name(st->codec->sample_fmt))
            av_log(NULL, AV_LOG_WARNING,
                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
                   av_get_sample_fmt_name(st->codec->sample_fmt),
                   codec->name,
                   av_get_sample_fmt_name(codec->sample_fmts[0]));
            st->codec->sample_fmt = codec->sample_fmts[0];
        }
    }
}

static char *choose_pix_fmts(OutputStream *ost)
{
     if (ost->keep_pix_fmt) {
        if (ost->filter)
            avfilter_graph_set_auto_convert(ost->filter->graph->graph,
                                            AVFILTER_AUTO_CONVERT_NONE);
        if (ost->st->codec->pix_fmt == AV_PIX_FMT_NONE)
            return NULL;
        return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
    }
    if (ost->st->codec->pix_fmt != AV_PIX_FMT_NONE) {
        return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
    } else if (ost->enc && ost->enc->pix_fmts) {
        const enum AVPixelFormat *p;
        AVIOContext *s = NULL;
        uint8_t *ret;
        int len;

        if (avio_open_dyn_buf(&s) < 0)
            exit_program(1);

        p = ost->enc->pix_fmts;
        if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
            if (ost->st->codec->codec_id == AV_CODEC_ID_MJPEG) {
                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
            } else if (ost->st->codec->codec_id == AV_CODEC_ID_LJPEG) {
                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
                                                    AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
            }
        }

        for (; *p != AV_PIX_FMT_NONE; p++) {
            const char *name = av_get_pix_fmt_name(*p);
            avio_printf(s, "%s|", name);
        }
        len = avio_close_dyn_buf(s, &ret);
        ret[len - 1] = 0;
        return ret;
    } else
        return NULL;
}

/* Define a function for building a string containing a list of
 * allowed formats. */
#define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name)           \
static char *choose_ ## var ## s(OutputStream *ost)                            \
{                                                                              \
    if (ost->st->codec->var != none) {                                         \
        get_name(ost->st->codec->var);                                         \
        return av_strdup(name);                                                \
    } else if (ost->enc && ost->enc->supported_list) {                         \
        const type *p;                                                         \
        AVIOContext *s = NULL;                                                 \
        uint8_t *ret;                                                          \
        int len;                                                               \
                                                                               \
        if (avio_open_dyn_buf(&s) < 0)                                         \
            exit_program(1);                                                           \
                                                                               \
        for (p = ost->enc->supported_list; *p != none; p++) {                  \
            get_name(*p);                                                      \
            avio_printf(s, "%s|", name);                                       \
        }                                                                      \
        len = avio_close_dyn_buf(s, &ret);                                     \
        ret[len - 1] = 0;                                                      \
        return ret;                                                            \
    } else                                                                     \
        return NULL;                                                           \
}

// DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
//                   GET_PIX_FMT_NAME)

DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
                  AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)

DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
                  GET_SAMPLE_RATE_NAME)

DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
                  GET_CH_LAYOUT_NAME)

FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
{
    FilterGraph *fg = av_mallocz(sizeof(*fg));

    if (!fg)
        exit_program(1);
    fg->index = nb_filtergraphs;

    GROW_ARRAY(fg->outputs, fg->nb_outputs);
    if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
        exit_program(1);
    fg->outputs[0]->ost   = ost;
    fg->outputs[0]->graph = fg;

    ost->filter = fg->outputs[0];

    GROW_ARRAY(fg->inputs, fg->nb_inputs);
    if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
        exit_program(1);
    fg->inputs[0]->ist   = ist;
    fg->inputs[0]->graph = fg;

    GROW_ARRAY(ist->filters, ist->nb_filters);
    ist->filters[ist->nb_filters - 1] = fg->inputs[0];

    GROW_ARRAY(filtergraphs, nb_filtergraphs);
    filtergraphs[nb_filtergraphs - 1] = fg;

    return fg;
}

static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
{
    InputStream *ist = NULL;
    enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
    int i;

    // TODO: support other filter types
    if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
        av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
               "currently.\n");
        exit_program(1);
    }

    if (in->name) {
        AVFormatContext *s;
        AVStream       *st = NULL;
        char *p;
        int file_idx = strtol(in->name, &p, 0);

        if (file_idx < 0 || file_idx >= nb_input_files) {
            av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
                   file_idx, fg->graph_desc);
            exit_program(1);
        }
        s = input_files[file_idx]->ctx;

        for (i = 0; i < s->nb_streams; i++) {
            enum AVMediaType stream_type = s->streams[i]->codec->codec_type;
            if (stream_type != type &&
                !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
                  type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
                continue;
            if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
                st = s->streams[i];
                break;
            }
        }
        if (!st) {
            av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
                   "matches no streams.\n", p, fg->graph_desc);
            exit_program(1);
        }
        ist = input_streams[input_files[file_idx]->ist_index + st->index];
    } else {
        /* find the first unused stream of corresponding type */
        for (i = 0; i < nb_input_streams; i++) {
            ist = input_streams[i];
            if (ist->st->codec->codec_type == type && ist->discard)
                break;
        }
        if (i == nb_input_streams) {
            av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
                   "unlabeled input pad %d on filter %s\n", in->pad_idx,
                   in->filter_ctx->name);
            exit_program(1);
        }
    }
    av_assert0(ist);

    ist->discard         = 0;
    ist->decoding_needed++;
    ist->st->discard = AVDISCARD_NONE;

    GROW_ARRAY(fg->inputs, fg->nb_inputs);
    if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
        exit_program(1);
    fg->inputs[fg->nb_inputs - 1]->ist   = ist;
    fg->inputs[fg->nb_inputs - 1]->graph = fg;

    GROW_ARRAY(ist->filters, ist->nb_filters);
    ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
}

static int insert_trim(OutputStream *ost, AVFilterContext **last_filter, int *pad_idx)
{
    OutputFile *of = output_files[ost->file_index];
    AVFilterGraph *graph = (*last_filter)->graph;
    AVFilterContext *ctx;
    const AVFilter *trim;
    const char *name = ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO ? "trim" : "atrim";
    char filter_name[128];
    int ret = 0;

    if (of->recording_time == INT64_MAX && !of->start_time)
        return 0;

    // Use with duration and without output starttime is buggy with trim filters
    if (!of->start_time)
        return 0;

    trim = avfilter_get_by_name(name);
    if (!trim) {
        av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
               "recording time.\n", name);
        return AVERROR_FILTER_NOT_FOUND;
    }

    snprintf(filter_name, sizeof(filter_name), "%s for output stream %d:%d",
             name, ost->file_index, ost->index);
    ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
    if (!ctx)
        return AVERROR(ENOMEM);

    if (of->recording_time != INT64_MAX) {
        ret = av_opt_set_double(ctx, "duration", (double)of->recording_time / 1e6,
                                AV_OPT_SEARCH_CHILDREN);
    }
    if (ret >= 0 && of->start_time) {
        ret = av_opt_set_double(ctx, "start", (double)of->start_time / 1e6,
                                AV_OPT_SEARCH_CHILDREN);
    }
    if (ret < 0) {
        av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
        return ret;
    }

    ret = avfilter_init_str(ctx, NULL);
    if (ret < 0)
        return ret;

    ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
    if (ret < 0)
        return ret;

    *last_filter = ctx;
    *pad_idx     = 0;
    return 0;
}

static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
{
    char *pix_fmts;
    OutputStream *ost = ofilter->ost;
    AVCodecContext *codec = ost->st->codec;
    AVFilterContext *last_filter = out->filter_ctx;
    int pad_idx = out->pad_idx;
    int ret;
    char name[255];

    snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
    ret = avfilter_graph_create_filter(&ofilter->filter,
                                       avfilter_get_by_name("buffersink"),
                                       name, NULL, NULL, fg->graph);

    if (ret < 0)
        return ret;

    if (codec->width || codec->height) {
        char args[255];
        AVFilterContext *filter;

        snprintf(args, sizeof(args), "%d:%d:0x%X",
                 codec->width,
                 codec->height,
                 (unsigned)ost->sws_flags);
        snprintf(name, sizeof(name), "scaler for output stream %d:%d",
                 ost->file_index, ost->index);
        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
                                                name, args, NULL, fg->graph)) < 0)
            return ret;
        if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
            return ret;

        last_filter = filter;
        pad_idx = 0;
    }

    if ((pix_fmts = choose_pix_fmts(ost))) {
        AVFilterContext *filter;
        snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
                 ost->file_index, ost->index);
        ret = avfilter_graph_create_filter(&filter,
                                                avfilter_get_by_name("format"),
                                                "format", pix_fmts, NULL,
                                                fg->graph);
        av_freep(&pix_fmts);
        if (ret < 0)
            return ret;
        if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
            return ret;

        last_filter = filter;
        pad_idx     = 0;
    }

    if (ost->frame_rate.num && 0) {
        AVFilterContext *fps;
        char args[255];

        snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
                 ost->frame_rate.den);
        snprintf(name, sizeof(name), "fps for output stream %d:%d",
                 ost->file_index, ost->index);
        ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
                                           name, args, NULL, fg->graph);
        if (ret < 0)
            return ret;

        ret = avfilter_link(last_filter, pad_idx, fps, 0);
        if (ret < 0)
            return ret;
        last_filter = fps;
        pad_idx = 0;
    }

    ret = insert_trim(ost, &last_filter, &pad_idx);
    if (ret < 0)
        return ret;

    if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
        return ret;

    return 0;
}

static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
{
    OutputStream *ost = ofilter->ost;
    AVCodecContext *codec  = ost->st->codec;
    AVFilterContext *last_filter = out->filter_ctx;
    OutputFile *of = output_files[ost->file_index];
    int pad_idx = out->pad_idx;
    char *sample_fmts, *sample_rates, *channel_layouts;
    char name[255];
    int ret;

    snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
    ret = avfilter_graph_create_filter(&ofilter->filter,
                                       avfilter_get_by_name("abuffersink"),
                                       name, NULL, NULL, fg->graph);
    if (ret < 0)
        return ret;
    if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
        return ret;

#define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
    AVFilterContext *filt_ctx;                                              \
                                                                            \
    av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
           "similarly to -af " filter_name "=%s.\n", arg);                  \
                                                                            \
    ret = avfilter_graph_create_filter(&filt_ctx,                           \
                                       avfilter_get_by_name(filter_name),   \
                                       filter_name, arg, NULL, fg->graph);  \
    if (ret < 0)                                                            \
        return ret;                                                         \
                                                                            \
    ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \
    if (ret < 0)                                                            \
        return ret;                                                         \
                                                                            \
    last_filter = filt_ctx;                                                 \
    pad_idx = 0;                                                            \
} while (0)
    if (ost->audio_channels_mapped) {
        int i;
        AVBPrint pan_buf;
        av_bprint_init(&pan_buf, 256, 8192);
        av_bprintf(&pan_buf, "0x%"PRIx64,
                   av_get_default_channel_layout(ost->audio_channels_mapped));
        for (i = 0; i < ost->audio_channels_mapped; i++)
            if (ost->audio_channels_map[i] != -1)
                av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);

        AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
        av_bprint_finalize(&pan_buf, NULL);
    }

    if (codec->channels && !codec->channel_layout)
        codec->channel_layout = av_get_default_channel_layout(codec->channels);

    sample_fmts     = choose_sample_fmts(ost);
    sample_rates    = choose_sample_rates(ost);
    channel_layouts = choose_channel_layouts(ost);
    if (sample_fmts || sample_rates || channel_layouts) {
        AVFilterContext *format;
        char args[256];
        args[0] = 0;

        if (sample_fmts)
            av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
                            sample_fmts);
        if (sample_rates)
            av_strlcatf(args, sizeof(args), "sample_rates=%s:",
                            sample_rates);
        if (channel_layouts)
            av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
                            channel_layouts);

        av_freep(&sample_fmts);
        av_freep(&sample_rates);
        av_freep(&channel_layouts);

        snprintf(name, sizeof(name), "audio format for output stream %d:%d",
                 ost->file_index, ost->index);
        ret = avfilter_graph_create_filter(&format,
                                           avfilter_get_by_name("aformat"),
                                           name, args, NULL, fg->graph);
        if (ret < 0)
            return ret;

        ret = avfilter_link(last_filter, pad_idx, format, 0);
        if (ret < 0)
            return ret;

        last_filter = format;
        pad_idx = 0;
    }

    if (audio_volume != 256 && 0) {
        char args[256];

        snprintf(args, sizeof(args), "%f", audio_volume / 256.);
        AUTO_INSERT_FILTER("-vol", "volume", args);
    }

    if (ost->apad && of->shortest) {
        char args[256];
        int i;

        for (i=0; i<of->ctx->nb_streams; i++)
            if (of->ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
                break;

        if (i<of->ctx->nb_streams) {
            snprintf(args, sizeof(args), "%s", ost->apad);
            AUTO_INSERT_FILTER("-apad", "apad", args);
        }
    }

    ret = insert_trim(ost, &last_filter, &pad_idx);
    if (ret < 0)
        return ret;

    if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
        return ret;

    return 0;
}

#define DESCRIBE_FILTER_LINK(f, inout, in)                         \
{                                                                  \
    AVFilterContext *ctx = inout->filter_ctx;                      \
    AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
    int       nb_pads = in ? ctx->input_count : ctx->output_count; \
    AVIOContext *pb;                                               \
                                                                   \
    if (avio_open_dyn_buf(&pb) < 0)                                \
        exit_program(1);                                           \
                                                                   \
    avio_printf(pb, "%s", ctx->filter->name);                      \
    if (nb_pads > 1)                                               \
        avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
    avio_w8(pb, 0);                                                \
    avio_close_dyn_buf(pb, &f->name);                              \
}

int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
{
    av_freep(&ofilter->name);
    DESCRIBE_FILTER_LINK(ofilter, out, 0);

    switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
    case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
    case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
    default: av_assert0(0);
    }
}

static int sub2video_prepare(InputStream *ist)
{
    AVFormatContext *avf = input_files[ist->file_index]->ctx;
    int i, w, h;

    /* Compute the size of the canvas for the subtitles stream.
       If the subtitles codec has set a size, use it. Otherwise use the
       maximum dimensions of the video streams in the same file. */
    w = ist->st->codec->width;
    h = ist->st->codec->height;
    if (!(w && h)) {
        for (i = 0; i < avf->nb_streams; i++) {
            if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
                w = FFMAX(w, avf->streams[i]->codec->width);
                h = FFMAX(h, avf->streams[i]->codec->height);
            }
        }
        if (!(w && h)) {
            w = FFMAX(w, 720);
            h = FFMAX(h, 576);
        }
        av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
    }
    ist->sub2video.w = ist->st->codec->width  = ist->resample_width  = w;
    ist->sub2video.h = ist->st->codec->height = ist->resample_height = h;

    /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
       palettes for all rectangles are identical or compatible */
    ist->resample_pix_fmt = ist->st->codec->pix_fmt = AV_PIX_FMT_RGB32;

    ist->sub2video.frame = av_frame_alloc();
    if (!ist->sub2video.frame)
        return AVERROR(ENOMEM);
    return 0;
}

static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
                                        AVFilterInOut *in)
{
    AVFilterContext *first_filter = in->filter_ctx;
    AVFilter *filter = avfilter_get_by_name("buffer");
    InputStream *ist = ifilter->ist;
    AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
                                         ist->st->time_base;
    AVRational fr = ist->framerate;
    AVRational sar;
    AVBPrint args;
    char name[255];
    int pad_idx = in->pad_idx;
    int ret;

    if (!fr.num)
        fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);

    if (ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
        ret = sub2video_prepare(ist);
        if (ret < 0)
            return ret;
    }

    sar = ist->st->sample_aspect_ratio.num ?
          ist->st->sample_aspect_ratio :
          ist->st->codec->sample_aspect_ratio;
    if(!sar.den)
        sar = (AVRational){0,1};
    av_bprint_init(&args, 0, 1);
    av_bprintf(&args,
             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
             "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
             ist->resample_height, ist->resample_pix_fmt,
             tb.num, tb.den, sar.num, sar.den,
             SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
    if (fr.num && fr.den)
        av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
    snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
             ist->file_index, ist->st->index);

    if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
                                            args.str, NULL, fg->graph)) < 0)
        return ret;

    if (ist->framerate.num) {
        AVFilterContext *setpts;

        snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
                 ist->file_index, ist->st->index);
        if ((ret = avfilter_graph_create_filter(&setpts,
                                                avfilter_get_by_name("setpts"),
                                                name, "N", NULL,
                                                fg->graph)) < 0)
            return ret;

        if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
            return ret;

        first_filter = setpts;
        pad_idx = 0;
    }

    if (do_deinterlace) {
        AVFilterContext *yadif;

        snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
                 ist->file_index, ist->st->index);
        if ((ret = avfilter_graph_create_filter(&yadif,
                                                avfilter_get_by_name("yadif"),
                                                name, "", NULL,
                                                fg->graph)) < 0)
            return ret;

        if ((ret = avfilter_link(yadif, 0, first_filter, pad_idx)) < 0)
            return ret;

        first_filter = yadif;
        pad_idx = 0;
    }

    if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
        return ret;
    return 0;
}

static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
                                        AVFilterInOut *in)
{
    AVFilterContext *first_filter = in->filter_ctx;
    AVFilter *filter = avfilter_get_by_name("abuffer");
    InputStream *ist = ifilter->ist;
    int pad_idx = in->pad_idx;
    AVBPrint args;
    char name[255];
    int ret;

    av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
    av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
             1, ist->st->codec->sample_rate,
             ist->st->codec->sample_rate,
             av_get_sample_fmt_name(ist->st->codec->sample_fmt));
    if (ist->st->codec->channel_layout)
        av_bprintf(&args, ":channel_layout=0x%"PRIx64,
                   ist->st->codec->channel_layout);
    else
        av_bprintf(&args, ":channels=%d", ist->st->codec->channels);
    snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
             ist->file_index, ist->st->index);

    if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
                                            name, args.str, NULL,
                                            fg->graph)) < 0)
        return ret;

#define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
    AVFilterContext *filt_ctx;                                              \
                                                                            \
    av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
           "similarly to -af " filter_name "=%s.\n", arg);                  \
                                                                            \
    snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
                fg->index, filter_name, ist->file_index, ist->st->index);   \
    ret = avfilter_graph_create_filter(&filt_ctx,                           \
                                       avfilter_get_by_name(filter_name),   \
                                       name, arg, NULL, fg->graph);         \
    if (ret < 0)                                                            \
        return ret;                                                         \
                                                                            \
    ret = avfilter_link(filt_ctx, 0, first_filter, pad_idx);                \
    if (ret < 0)                                                            \
        return ret;                                                         \
                                                                            \
    first_filter = filt_ctx;                                                  \
} while (0)

    if (audio_sync_method > 0) {
        char args[256] = {0};

        av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
        if (audio_drift_threshold != 0.1)
            av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
        if (!fg->reconfiguration)
            av_strlcatf(args, sizeof(args), ":first_pts=0");
        AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
    }

//     if (ost->audio_channels_mapped) {
//         int i;
//         AVBPrint pan_buf;
//         av_bprint_init(&pan_buf, 256, 8192);
//         av_bprintf(&pan_buf, "0x%"PRIx64,
//                    av_get_default_channel_layout(ost->audio_channels_mapped));
//         for (i = 0; i < ost->audio_channels_mapped; i++)
//             if (ost->audio_channels_map[i] != -1)
//                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
//         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
//         av_bprint_finalize(&pan_buf, NULL);
//     }

    if (audio_volume != 256) {
        char args[256];

        av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
               "audio filter instead.\n");

        snprintf(args, sizeof(args), "%f", audio_volume / 256.);
        AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
    }
    if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
        return ret;

    return 0;
}

static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
                                  AVFilterInOut *in)
{
    av_freep(&ifilter->name);
    DESCRIBE_FILTER_LINK(ifilter, in, 1);

    switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
    case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
    case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
    default: av_assert0(0);
    }
}

int configure_filtergraph(FilterGraph *fg)
{
    AVFilterInOut *inputs, *outputs, *cur;
    int ret, i, init = !fg->graph, simple = !fg->graph_desc;
    const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
                                      fg->graph_desc;

    avfilter_graph_free(&fg->graph);
    if (!(fg->graph = avfilter_graph_alloc()))
        return AVERROR(ENOMEM);

    if (simple) {
        OutputStream *ost = fg->outputs[0]->ost;
        char args[512];
        AVDictionaryEntry *e = NULL;

        snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
        fg->graph->scale_sws_opts = av_strdup(args);

        args[0] = 0;
        while ((e = av_dict_get(ost->swr_opts, "", e,
                                AV_DICT_IGNORE_SUFFIX))) {
            av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
        }
        if (strlen(args))
            args[strlen(args)-1] = 0;
        av_opt_set(fg->graph, "aresample_swr_opts", args, 0);

        args[0] = '\0';
        while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
                                AV_DICT_IGNORE_SUFFIX))) {
            av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
        }
        if (strlen(args))
            args[strlen(args) - 1] = '\0';
        fg->graph->resample_lavr_opts = av_strdup(args);
    }

    if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
        return ret;

    if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
        av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
               "exactly one input and output.\n", graph_desc);
        return AVERROR(EINVAL);
    }

    for (cur = inputs; !simple && init && cur; cur = cur->next)
        init_input_filter(fg, cur);

    for (cur = inputs, i = 0; cur; cur = cur->next, i++)
        if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
            return ret;
    avfilter_inout_free(&inputs);

    if (!init || simple) {
        /* we already know the mappings between lavfi outputs and output streams,
         * so we can finish the setup */
        for (cur = outputs, i = 0; cur; cur = cur->next, i++)
            configure_output_filter(fg, fg->outputs[i], cur);
        avfilter_inout_free(&outputs);

        if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
            return ret;
    } else {
        /* wait until output mappings are processed */
        for (cur = outputs; cur;) {
            GROW_ARRAY(fg->outputs, fg->nb_outputs);
            if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
                exit_program(1);
            fg->outputs[fg->nb_outputs - 1]->graph   = fg;
            fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
            cur = cur->next;
            fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
        }
    }

    fg->reconfiguration = 1;
    return 0;
}

int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
{
    int i;
    for (i = 0; i < fg->nb_inputs; i++)
        if (fg->inputs[i]->ist == ist)
            return 1;
    return 0;
}


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_cache_Context_h
#define mozilla_dom_cache_Context_h

#include "mozilla/dom/cache/Types.h"
#include "nsAutoPtr.h"
#include "nsCOMPtr.h"
#include "nsISupportsImpl.h"
#include "nsProxyRelease.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsTObserverArray.h"

class nsIEventTarget;
class nsIThread;

namespace mozilla {
namespace dom {
namespace cache {

class Action;
class Manager;
class OfflineStorage;

// The Context class is RAII-style class for managing IO operations within the
// Cache.
//
// When a Context is created it performs the complicated steps necessary to
// initialize the QuotaManager.  Action objects dispatched on the Context are
// delayed until this initialization is complete.  They are then allow to
// execute on any specified thread.  Once all references to the Context are
// gone, then the steps necessary to release the QuotaManager are performed.
// After initialization the Context holds a self reference, so it will stay
// alive until one of three conditions occur:
//
//  1) The Manager will call Context::AllowToClose() when all of the actors
//     have removed themselves as listener.  This means an idle context with
//     no active DOM objects will close gracefully.
//  2) The QuotaManager invalidates the storage area so it can delete the
//     files.  In this case the OfflineStorage calls Cache::Invalidate() which
//     in turn cancels all existing Action objects and then marks the Manager
//     as invalid.
//  3) Browser shutdown occurs and the Manager calls Context::CancelAll().
//
// In either case, though, the Action objects must be destroyed first to
// allow the Context to be destroyed.
//
// While the Context performs operations asynchronously on threads, all of
// methods in its public interface must be called on the same thread
// originally used to create the Context.
//
// As an invariant, all Context objects must be destroyed before permitting
// the "profile-before-change" shutdown event to complete.  This is ensured
// via the code in ShutdownObserver.cpp.
class Context final
{
public:
  // Define a class allowing other threads to hold the Context alive.  This also
  // allows these other threads to safely close or cancel the Context.
  class ThreadsafeHandle final
  {
    friend class Context;
  public:
    void AllowToClose();
    void InvalidateAndAllowToClose();
  private:
    explicit ThreadsafeHandle(Context* aContext);
    ~ThreadsafeHandle();

    // disallow copying
    ThreadsafeHandle(const ThreadsafeHandle&) = delete;
    ThreadsafeHandle& operator=(const ThreadsafeHandle&) = delete;

    void AllowToCloseOnOwningThread();
    void InvalidateAndAllowToCloseOnOwningThread();

    void ContextDestroyed(Context* aContext);

    // Cleared to allow the Context to close.  Only safe to access on
    // owning thread.
    nsRefPtr<Context> mStrongRef;

    // Used to support cancelation even while the Context is already allowed
    // to close.  Cleared by ~Context() calling ContextDestroyed().  Only
    // safe to access on owning thread.
    Context* mWeakRef;

    nsCOMPtr<nsIThread> mOwningThread;

    NS_INLINE_DECL_THREADSAFE_REFCOUNTING(cache::Context::ThreadsafeHandle)
  };

  // Different objects hold references to the Context while some work is being
  // performed asynchronously.  These objects must implement the Activity
  // interface and register themselves with the AddActivity().  When they are
  // destroyed they must call RemoveActivity().  This allows the Context to
  // cancel any outstanding Activity work when the Context is cancelled.
  class Activity
  {
  public:
    virtual void Cancel() = 0;
    virtual bool MatchesCacheId(CacheId aCacheId) const = 0;
  };

  // Create a Context attached to the given Manager.  The given Action
  // will run on the QuotaManager IO thread.  Note, this Action must
  // be execute synchronously.
  static already_AddRefed<Context>
  Create(Manager* aManager, nsIThread* aTarget,
         Action* aInitAction, Context* aOldContext);

  // Execute given action on the target once the quota manager has been
  // initialized.
  //
  // Only callable from the thread that created the Context.
  void Dispatch(Action* aAction);

  // Cancel any Actions running or waiting to run.  This should allow the
  // Context to be released and Listener::RemoveContext() will be called
  // when complete.
  //
  // Only callable from the thread that created the Context.
  void CancelAll();

  // True if CancelAll() has been called.
  bool IsCanceled() const;

  // Like CancelAll(), but also marks the Manager as "invalid".
  void Invalidate();

  // Remove any self references and allow the Context to be released when
  // there are no more Actions to process.
  void AllowToClose();

  // Cancel any Actions running or waiting to run that operate on the given
  // cache ID.
  //
  // Only callable from the thread that created the Context.
  void CancelForCacheId(CacheId aCacheId);

  void AddActivity(Activity* aActivity);
  void RemoveActivity(Activity* aActivity);

  const QuotaInfo&
  GetQuotaInfo() const
  {
    return mQuotaInfo;
  }

  // Tell the Context that some state information has been orphaned in the
  // data store and won't be cleaned up.  The Context will leave the marker
  // in place to trigger cleanup the next times its opened.
  void NoteOrphanedData();

private:
  class Data;
  class QuotaInitRunnable;
  class ActionRunnable;

  enum State
  {
    STATE_CONTEXT_PREINIT,
    STATE_CONTEXT_INIT,
    STATE_CONTEXT_READY,
    STATE_CONTEXT_CANCELED
  };

  struct PendingAction
  {
    nsCOMPtr<nsIEventTarget> mTarget;
    nsRefPtr<Action> mAction;
  };

  Context(Manager* aManager, nsIThread* aTarget);
  ~Context();
  void Init(Action* aInitAction, Context* aOldContext);
  void Start();
  void DispatchAction(Action* aAction, bool aDoomData = false);
  void OnQuotaInit(nsresult aRv, const QuotaInfo& aQuotaInfo,
                   nsMainThreadPtrHandle<OfflineStorage>& aOfflineStorage);

  already_AddRefed<ThreadsafeHandle>
  CreateThreadsafeHandle();

  void
  SetNextContext(Context* aNextContext);

  void
  DoomTargetData();

  nsRefPtr<Manager> mManager;
  nsCOMPtr<nsIThread> mTarget;
  nsRefPtr<Data> mData;
  State mState;
  bool mOrphanedData;
  QuotaInfo mQuotaInfo;
  nsRefPtr<QuotaInitRunnable> mInitRunnable;
  nsTArray<PendingAction> mPendingActions;

  // Weak refs since activites must remove themselves from this list before
  // being destroyed by calling RemoveActivity().
  typedef nsTObserverArray<Activity*> ActivityList;
  ActivityList mActivityList;

  // The ThreadsafeHandle may have a strong ref back to us.  This creates
  // a ref-cycle that keeps the Context alive.  The ref-cycle is broken
  // when ThreadsafeHandle::AllowToClose() is called.
  nsRefPtr<ThreadsafeHandle> mThreadsafeHandle;

  nsMainThreadPtrHandle<OfflineStorage> mOfflineStorage;
  nsRefPtr<Context> mNextContext;

public:
  NS_INLINE_DECL_REFCOUNTING(cache::Context)
};

} // namespace cache
} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_cache_Context_h


text:
namespace org {
  namespace apache {
    namespace lucene {
      namespace util {
        class Version;
      }
      namespace analysis {
        namespace util {
          class CharArraySet;
          class CharArrayMap;
        }
      }
    }
  }
}
namespace java {
  namespace lang {
    class String;
    class Class;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace analysis {
        namespace nl {

          class DutchAnalyzer : public ::org::apache::lucene::analysis::Analyzer {
          public:
            enum {
              mid_init$_0d96cf33,
              mid_init$_83eafe28,
              mid_init$_c9d7e4a3,
              mid_init$_0a2f8356,
              mid_getDefaultStopSet_d2d3505c,
              mid_createComponents_1be39cae,
              max_mid
            };

            static ::java::lang::Class *class$;
            static jmethodID *mids$;
            static bool live$;
            static jclass initializeClass(bool);

            explicit DutchAnalyzer(jobject obj) : ::org::apache::lucene::analysis::Analyzer(obj) {
              if (obj != NULL)
                env->getClass(initializeClass);
            }
            DutchAnalyzer(const DutchAnalyzer& obj) : ::org::apache::lucene::analysis::Analyzer(obj) {}

            static ::java::lang::String *DEFAULT_STOPWORD_FILE;

            DutchAnalyzer(const ::org::apache::lucene::util::Version &);
            DutchAnalyzer(const ::org::apache::lucene::util::Version &, const ::org::apache::lucene::analysis::util::CharArraySet &);
            DutchAnalyzer(const ::org::apache::lucene::util::Version &, const ::org::apache::lucene::analysis::util::CharArraySet &, const ::org::apache::lucene::analysis::util::CharArraySet &);
            DutchAnalyzer(const ::org::apache::lucene::util::Version &, const ::org::apache::lucene::analysis::util::CharArraySet &, const ::org::apache::lucene::analysis::util::CharArraySet &, const ::org::apache::lucene::analysis::util::CharArrayMap &);

            static ::org::apache::lucene::analysis::util::CharArraySet getDefaultStopSet();
          };
        }
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace analysis {
        namespace nl {
          extern PyTypeObject PY_TYPE(DutchAnalyzer);

          class t_DutchAnalyzer {
          public:
            PyObject_HEAD
            DutchAnalyzer object;
            static PyObject *wrap_Object(const DutchAnalyzer&);
            static PyObject *wrap_jobject(const jobject&);
            static void install(PyObject *module);
            static void initialize(PyObject *module);
          };
        }
      }
    }
  }
}

#endif


text:
/**
 * Fail a Jasmine test such that it displays the error object,
 * typically passed in the error path of an Observable.subscribe()
 * @param err - the error object
 */
export function failure(err: any) {
  fail(JSON.stringify(err));
}


text:
<?php

// This test also needs to exclude the protected and private variables
// since they cannot be accessed from the external object which iterates
// them.

class test implements IteratorAggregate
{
	public    $pub = "public";
	protected $pro = "protected";
	private   $pri = "private";

	function __construct()
	{
		$this->imp = "implicit";
	}

	function getIterator()
	{
		$it = new ArrayObject($this);
		return $it->getIterator();
	}
};

$test = new test;
$test->dyn = "dynamic";

print_r($test);

print_r($test->getIterator());

foreach($test as $key => $val)
{
	echo "$key => $val\n";
}

?>
===DONE===


text:
#import "EC2RequestSpotInstancesRequest.h"

@implementation EC2RequestSpotInstancesRequest

@synthesize spotPrice;
@synthesize instanceCount;
@synthesize type;
@synthesize validFrom;
@synthesize validUntil;
@synthesize launchGroup;
@synthesize availabilityZoneGroup;
@synthesize launchSpecification;

-(id)init
{
    if (self = [super init]) {
        spotPrice             = nil;
        instanceCount         = nil;
        type                  = nil;
        validFrom             = nil;
        validUntil            = nil;
        launchGroup           = nil;
        availabilityZoneGroup = nil;
        launchSpecification   = nil;
    }

    return self;
}

-(id)initWithSpotPrice:(NSString *)theSpotPrice
{
    if (self = [self init]) {
        self.spotPrice = theSpotPrice;
    }

    return self;
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"SpotPrice: %@,", spotPrice] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"InstanceCount: %@,", instanceCount] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"Type: %@,", type] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"ValidFrom: %@,", validFrom] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"ValidUntil: %@,", validUntil] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"LaunchGroup: %@,", launchGroup] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"AvailabilityZoneGroup: %@,", availabilityZoneGroup] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"LaunchSpecification: %@,", launchSpecification] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [spotPrice release];
    [instanceCount release];
    [type release];
    [validFrom release];
    [validUntil release];
    [launchGroup release];
    [availabilityZoneGroup release];
    [launchSpecification release];

    [super dealloc];
}

@end