text:
Filtres
=======

Les filtres sont des objets qui sont exécutés avant et/ou après les [actions de contrôleurs](structure-controllers.md#actions). Par exemple, un filtre de contrôle d'accès peut être exécuté avant les actions pour garantir qu'un utilisateur final particulier est autorisé à y accéder. Un filtre de compression de contenu peut être exécuté après les actions pour compresser la réponse avant de l'envoyer à l'utilisateur final.

Un filtre peut être constitué d''un pré-filtre (logique de filtrage appliquée *avant* les actions) et/ou un post-filtre (logique appliquée *après* les actions).

## Utilisation des filtres

Pour l'essentiel, les filtres sont des sortes de [comportements](concept-behaviors.md). Par conséquent, leur utilisation est identique à l' [utilisation des comportements](concept-behaviors.md#attaching-behaviors). Vous pouvez déclarer des filtres dans une classe de contrôleur en redéfinissant sa méthode [[yii\base\Controller::behaviors()|behaviors()]] de la manière suivante :

```php
public function behaviors()
{
    return [
        [
            'class' => 'yii\filters\HttpCache',
            'only' => ['index', 'view'],
            'lastModified' => function ($action, $params) {
                $q = new \yii\db\Query();
                return $q->from('user')->max('updated_at');
            },
        ],
    ];
}
```

Par défaut, les filtres déclarés dans une classe de contrôleur sont appliqués à *toutes* les action de ce contrôleur. Vous pouvez cependant, spécifier explicitement à quelles actions ils s'appliquent en configurant la propriété [[yii\base\ActionFilter::only|only]]. Dans l'exemple précédent, le filtre `HttpCache` s'applique uniquement aux actions `index` et `view`. Vous pouvez également configurer la propriété [[yii\base\ActionFilter::except|except]] pour empêcher quelques actions d'être filtrées.

En plus des contrôleurs, vous pouvez également déclarer des filtres dans un [module](structure-modules.md) ou dans une [application](structure-applications.md). Lorsque vous faites cela, les filtres s'appliquent à *toutes* les actions de contrôleur qui appartiennent à ce module ou à cette application, sauf si vous configurez les propriétés des filtres [[yii\base\ActionFilter::only|only]] et [[yii\base\ActionFilter::except|except]] comme expliqué précédemment.

> Note: lorsque vous déclarez des filtres dans des modules ou des applications, vous devriez utiliser des [routes](structure-controllers.md#routes) plutôt que des identifiants d'action dans les propriétés [[yii\base\ActionFilter::only|only]] et [[yii\base\ActionFilter::except|except]]. Cela tient au fait qu'un identifiant d'action seul ne peut pas pleinement spécifier une  action dans le cadre d'un module ou d'une application.

Lorsque plusieurs filtres sont configurés pour une même action, ils sont appliqués en respectant les règles et l'ordre qui suivent :

* Pré-filtrage
    - Les filtres déclarés dans l'application sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.
    - Les filtres déclarés dans le module sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.
    - Les filtres déclarés dans le contrôleur sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.
    - Si l'un quelconque des filtres annule l'exécution de l'action, les filtres subséquents (à la fois de pré-filtrage et de post-fitrage) ne sont pas appliqués.
* L'action est exécutée si les filtres de pré-filtrage réussissent.
* Post-filtrage
    - Les filtres déclarés dans le contrôleur sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.
    - Les filtres déclarés dans le module sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.
    - Les filtres déclarés dans l'application sont appliqués dans l'ordre dans lequel ils sont listés dans la méthode `behaviors()`.

## Création de filtres

Pour créer un filtre d'action, vous devez étendre la classe [[yii\base\ActionFilter]] et redéfinir la méthode [[yii\base\ActionFilter::beforeAction()|beforeAction()]] et/ou la méthode [[yii\base\ActionFilter::afterAction()|afterAction()]]. La première est exécutée avant l'exécution de l'action, tandis que la seconde est exécutée après l'exécution de l'action. Le valeur de retour de la méthode [[yii\base\ActionFilter::beforeAction()|beforeAction()]] détermine si une action doit être exécutée ou pas. Si c'est `false` (faux), les filtres qui suivent sont ignorés et l'action n'est pas exécutée.

L'exemple qui suit montre un filtre qui enregistre dans un journal le temps d'exécution de l'action :

```php
namespace app\components;

use Yii;
use yii\base\ActionFilter;

class ActionTimeFilter extends ActionFilter
{
    private $_startTime;

    public function beforeAction($action)
    {
        $this->_startTime = microtime(true);
        return parent::beforeAction($action);
    }

    public function afterAction($action, $result)
    {
        $time = microtime(true) - $this->_startTime;
        Yii::debug("Action '{$action->uniqueId}' spent $time second.");
        return parent::afterAction($action, $result);
    }
}
```

## Filtres du noyau

Yii fournit un jeu de filtres couramment utilisés, que l'on trouve en premier lieu dans l'espace de noms `yii\filters`. Dans ce qui suit, nous introduisons brièvement ces filtres.

### [[yii\filters\AccessControl|AccessControl]]

*AccessControl* (contrôle d'accès) fournit un contrôle d'accès simple basé sur un jeu de [[yii\filters\AccessControl::rules|règles]]. En particulier, avant qu'une action ne soit exécutée, *AccessControl* examine les règles listées et trouve la première qui  correspond aux variables du contexte courant (comme l'adresse IP, l'état de connexion de l'utilisateur, etc.). La règle qui correspond détermine si l'exécution de l'action requise doit être autorisée ou refusée. Si aucune des règles ne correspond, l'accès est refusé.

L'exemple suivant montre comment autoriser les utilisateurs authentifiés à accéder aux actions `create` et `update` tout en refusant l'accès à ces actions aux autres utilisateurs.

```php
use yii\filters\AccessControl;

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::class,
            'only' => ['create', 'update'],
            'rules' => [
                // autoriser les utilisateurs authentifiés
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // tout autre chose est interdite d'accès par défaut
            ],
        ],
    ];
}
```

Pour plus de détails sur le contrôle d'accès en général, reportez-vous à la section [Authorization](security-authorization.md).

### Filtres de méthodes d'authentification

Les filtres de méthodes d'authentification sont utilisés pour authentifier un utilisateur qui utilise des méthodes d'authentification variées comme
[HTTP Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication) ou [OAuth 2](https://oauth.net/2/). Les classes de filtre sont dans l'espace de noms `yii\filters\auth`.

L'exemple qui suit montre comment vous pouvez utiliser [[yii\filters\auth\HttpBasicAuth]] pour authentifier un utilisateur qui utilise un jeton d'accès basé sur la méthode  *HTTP Basic Auth*. Notez qu'afin que cela fonctionne, votre [[yii\web\User::identityClass|classe *identity* de l'utilisateur]] doit implémenter l'interface [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]].

```php
use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    return [
        'basicAuth' => [
            'class' => HttpBasicAuth::class,
        ],
    ];
}
```

Les filtres de méthode d'authentification sont communément utilisés dans la mise en œuvre des API pleinement REST. Pour plus de détails, reportez-vous à la section [Authentification REST](rest-authentication.md).

### [[yii\filters\ContentNegotiator|ContentNegotiator]]

*ContentNegotiator* (négociateur de contenu) prend en charge la négociation des formats de réponse et la négociation de langue d'application. Il essaye de déterminer le format de la réponse et/ou la langue en examinant les paramètres de la méthode `GET` et ceux de l'entête HTTP `Accept`.

Dans l'exemple qui suit, le filtre *ContentNegotiator* est configuré pour prendre en charge JSON et XML en tant que formats de réponse, et anglais (États-Unis) et allemand en tant que langues.

```php
use yii\filters\ContentNegotiator;
use yii\web\Response;

public function behaviors()
{
    return [
        [
            'class' => ContentNegotiator::class,
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
                'application/xml' => Response::FORMAT_XML,
            ],
            'languages' => [
                'en-US',
                'de',
            ],
        ],
    ];
}
```

Les formats de réponse et les langues nécessitent souvent d'être déterminés bien plus tôt durant le [cycle de vie de l'application](structure-applications.md#application-lifecycle). Pour cette raison, *ContentNegotiator* est conçu de manière à être également utilisé en tant que [composant du processus d'amorçage](structure-applications.md#bootstrap). Par exemple, vous pouvez le configurer dans la [configuration de l'application](structure-applications.md#application-configurations) de la manière suivante :

```php
use yii\filters\ContentNegotiator;
use yii\web\Response;

[
    'bootstrap' => [
        [
            'class' => ContentNegotiator::class,
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
                'application/xml' => Response::FORMAT_XML,
            ],
            'languages' => [
                'en-US',
                'de',
            ],
        ],
    ],
];
```

> Info: dans le cas où le type de contenu et la langue préférés ne peuvent être déterminés à partir de la requête, le premier format et la première langue listés dans [[formats]] et[[languages]], respectivement, sont utilisés.

### [[yii\filters\HttpCache|HttpCache]]

*HttpCache* met en œuvre  la mise en cache côté client en utilisant les entêtes HTTP `Last-Modified` (dernier modifié) et `Etag`.
Par exemple :

```php
use yii\filters\HttpCache;

public function behaviors()
{
    return [
        [
            'class' => HttpCache::class,
            'only' => ['index'],
            'lastModified' => function ($action, $params) {
                $q = new \yii\db\Query();
                return $q->from('user')->max('updated_at');
            },
        ],
    ];
}
```

Reportez-vous à  la section [Mise en cache HTTP](caching-http.md) pour plus de détails sur l'utilisation de  *HttpCache*.

### [[yii\filters\PageCache|PageCache]]

*PageCache* met en œuvre la mise en cache de pages entières côté serveur. Dans l'exemple qui suit, *PageCache0 est appliqué à l'action `index` pour mettre la page entière en cache pendant un maximum de 60 secondes ou jusqu'à un changement du nombre d'entrées dans la table `post`. Il stocke également différentes versions de la page en fonction de la langue choisie.

```php
use yii\filters\PageCache;
use yii\caching\DbDependency;

public function behaviors()
{
    return [
        'pageCache' => [
            'class' => PageCache::class,
            'only' => ['index'],
            'duration' => 60,
            'dependency' => [
                'class' => DbDependency::class,
                'sql' => 'SELECT COUNT(*) FROM post',
            ],
            'variations' => [
                \Yii::$app->language,
            ]
        ],
    ];
}
```

Reportez-vous à la section [Page Caching](caching-page.md) pour plus de détails sur l'utilisation de  *PageCache*.

### [[yii\filters\RateLimiter|RateLimiter]]

*RateLimiter* met en œuvre un algorithme de limitation de débit basé sur  l'[algorithme leaky bucket](https://en.wikipedia.org/wiki/Leaky_bucket). On l'utilise en premier lieu dans la mise en œuvre des API pleinement REST. Reportez-vous à la section [limitation de débit](rest-rate-limiting.md) pour plus de détails sur l'utilisation de ce filtre.

### [[yii\filters\VerbFilter|VerbFilter]]

*VerbFilter* vérifie si les méthodes de requête HTTP sont autorisées par l'action requise. Si ce n'est pas le cas, une exception HTTP 405 est levée. Dans l'exemple suivant, *VerbFilter* est déclaré pour spécifier un jeu typique de méthodes de requête pour des actions CRUD — Create (créer), Read (lire), Update (mettre à jour), DELETE (supprimer).

```php
use yii\filters\VerbFilter;

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::class,
            'actions' => [
                'index'  => ['get'],
                'view'   => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ],
    ];
}
```

### [[yii\filters\Cors|Cors]]

*Cross-origin resource sharing* [CORS](https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS) est un mécanisme qui permet à des ressource (e.g. fonts, JavaScript, etc.) d'être requises d'un autre domaine en dehors du domaine dont la ressource est originaire. En particulier, les appels AJAX de Javascript peuvent utiliser le mécanisme *XMLHttpRequest*. Autrement, de telles requêtes "cross-domain" (inter domaines) seraient interdites par les navigateurs, à cause de la politique de sécurité dite d'origine identique (*same origin*). *CORS* définit une manière par laquelle le navigateur et le serveur interagissent pour déterminer si, oui ou non, la requête *cross-origin* (inter-site) est autorisée.

Le [[yii\filters\Cors|filtre Cors]] doit être défini avant les filtres d'authentification et/ou d'autorisation pour garantir que les entêtes CORS sont toujours envoyés.

```php
use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::class,
        ],
    ], parent::behaviors());
}
```

Consultez également la section sur les [contrôleurs REST](rest-controllers.md#cors) si vous voulez ajouter le filtre CORS à une classe
[[yii\rest\ActiveController]] dans votre API.

Les filtrages Cors peuvent être peaufinés via la propriété [[yii\filters\Cors::$cors|$cors]].

* `cors['Origin']`: un tableau utilisé pour définir les origines autorisées. Peut être `['*']` (tout le monde) ou `['http://www.myserver.net', 'http://www.myotherserver.com']`. Valeur par défaut  `['*']`.
* `cors['Access-Control-Request-Method']`: un tableau des verbes autorisés tel que `['GET', 'OPTIONS', 'HEAD']`.  Valeur par défaut `['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']`.
* `cors['Access-Control-Request-Headers']`: un tableau des entêtes autorisés. Peut être`['*']` tous les entêtes ou certains spécifiquement `['X-Request-With']`. Valeur par défaut `['*']`.
* `cors['Access-Control-Allow-Credentials']`: définit si la requête courante peut être faite en utilisant des identifiants de connexion.  Peut être `true` (vrai), `false` (faux) ou  `null` (non défini). Valeur par défaut `null`.
* `cors['Access-Control-Max-Age']`: définit la durée de vie des requêtes de pré-vérification (*preflight requests*). Valeur par défaut `86400`.

Par exemple, autoriser  CORS pour l'origine  `http://www.myserver.net` avec les méthodes `GET`, `HEAD` et `OPTIONS` :

```php
use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['http://www.myserver.net'],
                'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
            ],
        ],
    ], parent::behaviors());
}
```

Vous pouvez peaufiner les entêtes CORS en redéfinissant les paramètres par défaut action par action. Par exemple, ajouter les `Access-Control-Allow-Credentials`  (autoriser les identifiants de contrôle d'accès) pour l'action`login` pourrait être réalisé comme ceci :

```php
use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['http://www.myserver.net'],
                'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
            ],
            'actions' => [
                'login' => [
                    'Access-Control-Allow-Credentials' => true,
                ]
            ]
        ],
    ], parent::behaviors());
}
```


text:
#ifndef SRC_IO_INPUTSTREAM_H_
#define SRC_IO_INPUTSTREAM_H_

#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>

namespace netflix {
namespace msl {
typedef std::vector<uint8_t> ByteArray;
namespace io {

/**
 * An input stream provides read capability of raw bytes.
 *
 * Timeouts are triggered if no character has been read within the timeout
 * period. A slow operation that is able to read at least one character per
 * timeout period will not trigger a timeout.
 *
 * @interface
 */
class InputStream
{
public:
	virtual ~InputStream() {}

    /**
     * Aborts any outstanding operations.
     */
    virtual void abort() = 0;

    /**
     * Closes this input stream and releases any resources associated with the
     * stream.
     *
     * @param timeout write timeout in milliseconds or -1 for no timeout.
     * @return true on success, false on timeout or abort.
     */
    virtual bool close(int timeout = -1) = 0;

    /**
     * Marks the current position in this input stream. A subsequent call to
     * the reset method repositions this stream at the last marked position so
     * that subsequent reads re-read the same bytes.
     *
     *
 The readlimit arguments tells this input stream to
     * allow that many bytes to be read before the mark position gets
     * invalidated.
     *
     *
 The general contract of mark is that, if the method
     * markSupported returns true, the stream somehow
     * remembers all the bytes read after the call to mark and
     * stands ready to supply those same bytes again if and whenever the method
     * reset is called.  However, the stream is not required to
     * remember any data at all if more than readlimit bytes are
     * read from the stream before reset is called.
     *
     * @param readlimit optional maximum limit of bytes that can be read before
     *        the mark position becomes invalid.
     * @see #reset()
     */
    virtual void mark(size_t readlimit) = 0;

    /**
     * Repositions this stream to the position at the time the mark method was
     * last called on this input stream.
     *
     * @throws IOException if this stream has not been marked.
     * @see #mark()
     */
    virtual void reset() = 0;

    /**
     * @return true if the mark and reset operations are supported.
     */
    virtual bool markSupported() = 0;

    /**
     *
Reads some bytes from the input stream, which may be less than the
     * number requested. This is equivalent to a call to
     * {@link #read(ByteArray&, size_t, size_t, int)} with an offset of 0 and
     * length equal to the current size of the destination byte buffer.

     *
     *
Unless the byte buffer length is zero, this method will block until
     * at least one byte is available or the timeout is hit. If the timeout is
     * hit then whatever bytes that have been read will be returned.

     *
     *
If there are no more bytes available (i.e. end of stream is hit)
     * then -1 is returned. This is the only reliable indicator that no more
     * data is available.

     *
     * @param out destination byte buffer.
     * @param timeout read timeout in milliseconds or -1 for no timeout.
     * @return the number of bytes read or -1 on end of stream.
     * @throws IOException if there is an error reading the data or the stream
     *         is closed.
     */
    virtual int read(ByteArray& out, int timeout = -1) = 0;

    /**
     *
Reads some bytes from the input stream, which may be less than the
     * number requested. If 0 is specified for the length then zero bytes are
     * returned.

     *
     *
Unless zero bytes are requested, this method will block until at
     * least one byte is available or the timeout is hit. If the timeout is
     * hit then whatever bytes that have been read will be returned.

     *
     *
If there are no more bytes available (i.e. end of stream is hit)
     * then -1 is returned. This is the only reliable indicator that no
     * more data is available.

     *
     * @param out destination byte buffer.
     * @param len the number of bytes to read.
     * @param timeout read timeout in milliseconds or -1 for no timeout.
     * @return the number of bytes read or -1 on end of stream.
     * @throws IOException if there is an error reading the data or the stream
     *         is closed.
     */
    virtual int read(ByteArray& out, size_t offset, size_t len, int timeout = -1) = 0;

    /**
     *
Skips over and discards n bytes of data from this
     * input stream. The skip method may, for a variety of
     * reasons, end up skipping over some smaller number of bytes, possibly
     * 0.

     *
     *
Skipped bytes must still be accounted for by mark() and
     * reset().

     *
     *
The default implementation calls read() with the requested number
     * of bytes.

     *
     * @param the number of bytes to be skipped.
     * @param timeout skip timeout in milliseconds or -1 for no timeout.
     * @return the actual number of bytes skipped.
     * @throws IOException if skip is not supported, if there is an error
     *         skipping over the data, or if the stream is closed.
     */
    virtual int skip(size_t n, int timeout = -1)
    {
        ByteArray data(n);
        return read(data, timeout);
    }
};

}}} // namespace netflix::msl::io

#endif /* SRC_IO_INPUTSTREAM_H_ */

redpajama_set_name: RedPajamaGithub


text:
extern "C" {
#endif
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#ifdef __cplusplus
}
#endif

DEFINE_NS_MEDIA_CODEC

namespace FFmpeg
{
	inline REFERENCE_TIME dt2hns(int64_t dt, AVStream* stream)
	{
		auto sec_base = stream ? (float)stream->time_base.num / stream->time_base.den : 1.f / AV_TIME_BASE;
		auto hns = dt * sec_base * 1e7;
		return static_cast<REFERENCE_TIME>(hns);
	}

	inline REFERENCE_TIME dt2hns(int64_t dt, const AVRational& time_base)
	{
		auto sec_base = (float)time_base.num / time_base.den;
		auto hns = dt * sec_base * 1e7;
		return static_cast<REFERENCE_TIME>(hns);
	}

	inline int64_t hns2dt(REFERENCE_TIME hns, AVStream* stream)
	{
		auto sec_base = stream ? (float)stream->time_base.num / stream->time_base.den : 1.f / AV_TIME_BASE;
		auto dt = hns / sec_base / 1e7;
		return static_cast<int64_t>(dt);
	}

	void Initialize();
	class MFAVIOContext;

	namespace Wrappers
	{
		class AVIOContextWrapper : Core::NonCopyable
		{
		public:
			AVIOContextWrapper() noexcept;
			AVIOContextWrapper(AVIOContext* context) noexcept;
			~AVIOContextWrapper();
			operator bool() const noexcept { return _context != nullptr; }

			void Reset() noexcept { _context = nullptr; }
			AVIOContext* Get() const noexcept { return _context; }
		private:
			AVIOContext* _context;
		};

		class AVFormatContextWrapper : Core::NonCopyable
		{
		public:
			AVFormatContextWrapper(AVFormatContext* context) noexcept;
			AVFormatContextWrapper(AVFormatContextWrapper&& other) noexcept;
			~AVFormatContextWrapper();
			operator bool() const noexcept { return _context != nullptr; }
			void Open(std::shared_ptr<void>&& opaque, AVIOContext* context);

			void Reset() noexcept { _context = nullptr; }
			AVFormatContext* Get() const noexcept { return _context; }
			AVFormatContext** GetAddress() noexcept { return &_context; }
			AVFormatContext* operator->() const noexcept { return _context; }
		private:
			AVFormatContext* _context;
			bool _opened = false;
			std::shared_ptr<void> _opaque;
		};
	}

	class MFAVIOContext : public std::enable_shared_from_this<MFAVIOContext>
	{
	public:
		MFAVIOContext(IMFByteStream* byteStream, size_t bufferSize, bool canWrite);
		virtual ~MFAVIOContext();

		Wrappers::AVFormatContextWrapper OpenFormatContext();
		Wrappers::AVIOContextWrapper& Get() { return _ioContext; }
	private:
		static int ReadPacket(void *opaque, uint8_t *buf, int buf_size) noexcept;
		static int WritePacket(void *opaque, uint8_t *buf, int buf_size) noexcept;
		static int64_t Seek(void *opaque, int64_t offset, int whence) noexcept;
	private:
		WRL::ComPtr<IMFByteStream> _byteStream;
		Wrappers::AVIOContextWrapper _ioContext;
	};

	struct avcodecparameters_deleter
	{
		void operator()(AVCodecParameters* handle) const noexcept;
	};
	using unique_avcodecparameters = std::unique_ptr<AVCodecParameters, avcodecparameters_deleter>;

	struct WAVEFORMATLIBAV : public WAVEFORMATEXTENSIBLE
	{
		WAVEFORMATLIBAV()
		{
			this->Format = { 0 };
			this->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
			this->Format.cbSize = sizeof(WAVEFORMATLIBAV) - sizeof(WAVEFORMATEX);
			this->SubFormat = MFAudioFormat_LibAV;
		}

		WORD DesiredDecodedFormat;
		AVRational TimeBase;
		int64_t ChannelLayout;

		static WAVEFORMATLIBAV CreateFromStream(AVStream* stream);
	private:
	};

	struct LibAVAudioCodecOptions : public WRL::RuntimeClass<WRL::RuntimeClassFlags<WRL::ClassicCom>, IUnknown>
	{
		FFmpeg::unique_avcodecparameters codecpar;

		static WRL::ComPtr<LibAVAudioCodecOptions> CreateFromStream(AVStream* stream);
	};

	struct avcodeccontext_deleter
	{
		void operator()(AVCodecContext* handle) const noexcept;
	};
	using unique_avcodeccontext = std::unique_ptr<AVCodecContext, avcodeccontext_deleter>;

	struct avframe_deleter
	{
		void operator()(AVFrame* handle) const noexcept;
	};
	using unique_avframe = std::unique_ptr<AVFrame, avframe_deleter>;

	struct swrcontext_deleter
	{
		void operator()(SwrContext* handle) const noexcept;
	};
	using unique_swrcontext = std::unique_ptr<SwrContext, swrcontext_deleter>;

	struct AVPacketRAII : public AVPacket, Core::NonCopyable
	{
		AVPacketRAII();
		~AVPacketRAII();
		AVPacketRAII(AVPacketRAII&& other) noexcept;
		AVPacketRAII& operator=(AVPacketRAII&& other) noexcept;
	};

	class MFMediaBufferOnAVPacket : public WRL::RuntimeClass<WRL::RuntimeClassFlags<WRL::ClassicCom>, IMFMediaBuffer>
	{
	public:
		MFMediaBufferOnAVPacket(AVPacketRAII && packet);

		// ͨ¹ý RuntimeClass ¼Ì³Ð
		STDMETHODIMP Lock(BYTE ** ppbBuffer, DWORD * pcbMaxLength, DWORD * pcbCurrentLength) override;
		STDMETHODIMP Unlock(void) override;
		STDMETHODIMP GetCurrentLength(DWORD * pcbCurrentLength) override;
		STDMETHODIMP SetCurrentLength(DWORD cbCurrentLength) override;
		STDMETHODIMP GetMaxLength(DWORD * pcbMaxLength) override;

		const AVPacketRAII& GetPacket() const noexcept { return _packet; }
	private:
		AVPacketRAII _packet;
		DWORD _currentLength;
	};

	void CreateMFMediaBufferOnAVPacket(AVPacketRAII&& packet, IMFMediaBuffer** mediaBuffer);
}

END_NS_MEDIA_CODEC


text: These should be published as npm modules or consumable directly from github


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Les paramètres du langage
	Changer votre mot de passe
</labels>


text:
@interface ExploreCellController : UIViewController {
	UILabel *titleLabel;
	UILabel *descriptionLabel;

	UIImageView *imageView;
}

@property (nonatomic, retain) IBOutlet UILabel *titleLabel;
@property (nonatomic, retain) IBOutlet UILabel *descriptionLabel;

@property (nonatomic, retain) IBOutlet UIImageView *imageView;

@end


text:
const CGFloat MJRefreshHeaderHeight = 54.0;
const CGFloat MJRefreshFooterHeight = 44.0;
const CGFloat MJRefreshFastAnimationDuration = 0.25;
const CGFloat MJRefreshSlowAnimationDuration = 0.4;

NSString *const MJRefreshKeyPathContentOffset = @"contentOffset";
NSString *const MJRefreshKeyPathContentInset = @"contentInset";
NSString *const MJRefreshKeyPathContentSize = @"contentSize";
NSString *const MJRefreshKeyPathPanState = @"state";

NSString *const MJRefreshHeaderLastUpdatedTimeKey = @"MJRefreshHeaderLastUpdatedTimeKey";

NSString *const MJRefreshHeaderIdleText = @"下拉可以刷新";
NSString *const MJRefreshHeaderPullingText = @"鬆開立即刷新";
NSString *const MJRefreshHeaderRefreshingText = @"正在刷新數據中...";

NSString *const MJRefreshAutoFooterIdleText = @"點擊或上拉加載更多";
NSString *const MJRefreshAutoFooterRefreshingText = @"正在加載更多的數據...";
NSString *const MJRefreshAutoFooterNoMoreDataText = @"已經全部加載完畢";

NSString *const MJRefreshBackFooterIdleText = @"上拉可以加載更多";
NSString *const MJRefreshBackFooterPullingText = @"鬆開立即加載更多";
NSString *const MJRefreshBackFooterRefreshingText = @"正在加載更多的數據...";
NSString *const MJRefreshBackFooterNoMoreDataText = @"已經全部加載完畢";


text:
package org.suda.customerMgr.dao;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.suda.customerMgr.dao.api.CustomerDAO;
import org.suda.customerMgr.domain.Customer;

import java.util.List;

@Repository
public class CustomerDAOImpl implements CustomerDAO {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerDAOImpl.class);
    @Autowired
    private SessionFactory sessionFactory;

    public boolean addCustomer(Customer customer) {
        LOGGER.info("Adding customer: " + customer);
        try {
            sessionFactory.getCurrentSession().save(customer);
            return true;
        } catch (Exception e) {
            LOGGER.error("Error in adding Customer", e);
        }
        return false;
    }

    public List<Customer> listCustomer() {
        LOGGER.info("Listing all users ");
        return sessionFactory.getCurrentSession().createQuery("from Customer").list();
    }

    public void removeCustomer(Integer id) {
        Customer customer = (Customer) sessionFactory.getCurrentSession().load(
                Customer.class, id);
        if (null != customer) {
            sessionFactory.getCurrentSession().delete(customer);
        }

    }
}


text:
require 'spec_helper'

module Spree
  describe Api::V1::StatesController, type: :controller do
    render_views

    let!(:state) { create(:state, name: "Victoria") }
    let(:attributes) { [:id, :name, :abbr, :country_id] }

    before do
      stub_authentication!
    end

    it "gets all states" do
      api_get :index
      expect(json_response["states"].first).to have_attributes(attributes)
      expect(json_response['states'].first['name']).to eq(state.name)
    end

    it "gets all the states for a particular country" do
      api_get :index, country_id: state.country.id
      expect(json_response["states"].first).to have_attributes(attributes)
      expect(json_response['states'].first['name']).to eq(state.name)
    end

    context "pagination" do
      let(:scope) { double('scope') }

      before do
        expect(scope).to receive_messages(last: state)
        expect(State).to receive_messages(accessible_by: scope)
        expect(scope).to receive_messages(order: scope)
        allow(scope).to receive_message_chain(:ransack, :result, :includes).and_return(scope)
      end

      it "does not paginate states results when asked not to do so" do
        expect(scope).not_to receive(:page)
        expect(scope).not_to receive(:per)
        api_get :index
      end

      it "paginates when page parameter is passed through" do
        expect(scope).to receive(:page).with("1").and_return(scope)
        expect(scope).to receive(:per).with(nil).and_return(scope)
        api_get :index, page: 1
      end

      it "paginates when per_page parameter is passed through" do
        expect(scope).to receive(:page).with(nil).and_return(scope)
        expect(scope).to receive(:per).with("25").and_return(scope)
        api_get :index, per_page: 25
      end
    end

    context "with two states" do
      before { create(:state, name: "New South Wales") }

      it "gets all states for a country" do
        country = create(:country, states_required: true)
        state.country = country
        state.save

        api_get :index, country_id: country.id
        expect(json_response["states"].first).to have_attributes(attributes)
        expect(json_response["states"].count).to eq(1)
        json_response["states_required"] = true
      end

      it "can view all states" do
        api_get :index
        expect(json_response["states"].first).to have_attributes(attributes)
      end

      it 'can query the results through a paramter' do
        api_get :index, q: { name_cont: 'Vic' }
        expect(json_response['states'].first['name']).to eq("Victoria")
      end
    end

    it "can view a state" do
      api_get :show, id: state.id
      expect(json_response).to have_attributes(attributes)
    end
  end
end


text:
module Cul::Omniauth::RemoteIpAbility
  extend ActiveSupport::Concern
  def current_ability
    @current_ability ||= Ability.new(current_user, roles: session["devise.roles"], remote_ip:request.remote_ip)
  end
end


text:
from insights.parsers.crontab import CrontabL, HeatCrontab, KeystoneCrontab, NovaCrontab, RootCrontab
from insights.tests import context_wrap
from insights.parsers import ParseException

import pytest

CRONTAB_DATA = """
# comment line
* * * * * /usr/bin/keystone-manage token_flush > /dev/null 2>&1
33 0 1 3 6 /bin/heat-manage purge_deleted -g days 7
# Test all the range and list and named options
  00-59/20  1,2,3,5,8,13,21 */2 1,MAR,7-Dec/2   Tue,4-Sun   /bin/mail -s "Foo has occurred" admin%Foo has occurred, time to bail out
* * * * * user_name /usr/local/bin/motd_update
MAILTO=admin
CRON_TZ = Europe/France
"""

CRONTAB_EXTENSIONS = """
@reboot /usr/local/bin/unmangle_database
@daily  /usr/sbin/logrotate
"""

CRONTAB_BAD_DATA = """
* * * *  /usr/bin/heat-manage purge_deleted >/dev/null 2>&1
Error reading crontab
"""

CRONTAB_BAD_NICKNAME = """
@huorly  /usr/bin/check_init
"""

def crontab_tests(crontab_class):
    crontab = crontab_class(context_wrap(CRONTAB_DATA))
    assert crontab is not None
    assert [r.get('minute') for r in crontab] == ['*', '33', '00-59/20', '*']
    assert crontab.search('heat-manage') == [
        {'minute': '33',
         'hour': '0',
         'day_of_month': '1',
         'month': '3',
         'day_of_week': '6',
         'command': '/bin/heat-manage purge_deleted -g days 7'}]
    assert crontab.search('crazy_123') == []
    assert crontab.search('motd')[0]['command'] == 'user_name /usr/local/bin/motd_update'
    assert crontab.invalid_lines == []

    # Test environment variable handling
    assert hasattr(crontab, 'environment')
    assert isinstance(crontab.environment, dict)
    assert 'MAILTO' in crontab.environment
    assert crontab.environment['MAILTO'] == 'admin'
    assert 'CRON_TZ' in crontab.environment
    assert crontab.environment['CRON_TZ'] == 'Europe/France'

    # Test that bad data gets stored in the invalid_lines property
    crontab = crontab_class(context_wrap(CRONTAB_DATA + CRONTAB_BAD_DATA))
    assert crontab is not None
    assert crontab.invalid_lines == [
        '* * * *  /usr/bin/heat-manage purge_deleted >/dev/null 2>&1',
        'Error reading crontab',
    ]

    # Test that crontab 'special time nicknames' are parsed correctly
    crontab = crontab_class(context_wrap(CRONTAB_EXTENSIONS))
    assert crontab is not None
    assert crontab.invalid_lines == []
    assert crontab[0] == {
        'time': '@reboot',
        'command': '/usr/local/bin/unmangle_database',
    }
    assert crontab[1] == {
        'minute': '0',
        'hour': '0',
        'day_of_month': '*',
        'month': '*',
        'day_of_week': '*',
        'command': '/usr/sbin/logrotate',
    }

    # Test that crontab 'special names' only works with known names
    with pytest.raises(ParseException) as exc:
        crontab = crontab_class(context_wrap(CRONTAB_EXTENSIONS + CRONTAB_BAD_NICKNAME))
    assert "@huorly not recognised as a time specification 'nickname'" in str(exc)

    # Test that crontab 'special time nicknames' are parsed correctly
    crontab = crontab_class(context_wrap(CRONTAB_EXTENSIONS))
    assert crontab is not None
    assert crontab.invalid_lines == []
    assert crontab[0] == {
        'time': '@reboot',
        'command': '/usr/local/bin/unmangle_database',
    }
    assert crontab[1] == {
        'minute': '0',
        'hour': '0',
        'day_of_month': '*',
        'month': '*',
        'day_of_week': '*',
        'command': '/usr/sbin/logrotate',
    }

def test_crontab():
    crontab_tests(CrontabL)

def test_heat_crontab():
    crontab_tests(HeatCrontab)

def test_keystone_crontab():
    crontab_tests(KeystoneCrontab)

def test_nova_crontab():
    crontab_tests(NovaCrontab)

def test_root_crontab():
    crontab_tests(RootCrontab)


text:
package org.apache.camel.component.netty.http;

import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.apache.camel.Exchange.HTTP_METHOD;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NettyHttpRestContextPathMatcherTest extends BaseNettyTest {

    @Test
    public void shouldReturnCustomResponseForOptions() {
        String response = template.requestBodyAndHeader("netty-http:http://localhost:{{port}}/foo", "", HTTP_METHOD, "OPTIONS",
                String.class);
        assertEquals("expectedOptionsResponse", response);
    }

    @Test
    public void shouldPreferStrictMatchOverPrefixMatch() {
        String response = template.requestBodyAndHeader("netty-http:http://localhost:{{port}}/path2/foo", "", HTTP_METHOD,
                "GET", String.class);
        assertEquals("exact", response);
    }

    @Test
    public void shouldPreferOptionsForEqualPaths() {
        String response = template.requestBodyAndHeader("netty-http:http://localhost:{{port}}/path3", "", HTTP_METHOD, "POST",
                String.class);
        assertEquals("postPath3", response);
        response = template.requestBodyAndHeader("netty-http:http://localhost:{{port}}/path3", "", HTTP_METHOD, "OPTIONS",
                String.class);
        assertEquals("optionsPath3", response);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("netty-http:http://0.0.0.0:{{port}}/path1?httpMethodRestrict=POST").setBody().constant("somePostResponse");
                from("netty-http:http://0.0.0.0:{{port}}?matchOnUriPrefix=true&httpMethodRestrict=OPTIONS").setBody()
                        .constant("expectedOptionsResponse");

                from("netty-http:http://0.0.0.0:{{port}}/path2/foo").setBody().constant("exact");
                from("netty-http:http://0.0.0.0:{{port}}/path2?matchOnUriPrefix=true").setBody().constant("wildcard");

                from("netty-http:http://0.0.0.0:{{port}}/path3?httpMethodRestrict=POST").setBody().constant("postPath3");
                from("netty-http:http://0.0.0.0:{{port}}/path3?httpMethodRestrict=OPTIONS").setBody().constant("optionsPath3");
            }
        };
    }

}


text:
import helper
from helper import Command

def start(args, logfile, errfile):
  db_host = "DB_HOST={0}".format(args.database_host or 'localhost')
  start_server = db_host + " rvm jruby-1.7.8 do bundle exec trinidad --config config/trinidad.yml"

  commands = [
    Command("rvm jruby-1.7.8 do bundle --jobs 4", True),
    Command(start_server, False)
  ]

  return helper.run(commands, logfile, errfile, args.troot)

def stop(logfile, errfile):
  return helper.stop('trinidad', logfile, errfile)


text:
<?php

declare(strict_types=1);

namespace LAG\AdminBundle\Factory\Configuration;

use LAG\AdminBundle\Configuration\AdminConfiguration;
use LAG\AdminBundle\Exception\ConfigurationException;

interface AdminConfigurationFactoryInterface
{
    /**
     * Create a new admin configuration object, resolved with the given options. If the configuration is invalid, an
     * exception will be thrown.
     *
     * @throws ConfigurationException
     */
    public function create(string $adminName, array $options = []): AdminConfiguration;
}


text:
namespace app {
namespace Uno {

::uDelegateType* Func__Outracks_Simulator_Bytecode_RemoveEventHandler__object__typeof();

}}

#endif


text:
package com.maybe.mh.pojo;

public class LoginResponse {

	private boolean success;

	private User user;

	public LoginResponse() {
		super();
		// TODO Auto-generated constructor stub
	}

	public LoginResponse(boolean success, User user) {
		super();
		this.success = success;
		this.user = user;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String toString() {
		return "LoginResponse [success=" + success + ", user=" + user + "]";
	}

}


text:
using SimplCommerce.Module.News.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace SimplCommerce.Module.News.Services
{
    public interface INewsItemService
    {
        void Create(NewsItem newsItem);

        void Update(NewsItem newsItem);

        void Delete(long id);

        void Delete(NewsItem newsItem);
    }
}


text:
Edit Post Stay Charge

		Case Number:
		<input type="text" placeholder="Enter case number..." name="case_number" class="form-control" ng-model="edit.caseNumber" ng-required="true">

This is required

		Damage Claim Opened?
		<input type="checkbox" class="checkbox-cursor" ng-true-value="'YES'" ng-false-value="'NO'" ng-model="edit.damageClaim">

{{ edit.damageClaim }}

		Damage Claim Number:
		<input type="text" placeholder="If Yes Above, Enter Damage Claim Number..." class="form-control" ng-model="edit.damageClaimNumber">

		Date Reported:
		<input type="date" class="form-control" ng-model="edit.reportedDate" required>

		Traveler Checkout Date:
		<input type="date" class="form-control" ng-model="edit.travelerCheckoutDate" required>

		Post Stay Charge Resolved?
		<input type="checkbox" class="checkbox-cursor" ng-true-value="'YES'" ng-false-value="'NO'" ng-model="edit.resolved">

{{ edit.resolved }}

Enter Charge Requests

			Description of Charge Request:
			<input type="text" class="form-control" placeholder="Describe The Requested Charge..." ng-model="edit.itemOne.name" required>

				Photos?
				<input type="checkbox" class="checkbox-cursor" ng-true-value="'YES'" ng-false-value="'NO'" ng-model="edit.itemOne.photo">

{{ edit.itemOne.photo }}

				Invoice?
				<input type="checkbox" class="checkbox-cursor" ng-true-value="'YES'" ng-false-value="'NO'" ng-model="edit.itemOne.invoice">

{{ edit.itemOne.invoice }}

				Credit Card Charged?
				<input type="checkbox" class="checkbox-cursor" ng-true-value="'YES'" ng-false-value="'NO'" ng-model="edit.itemOne.chargeSuccess">

{{ edit.itemOne.chargeSuccess }}

	<button class="btn btn-primary" type="button" ng-click="create()">Edit</button>
	<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>


text:
package handlers

import (
	"net/http"

	"github.com/go-box/brochure/config"
	"github.com/go-box/brochure/logger"
	"github.com/go-zoo/bone"
)

// The Handler struct that takes a configured Env and a function matching
// our useful signature.
type Handler struct {
	Ctx *Context
	H   func(e *Context, w http.ResponseWriter, r *http.Request) error
}

// ServeHTTP allows our Handler type to satisfy http.Handler.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	err := h.H(h.Ctx, w, r)
	if err != nil {
		switch e := err.(type) {
		case Error:
			// We can retrieve the status here and write out a specific
			// HTTP status code.
			h.Ctx.LG.Log("err", "HTTP %d - %s", e.Status(), e)
			http.Error(w, e.Error(), e.Status())
		default:
			// Any error types we don't specifically look out for default
			// to serving a HTTP 500
			http.Error(w, http.StatusText(http.StatusInternalServerError),
				http.StatusInternalServerError)
		}
	}
}

// SetupHandlers sets up the initial handlers for the application.
func SetupHandlers(lg logger.Logger, conf *config.Config) *bone.Mux {

	mux := bone.New()

	context := NewContext(conf, lg)

	mux.Handle("/", Handler{context, Index})

	if conf.Debug {
		mux.Get("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	}

	return mux

}


text:
package com.chrisvfabio.app;

public class Staff extends Person {

    private static long sequenceId = 1;
    private long staffId;

    public Staff(String firstName, String lastName) {
        super(firstName, lastName);
        this.staffId = sequenceId++;
    }

    public long getStaffId() {
        return staffId;
    }

    public void setStaffId(long staffId) {
        this.staffId = staffId;
    }
}


text:
                    ×
                    {{vm.message}}

{{"views.welcome_back" | translate}} {{vm.login_greetings}}!

{{"views.login.header" | translate}}
 {{vm.organization_name}}

      <form class="login-form forgot-form" ng-submit="vm.reset(vm.user)">

{{"views.forgot_password.associate_email" | translate}}

            <input type="email" class="form-control inverse" id="email" placeholder="Email Address" ng-model="vm.user.email" autocomplete="off">

            <button type="submit" class="hvr-fade btn btn-login btn-full">{{"views.submit" | translate}}</button>

      </form>

Never share your password with anyone. ?

{{"views.login.about_psesd" | translate}}

{{"views.about_student_success_link" | translate}}

{{"views.privacy_policy" | translate}}


text:
package sk.gymy.seminar.domain;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import sk.gymy.seminar.common.AbstractTest;

public class PersonTest extends AbstractTest {

    @Test
    public void equalsAndHashCodeTest() {
        Person p1 = new Person();
        Person p2 = new Person();
        assertEquals(p1, p2);
        assertFalse(p1 == p2);
        assertEquals(p1.hashCode(), p2.hashCode());
        p1.setIndex(1);
        assertNotEquals(p1, p2);
        assertFalse(p1 == p2);
        assertNotEquals(p1.hashCode(), p2.hashCode());
        p2.setIndex(1);
        assertEquals(p1, p2);
        assertFalse(p1 == p2);
        assertEquals(p1.hashCode(), p2.hashCode());
        p1.setIndex(2);
        assertNotEquals(p1, p2);
        assertFalse(p1 == p2);
        assertNotEquals(p1.hashCode(), p2.hashCode());
        p2.setIndex(p1.getIndex());
        p1.setName("");
        p2.setName("");
        assertEquals(p1, p2);
        assertFalse(p1 == p2);
        assertEquals(p1.hashCode(), p2.hashCode());
        p1.setName("Anna Harbour");
        assertNotEquals(p1, p2);
        assertFalse(p1 == p2);
        assertNotEquals(p1.hashCode(), p2.hashCode());
        p2.setName("Anna Harbour");
        assertEquals(p1, p2);
        assertFalse(p1 == p2);
        assertEquals(p1.hashCode(), p2.hashCode());

    }

    @Test
    public void toStringTest() {
        Person person = new Person();
        assertEquals(null, person.toString());
        person.setIndex(1234);
        assertEquals(null, person.toString());
        person.setName("John Stuart");
        assertEquals("John Stuart", person.toString());
    }

}


text:
using System;

namespace HttpServer.Parser
{
    /// <summary>
    /// Arguments used when more body bytes have come.
    /// </summary>
    public class BodyEventArgs : EventArgs
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BodyEventArgs"/> class.
        /// </summary>
        /// <param name="buffer">buffer that contains the received bytes.</param>
        /// <param name="offset">offset in buffer where to start processing.</param>
        /// <param name="count">number of bytes from <paramref name="offset"/> that should be parsed.</param>
        public BodyEventArgs(byte[] buffer, int offset, int count)
        {
            Check.Require(buffer, "buffer");
            Check.Min(1, offset, "offset");
            Check.Min(1, count, "count");

            Buffer = buffer;
            Offset = offset;
            Count = count;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BodyEventArgs"/> class.
        /// </summary>
        public BodyEventArgs()
        {
        }

        /// <summary>
        /// Gets or sets buffer that contains the received bytes.
        /// </summary>
        public byte[] Buffer { get; set; }
        /*
        /// <summary>
        /// Gets or sets number of bytes used by the request.
        /// </summary>
        public int BytesUsed { get; set; }
        */
        /// <summary>
        /// Gets or sets number of bytes from <see cref="Offset"/> that should be parsed.
        /// </summary>
        public int Count { get; set; }
        /*
        /// <summary>
        /// Gets or sets whether the body is complete.
        /// </summary>
        public bool IsBodyComplete { get; set; }
        */
        /// <summary>
        /// Gets or sets offset in buffer where to start processing.
        /// </summary>
        public int Offset { get; set; }
    }
}


text:
import datetime
import os

from google.appengine.ext import db

from mcfw.consts import MISSING
import oca_unittest
from rogerthat.bizz.service import create_service
from rogerthat.dal import put_and_invalidate_cache
from rogerthat.dal.profile import get_user_profile
from rogerthat.models import ServiceProfile
from rogerthat.rpc import users
from rogerthat.settings import get_server_settings
from rogerthat.to.service import UserDetailsTO
from rogerthat.translations import DEFAULT_LANGUAGE
from rogerthat.utils import get_epoch_from_datetime
from solutions.common.bizz.menu import get_item_image_url
from solutions.common.bizz.reservation import availability_and_shift, STATUS_AVAILABLE, STATUS_TOO_MANY_PEOPLE, \
    cancel_reservation, move_reservation, edit_reservation
from solutions.common.models import SolutionSettings, SolutionMainBranding,\
    RestaurantMenu
from solutions.common.models.reservation import RestaurantReservation, RestaurantSettings
from solutions.common.models.reservation.properties import ShiftTO
from solutions.common.to import MenuTO
from solutions.flex import SOLUTION_FLEX

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

class Test(oca_unittest.TestCase):

    def _test_reserve_table(self, service_user, service_identity, user_details, date, people, name, phone, comment, force=False):
        # TODO: race conditions?
        status, shift_start = availability_and_shift(service_user, None, user_details, date, people, force)
        if status != STATUS_AVAILABLE:
            return status

        date = datetime.datetime.utcfromtimestamp(date)
        rogerthat_user = users.User(user_details[0].email) if user_details else None
        reservation = RestaurantReservation(service_user=service_user,
                                            user=rogerthat_user, name=name or "John Doe", phone=phone, date=date,
                                            people=people, comment=comment, shift_start=shift_start,
                                            creation_date=datetime.datetime.now())
        reservation.put()
        key_ = reservation.key()
        return unicode(key_), STATUS_AVAILABLE

    def test_create_restaurant_identity(self):
        self.set_datastore_hr_probability(1)

        root_proj = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')
        branding_url = os.path.join(root_proj, 'src-test', 'rogerthat_tests', 'mobicage', 'bizz',
                                    'nuntiuz.zip')

        email = u"resto_soluton@foo.com"
        name = u"resto_soluton"
        service_user = users.User(email)

        create_service(email=email, name=name, password=u"test1", languages=[u"en"], solution=SOLUTION_FLEX,
                       organization_type=ServiceProfile.ORGANIZATION_TYPE_PROFIT)

        solutionSettings = SolutionSettings(key=SolutionSettings.create_key(service_user), name=name,
                            menu_item_color=None, address=u"lochristi", phone_number=None,
                            currency=u"EUR", main_language=DEFAULT_LANGUAGE, solution=SOLUTION_FLEX)

        settings = RestaurantSettings(key=RestaurantSettings.create_key(service_user))
        settings.language = DEFAULT_LANGUAGE

        stream = StringIO()
        stream.write(open(branding_url).read())
        stream.seek(0)

        main_branding = SolutionMainBranding(key=SolutionMainBranding.create_key(service_user))
        main_branding.blob = db.Blob(stream.read())
        main_branding.branding_key = None

        settings.shifts = None
        shifts = {}
        shift = ShiftTO()
        shift.name = u'shift-lunch'
        shift.capacity = 50
        shift.max_group_size = 6
        shift.leap_time = 30
        shift.threshold = 70
        shift.start = 12 * 60 * 60
        shift.end = 14 * 60 * 60
        shift.days = [1, 2, 3, 4, 5, 6, 7]
        shift.comment = u'shift-comment0'
        shifts[shift.name] = shift

        shift = ShiftTO()
        shift.name = u'shift-dinner'
        shift.capacity = 50
        shift.max_group_size = 6
        shift.leap_time = 30
        shift.threshold = 70
        shift.start = 18 * 60 * 60
        shift.end = 21 * 60 * 60
        shift.days = [1, 2, 3, 4, 5, 6, 7]
        shift.comment = u'shift-comment1'
        shifts[shift.name] = shift
        settings.save_shifts(shifts)
        put_and_invalidate_cache(solutionSettings, settings, main_branding)

        date_ = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=10), datetime.datetime.min.time())
        date_ = date_ + datetime.timedelta(hours=19)
        today_ = get_epoch_from_datetime(date_)
        service_identity = None

        user_detail = UserDetailsTO.fromUserProfile(get_user_profile(users.get_current_user()))

        reservationOkKey, reservationOk = \
            self._test_reserve_table(service_user, service_identity, user_details=[user_detail], date=today_, people=3,
                                     name=u"text Name", phone=None, comment=u"comment", force=False)
        reservationTooMany = self._test_reserve_table(service_user, service_identity, user_details=[user_detail],
                                                      date=today_, people=50, name=u"text Name", phone=None,
                                                      comment=u"comment", force=False)

        self.assertEqual(STATUS_AVAILABLE, reservationOk)
        self.assertEqual(STATUS_TOO_MANY_PEOPLE, reservationTooMany)

        editReservationOk = edit_reservation(service_user, reservationOkKey, people=4, comment=None, force=False)
        self.assertEqual(STATUS_AVAILABLE, editReservationOk)

        cancel_reservation(service_user, reservationOkKey, notified=False)
        move_reservation(service_user, None, reservationOkKey, u'shift-lunch')

        menu_settings = RestaurantMenu(key=RestaurantMenu.create_key(solutionSettings.service_user, solutionSettings.solution))
        menu_settings.categories_json = u'{"a46472d3-4ba6-a583-e527-7a7046a867e0":{"index":0,"name":"Tuinonderhoud","predescription":"Snoeiwerken","items":[{"name":"haag snoeien","price":3900,"custom_unit":5,"step":1,"visible_in":3,"has_price":true,"id":"c6696ba4-de8b-436d-bfa4-61628f8adee3","unit":5,"description":""}],"postdescription":null,"id":"a46472d3-4ba6-a583-e527-7a7046a867e0"}}'
        menu_settings.predescription = u'Dit is de uitleiding van jouw menu'
        menu_settings.postdescription = u'Dit is de inleiding van jouw menu'
        menu_settings.name = None
        menu_settings.is_default = False
        menu_settings.put()

        server_settings = get_server_settings()
        menu = MenuTO.fromMenuObject(RestaurantMenu.get(RestaurantMenu.create_key(solutionSettings.service_user, solutionSettings.solution)))
        for cat in menu.categories:
            cat.has_visible = False
            cat.has_visible_with_pay = False
            for item in cat.items:
                if item.image_id and item.image_id is not MISSING:
                    item.image_url = get_item_image_url(item.image_id, server_settings)
                else:
                    item.image_url = None
                self.assertEqual(None, item.image_url)


text:
define([
    "./core"
], function( Cinematic ) {

var msg;

function connTimeout() {
    msg = new Message( "loading...", "bottom");
}

function connFail() {
    msg = new Message( "No network connection", "top");
}

function contentTimeout( title, year, plot ) {
    plot.text('Loading...');
    year.text('Loading...');
    title.text('Loading...');
}

//TODO re-indent
Cinematic.extend( "query", function( name, searchType, reset) {
    // We do two requests each first search
    // since omdbAPI limit each request to 10
    // movies per page.
    var reset = reset || false;
    if ( reset ) {
        // Reset
        Cinematic.lastPage = 1;
        Cinematic.clearResults();
        Cinematic.newRequest( name, searchType );
        Cinematic.newRequest( name, searchType );
    } else {
        Cinematic.newRequest( name, searchType );
    }
}, true);

Cinematic.extend( "newRequest", function( name, searchType ) {
    var timeout = setTimeout( connTimeout, 1000),
        URI = "http://www.omdbapi.com/?s=" + name + "&page=" + Cinematic.lastPage++
        + "&type=" + searchType;
    $.ajax({
        url: URI,
        "success": function( data ){
            clearTimeout( timeout );
            if ( data.Response == 'True' ) {
                Cinematic.lastResults = data;
                Cinematic.lastTitleSearch = name;
                Cinematic.appendResults();
            } else {
                new Message( "No results for search", "top" );
            }
            if ( msg ) msg.miss();
        },
        "error": function( XMLHttpRequest ) {
            if ( XMLHttpRequest.readyState == 0) connFail();
        }
    });
}, true);

Cinematic.extend( "getContents", function( imdbID ) {
    var timeout,
        URI = "http://www.omdbapi.com/?i="+imdbID+"&plot=full&r=json",
        title = $('sidebar .title'),
        year = $('sidebar .year'),
        plot = $('sidebar .plot');
        timeout = setTimeout(function() {
            contentTimeout( title, year, plot)
        }, 500);
    $.ajax({
        url: URI,
        "success": function( data ) {
            clearTimeout(timeout)
            title.text(data.Title);
            year.text(data.Year);
            plot.text(data.Plot);
        }
    });
}, true)

Cinematic.extend( "update", function() {
    Cinematic.query( Cinematic.lastTitleSearch, Cinematic.searchType );
}, true)

Cinematic.debug.extend( "newRequest", function( onSuccessFn ) {
    const URI = "../test/assets/movie.fixture.json";
    $.ajax({
        url: URI,
        "success": onSuccessFn
    });
}, true);

});


text:
using HttpNotFoundException = Saklient.Errors.HttpNotFoundException;

namespace Saklient.Cloud.Errors
{

	/// <summary>対象が見つかりません。パスに使用できない文字が含まれています。
	/// </summary>
	public class InvalidUriArgumentException : HttpNotFoundException
	{

		/// <summary>
		/// <param name="status" />
		/// <param name="code" />
		/// <param name="message" />
		/// </summary>
		public InvalidUriArgumentException(long status, string code=null, string message="") : base(status, code, message == null || message == "" ? "対象が見つかりません。パスに使用できない文字が含まれています。" : message)
		{
			/*!base!*/;
		}

	}

}


text:
import uuid
import json
import os
import xml.etree.ElementTree

class File(object):
    def __init__(self, name):
        self.name = name
        self.functions_found = 0
        self.functions_hit = 0
        self.branches_found = 0
        self.branches_hit = 0
        self.lines_hit = 0
        self.lines_found = 0

class Parser(object):
    def __init__(self, i):
        self.input = i
        self.files = []

    def __convert_clover_xml(self):
        e = xml.etree.ElementTree.parse(self.input).getroot()
        data = e.findall('./project/metrics/file')

        for d in data:
            print d
            f = File(d.get('name'))
            metrics = d.find('metrics')

            f.functions_found = int(metrics.get('methods', 0))
            f.functions_hit = int(metrics.get('coveredmethods', 0))
            f.branches_found = int(metrics.get('conditionals', 0))
            f.branches_hit = int(metrics.get('coveredconditionals', 0))
            f.lines_found = int(metrics.get('statements', 0))
            f.lines_hit = int(metrics.get('coveredstatements', 0))

            self.files.append(f)

    def __convert_xml(self):
        root = xml.etree.ElementTree.parse(self.input).getroot()

        data = root.get('clover', None)
        if data:
            self.__convert_clover_xml()
            return

        data = root.findall('.//packages//class//lines')
        if data:
            self.__convert_cobertura()
            return

        raise Exception('Could not detect coverage format')

    def __convert_cobertura(self):
        e = xml.etree.ElementTree.parse(self.input).getroot()

        for c in e.findall('.//class'):
            lines = c.findall('.//line')
            f = File(c.get('filename'))

            branches_count = 0
            branches_missing = 0
            branches_partial = 0
            statements_count = len(lines)
            statements_missing = 0

            for l in lines:
                is_branch = l.get("branch", False)
                is_branch = is_branch in (True, 'true', 'True')

                if is_branch:
                    cc = l.get("condition-coverage")
                    cc = cc[cc.find("(")+1:cc.find(")")]
                    cc = cc.split("/")

                    if int(cc[0]) > 0:
                        branches_partial += int(cc[1]) - int(cc[0])
                    else:
                        branches_missing += int(cc[1]) - int(cc[0])

                    branches_count += int(cc[1])

                hits = int(l.get('hits', 0))
                if hits == 0:
                    statements_missing += 1

            f.branches_found = branches_count
            f.branches_hit = branches_count - branches_missing
            f.lines_found = statements_count
            f.lines_hit = statements_count - statements_missing

            self.files.append(f)

    def __convert_lcov(self):
        with open(self.input) as i:
            content = i.readlines()
            content = [x.strip() for x in content]

        f = None
        for l in content:
            if l.startswith("SF:"):
                f = File(l[3:-1])
            elif l.startswith("FNF:"):
                f.functions_found = int(l[4:])
            elif l.startswith("FNH:"):
                f.functions_hit = int(l[4:])
            elif l.startswith("BRF:"):
                f.branches_found = int(l[4:])
            elif l.startswith("BRH:"):
                f.branches_hit = int(l[4:])
            elif l.startswith("LH:"):
                f.lines_hit = int(l[3:])
            elif l.startswith("LF:"):
                f.lines_found = int(l[3:])
            elif l == "end_of_record":
                self.files.append(f)

    def __create_markup(self, badge_dir):
        functions_found = 0
        functions_hit = 0
        branches_found = 0
        branches_hit = 0
        lines_found = 0
        lines_hit = 0

        for f in self.files:
            functions_found += f.functions_found
            functions_hit += f.functions_hit
            branches_found += f.branches_found
            branches_hit += f.branches_hit
            lines_found += f.lines_found
            lines_hit += f.lines_hit

        found = functions_found + branches_found + lines_found
        hit = functions_hit + branches_hit + lines_hit
        cov = 0
        if found > 0:
            cov = int((hit / float(found)) * 100)

        rows = []
        for f in self.files:
            branches_cov = 0
            lines_cov = 0
            functions_cov = 0

            if f.branches_found > 0:
                branches_cov = int((f.branches_hit / float(f.branches_found) * 100.0))

            if f.functions_found > 0:
                functions_cov = int((f.functions_hit / float(f.functions_found) * 100.0))

            if f.lines_found > 0:
                lines_cov = int((f.lines_hit / float(f.lines_found) * 100.0))

            rows.append([{
                "type": "text",
                "text": f.name
            }, {
                "type": "text",
                "text": "%s%%" % branches_cov
            }, {
                "type": "text",
                "text": "%s/%s" % (f.branches_hit, f.branches_found)
            }, {
                "type": "text",
                "text": "%s%%" % functions_cov
            }, {
                "type": "text",
                "text": "%s/%s" % (f.functions_hit, f.functions_found)
            }, {
                "type": "text",
                "text": "%s%%" %  lines_cov
            }, {
                "type": "text",
                "text": "%s/%s" % (f.lines_hit, f.lines_found)
            }])

        # Headline
        elements = []
        elements.append({
            "type": "h1",
            "text": "Coverage Report: %s%%" % cov
        })

        headers = [{
            "type": "text",
            "text": "File"
        }, {
            "type": "text",
            "text": "Branches"
        }, {
            "type": "text",
            "text": " "
        }, {
            "type": "text",
            "text": "Functions"
        }, {
            "type": "text",
            "text": " "
        }, {
            "type": "text",
            "text": "Lines"
        }, {
            "type": "text",
            "text": " "
        }]

        elements.append({
            "type": "table",
            "headers": headers,
            "rows": rows
        })

        doc = {
            "version": 1,
            "title": "Code Coverage",
            "elements": elements
        }

        badge_path = os.path.join(badge_dir, "%s.json" % str(uuid.uuid4()))
        json.dump({
            "version": 1,
            "subject": "coverage",
            "status": "%s %%" % cov,
            "color": "green"
        }, open(badge_path, 'w+'), indent=4)

        return doc

    def parse(self, badge_dir):
        self.__convert_xml()
        return self.__create_markup(badge_dir)


text:
@interface KZPNewController ()

@end

@implementation KZPNewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNav];
//    self.tabBarItem.enabled = NO;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpNav {
    //设置左边 barButtonItem
    //如果直接用 btn 来包装 barBtnItem  超过 btn 的部分  btn 也会响应
    //    用一个 view 来包装

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"MainTagSubIcon" hightlightedImageName:@"MainTagSubIconClick" andAddTarget:self action:@selector(mainTagBtnClick) forControlEvents:UIControlEventTouchUpInside];

    //设置 中间
    self.navigationItem.titleView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MainTitle"]];

}
- (void)mainTagBtnClick {

    [self.navigationController pushViewController:[[KZPFollowController alloc]init] animated:YES];
}
@end


text:
{% load myfilter %}

    {% include 'app/memotop.html' %}

    {% if messages %}
    {% for message in messages %}

    {% if message.tags == 'success' %}

{{ message }}

    {% endif %}

    {% if message.tags == 'error' %}

{{ message }}

    {% endif %}

    {% if message.tags == 'warning' %}

{{ message }}

    {% endif %}

    {% if message.tags == 'info' %}

{{ message }}

    {% endif %}

    {% endfor %}
    {% endif %}

    {% for item in all_memo.object_list %}

            {{ item.title }}

                {{ item.pub_date }}

            {% if user == item.user %}

                <button type="button" class="btn btn-sm btn-primary" data-toggle="modal"
                    data-target="#myModalEdit{{ item.id }}">

                </button>
                <button type="button" class="btn btn-sm btn-danger" data-toggle="modal"
                    data-target="#myModalDelete{{ item.id }}">

                </button>

            {% endif %}

            {{ item.content | markdown2html | safe }}

            {% for tag in item.tags.all %}
            {{ tag }}
            {% endfor %}

    {% if user == item.user %}

    <form method="post" action="{% url 'app:edit_memo' item.id %}">
        {% csrf_token %}

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            ×
                        </button>

_mondja_py_( ..)φ

                            Title:
                            <input id="id_title" class="form-control" maxlength="200" name="title" type="text"
                                placeholder="Type a title" value="{{ item.title }}" autofocus required />

                            Content:
                            <textarea cols="75" id="id_content" class="form-control mydialog" name="content" rows="12"
                                placeholder="Type a content (Markdown)" required>{{ item.content }}</textarea>

                            Tags:
                            <input id="id_tags" class="form-control" maxlength="32" name="tags-text" type="text"
                                placeholder="Type a tags" value="{{ item.get_tags_str }}" />

                        <input type="hidden" name="user" value="{{ user.id }}" id="id_user" />

                        <button type="button" class="btn btn-default" data-dismiss="modal">

                            Cancel
                        </button>
                        <button type="submit" class="btn btn-success">

                            Submit
                        </button>

    </form>

    <form method="post" action="{% url 'app:delete_memo' item.id %}">
        {% csrf_token %}

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            ×
                        </button>

_mondja_py_( ..)φ

Are you sure you want to permanently delete this memo ?

                        <button type="button" class="btn btn-default" data-dismiss="modal">

                            Cancel
                        </button>
                        <button type="submit" class="btn btn-danger">

                            Delete
                        </button>

    </form>
    {% endif %}

    {% endfor%}

    {% include 'app/pagination.html' %}


text:
	×
	Success! {MESSAGE}


text:
require 'librato/librato_api_v1'

# Fix bug in module Librato::Metrics::Processor by monkey patching

module Librato
  module Metrics

    module Processor
      private

      def create_persister
        type = self.client.persistence.to_s.camelize
        Librato::Metrics::Persistence.const_get(type).new
      end

    end
  end
end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ftfl.icare.UserProfileCreateActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/tvName"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:text="Name :"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <EditText
                    android:id="@+id/etName"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:ems="10"
                    android:hint="name"
                    android:inputType="textPersonName" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/tvPhone"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:text="DOB :"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <Button
                    android:id="@+id/bBirthDate"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:background="#bcecdc"
                    android:text="12/02/2015" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/tvMail"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:text="Height :"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <EditText
                    android:id="@+id/etHeight"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:ems="10"
                    android:hint="height"
                    android:inputType="textEmailAddress" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/textView5"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:text="Weight :"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <EditText
                    android:id="@+id/etWeight"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:ems="10"
                    android:hint="weight"
                    android:inputType="textPersonName" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="horizontal" >

                <RadioGroup
                    android:id="@+id/radioGroup1"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="3"
                    android:orientation="horizontal"
                    android:paddingLeft="10dp" >

                    <RadioButton
                        android:id="@+id/radioButtonMale"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:checked="true"
                        android:text="Male" />

                    <RadioButton
                        android:id="@+id/radioButtonFemale"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Female" />
                </RadioGroup>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/bSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#bcecdc"
        android:text="Save" />

</LinearLayout>


text:
module Rack
  module OAuth2
    module Server
      module Abstract
        class Request < Rack::Request
          include AttrRequired, AttrOptional
          attr_required :client_id
          attr_optional :scope

          def initialize(env)
            super
            @client_id ||= params['client_id']
            @scope = Array(params['scope'].to_s.split(' '))
          end

          def attr_missing_with_error_handling!
            if Util.check_presence_of(params['client_id']) && @client_id != params['client_id']
              invalid_request! 'Multiple client credentials are provided.'
            end
            attr_missing_without_error_handling!
          rescue AttrRequired::AttrMissing => e
            invalid_request! e.message, state: @state, redirect_uri: @redirect_uri
          end

          alias_method :attr_missing_without_error_handling!, :attr_missing!
          alias_method :attr_missing!, :attr_missing_with_error_handling!
        end
      end
    end
  end
end


text:
package com.perforce.p4java.impl.mapbased.server.cmd;

import static com.perforce.p4java.common.base.ObjectUtils.isNull;
import static com.perforce.p4java.common.base.ObjectUtils.nonNull;
import static com.perforce.p4java.impl.mapbased.server.Parameters.processParameters;
import static com.perforce.p4java.impl.mapbased.server.cmd.ResultMapParser.handleErrorStr;
import static com.perforce.p4java.impl.mapbased.server.cmd.ResultMapParser.isExistClientOrLabelOrUser;
import static com.perforce.p4java.impl.mapbased.server.cmd.ResultMapParser.isInfoMessage;
import static com.perforce.p4java.impl.mapbased.server.cmd.ResultMapParser.parseCommandResultMapAsString;
import static com.perforce.p4java.impl.mapbased.server.cmd.ResultMapParser.parseCommandResultMapIfIsInfoMessageAsString;
import static com.perforce.p4java.server.CmdSpec.LABEL;

import java.util.List;
import java.util.Map;

import com.perforce.p4java.Log;
import com.perforce.p4java.core.ILabel;
import com.perforce.p4java.exception.AccessException;
import com.perforce.p4java.exception.ConnectionException;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.RequestException;
import com.perforce.p4java.impl.generic.core.InputMapper;
import com.perforce.p4java.impl.generic.core.Label;
import com.perforce.p4java.option.server.DeleteLabelOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.delegator.ILabelDelegator;
import org.apache.commons.lang3.Validate;

/**
 * Implementation to handle the Label command.
 */
public class LabelDelegator extends BaseDelegator implements ILabelDelegator {
    /**
     * Instantiate a new LabelDelegator, providing the server object that will be used to
     * execute Perforce Helix attribute commands.
     *
     * @param server a concrete implementation of a Perforce Helix Server
     */
    public LabelDelegator(IOptionsServer server) {
        super(server);
    }

    @Override
    public ILabel getLabel(final String labelName)
            throws ConnectionException, RequestException, AccessException {

        Validate.notBlank(labelName, "Label name shouldn't null or empty.");
        ILabel label = null;
        final String OFLAG = "-o";
        List<Map<String, Object>> resultMaps = execMapCmdList(
                LABEL,
                new String[]{OFLAG, labelName},
                null);

        if (isNull(resultMaps)) {
            Log.warn("Unexpected null map array returned to ServerImpl.getLabel()");
        } else {
            // Note that the only way to tell whether the requested label
            // existed or not is to look for the returned Access and Update
            // fields -- if they're both missing it's probably not a real
            // label, just the public new label template coming back from
            // the server.
            for (Map<String, Object> map : resultMaps) {
                if (nonNull(map)) {
                    handleErrorStr(map);
                    if (!isInfoMessage(map)) {
                        if (isExistClientOrLabelOrUser(map)) {
                            label = new Label(map, server);
                        }
                    }
                }
            }
        }

        return label;
    }

    @Override
    public String createLabel(final ILabel label)
            throws ConnectionException, RequestException, AccessException {

        Validate.notNull(label);
        List<Map<String, Object>> resultMaps = execMapCmdList(
                LABEL,
                new String[]{"-i"},
                InputMapper.map(label));

        return parseCommandResultMapIfIsInfoMessageAsString(resultMaps);
    }

    @Override
    public String updateLabel(final ILabel label)
            throws ConnectionException, RequestException, AccessException {

        Validate.notNull(label);

        List<Map<String, Object>> resultMaps = execMapCmdList(
                LABEL,
                new String[]{"-i"},
                InputMapper.map(label));

        return parseCommandResultMapAsString(resultMaps);
    }

    @Override
    public String deleteLabel(final String labelName, final boolean force)
            throws ConnectionException, RequestException, AccessException {

        try {
            return deleteLabel(labelName, new DeleteLabelOptions().setForce(force));
        } catch (final ConnectionException | AccessException | RequestException exc) {
            throw exc;
        } catch (P4JavaException exc) {
            throw new RequestException(exc.getMessage(), exc);
        }
    }

    @Override
    public String deleteLabel(final String labelName, final DeleteLabelOptions opts)
            throws P4JavaException {

        Validate.notBlank(labelName, "Label name shouldn't null or empty.");
        List<Map<String, Object>> resultMaps = execMapCmdList(
                LABEL,
                processParameters(opts, null, new String[]{"-d", labelName}, server),
                null);

        return parseCommandResultMapIfIsInfoMessageAsString(resultMaps);
    }
}


text:
package org.ebayopensource.fido.uaf.msg.asm.obj;

public class GetRegistrationsOut {
	public AppRegistration[] appRegs;
}


text:
/**
 * The main classes that library users should know about Rocket-Config. The class to begin with is
 * ConfigModel.
 */
package ws.rocket.config;