text:
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/redshift/model/Tag.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{

  /**
   *
Returns information about an HSM client certificate. The certificate is
   * stored in a secure Hardware Storage Module (HSM), and used by the Amazon
   * Redshift cluster to encrypt data files.

   */
  class AWS_REDSHIFT_API HsmClientCertificate
  {
  public:
    HsmClientCertificate();
    HsmClientCertificate(const Aws::Utils::Xml::XmlNode& xmlNode);
    HsmClientCertificate& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The identifier of the HSM client certificate.

     */
    inline const Aws::String& GetHsmClientCertificateIdentifier() const{ return m_hsmClientCertificateIdentifier; }

    /**
     *
The identifier of the HSM client certificate.

     */
    inline void SetHsmClientCertificateIdentifier(const Aws::String& value) { m_hsmClientCertificateIdentifierHasBeenSet = true; m_hsmClientCertificateIdentifier = value; }

    /**
     *
The identifier of the HSM client certificate.

     */
    inline void SetHsmClientCertificateIdentifier(Aws::String&& value) { m_hsmClientCertificateIdentifierHasBeenSet = true; m_hsmClientCertificateIdentifier = value; }

    /**
     *
The identifier of the HSM client certificate.

     */
    inline void SetHsmClientCertificateIdentifier(const char* value) { m_hsmClientCertificateIdentifierHasBeenSet = true; m_hsmClientCertificateIdentifier.assign(value); }

    /**
     *
The identifier of the HSM client certificate.

     */
    inline HsmClientCertificate& WithHsmClientCertificateIdentifier(const Aws::String& value) { SetHsmClientCertificateIdentifier(value); return *this;}

    /**
     *
The identifier of the HSM client certificate.

     */
    inline HsmClientCertificate& WithHsmClientCertificateIdentifier(Aws::String&& value) { SetHsmClientCertificateIdentifier(value); return *this;}

    /**
     *
The identifier of the HSM client certificate.

     */
    inline HsmClientCertificate& WithHsmClientCertificateIdentifier(const char* value) { SetHsmClientCertificateIdentifier(value); return *this;}

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline const Aws::String& GetHsmClientCertificatePublicKey() const{ return m_hsmClientCertificatePublicKey; }

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline void SetHsmClientCertificatePublicKey(const Aws::String& value) { m_hsmClientCertificatePublicKeyHasBeenSet = true; m_hsmClientCertificatePublicKey = value; }

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline void SetHsmClientCertificatePublicKey(Aws::String&& value) { m_hsmClientCertificatePublicKeyHasBeenSet = true; m_hsmClientCertificatePublicKey = value; }

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline void SetHsmClientCertificatePublicKey(const char* value) { m_hsmClientCertificatePublicKeyHasBeenSet = true; m_hsmClientCertificatePublicKey.assign(value); }

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline HsmClientCertificate& WithHsmClientCertificatePublicKey(const Aws::String& value) { SetHsmClientCertificatePublicKey(value); return *this;}

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline HsmClientCertificate& WithHsmClientCertificatePublicKey(Aws::String&& value) { SetHsmClientCertificatePublicKey(value); return *this;}

    /**
     *
The public key that the Amazon Redshift cluster will use to connect to the
     * HSM. You must register the public key in the HSM.

     */
    inline HsmClientCertificate& WithHsmClientCertificatePublicKey(const char* value) { SetHsmClientCertificatePublicKey(value); return *this;}

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline HsmClientCertificate& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline HsmClientCertificate& WithTags(Aws::Vector<Tag>&& value) { SetTags(value); return *this;}

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline HsmClientCertificate& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
The list of tags for the HSM client certificate.

     */
    inline HsmClientCertificate& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

  private:
    Aws::String m_hsmClientCertificateIdentifier;
    bool m_hsmClientCertificateIdentifierHasBeenSet;
    Aws::String m_hsmClientCertificatePublicKey;
    bool m_hsmClientCertificatePublicKeyHasBeenSet;
    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;
  };

} // namespace Model
} // namespace Redshift
} // namespace Aws


text:
#pragma once

#include "MyFbx.h"

namespace MyFbx
{
	class MyFbxMaterialAnalyzer final
	{
	public:
		typedef std::shared_ptr<MyFbxMaterialAnalyzer> TSharedPtr;
		typedef std::shared_ptr<const MyFbxMaterialAnalyzer> TConstSharedPtr;
	public:
		enum PropertyType
		{
			PropertyType_Ambient,
			PropertyType_Diffuse,
			PropertyType_Specular,
			PropertyType_Emissive,
			PropertyType_Bump,
			PropertyType_NormalMap,
			PropertyType_TransparentColor,
			PropertyType_TransparencyFactor,
			PropertyType_Reflection,
		};

	public:
		MyFbxMaterialAnalyzer();

		virtual ~MyFbxMaterialAnalyzer();

		void Analyze(const FbxSurfaceMaterial* material);

		const MyMath::Vector3F& GetFbxRgbAmbient() const { return m_fbxRgbAmbient; }
		const MyMath::Vector3F& GetFbxRgbDiffuse() const { return m_fbxRgbDiffuse; }
		const MyMath::Vector3F& GetFbxRgbSpecular() const { return m_fbxRgbSpecular; }
		const MyMath::Vector3F& GetFbxRgbEmissive() const { return m_fbxRgbEmissive; }
		const MyMath::Vector3F& GetFbxRgbBump() const { return m_fbxRgbBump; }
		const MyMath::Vector3F& GetFbxRgbNormalMap() const { return m_fbxRgbNormalMap; }
		const MyMath::Vector3F& GetFbxRgbTransparentColor() const { return m_fbxRgbTransparentColor; }
		const MyMath::Vector3F& GetFbxRgbReflection() const { return m_fbxRgbReflection; }

		float GetFbxAmbientFactor() const { return m_fbxAmbientFactor; }
		float GetFbxDiffuseFactor() const { return m_fbxDiffuseFactor; }
		float GetFbxSpecularFactor() const { return m_fbxSpecularFactor; }
		float GetFbxEmissiveFactor() const { return m_fbxEmissiveFactor; }
		float GetFbxBumpFactor() const { return m_fbxBumpFactor; }
		float GetFbxNormalFactor() const { return m_fbxBumpFactor; }

		float GetFbxTransparencyFactor() const { return m_fbxTransparencyFactor; }
		float GetFbxReflectionFactor() const { return m_fbxReflectionFactor; }
		float GetFbxShininess() const { return m_fbxShininess; }

#pragma region // Custom Properties //
		float GetFbxRoughness() const { return m_fbxRoughness; }
		float GetFbxReflectivity() const { return m_fbxReflectivity; }
		float GetFbxIndexOfRefraction() const { return m_fbxIndexOfRefraction; }
		float GetFbxTranslucency() const { return m_fbxTranslucency; }
		float GetFbxOpacity() const { return m_fbxOpacity; }
#pragma endregion

		const MyMath::Vector3F& GetFbxRgbColorRGB(PropertyType propertyType) const;

		const float GetFbxFactor(PropertyType propertyType) const;

		//! @brief  テクスチャ名(FBX オブジェクト名)を取得する。

		const std::wstring& GetTextureName(PropertyType propertyType) const;

		//! @brief  テクスチャのファイル名を取得する。

		const std::wstring& GetTextureFileName(PropertyType propertyType) const;

		//! @brief  テクスチャの相対ファイル名を取得する。

		const std::wstring& GetTextureRelativeFileName(PropertyType propertyType) const;

		void SetMaterialName(const char* pName) { m_strMaterialName = MyUtils::SafeConvertUtf8toUtf16(pName); }
		void SetMaterialName(const wchar_t* pName) { m_strMaterialName = pName ? pName : L""; }

		const std::wstring& GetMaterialNameW() const { return m_strMaterialName; }

	private:
		// Lambert 情報の抽出。
		void ExtractLambertInfo(const FbxSurfaceLambert* lambert);

		// Vector3 の X, Y, Z が R, G, B にそれぞれ相当する。
		// FBX ではディフューズ カラーとディフューズ強度(拡散光レベル)が分離されている。
		// Max フォーマット、および DirectX の X フォーマットではディフューズ カラーとディフューズ強度が合成されている。
		// なお、Metasequoia や LightWave ではマテリアル カラーとディフューズ強度が分離されている。
	private:
		MyMath::Vector3F m_fbxRgbAmbient; // アンビエント カラー
		MyMath::Vector3F m_fbxRgbDiffuse; // ディフューズ カラー
		MyMath::Vector3F m_fbxRgbSpecular; // スペキュラー カラー
		MyMath::Vector3F m_fbxRgbEmissive; // エミッシブ カラー
		MyMath::Vector3F m_fbxRgbBump; // バンプ カラー
		MyMath::Vector3F m_fbxRgbNormalMap; // 法線マップ カラー
		MyMath::Vector3F m_fbxRgbTransparentColor; //!< 透過カラー。

		MyMath::Vector3F m_fbxRgbReflection;

		// 詳しいことはよく分からないが、Maya では透明度はスカラーだけでなくカラーアトリビュート設定も可能らしい。
		// Shade でも透過色を指定できるらしい。色付きのガラスや水の表現にそのまま使える。
		// LightWave 標準マテリアルや Metasequoia では透過色はサポートされない。

		float m_fbxAmbientFactor;
		float m_fbxDiffuseFactor;
		float m_fbxSpecularFactor;
		float m_fbxEmissiveFactor;
		float m_fbxBumpFactor;

		float m_fbxTransparencyFactor; //!< 透過度。Trasparency = (1 - Opacity) = (1 - Alpha) であることに注意。

		float m_fbxReflectionFactor; //!< Reflection と Reflectivity との違いがよく分からない。Reflectivity はブレンド比率だと思うが、Factor は?

		float m_fbxShininess; //!< 光沢の強さ(Power)。

#pragma region // Custom Properties //
		float m_fbxRoughness; //!< 面の粗さ。

		float m_fbxReflectivity; //!< 反射率(Reflectivity)。

		float m_fbxIndexOfRefraction;
		float m_fbxTranslucency;
		float m_fbxOpacity; //!< 不透明度。

#pragma endregion

		// FBX に Refractivity や Index of Refraction(IOR = 屈折率)はないらしい。
		// SSS(Subsurface Scattering)で必要となる Translucency(半透明度)もないらしい。
		// 3ds Max には Translucency が存在する。
		// http://docs.autodesk.com/3DSMAX/16/JPN/3ds-Max-Help/index.html?url=files/GUID-B8011F77-73AC-4BB8-BA73-5094465A7152.htm,topicNumber=d30e477247
		// FBX マテリアルは標準のプロパティ(FbxSurfaceMaterial クラスに名前のリテラルが定義されているもの)に加えて、
		// 独自のカスタム プロパティを追加できるらしい。
		// Collada には IOR はあるが、Translucency はないらしい。
		// FBX SDK の <2014.2\include\fbxsdk\fileio\collada\fbxcolladatokens.h> に、
		// COLLADA_INDEXOFREFRACTION_MATERIAL_PARAMETER の定義がある。
		// LightWave には屈折インデックスおよび半透明度が存在する。
		// なお、シェーダーで「空気→ガラス→水→ガラス→空気」などの透過条件で屈折マッピングしようと思ったら
		// 屈折率の比が要るために隣接マテリアルの情報が要るはず。
		// 素直にレイトレースかフォトンマッピングするべき領域かもしれない。
		// Refractivity は IOR とは別物のようなので、そもそも不要かも。
		//
		// 3ds Max では Roughness と Glossiness 両方を持っている。
		// Roughness が大きいほど光沢がなくなり、また Glossiness が大きいほどハイライトが小さくなるが、
		// 両者は対立する概念ではない。
		// http://docs.autodesk.com/3DSMAX/16/JPN/3ds-Max-Help/index.html?url=files/GUID-21BB5B24-C553-47A7-8472-8443936E13FB.htm,topicNumber=d30e477152
		// http://docs.autodesk.com/3DSMAX/16/JPN/3ds-Max-Help/index.html?url=files/GUID-7C791BBC-B27F-4BD2-821D-D7DBEA9E7CC9.htm,topicNumber=d30e477568
		// http://docs.autodesk.com/3DSMAX/16/JPN/3ds-Max-Help/index.html?url=files/GUID-8E3FF64C-63B6-42FA-A198-D65E10387A5D.htm,topicNumber=d30e477778
		// グロスマップはともかく、単体(スカラー)のラフネスではなくラフネスマップを使って面のマイクロファセットを定義するようにしたほうがいいかも。
		// Shininess と Roughness の換算式は一応存在するようだが、数学関数を使わなければならないのでヘビー。
		// Shininess = exp((10 * (1 - Roughness) + 2) * log(2)))
		// http://lifewithmodo.blogspot.jp/2011/12/fbx.html
		// この log は log10 なのか? それとも ln なのか?
		// もし log10 であるならば、R = 1 のとき S = 1.8 で、R = 0 のとき S = 37 となる。
		// もし ln であるならば、R = 1 のとき S = 4 で、R = 0 のとき S = 4096 となる。

		std::wstring m_strMaterialName; //!< マテリアル名。

		std::wstring m_texNameAmbient; // アンビエント テクスチャ名
		std::wstring m_texNameDiffuse; // ディフューズ テクスチャ名
		std::wstring m_texNameSpecular; // スペキュラー テクスチャ名
		std::wstring m_texNameEmissive; // エミッシブ テクスチャ名
		std::wstring m_texNameBump; // バンプ テクスチャ名
		std::wstring m_texNameNormalMap; // 法線マップ テクスチャ名
		std::wstring m_texNameTransparentColor;
		std::wstring m_texNameTransparencyFactor;
		// アルファ マップ相当は TransparencyFactor のほう?
		std::wstring m_texNameReflection;

		std::wstring m_texFileNameAmbient; // アンビエント テクスチャのファイル名
		std::wstring m_texFileNameDiffuse; // ディフューズ テクスチャのファイル名
		std::wstring m_texFileNameSpecular; // スペキュラー テクスチャのファイル名
		std::wstring m_texFileNameEmissive; // エミッシブ テクスチャのファイル名
		std::wstring m_texFileNameBump; // バンプ テクスチャのファイル名
		std::wstring m_texFileNameNormalMap; // 法線マップ テクスチャのファイル名
		std::wstring m_texFileNameTransparentColor;
		std::wstring m_texFileNameTransparencyFactor;
		std::wstring m_texFileNameReflection;

		std::wstring m_texRelativeFileNameAmbient; // アンビエント テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameDiffuse; // ディフューズ テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameSpecular; // スペキュラー テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameEmissive; // エミッシブ テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameBump; // バンプ テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameNormalMap; // 法線マップ テクスチャ相対ファイル名
		std::wstring m_texRelativeFileNameTransparentColor;
		std::wstring m_texRelativeFileNameTransparencyFactor;
		std::wstring m_texRelativeFileNameReflection;
	};
} // end of namespace

redpajama_set_name: RedPajamaGithub


text:
package org.bouncycastle.pqc.jcajce.provider.falcon;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters;
import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory;
import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.pqc.jcajce.interfaces.FalconPrivateKey;
import org.bouncycastle.pqc.jcajce.interfaces.FalconPublicKey;
import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil;
import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;

public class BCFalconPrivateKey
    implements FalconPrivateKey
{
    private static final long serialVersionUID = 1L;

    private transient FalconPrivateKeyParameters params;
    private transient String algorithm;
    private transient byte[] encoding;
    private transient ASN1Set attributes;

    public BCFalconPrivateKey(
            FalconPrivateKeyParameters params)
    {
        init(params, null);
    }

    public BCFalconPrivateKey(PrivateKeyInfo keyInfo)
            throws IOException
    {
        init(keyInfo);
    }

    private void init(PrivateKeyInfo keyInfo)
            throws IOException
    {
        init((FalconPrivateKeyParameters) PrivateKeyFactory.createKey(keyInfo), keyInfo.getAttributes());
    }

    private void init(FalconPrivateKeyParameters params, ASN1Set attributes)
    {
        this.attributes = attributes;
        this.params = params;
        this.algorithm = Strings.toUpperCase(params.getParameters().getName());
    }

    /**
     * Compare this Falcon private key with another object.
     *
     * @param o the other object
     * @return the result of the comparison
     */
    public boolean equals(Object o)
    {
        if (o == this)
        {
            return true;
        }

        if (o instanceof BCFalconPrivateKey)
        {
            BCFalconPrivateKey otherKey = (BCFalconPrivateKey)o;

            return Arrays.areEqual(getEncoded(), otherKey.getEncoded());
        }

        return false;
    }

    public int hashCode()
    {
        return Arrays.hashCode(getEncoded());
    }

    /**
     * @return name of the algorithm - "FALCON-512 or FALCON-1024"
     */
    public final String getAlgorithm()
    {
        return algorithm;
    }

    public byte[] getEncoded()
    {
        if (encoding == null)
        {
            encoding = KeyUtil.getEncodedPrivateKeyInfo(params, attributes);
        }

        return Arrays.clone(encoding);
    }

    public FalconParameterSpec getParameterSpec()
    {
        return FalconParameterSpec.fromName(params.getParameters().getName());
    }

    public String getFormat()
    {
        return "PKCS#8";
    }

    public FalconPublicKey getPublicKey()
    {
        return new BCFalconPublicKey(new FalconPublicKeyParameters(params.getParameters(), params.getPublicKey()));
    }

    FalconPrivateKeyParameters getKeyParams()
    {
        return params;
    }

    private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();

        byte[] enc = (byte[])in.readObject();

        init(PrivateKeyInfo.getInstance(enc));
    }

    private void writeObject(
            ObjectOutputStream out)
            throws IOException
    {
        out.defaultWriteObject();

        out.writeObject(this.getEncoded());
    }
}


text:
<?php

namespace Zend\Expressive\Container;

use Interop\Container\ContainerInterface;
use Zend\Expressive\WhoopsErrorHandler;

/**
 * Create and return an instance of the whoops error handler.
 *
 * Register this factory as the service `Zend\Expressive\FinalHandler` in
 * the container of your choice.
 *
 * This factory has optional dependencies on the following services:
 *
 * - 'Zend\Expressive\Template\TemplateRendererInterface', which should return an
 *   implementation of that interface. If not present, the error handler
 *   will not create templated responses.
 * - 'config' (which should return an array or array-like object with a
 *   "zend-expressive" top-level key, and an "error_handler" subkey,
 *   containing the configuration for the error handler).
 *
 * This factory has required dependencies on the following services:
 *
 * - Zend\Expressive\Whoops, which should return a Whoops\Run instance.
 * - Zend\Expressive\WhoopsPageHandler, which should return a
 *   Whoops\Handler\PrettyPageHandler instance.
 *
 * Configuration should look like the following:
 *
 * <code>
 * 'zend-expressive' => [
 *     'error_handler' => [
 *         'template_404'   => 'name of 404 template',
 *         'template_error' => 'name of error template',
 *     ],
 * ]
 * </code>
 *
 * If any of the keys are missing, default values will be used.
 */
class WhoopsErrorHandlerFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $template = $container->has('Zend\Expressive\Template\TemplateRendererInterface')
            ? $container->get('Zend\Expressive\Template\TemplateRendererInterface')
            : null;

        $config = $container->has('config')
            ? $container->get('config')
            : [];

        $config = isset($config['zend-expressive']['error_handler'])
            ? $config['zend-expressive']['error_handler']
            : [];

        return new WhoopsErrorHandler(
            $container->get('Zend\Expressive\Whoops'),
            $container->get('Zend\Expressive\WhoopsPageHandler'),
            $template,
            (isset($config['template_404']) ? $config['template_404'] : 'error/404'),
            (isset($config['template_error']) ? $config['template_error'] : 'error/error')
        );
    }
}


text:
{
    matrix_id: '2264',
    name: 'tomographic1',
    group: 'Clark',
    description: 'Tomographic reconstruction of a particle field in fluid flow, T. Clark',
    author: 'T. Clark',
    editor: 'T. Davis',
    date: '2009',
    kind: 'computer graphics/vision problem',
    problem_2D_or_3D: '1',
    num_rows: '73159',
    num_cols: '59498',
    nonzeros: '647495',
    num_explicit_zeros: '0',
    num_strongly_connected_components: '27546',
    num_dmperm_blocks: '3546',
    structural_full_rank: 'false',
    structural_rank: '42208',
    pattern_symmetry: '0.000',
    numeric_symmetry: '0.000',
    rb_type: 'real',
    structure: 'rectangular',
    cholesky_candidate: 'no',
    positive_definite: 'no',
    notes: 'Tomographic reconstruction of a particle field in fluid flow, T. Clark
See http://www.mathworks.com/matlabcentral/newsreader/view_thread/254747
for a discussion.  The problem can be solved via lsqlin in MATLAB:
lb = zeros (n,1) ;
x = lsqlin (A, b, [ ], [ ], [ ], [ ], lb) ;
',
    b_field: 'full 73159-by-1
',
    image_files: 'tomographic1.png,tomographic1_scc.png,tomographic1_graph.gif,',
}


text:
package io.iansoft.blockchain.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.*;
import javax.validation.constraints.*;

import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Objects;

/**
 * A Quote.
 */
@Entity
@Table(name = "quote")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "quote")
public class Quote extends AbstractAuditingEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    public Quote(Quote that) {
        this(that.getId(),that.getLastPrice(), that.getVolume(),that.getLowPrice(), that.getHighPrice(), that.getAvgPrice(),that.getBuyPrice(),that.getSellPrice(),that.getOpeningPrice(),
            that.getClosingPrice(),that.getQuoteTime(),that.getMarketCoin());
    }
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword)
    private Long id;

    @NotNull
    @Column(name = "last_price", precision=30, scale=15, nullable = false)
    private BigDecimal lastPrice;

    @Column(name = "volume", precision=30, scale=15)
    private BigDecimal volume;

    @Column(name = "low_price", precision=20, scale=10)
    private BigDecimal lowPrice;

    @Column(name = "high_price", precision=20, scale=10)
    private BigDecimal highPrice;

    @Column(name = "avg_price", precision=20, scale=10)
    private BigDecimal avgPrice;

    @Column(name = "buy_price", precision=20, scale=10)
    private BigDecimal buyPrice;

    @Column(name = "sell_price", precision=20, scale=10)
    private BigDecimal sellPrice;

    @Column(name = "opening_price", precision=20, scale=10)
    private BigDecimal openingPrice;

    @Column(name = "closing_price", precision=20, scale=10)
    private BigDecimal closingPrice;

    @Column(name = "quote_time")
    private Instant quoteTime;

    @ManyToOne
    @JsonIgnoreProperties("quotes")
    private MarketCoin marketCoin;

    public Quote(Long id,BigDecimal lastPrice, BigDecimal volume, BigDecimal lowPrice, BigDecimal highPrice, BigDecimal avgPrice, BigDecimal buyPrice, BigDecimal sellPrice, BigDecimal openingPrice, BigDecimal closingPrice, Instant quoteTime, MarketCoin marketCoin) {
        this.id = id;
        this.lastPrice = lastPrice;
        this.volume = volume;
        this.lowPrice = lowPrice;
        this.highPrice = highPrice;
        this.avgPrice = avgPrice;
        this.buyPrice = buyPrice;
        this.sellPrice = sellPrice;
        this.openingPrice = openingPrice;
        this.closingPrice = closingPrice;
        this.quoteTime = quoteTime;
        this.marketCoin = marketCoin;
    }

    public Quote() {

    }

    // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public BigDecimal getLastPrice() {
        return lastPrice;
    }

    public Quote lastPrice(BigDecimal lastPrice) {
        this.lastPrice = lastPrice;
        return this;
    }

    public void setLastPrice(BigDecimal lastPrice) {
        this.lastPrice = lastPrice;
    }

    public BigDecimal getVolume() {
        return volume;
    }

    public Quote volume(BigDecimal volume) {
        this.volume = volume;
        return this;
    }

    public void setVolume(BigDecimal volume) {
        this.volume = volume;
    }

    public BigDecimal getLowPrice() {
        return lowPrice;
    }

    public Quote lowPrice(BigDecimal lowPrice) {
        this.lowPrice = lowPrice;
        return this;
    }

    public void setLowPrice(BigDecimal lowPrice) {
        this.lowPrice = lowPrice;
    }

    public BigDecimal getHighPrice() {
        return highPrice;
    }

    public Quote highPrice(BigDecimal highPrice) {
        this.highPrice = highPrice;
        return this;
    }

    public void setHighPrice(BigDecimal highPrice) {
        this.highPrice = highPrice;
    }

    public BigDecimal getAvgPrice() {
        return avgPrice;
    }

    public Quote avgPrice(BigDecimal avgPrice) {
        this.avgPrice = avgPrice;
        return this;
    }

    public void setAvgPrice(BigDecimal avgPrice) {
        this.avgPrice = avgPrice;
    }

    public BigDecimal getBuyPrice() {
        return buyPrice;
    }

    public Quote buyPrice(BigDecimal buyPrice) {
        this.buyPrice = buyPrice;
        return this;
    }

    public void setBuyPrice(BigDecimal buyPrice) {
        this.buyPrice = buyPrice;
    }

    public BigDecimal getSellPrice() {
        return sellPrice;
    }

    public Quote sellPrice(BigDecimal sellPrice) {
        this.sellPrice = sellPrice;
        return this;
    }

    public void setSellPrice(BigDecimal sellPrice) {
        this.sellPrice = sellPrice;
    }

    public BigDecimal getOpeningPrice() {
        return openingPrice;
    }

    public Quote openingPrice(BigDecimal openingPrice) {
        this.openingPrice = openingPrice;
        return this;
    }

    public void setOpeningPrice(BigDecimal openingPrice) {
        this.openingPrice = openingPrice;
    }

    public BigDecimal getClosingPrice() {
        return closingPrice;
    }

    public Quote closingPrice(BigDecimal closingPrice) {
        this.closingPrice = closingPrice;
        return this;
    }

    public void setClosingPrice(BigDecimal closingPrice) {
        this.closingPrice = closingPrice;
    }

    public Instant getQuoteTime() {
        return quoteTime;
    }

    public Quote quoteTime(Instant quoteTime) {
        this.quoteTime = quoteTime;
        return this;
    }

    public void setQuoteTime(Instant quoteTime) {
        this.quoteTime = quoteTime;
    }

    public MarketCoin getMarketCoin() {
        return marketCoin;
    }

    public Quote marketCoin(MarketCoin marketCoin) {
        this.marketCoin = marketCoin;
        return this;
    }

    public void setMarketCoin(MarketCoin marketCoin) {
        this.marketCoin = marketCoin;
    }
    // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Quote)) {
            return false;
        }
        return id != null && id.equals(((Quote) o).id);
    }

    @Override
    public int hashCode() {
        return 31;
    }

    @Override
    public String toString() {
        return "Quote{" +
            "id=" + getId() +
            ", lastPrice=" + getLastPrice() +
            ", volume=" + getVolume() +
            ", lowPrice=" + getLowPrice() +
            ", highPrice=" + getHighPrice() +
            ", avgPrice=" + getAvgPrice() +
            ", buyPrice=" + getBuyPrice() +
            ", sellPrice=" + getSellPrice() +
            ", openingPrice=" + getOpeningPrice() +
            ", closingPrice=" + getClosingPrice() +
            ", quoteTime='" + getQuoteTime() + "'" +
            "}";
    }
}


text:
require 'version'

project = 'piriscope'

Dir.chdir(File.dirname(__FILE__))

system("docker build -f Dockerfile-go -t #{project}-go .") || fail
system("docker run -it -e VERSION=#{$version} -e COMMIT=#{$commit} #{project}-go") || fail
id = `docker ps -l -q`.strip
system("docker cp '#{id}:/go/src/github.com/schmich/#{project}/#{project}' .") || fail
system("docker rm #{id}") || fail


text:
/**
 * Loads the Template panel
 *
 * @class MODx.panel.Template
 * @extends MODx.FormPanel
 * @param {Object} config An object of configuration properties
 * @xtype modx-panel-template
 */
MODx.panel.Template = function(config) {
    config = config || {record:{}};
    config.record = config.record || {};
    Ext.applyIf(config,{
        url: MODx.config.connectors_url+'element/template.php'
        ,baseParams: {}
        ,id: 'modx-panel-template'
		,cls: 'container form-with-labels'
        ,class_key: 'modTemplate'
        ,template: ''
        ,bodyStyle: ''
        ,items: [{
            html: '
'+_('template_new')+'
'
            ,id: 'modx-template-header'
            ,cls: 'modx-page-header'
            ,border: false
        },MODx.getPageStructure([{
            title: _('template_title')
            ,defaults: { border: false ,msgTarget: 'side' }
            ,layout: 'form'
            ,id: 'modx-template-form'
            ,labelWidth: 150
            ,items: [{
                html: '
'+_('template_msg')+'
'
                ,id: 'modx-template-msg'
				,bodyCssClass: 'panel-desc'
            },{
                layout: 'column'
                ,border: false
                ,defaults: {
                    layout: 'form'
                    ,labelAlign: 'top'
                    ,anchor: '100%'
                    ,border: false
                    ,cls:'main-wrapper'
                    ,labelSeparator: ''
                }
                ,items: [{
                    columnWidth: .6
                    ,items: [{
                        xtype: 'hidden'
                        ,name: 'id'
                        ,id: 'modx-template-id'
                        ,value: config.template
                    },{
                        xtype: 'hidden'
                        ,name: 'props'
                        ,id: 'modx-template-props'
                        ,value: config.record.props || null
                    },{
                        xtype: 'textfield'
                        ,fieldLabel: _('name')+'*'
                        ,description: MODx.expandHelp ? '' : _('template_desc_name')
                        ,name: 'templatename'
                        ,id: 'modx-template-templatename'
                        ,anchor: '100%'
                        ,maxLength: 100
                        ,enableKeyEvents: true
                        ,allowBlank: false
                        ,value: config.record.templatename
                        ,listeners: {
                            'keyup': {scope:this,fn:function(f,e) {
                                Ext.getCmp('modx-template-header').getEl().update('
'+_('template')+': '+f.getValue()+'
');
                            }}
                        }
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-templatename'
                        ,html: _('template_desc_name')
                        ,cls: 'desc-under'
                    },{
                        xtype: 'textarea'
                        ,fieldLabel: _('template_desc')
                        ,description: MODx.expandHelp ? '' : _('template_desc_description')
                        ,name: 'description'
                        ,id: 'modx-template-description'
                        ,anchor: '100%'
                        ,maxLength: 255
                        ,value: config.record.description || ''
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-description'
                        ,html: _('template_desc_description')
                        ,cls: 'desc-under'
                    },{
                        xtype: 'modx-combo-browser'
                        ,browserEl: 'modx-browser'
                        ,fieldLabel: _('static_file')
                        ,description: MODx.expandHelp ? '' : _('static_file_msg')
                        ,name: 'static_file'
                        ,hideFiles: true
                        ,openTo: config.record.openTo || ''
                        ,id: 'modx-template-static-file'
                        ,anchor: '100%'
                        ,maxLength: 255
                        ,value: config.record.static_file || ''
                        ,hidden: !config.record['static']
                        ,hideMode: 'offsets'
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-static-file'
                        ,id: 'modx-template-static-file-help'
                        ,html: _('static_file_msg')
                        ,cls: 'desc-under'
                        ,hidden: !config.record['static']
                        ,hideMode: 'offsets'
                    },{
                        html: MODx.onTempFormRender
                        ,border: false
                    }]
                },{
                    columnWidth: .4
                    ,items: [{
                        xtype: 'modx-combo-category'
                        ,fieldLabel: _('category')
                        ,description: MODx.expandHelp ? '' : _('template_desc_category')
                        ,name: 'category'
                        ,id: 'modx-template-category'
                        ,anchor: '100%'
                        ,value: config.record.category || 0
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-category'
                        ,html: _('template_desc_category')
                        ,cls: 'desc-under'
                    },{
                        xtype: 'xcheckbox'
                        ,boxLabel: _('template_lock')
                        ,description: _('template_lock_msg')
                        ,name: 'locked'
                        ,id: 'modx-template-locked'
                        ,inputValue: 1
                        ,checked: config.record.locked || false
                    },{
                        xtype: 'checkbox'
                        ,boxLabel: _('clear_cache_on_save')
                        ,description: _('clear_cache_on_save_msg')
                        ,hideLabel: true
                        ,name: 'clearCache'
                        ,id: 'modx-template-clear-cache'
                        ,inputValue: 1
                        ,checked: Ext.isDefined(config.record.clearCache) || true
                    },{
                        xtype: 'xcheckbox'
                        ,hideLabel: true
                        ,boxLabel: _('is_static')
                        ,description: MODx.expandHelp ? '' : _('is_static_msg')
                        ,name: 'static'
                        ,id: 'modx-template-static'
                        ,inputValue: 1
                        ,checked: config.record['static'] || false
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-static'
                        ,id: 'modx-template-static-help'
                        ,html: _('is_static_msg')
                        ,cls: 'desc-under'
                    },{
                        xtype: 'modx-combo-source'
                        ,fieldLabel: _('static_source')
                        ,description: MODx.expandHelp ? '' : _('static_source_msg')
                        ,name: 'source'
                        ,id: 'modx-template-static-source'
                        ,anchor: '100%'
                        ,maxLength: 255
                        ,value: config.record.source != null ? config.record.source : MODx.config.default_media_source
                        ,hidden: !config.record['static']
                        ,hideMode: 'offsets'
                        ,baseParams: {
                            action: 'getList'
                            ,showNone: true
                            ,streamsOnly: true
                        }
                    },{
                        xtype: MODx.expandHelp ? 'label' : 'hidden'
                        ,forId: 'modx-template-static-source'
                        ,id: 'modx-template-static-source-help'
                        ,html: _('static_source_msg')
                        ,cls: 'desc-under'
                        ,hidden: !config.record['static']
                        ,hideMode: 'offsets'
                    }]
                }]
			},{
				xtype: 'panel'
				,border: false
				,layout: 'form'
				,cls:'main-wrapper'
				,labelAlign: 'top'
				,items: [{
					xtype: 'textarea'
					,fieldLabel: _('template_code')
					,name: 'content'
					,id: 'modx-template-content'
					,anchor: '100%'
					,height: 400
					,value: config.record.content || ''
				}]
			}]
        },{
            xtype: 'modx-panel-element-properties'
            ,preventRender: true
            ,collapsible: true
            ,elementPanel: 'modx-panel-template'
            ,elementId: config.template
            ,elementType: 'modTemplate'
            ,record: config.record
        },{
            title: _('template_variables')
            ,itemId: 'form-template'
            ,defaults: { autoHeight: true }
			,layout: 'form'
            ,items: [{
                html: '
'+_('template_tv_msg')+'
'
				,bodyCssClass: 'panel-desc'
                ,border: false
            },{
               xtype: 'modx-grid-template-tv'
			   ,cls:'main-wrapper'
               ,preventRender: true
               ,anchor: '100%'
               ,template: config.template
               ,listeners: {
                    'rowclick': {fn:this.markDirty,scope:this}
                    ,'afterEdit': {fn:this.markDirty,scope:this}
                    ,'afterRemoveRow': {fn:this.markDirty,scope:this}
               }
            }]
        }],{
            id: 'modx-template-tabs'
        })]
        ,useLoadingMask: true
        ,listeners: {
            'setup': {fn:this.setup,scope:this}
            ,'success': {fn:this.success,scope:this}
            ,'beforeSubmit': {fn:this.beforeSubmit,scope:this}
        }
    });
    MODx.panel.Template.superclass.constructor.call(this,config);
    var isStatic = Ext.getCmp('modx-template-static');
    if (isStatic) { isStatic.on('check',this.toggleStaticFile); }
};
Ext.extend(MODx.panel.Template,MODx.FormPanel,{
    initialized: false
    ,setup: function() {
        if (this.initialized) { this.clearDirty(); return true; }
        this.getForm().setValues(this.config.record);
        if (!Ext.isEmpty(this.config.record.templatename)) {
            Ext.getCmp('modx-template-header').getEl().update('
'+_('template')+': '+this.config.record.templatename+'
');
        }
        if (!Ext.isEmpty(this.config.record.properties)) {
            var d = this.config.record.properties;
            var g = Ext.getCmp('modx-grid-element-properties');
            if (g) {
                g.defaultProperties = d;
                g.getStore().loadData(d);
            }
        }
        this.fireEvent('ready',this.config.record);
        if (MODx.onLoadEditor) { MODx.onLoadEditor(this); }
        this.clearDirty();
        this.initialized = true;
        MODx.fireEvent('ready');
        return true;
    }
    ,beforeSubmit: function(o) {
        var g = Ext.getCmp('modx-grid-template-tv');
        Ext.apply(o.form.baseParams,{
            tvs: g.encodeModified()
            ,propdata: Ext.getCmp('modx-grid-element-properties').encode()
        });
        this.cleanupEditor();
        return this.fireEvent('save',{
            values: this.getForm().getValues()
            ,stay: MODx.config.stay
        });
    }
    ,success: function(r) {
        if (MODx.request.id) Ext.getCmp('modx-grid-element-properties').save();
        Ext.getCmp('modx-grid-template-tv').getStore().commitChanges();
        this.getForm().setValues(r.result.object);

        var t = Ext.getCmp('modx-element-tree');
        if (t) {
            var c = Ext.getCmp('modx-template-category').getValue();
            var u = c != '' && c != null && c != 0 ? 'n_template_category_'+c : 'n_type_template';
            var node = t.getNodeById('n_template_element_' + Ext.getCmp('modx-template-id').getValue() + '_' + r.result.object.previous_category);
            if (node) node.destroy();
            t.refreshNode(u,true);
        }
    }
    ,changeEditor: function() {
        this.cleanupEditor();
        this.on('success',function(o) {
            var id = o.result.object.id;
            var w = Ext.getCmp('modx-template-which-editor').getValue();
            MODx.request.a = MODx.action['element/template/update'];
            var u = '?'+Ext.urlEncode(MODx.request)+'&which_editor='+w+'&id='+id;
            location.href = u;
        });
        this.submit();
    }
    ,cleanupEditor: function() {
        if (MODx.onSaveEditor) {
            var fld = Ext.getCmp('modx-template-content');
            MODx.onSaveEditor(fld);
        }
    }
    ,toggleStaticFile: function(cb) {
        var flds = ['modx-template-static-file','modx-template-static-file-help','modx-template-static-source','modx-template-static-source-help'];
        var fld,i;
        if (cb.checked) {
            for (i in flds) {
                fld = Ext.getCmp(flds[i]);
                if (fld) { fld.show(); }
            }
        } else {
            for (i in flds) {
                fld = Ext.getCmp(flds[i]);
                if (fld) { fld.hide(); }
            }
        }
    }
});
Ext.reg('modx-panel-template',MODx.panel.Template);


text:
Emoji
=====

Emoji for Python.  This project was inspired by `kyokomi <https://github.com/kyokomi/emoji>`__.

Example
-------

The entire set of Emoji codes as defined by the `unicode consortium <http://www.unicode.org/Public/emoji/1.0/full-emoji-list.html>`__
is supported in addition to a bunch of `aliases <http://www.emoji-cheat-sheet.com/>`__.  By
default only the official list is enabled but doing ``emoji.emojize(use_aliases=True)`` enables
both the full list and aliases.

.. code-block:: python

    >> import emoji
    >> print(emoji.emojize('Python is :thumbs_up_sign:'))
    Python is 👍
    >> print(emoji.emojize('Python is :thumbsup:', use_aliases=True))
    Python is 👍

Installation
------------

Via pip:

.. code-block:: console

    $ pip install emoji --upgrade

From master branch:

.. code-block:: console

    $ git clone https://github.com/carpedm20/emoji.git
    $ cd emoji
    $ python setup.py install

Link
----

`Emoji Cheat Sheet <http://www.emoji-cheat-sheet.com/>`__

`Official unicode list <http://www.unicode.org/Public/emoji/1.0/full-emoji-list.html>`__

Authors
-------

Taehoon Kim / `@carpedm20 <http://carpedm20.github.io/about/>`__

Kevin Wurster / `@geowurster <http://twitter.com/geowurster/>`__


text:
/**
 * This is where you build your AI for the Coreminer game.
 */
package games.coreminer;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import joueur.BaseAI;

// <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional import(s) here
// <<-- /Creer-Merge: imports -->>

/**
 * This is where you build your AI for the Coreminer game.
 */
public class AI extends BaseAI {
    /**
     * This is the Game object itself, it contains all the information about the current game
     */
    public Game game;

    /**
     * This is your AI's player. This AI class is not a player, but it should command this Player.
     */
    public Player player;

    // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
    // you can add additional fields here for your AI to use
    // <<-- /Creer-Merge: fields -->>

    /**
     * This returns your AI's name to the game server. Just replace the string.
     * @return string of you AI's name
     */
    public String getName() {
        // <<-- Creer-Merge: get-name -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        return "Coreminer Java Player"; // REPLACE THIS WITH YOUR TEAM NAME!
        // <<-- /Creer-Merge: get-name -->>
    }

    /**
     * This is automatically called when the game first starts, once the Game object and all GameObjects have been initialized, but before any players do anything.
     * This is a good place to initialize any variables you add to your AI, or start tracking game objects.
     */
    public void start() {
        // <<-- Creer-Merge: start -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        super.start();
        // <<-- /Creer-Merge: start -->>
    }

    /**
     * This is automatically called every time the game (or anything in it) updates.
     * If a function you call triggers an update this will be called before that function returns.
     */
    public void gameUpdated() {
        // <<-- Creer-Merge: game-updated -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        super.gameUpdated();
        // <<-- /Creer-Merge: game-updated -->>
    }

    /**
     * This is automatically called when the game ends.
     * You can do any cleanup of you AI here, or do custom logging. After this function returns the application will close.
     * @param  won  true if your player won, false otherwise
     * @param  reason  a string explaining why you won or lost
     */
    public void ended(boolean won, String reason) {
        // <<-- Creer-Merge: ended -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        super.ended(won, reason);
        // <<-- /Creer-Merge: ended -->>
    }

    /**
     * This is called every time it is this AI.player's turn.
     *
     * @return Represents if you want to end your turn. True means end your turn, False means to keep your turn going and re-call this function.
     */
    public boolean runTurn() {
        // <<-- Creer-Merge: runTurn -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        // Put your game logic here for runTurn
        return true;
        // <<-- /Creer-Merge: runTurn -->>
    }

    /**
     * A very basic path finding algorithm (Breadth First Search) that when given a starting Tile, will return a valid path to the goal Tile.
     * @param  start  the starting Tile
     * @param  goal  the goal Tile
     * @return A List of Tiles representing the path, the the first element being a valid adjacent Tile to the start, and the last element being the goal. Or an empty list if no path found.
     */
    List<Tile> findPath(Tile start, Tile goal) {
        // no need to make a path to here...
        if (start == goal) {
            return new ArrayList<Tile>();
        }

        // the tiles that will have their neighbors searched for 'goal'
        Queue<Tile> fringe = new LinkedList<Tile>();

        // How we got to each tile that went into the fringe.
        HashMap<Tile, Tile> cameFrom = new HashMap<Tile, Tile>();

        // Enqueue start as the first tile to have its neighbors searched.
        fringe.add(start);

        // keep exploring neighbors of neighbors... until there are no more.
        while (!fringe.isEmpty()) {
            // the tile we are currently exploring.
            Tile inspect = fringe.remove();

            // cycle through the tile's neighbors.
            List<Tile> neighbors = inspect.getNeighbors();
            for (int i = 0; i < neighbors.size(); i++) {
                Tile neighbor = neighbors.get(i);

                // If we found the goal we've found the path!
                if (neighbor == goal) {
                    // Follow the path backward starting at the goal and return it.
                    List<Tile> path = new ArrayList<Tile>();
                    path.add(goal);

                    // Starting at the tile we are currently at, insert them retracing our steps till we get to the starting tile
                    for (Tile step = inspect; step != start; step = cameFrom.get(step)) {
                        path.add(0, step);
                    }

                    return path;
                }

                // if the tile exists, has not been explored or added to the fringe yet, and it is pathable
                if (neighbor != null && !cameFrom.containsKey(neighbor) && neighbor.isPathable()) {
                    // add it to the tiles to be explored and add where it came from.
                    fringe.add(neighbor);
                    cameFrom.put(neighbor, inspect);
                }

            } // for each neighbor

        } // while fringe not empty

        // if you're here, that means that there was not a path to get to where you want to go.
        //   in that case, we'll just return an empty path.
        return new ArrayList<Tile>();
    }

    // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
    // you can add additional methods here for your AI to call
    // <<-- /Creer-Merge: methods -->>
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/attestation/platform_verification_flow.h"

#include <utility>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/chromeos/attestation/attestation_ca_client.h"
#include "chrome/browser/chromeos/attestation/attestation_signed_data.pb.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/media/protected_media_identifier_permission_context.h"
#include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/attestation/attestation_flow.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/cryptohome/async_method_caller.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/user_manager/user.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "net/cert/pem_tokenizer.h"
#include "net/cert/x509_certificate.h"

namespace {

using chromeos::attestation::PlatformVerificationFlow;

const int kTimeoutInSeconds = 8;
const char kAttestationResultHistogram[] =
    "ChromeOS.PlatformVerification.Result";
const char kAttestationAvailableHistogram[] =
    "ChromeOS.PlatformVerification.Available";
const char kAttestationExpiryHistogram[] =
    "ChromeOS.PlatformVerification.ExpiryStatus";
const int kOpportunisticRenewalThresholdInDays = 30;

// A callback method to handle DBus errors.
void DBusCallback(const base::Callback<void(bool)>& on_success,
                  const base::Closure& on_failure,
                  chromeos::DBusMethodCallStatus call_status,
                  bool result) {
  if (call_status == chromeos::DBUS_METHOD_CALL_SUCCESS) {
    on_success.Run(result);
  } else {
    LOG(ERROR) << "PlatformVerificationFlow: DBus call failed!";
    on_failure.Run();
  }
}

// A helper to call a ChallengeCallback with an error result.
void ReportError(
    const PlatformVerificationFlow::ChallengeCallback& callback,
    chromeos::attestation::PlatformVerificationFlow::Result error) {
  UMA_HISTOGRAM_ENUMERATION(kAttestationResultHistogram, error,
                            PlatformVerificationFlow::RESULT_MAX);
  callback.Run(error, std::string(), std::string(), std::string());
}

// A helper to report expiry status to UMA.
void ReportExpiryStatus(PlatformVerificationFlow::ExpiryStatus status) {
  UMA_HISTOGRAM_ENUMERATION(kAttestationExpiryHistogram, status,
                            PlatformVerificationFlow::EXPIRY_STATUS_MAX);
}

}  // namespace

namespace chromeos {
namespace attestation {

// A default implementation of the Delegate interface.
class DefaultDelegate : public PlatformVerificationFlow::Delegate {
 public:
  DefaultDelegate() {}
  ~DefaultDelegate() override {}

  const GURL& GetURL(content::WebContents* web_contents) override {
    const GURL& url = web_contents->GetLastCommittedURL();
    if (!url.is_valid())
      return web_contents->GetVisibleURL();
    return url;
  }

  const user_manager::User* GetUser(
      content::WebContents* web_contents) override {
    return ProfileHelper::Get()->GetUserByProfile(
        Profile::FromBrowserContext(web_contents->GetBrowserContext()));
  }

  bool IsPermittedByUser(content::WebContents* web_contents) override {
    ProtectedMediaIdentifierPermissionContext* permission_context =
        ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
            Profile::FromBrowserContext(web_contents->GetBrowserContext()));

    // TODO(xhwang): Using delegate_->GetURL() here is not right. The platform
    // verification may be requested by a frame from a different origin. This
    // will be solved when http://crbug.com/454847 is fixed.
    const GURL& requesting_origin = GetURL(web_contents).GetOrigin();

    GURL embedding_origin = web_contents->GetLastCommittedURL().GetOrigin();

    ContentSetting content_setting = permission_context->GetPermissionStatus(
        requesting_origin, embedding_origin);

    return content_setting == CONTENT_SETTING_ALLOW;
  }

  bool IsInSupportedMode(content::WebContents* web_contents) override {
    Profile* profile =
        Profile::FromBrowserContext(web_contents->GetBrowserContext());
    if (profile->IsOffTheRecord() || profile->IsGuestSession())
      return false;

    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    return !command_line->HasSwitch(chromeos::switches::kSystemDevMode) ||
           command_line->HasSwitch(chromeos::switches::kAllowRAInDevMode);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);
};

PlatformVerificationFlow::ChallengeContext::ChallengeContext(
    content::WebContents* web_contents,
    const std::string& service_id,
    const std::string& challenge,
    const ChallengeCallback& callback)
    : web_contents(web_contents),
      service_id(service_id),
      challenge(challenge),
      callback(callback) {}

PlatformVerificationFlow::ChallengeContext::~ChallengeContext() {}

PlatformVerificationFlow::PlatformVerificationFlow()
    : attestation_flow_(NULL),
      async_caller_(cryptohome::AsyncMethodCaller::GetInstance()),
      cryptohome_client_(DBusThreadManager::Get()->GetCryptohomeClient()),
      delegate_(NULL),
      timeout_delay_(base::TimeDelta::FromSeconds(kTimeoutInSeconds)) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  scoped_ptr<ServerProxy> attestation_ca_client(new AttestationCAClient());
  default_attestation_flow_.reset(new AttestationFlow(
      async_caller_, cryptohome_client_, std::move(attestation_ca_client)));
  attestation_flow_ = default_attestation_flow_.get();
  default_delegate_.reset(new DefaultDelegate());
  delegate_ = default_delegate_.get();
}

PlatformVerificationFlow::PlatformVerificationFlow(
    AttestationFlow* attestation_flow,
    cryptohome::AsyncMethodCaller* async_caller,
    CryptohomeClient* cryptohome_client,
    Delegate* delegate)
    : attestation_flow_(attestation_flow),
      async_caller_(async_caller),
      cryptohome_client_(cryptohome_client),
      delegate_(delegate),
      timeout_delay_(base::TimeDelta::FromSeconds(kTimeoutInSeconds)) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (!delegate_) {
    default_delegate_.reset(new DefaultDelegate());
    delegate_ = default_delegate_.get();
  }
}

PlatformVerificationFlow::~PlatformVerificationFlow() {
}

void PlatformVerificationFlow::ChallengePlatformKey(
    content::WebContents* web_contents,
    const std::string& service_id,
    const std::string& challenge,
    const ChallengeCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!delegate_->GetURL(web_contents).is_valid()) {
    LOG(WARNING) << "PlatformVerificationFlow: Invalid URL.";
    ReportError(callback, INTERNAL_ERROR);
    return;
  }

  // Note: The following two checks are also checked in GetPermissionStatus.
  // Checking them here explicitly to report the correct error type.

  if (!IsAttestationAllowedByPolicy()) {
    VLOG(1) << "Platform verification not allowed by device policy.";
    ReportError(callback, POLICY_REJECTED);
    return;
  }

  // TODO(xhwang): Change to DCHECK when prefixed EME support is removed.
  // See http://crbug.com/249976
  if (!delegate_->IsInSupportedMode(web_contents)) {
    VLOG(1) << "Platform verification denied because it's not supported in the "
            << "current mode.";
    ReportError(callback, PLATFORM_NOT_VERIFIED);
    return;
  }

  if (!delegate_->IsPermittedByUser(web_contents)) {
    VLOG(1) << "Platform verification not permitted by user.";
    ReportError(callback, USER_REJECTED);
    return;
  }

  ChallengeContext context(web_contents, service_id, challenge, callback);
  // Check if the device has been prepared to use attestation.
  BoolDBusMethodCallback dbus_callback =
      base::Bind(&DBusCallback,
                 base::Bind(&PlatformVerificationFlow::OnAttestationPrepared,
                            this, context),
                 base::Bind(&ReportError, callback, INTERNAL_ERROR));
  cryptohome_client_->TpmAttestationIsPrepared(dbus_callback);
}

void PlatformVerificationFlow::OnAttestationPrepared(
    const ChallengeContext& context,
    bool attestation_prepared) {
  UMA_HISTOGRAM_BOOLEAN(kAttestationAvailableHistogram, attestation_prepared);

  if (!attestation_prepared) {
    // This device is not currently able to use attestation features.
    ReportError(context.callback, PLATFORM_NOT_VERIFIED);
    return;
  }

  // Permission allowed. Now proceed to get certificate.
  const user_manager::User* user = delegate_->GetUser(context.web_contents);
  if (!user) {
    ReportError(context.callback, INTERNAL_ERROR);
    LOG(ERROR) << "Profile does not map to a valid user.";
    return;
  }

  GetCertificate(context, user->email(), false /* Don't force a new key */);
}

void PlatformVerificationFlow::GetCertificate(const ChallengeContext& context,
                                              const std::string& user_id,
                                              bool force_new_key) {
  scoped_ptr<base::Timer> timer(new base::Timer(false,    // Don't retain.
                                                false));  // Don't repeat.
  base::Closure timeout_callback = base::Bind(
      &PlatformVerificationFlow::OnCertificateTimeout,
      this,
      context);
  timer->Start(FROM_HERE, timeout_delay_, timeout_callback);

  AttestationFlow::CertificateCallback certificate_callback = base::Bind(
      &PlatformVerificationFlow::OnCertificateReady,
      this,
      context,
      user_id,
      base::Passed(&timer));
  attestation_flow_->GetCertificate(
      PROFILE_CONTENT_PROTECTION_CERTIFICATE,
      user_id,
      context.service_id,
      force_new_key,
      certificate_callback);
}

void PlatformVerificationFlow::OnCertificateReady(
    const ChallengeContext& context,
    const std::string& user_id,
    scoped_ptr<base::Timer> timer,
    bool operation_success,
    const std::string& certificate_chain) {
  // Log failure before checking the timer so all failures are logged, even if
  // they took too long.
  if (!operation_success) {
    LOG(WARNING) << "PlatformVerificationFlow: Failed to certify platform.";
  }
  if (!timer->IsRunning()) {
    LOG(WARNING) << "PlatformVerificationFlow: Certificate ready but call has "
                 << "already timed out.";
    return;
  }
  timer->Stop();
  if (!operation_success) {
    ReportError(context.callback, PLATFORM_NOT_VERIFIED);
    return;
  }
  ExpiryStatus expiry_status = CheckExpiry(certificate_chain);
  ReportExpiryStatus(expiry_status);
  if (expiry_status == EXPIRY_STATUS_EXPIRED) {
    GetCertificate(context, user_id, true /* Force a new key */);
    return;
  }
  bool is_expiring_soon = (expiry_status == EXPIRY_STATUS_EXPIRING_SOON);
  cryptohome::AsyncMethodCaller::DataCallback cryptohome_callback =
      base::Bind(&PlatformVerificationFlow::OnChallengeReady, this, context,
                 user_id, certificate_chain, is_expiring_soon);
  std::string key_name = kContentProtectionKeyPrefix;
  key_name += context.service_id;
  async_caller_->TpmAttestationSignSimpleChallenge(KEY_USER,
                                                   user_id,
                                                   key_name,
                                                   context.challenge,
                                                   cryptohome_callback);
}

void PlatformVerificationFlow::OnCertificateTimeout(
    const ChallengeContext& context) {
  LOG(WARNING) << "PlatformVerificationFlow: Timing out.";
  ReportError(context.callback, TIMEOUT);
}

void PlatformVerificationFlow::OnChallengeReady(
    const ChallengeContext& context,
    const std::string& user_id,
    const std::string& certificate_chain,
    bool is_expiring_soon,
    bool operation_success,
    const std::string& response_data) {
  if (!operation_success) {
    LOG(ERROR) << "PlatformVerificationFlow: Failed to sign challenge.";
    ReportError(context.callback, INTERNAL_ERROR);
    return;
  }
  SignedData signed_data_pb;
  if (response_data.empty() || !signed_data_pb.ParseFromString(response_data)) {
    LOG(ERROR) << "PlatformVerificationFlow: Failed to parse response data.";
    ReportError(context.callback, INTERNAL_ERROR);
    return;
  }
  VLOG(1) << "Platform verification successful.";
  UMA_HISTOGRAM_ENUMERATION(kAttestationResultHistogram, SUCCESS, RESULT_MAX);
  context.callback.Run(SUCCESS, signed_data_pb.data(),
                       signed_data_pb.signature(), certificate_chain);
  if (is_expiring_soon && renewals_in_progress_.count(certificate_chain) == 0) {
    renewals_in_progress_.insert(certificate_chain);
    // Fire off a certificate request so next time we'll have a new one.
    AttestationFlow::CertificateCallback renew_callback =
        base::Bind(&PlatformVerificationFlow::RenewCertificateCallback, this,
                   certificate_chain);
    attestation_flow_->GetCertificate(PROFILE_CONTENT_PROTECTION_CERTIFICATE,
                                      user_id, context.service_id,
                                      true,  // force_new_key
                                      renew_callback);
  }
}

bool PlatformVerificationFlow::IsAttestationAllowedByPolicy() {
  // Check the device policy for the feature.
  bool enabled_for_device = false;
  if (!CrosSettings::Get()->GetBoolean(kAttestationForContentProtectionEnabled,
                                       &enabled_for_device)) {
    LOG(ERROR) << "Failed to get device setting.";
    return false;
  }
  if (!enabled_for_device) {
    VLOG(1) << "Platform verification denied because Verified Access is "
            << "disabled for the device.";
    return false;
  }

  return true;
}

PlatformVerificationFlow::ExpiryStatus PlatformVerificationFlow::CheckExpiry(
    const std::string& certificate_chain) {
  bool is_expiring_soon = false;
  bool invalid_certificate_found = false;
  int num_certificates = 0;
  net::PEMTokenizer pem_tokenizer(certificate_chain, {"CERTIFICATE"});
  while (pem_tokenizer.GetNext()) {
    ++num_certificates;
    scoped_refptr<net::X509Certificate> x509 =
        net::X509Certificate::CreateFromBytes(pem_tokenizer.data().data(),
                                              pem_tokenizer.data().length());
    if (!x509.get() || x509->valid_expiry().is_null()) {
      // This logic intentionally fails open. In theory this should not happen
      // but in practice parsing X.509 can be brittle and there are a lot of
      // factors including which underlying module is parsing the certificate,
      // whether that module performs more checks than just ASN.1/DER format,
      // and the server module that generated the certificate(s). Renewal is
      // expensive so we only renew certificates with good evidence that they
      // have expired or will soon expire; if we don't know, we don't renew.
      LOG(WARNING) << "Failed to parse certificate, cannot check expiry.";
      invalid_certificate_found = true;
      continue;
    }
    if (base::Time::Now() > x509->valid_expiry()) {
      return EXPIRY_STATUS_EXPIRED;
    }
    base::TimeDelta threshold =
        base::TimeDelta::FromDays(kOpportunisticRenewalThresholdInDays);
    if (x509->valid_expiry() - base::Time::Now() < threshold) {
      is_expiring_soon = true;
    }
  }
  if (is_expiring_soon) {
    return EXPIRY_STATUS_EXPIRING_SOON;
  }
  if (invalid_certificate_found) {
    return EXPIRY_STATUS_INVALID_X509;
  }
  if (num_certificates == 0) {
    LOG(WARNING) << "Failed to parse certificate chain, cannot check expiry.";
    return EXPIRY_STATUS_INVALID_PEM_CHAIN;
  }
  return EXPIRY_STATUS_OK;
}

void PlatformVerificationFlow::RenewCertificateCallback(
    const std::string& old_certificate_chain,
    bool operation_success,
    const std::string& certificate_chain) {
  renewals_in_progress_.erase(old_certificate_chain);
  if (!operation_success) {
    LOG(WARNING) << "PlatformVerificationFlow: Failed to renew platform "
                    "certificate.";
    return;
  }
  VLOG(1) << "Certificate successfully renewed.";
}

}  // namespace attestation
}  // namespace chromeos


text:
const AdmZip = require('adm-zip');

module.exports = function (path) {
    const zip = new AdmZip(path);
    return zip.readAsText('project.json', 'utf8');
};


text:
<?php
namespace Core\Filesystem\Content\Xml\Dom;

/**
 * Class XPathFactory
 */
class XPathFactory
{
    /**
     * Create new object DOMXPath for DOM document
     *
     * @param \DOMDocument $document
     * @return \DOMXPath
     */
    public function create(\DOMDocument $document)
    {
        return new \DOMXPath($document);
    }
}


text:
package httploc

import (
	"fmt"
	log "github.com/mailgun/gotools-log"
	timetools "github.com/mailgun/gotools-time"
	. "github.com/mailgun/vulcan/endpoint"
	"github.com/mailgun/vulcan/failover"
	"github.com/mailgun/vulcan/headers"
	. "github.com/mailgun/vulcan/loadbalance"
	. "github.com/mailgun/vulcan/middleware"
	"github.com/mailgun/vulcan/netutils"
	. "github.com/mailgun/vulcan/request"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

// Location with built in failover and load balancing support
type HttpLocation struct {
	// Unique identifier of this location
	id string
	// Transport with customized timeouts
	transport *http.Transport
	// Load balancer controls endpoints for this location
	loadBalancer LoadBalancer
	// Timeouts, failover and other optional settings
	options Options
	// Chain with pluggable middlewares that can intercept the request
	middlewareChain *MiddlewareChain
	// Chain of observers that watch the request
	observerChain *ObserverChain
}

// Additional options to control this location, such as timeouts
type Options struct {
	Timeouts struct {
		// Socket read timeout (before we receive the first reply header)
		Read time.Duration
		// Socket connect timeout
		Dial time.Duration
	}
	// Predicate that defines when requests are allowed to failover
	ShouldFailover failover.Predicate
	// Used in forwarding headers
	Hostname string
	// In this case appends new forward info to the existing header
	TrustForwardHeader bool
	// Time provider (useful for testing purposes)
	TimeProvider timetools.TimeProvider
}

func NewLocation(id string, loadBalancer LoadBalancer) (*HttpLocation, error) {
	return NewLocationWithOptions(id, loadBalancer, Options{})
}

func NewLocationWithOptions(id string, loadBalancer LoadBalancer, o Options) (*HttpLocation, error) {
	if loadBalancer == nil {
		return nil, fmt.Errorf("Provide load balancer")
	}
	o, err := parseOptions(o)
	if err != nil {
		return nil, err
	}

	observerChain := NewObserverChain()
	observerChain.Append(BalancerId, loadBalancer)

	middlewareChain := NewMiddlewareChain()
	middlewareChain.Append(BalancerId, loadBalancer)

	return &HttpLocation{
		id:           id,
		loadBalancer: loadBalancer,
		transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return net.DialTimeout(network, addr, o.Timeouts.Dial)
			},
			ResponseHeaderTimeout: o.Timeouts.Read,
		},
		options:         o,
		middlewareChain: middlewareChain,
		observerChain:   observerChain,
	}, nil
}

func (l *HttpLocation) GetMiddlewareChain() *MiddlewareChain {
	return l.middlewareChain
}

func (l *HttpLocation) GetObserverChain() *ObserverChain {
	return l.observerChain
}

// Round trips the request to one of the endpoints and returns the response
func (l *HttpLocation) RoundTrip(req Request) (*http.Response, error) {
	for {
		_, err := req.GetBody().Seek(0, 0)
		if err != nil {
			return nil, err
		}

		endpoint, err := l.loadBalancer.NextEndpoint(req)
		if err != nil {
			log.Errorf("Load Balancer failure: %s", err)
			return nil, err
		}

		// Adds headers, changes urls
		newRequest := l.rewriteRequest(req.GetHttpRequest(), endpoint)

		// In case if error is not nil, we allow load balancer to choose the next endpoint
		// e.g. to do request failover. Nil error means that we got proxied the request successfully.
		response, err := l.proxyToEndpoint(endpoint, req, newRequest)
		if l.options.ShouldFailover(req) {
			log.Errorf("Request(%s) failover", req)
			continue
		} else {
			return response, err
		}
	}
	log.Errorf("All endpoints failed!")
	return nil, fmt.Errorf("All endpoints failed")
}

func (l *HttpLocation) GetLoadBalancer() LoadBalancer {
	return l.loadBalancer
}

func (l *HttpLocation) GetId() string {
	return l.id
}

// Unwind middlewares iterator in reverse order
func (l *HttpLocation) unwindIter(it *MiddlewareIter, req Request, a Attempt) {
	for v := it.Prev(); v != nil; v = it.Prev() {
		v.ProcessResponse(req, a)
	}
}

// Proxy the request to the given endpoint, execute observers and middlewares chains
func (l *HttpLocation) proxyToEndpoint(endpoint Endpoint, req Request, httpReq *http.Request) (*http.Response, error) {

	a := &BaseAttempt{Endpoint: endpoint}

	l.observerChain.ObserveRequest(req)
	defer l.observerChain.ObserveResponse(req, a)
	defer req.AddAttempt(a)

	it := l.middlewareChain.GetIter()
	defer l.unwindIter(it, req, a)

	for v := it.Next(); v != nil; v = it.Next() {
		a.Response, a.Error = v.ProcessRequest(req)
		if a.Response != nil || a.Error != nil {
			// Move the iterator forward to count it again once we unwind the chain
			it.Next()
			log.Errorf("Midleware intercepted request with response=%s, error=%s", a.Response.Status, a.Error)
			return a.Response, a.Error
		}
	}

	// Forward the request and mirror the response
	start := l.options.TimeProvider.UtcNow()
	a.Response, a.Error = l.transport.RoundTrip(httpReq)
	a.Duration = l.options.TimeProvider.UtcNow().Sub(start)
	return a.Response, a.Error
}

// This function alters the original request - adds/removes headers, removes hop headers, changes the request path.
func (l *HttpLocation) rewriteRequest(req *http.Request, endpoint Endpoint) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL.Scheme = endpoint.GetUrl().Scheme
	outReq.URL.Host = endpoint.GetUrl().Host
	outReq.URL.RawQuery = req.URL.RawQuery

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1
	outReq.Close = false

	outReq.Header = make(http.Header)
	netutils.CopyHeaders(outReq.Header, req.Header)

	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		if l.options.TrustForwardHeader {
			if prior, ok := outReq.Header[headers.XForwardedFor]; ok {
				clientIP = strings.Join(prior, ", ") + ", " + clientIP
			}
		}
		outReq.Header.Set(headers.XForwardedFor, clientIP)
	}
	if req.TLS != nil {
		outReq.Header.Set(headers.XForwardedProto, "https")
	} else {
		outReq.Header.Set(headers.XForwardedProto, "http")
	}
	if req.Host != "" {
		outReq.Header.Set(headers.XForwardedHost, req.Host)
	}
	outReq.Header.Set(headers.XForwardedServer, l.options.Hostname)

	// Remove hop-by-hop headers to the backend.  Especially important is "Connection" because we want a persistent
	// connection, regardless of what the client sent to us.
	netutils.RemoveHeaders(headers.HopHeaders, outReq.Header)
	return outReq
}

// Standard dial and read timeouts, can be overriden when supplying location
const (
	DefaultHttpReadTimeout = time.Duration(10) * time.Second
	DefaultHttpDialTimeout = time.Duration(10) * time.Second
)

func parseOptions(o Options) (Options, error) {
	if o.Timeouts.Read <= time.Duration(0) {
		o.Timeouts.Read = DefaultHttpReadTimeout
	}
	if o.Timeouts.Dial <= time.Duration(0) {
		o.Timeouts.Dial = DefaultHttpDialTimeout
	}

	if o.Hostname == "" {
		h, err := os.Hostname()
		if err == nil {
			o.Hostname = h
		}
	}
	if o.TimeProvider == nil {
		o.TimeProvider = &timetools.RealTime{}
	}
	if o.ShouldFailover == nil {
		// Failover on errors for 2 times maximum on GET requests only.
		o.ShouldFailover = failover.And(failover.MaxAttempts(2), failover.OnErrors, failover.OnGets)
	}
	return o, nil
}

const (
	BalancerId = "__loadBalancer"
)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2016. 소프트웨어
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:padding="10dp"
        android:background="@drawable/drawable_016_bg_seekbar"
        android:progressDrawable="@drawable/drawable_016_pd_seekbar"
        android:thumb="@drawable/drawable_016_selector_seekbar_thumb"/>

</RelativeLayout>


text:
require_relative 'test_helper'

describe "FastExcel::Worksheet" do

  it "should get_worksheet_by_name" do
    workbook = FastExcel.open(constant_memory: false)
    workbook.add_worksheet("Page1")

    ws = workbook.get_worksheet_by_name("Page1")
    ws.write_row(0, ['1'])

    workbook.close

    error = assert_raises do
      FastExcel.open(workbook.filename, constant_memory: false)
    end

    assert_equal(error.class, ArgumentError)
    assert_equal(error.message, "File '#{workbook.filename}' already exists. FastExcel can not open existing files, only create new files")
  end

end


text:
'use strict';

describe('Directive: iadssTabBar', function () {
  beforeEach(module('iadssWebApp'));

  var element;

  it('should make hidden element visible', inject(function ($rootScope, $compile) {
    element = angular.element('<iadss-side-bar></iadss-side-bar>');
    element = $compile(element)($rootScope);
    expect(element.text()).toBe('this is the iadssTabBar directive');
  }));
});


text:
using System;

namespace Veldy.Net.CommandProcessor
{
	/// <summary>
	///     Interface IMessage
	/// </summary>
	/// <typeparam name="TIdentifier">The type of the t identifier.</typeparam>
	/// <typeparam name="TStore">The type of the t store.</typeparam>
	public interface IMessage<out TIdentifier, TStore>
		where TIdentifier : struct, IConvertible, IComparable<TStore>
		where TStore : class
	{
		/// <summary>
		///     Gets the key.
		/// </summary>
		/// <value>
		///     The key.
		/// </value>
		IKey<TIdentifier, TStore> Key { get; }

		/// <summary>
		///     Gets the store.
		/// </summary>
		/// <value>
		///     The store.
		/// </value>
		TStore Store { get; }
	}
}


text:
/* globals localforage, define */

define('localforage', [], function() {
  "use strict";

  return {
    'default': localforage
  };
});


text:
"""The extractor class definitions.

An extractor is a class used to extract information from "raw" data.
"""

from __future__ import unicode_literals

import copy

import pysigscan

from dfvfs.helpers import file_system_searcher
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.lib import errors as dfvfs_errors
from dfvfs.resolver import resolver as path_spec_resolver

from plaso.engine import logger
from plaso.lib import errors
from plaso.parsers import interface as parsers_interface
from plaso.parsers import manager as parsers_manager

class EventExtractor(object):
  """Event extractor.

  An event extractor extracts events from event sources.
  """

  _PARSE_RESULT_FAILURE = 1
  _PARSE_RESULT_SUCCESS = 2
  _PARSE_RESULT_UNSUPPORTED = 3

  def __init__(self, parser_filter_expression=None):
    """Initializes an event extractor.

    Args:
      parser_filter_expression (Optional[str]): parser filter expression,
          where None represents all parsers and plugins.

          A parser filter expression is a comma separated value string that
          denotes which parsers and plugins should be used. See
          filters/parser_filter.py for details of the expression syntax.
    """
    super(EventExtractor, self).__init__()
    self._file_scanner = None
    self._filestat_parser = None
    self._formats_with_signatures = None
    self._mft_parser = None
    self._non_sigscan_parser_names = None
    self._parsers = None
    self._parsers_profiler = None
    self._usnjrnl_parser = None

    self._InitializeParserObjects(
        parser_filter_expression=parser_filter_expression)

  def _CheckParserCanProcessFileEntry(self, parser, file_entry):
    """Determines if a parser can process a file entry.

    Args:
      file_entry (dfvfs.FileEntry): file entry.
      parser (BaseParser): parser.

    Returns:
      bool: True if the file entry can be processed by the parser object.
    """
    for filter_object in parser.FILTERS:
      if filter_object.Match(file_entry):
        return True

    return False

  def _GetSignatureMatchParserNames(self, file_object):
    """Determines if a file-like object matches one of the known signatures.

    Args:
      file_object (file): file-like object whose contents will be checked
          for known signatures.

    Returns:
      list[str]: parser names for which the contents of the file-like object
          matches their known signatures.
    """
    parser_names = []
    scan_state = pysigscan.scan_state()
    self._file_scanner.scan_file_object(scan_state, file_object)

    for scan_result in iter(scan_state.scan_results):
      format_specification = (
          self._formats_with_signatures.GetSpecificationBySignature(
              scan_result.identifier))

      if format_specification.identifier not in parser_names:
        parser_names.append(format_specification.identifier)

    return parser_names

  def _InitializeParserObjects(self, parser_filter_expression=None):
    """Initializes the parser objects.

    Args:
      parser_filter_expression (Optional[str]): parser filter expression,
          where None represents all parsers and plugins.

          A parser filter expression is a comma separated value string that
          denotes which parsers and plugins should be used. See
          filters/parser_filter.py for details of the expression syntax.
    """
    self._formats_with_signatures, non_sigscan_parser_names = (
        parsers_manager.ParsersManager.GetFormatsWithSignatures(
            parser_filter_expression=parser_filter_expression))

    self._non_sigscan_parser_names = []
    for parser_name in non_sigscan_parser_names:
      if parser_name not in ('filestat', 'usnjrnl'):
        self._non_sigscan_parser_names.append(parser_name)

    self._file_scanner = parsers_manager.ParsersManager.CreateSignatureScanner(
        self._formats_with_signatures)

    self._parsers = parsers_manager.ParsersManager.GetParserObjects(
        parser_filter_expression=parser_filter_expression)

    active_parser_names = ', '.join(sorted(self._parsers.keys()))
    logger.debug('Active parsers: {0:s}'.format(active_parser_names))

    self._filestat_parser = self._parsers.get('filestat', None)
    if 'filestat' in self._parsers:
      del self._parsers['filestat']

    self._mft_parser = self._parsers.get('mft', None)

    self._usnjrnl_parser = self._parsers.get('usnjrnl', None)
    if 'usnjrnl' in self._parsers:
      del self._parsers['usnjrnl']

  def _ParseDataStreamWithParser(
      self, parser_mediator, parser, file_entry, data_stream_name):
    """Parses a data stream of a file entry with a specific parser.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      parser (BaseParser): parser.
      file_entry (dfvfs.FileEntry): file entry.
      data_stream_name (str): data stream name.

    Raises:
      RuntimeError: if the file-like object is missing.
    """
    file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
    if not file_object:
      raise RuntimeError('Unable to retrieve file-like object from file entry.')

    try:
      self._ParseFileEntryWithParser(
          parser_mediator, parser, file_entry, file_object=file_object)

    finally:
      file_object.close()

  def _ParseFileEntryWithParser(
      self, parser_mediator, parser, file_entry, file_object=None):
    """Parses a file entry with a specific parser.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      parser (BaseParser): parser.
      file_entry (dfvfs.FileEntry): file entry.
      file_object (Optional[file]): file-like object to parse.
          If not set the parser will use the parser mediator to open
          the file entry's default data stream as a file-like object.

    Returns:
      int: parse result which is _PARSE_RESULT_FAILURE if the file entry
          could not be parsed, _PARSE_RESULT_SUCCESS if the file entry
          successfully was parsed or _PARSE_RESULT_UNSUPPORTED when
          UnableToParseFile was raised.

    Raises:
      TypeError: if parser object is not a supported parser type.
    """
    if not isinstance(parser, (
        parsers_interface.FileEntryParser, parsers_interface.FileObjectParser)):
      raise TypeError('Unsupported parser object type.')

    parser_mediator.ClearParserChain()

    reference_count = (
        parser_mediator.resolver_context.GetFileObjectReferenceCount(
            file_entry.path_spec))

    parser_mediator.SampleStartTiming(parser.NAME)

    try:
      if isinstance(parser, parsers_interface.FileEntryParser):
        parser.Parse(parser_mediator)
      elif isinstance(parser, parsers_interface.FileObjectParser):
        parser.Parse(parser_mediator, file_object)
      result = self._PARSE_RESULT_SUCCESS

    # We catch IOError so we can determine the parser that generated the error.
    except (IOError, dfvfs_errors.BackEndError) as exception:
      display_name = parser_mediator.GetDisplayName(file_entry)
      logger.warning(
          '{0:s} unable to parse file: {1:s} with error: {2!s}'.format(
              parser.NAME, display_name, exception))
      result = self._PARSE_RESULT_FAILURE

    except errors.UnableToParseFile as exception:
      display_name = parser_mediator.GetDisplayName(file_entry)
      logger.debug(
          '{0:s} unable to parse file: {1:s} with error: {2!s}'.format(
              parser.NAME, display_name, exception))
      result = self._PARSE_RESULT_UNSUPPORTED

    finally:
      parser_mediator.SampleStopTiming(parser.NAME)
      parser_mediator.SampleMemoryUsage(parser.NAME)

      new_reference_count = (
          parser_mediator.resolver_context.GetFileObjectReferenceCount(
              file_entry.path_spec))
      if reference_count != new_reference_count:
        display_name = parser_mediator.GetDisplayName(file_entry)
        logger.warning((
            '[{0:s}] did not explicitly close file-object for file: '
            '{1:s}.').format(parser.NAME, display_name))

    return result

  def _ParseFileEntryWithParsers(
      self, parser_mediator, parser_names, file_entry, file_object=None):
    """Parses a file entry with a specific parsers.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      parser_names (list[str]): names of parsers.
      file_entry (dfvfs.FileEntry): file entry.
      file_object (Optional[file]): file-like object to parse.
          If not set the parser will use the parser mediator to open
          the file entry's default data stream as a file-like object.

    Returns:
      int: parse result which is _PARSE_RESULT_FAILURE if the file entry
          could not be parsed, _PARSE_RESULT_SUCCESS if the file entry
          successfully was parsed or _PARSE_RESULT_UNSUPPORTED when
          UnableToParseFile was raised or no names of parser were provided.

    Raises:
      RuntimeError: if the parser object is missing.
    """
    parse_results = self._PARSE_RESULT_UNSUPPORTED
    for parser_name in parser_names:
      parser = self._parsers.get(parser_name, None)
      if not parser:
        raise RuntimeError(
            'Parser object missing for parser: {0:s}'.format(parser_name))

      if parser.FILTERS:
        if not self._CheckParserCanProcessFileEntry(parser, file_entry):
          parse_results = self._PARSE_RESULT_SUCCESS
          continue

      display_name = parser_mediator.GetDisplayName(file_entry)
      logger.debug((
          '[ParseFileEntryWithParsers] parsing file: {0:s} with parser: '
          '{1:s}').format(display_name, parser_name))

      parse_result = self._ParseFileEntryWithParser(
          parser_mediator, parser, file_entry, file_object=file_object)

      if parse_result == self._PARSE_RESULT_FAILURE:
        return self._PARSE_RESULT_FAILURE

      if parse_result == self._PARSE_RESULT_SUCCESS:
        parse_results = self._PARSE_RESULT_SUCCESS

    return parse_results

  def ParseDataStream(self, parser_mediator, file_entry, data_stream_name):
    """Parses a data stream of a file entry with the enabled parsers.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      file_entry (dfvfs.FileEntry): file entry.
      data_stream_name (str): data stream name.

    Raises:
      RuntimeError: if the file-like object or the parser object is missing.
    """
    file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
    if not file_object:
      raise RuntimeError(
          'Unable to retrieve file-like object from file entry.')

    try:
      parser_names = self._GetSignatureMatchParserNames(file_object)

      parse_with_non_sigscan_parsers = True
      if parser_names:
        parse_result = self._ParseFileEntryWithParsers(
            parser_mediator, parser_names, file_entry, file_object=file_object)
        if parse_result in (
            self._PARSE_RESULT_FAILURE, self._PARSE_RESULT_SUCCESS):
          parse_with_non_sigscan_parsers = False

      if parse_with_non_sigscan_parsers:
        self._ParseFileEntryWithParsers(
            parser_mediator, self._non_sigscan_parser_names, file_entry,
            file_object=file_object)

    finally:
      file_object.close()

  def ParseFileEntryMetadata(self, parser_mediator, file_entry):
    """Parses the file entry metadata such as file system data.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      file_entry (dfvfs.FileEntry): file entry.
    """
    if self._filestat_parser:
      self._ParseFileEntryWithParser(
          parser_mediator, self._filestat_parser, file_entry)

  def ParseMetadataFile(
      self, parser_mediator, file_entry, data_stream_name):
    """Parses a metadata file.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      file_entry (dfvfs.FileEntry): file entry.
      data_stream_name (str): data stream name.
    """
    parent_path_spec = getattr(file_entry.path_spec, 'parent', None)
    filename_upper = file_entry.name.upper()
    if (self._mft_parser and parent_path_spec and
        filename_upper in ('$MFT', '$MFTMIRR') and not data_stream_name):
      self._ParseDataStreamWithParser(
          parser_mediator, self._mft_parser, file_entry, '')

    elif (self._usnjrnl_parser and parent_path_spec and
          filename_upper == '$USNJRNL' and data_stream_name == '$J'):
      # To be able to ignore the sparse data ranges the UsnJrnl parser
      # needs to read directly from the volume.
      volume_file_object = path_spec_resolver.Resolver.OpenFileObject(
          parent_path_spec, resolver_context=parser_mediator.resolver_context)

      try:
        self._ParseFileEntryWithParser(
            parser_mediator, self._usnjrnl_parser, file_entry,
            file_object=volume_file_object)
      finally:
        volume_file_object.close()

class PathSpecExtractor(object):
  """Path specification extractor.

  A path specification extractor extracts path specification from a source
  directory, file or storage media device or image.
  """

  _MAXIMUM_DEPTH = 255

  def _ExtractPathSpecs(
      self, path_spec, find_specs=None, recurse_file_system=True,
      resolver_context=None):
    """Extracts path specification from a specific source.

    Args:
      path_spec (dfvfs.PathSpec): path specification.
      find_specs (Optional[list[dfvfs.FindSpec]]): find specifications
          used in path specification extraction.
      recurse_file_system (Optional[bool]): True if extraction should
          recurse into a file system.
      resolver_context (Optional[dfvfs.Context]): resolver context.

    Yields:
      dfvfs.PathSpec: path specification of a file entry found in the source.
    """
    file_entry = None
    try:
      file_entry = path_spec_resolver.Resolver.OpenFileEntry(
          path_spec, resolver_context=resolver_context)
    except (
        dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
        dfvfs_errors.PathSpecError) as exception:
      logger.error('Unable to open file entry with error: {0!s}'.format(
          exception))

    if not file_entry:
      logger.warning('Unable to open: {0:s}'.format(path_spec.comparable))

    elif (not file_entry.IsDirectory() and not file_entry.IsFile() and
          not file_entry.IsDevice()):
      logger.warning((
          'Source path specification not a device, file or directory.\n'
          '{0:s}').format(path_spec.comparable))

    elif file_entry.IsFile():
      yield path_spec

    else:
      for extracted_path_spec in self._ExtractPathSpecsFromFileSystem(
          path_spec, find_specs=find_specs,
          recurse_file_system=recurse_file_system,
          resolver_context=resolver_context):
        yield extracted_path_spec

  def _ExtractPathSpecsFromDirectory(self, file_entry, depth=0):
    """Extracts path specification from a directory.

    Args:
      file_entry (dfvfs.FileEntry): file entry that refers to the directory.
      depth (Optional[int]): current depth where 0 represents the file system
          root.

    Yields:
      dfvfs.PathSpec: path specification of a file entry found in the directory.

    Raises:
      MaximumRecursionDepth: when the maximum recursion depth is reached.
    """
    if depth >= self._MAXIMUM_DEPTH:
      raise errors.MaximumRecursionDepth('Maximum recursion depth reached.')

    # Need to do a breadth-first search otherwise we'll hit the Python
    # maximum recursion depth.
    sub_directories = []

    for sub_file_entry in file_entry.sub_file_entries:
      try:
        if not sub_file_entry.IsAllocated() or sub_file_entry.IsLink():
          continue
      except dfvfs_errors.BackEndError as exception:
        logger.warning(
            'Unable to process file: {0:s} with error: {1!s}'.format(
                sub_file_entry.path_spec.comparable.replace(
                    '\n', ';'), exception))
        continue

      # For TSK-based file entries only, ignore the virtual /$OrphanFiles
      # directory.
      if sub_file_entry.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK:
        if file_entry.IsRoot() and sub_file_entry.name == '$OrphanFiles':
          continue

      if sub_file_entry.IsDirectory():
        sub_directories.append(sub_file_entry)

      for path_spec in self._ExtractPathSpecsFromFile(sub_file_entry):
        yield path_spec

    for sub_file_entry in sub_directories:
      try:
        for path_spec in self._ExtractPathSpecsFromDirectory(
            sub_file_entry, depth=(depth + 1)):
          yield path_spec

      except (
          IOError, dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
          dfvfs_errors.PathSpecError) as exception:
        logger.warning('{0!s}'.format(exception))

  def _ExtractPathSpecsFromFile(self, file_entry):
    """Extracts path specification from a file.

    Args:
      file_entry (dfvfs.FileEntry): file entry that refers to the file.

    Yields:
      dfvfs.PathSpec: path specification of a file entry found in the file.
    """
    produced_main_path_spec = False
    for data_stream in file_entry.data_streams:
      # Make a copy so we don't make the changes on a path specification
      # directly. Otherwise already produced path specifications can be
      # altered in the process.
      path_spec = copy.deepcopy(file_entry.path_spec)
      if data_stream.name:
        setattr(path_spec, 'data_stream', data_stream.name)
      yield path_spec

      if not data_stream.name:
        produced_main_path_spec = True

    if not produced_main_path_spec:
      yield file_entry.path_spec

  def _ExtractPathSpecsFromFileSystem(
      self, path_spec, find_specs=None, recurse_file_system=True,
      resolver_context=None):
    """Extracts path specification from a file system within a specific source.

    Args:
      path_spec (dfvfs.PathSpec): path specification of the root of
          the file system.
      find_specs (Optional[list[dfvfs.FindSpec]]): find specifications
          used in path specification extraction.
      recurse_file_system (Optional[bool]): True if extraction should
          recurse into a file system.
      resolver_context (Optional[dfvfs.Context]): resolver context.

    Yields:
      dfvfs.PathSpec: path specification of a file entry found in
          the file system.
    """
    file_system = None
    try:
      file_system = path_spec_resolver.Resolver.OpenFileSystem(
          path_spec, resolver_context=resolver_context)
    except (
        dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
        dfvfs_errors.PathSpecError) as exception:
      logger.error('Unable to open file system with error: {0!s}'.format(
          exception))

    if file_system:
      try:
        if find_specs:
          searcher = file_system_searcher.FileSystemSearcher(
              file_system, path_spec)
          for extracted_path_spec in searcher.Find(find_specs=find_specs):
            yield extracted_path_spec

        elif recurse_file_system:
          file_entry = file_system.GetFileEntryByPathSpec(path_spec)
          if file_entry:
            for extracted_path_spec in self._ExtractPathSpecsFromDirectory(
                file_entry):
              yield extracted_path_spec

        else:
          yield path_spec

      except (
          dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
          dfvfs_errors.PathSpecError) as exception:
        logger.warning('{0!s}'.format(exception))

      finally:
        file_system.Close()

  def ExtractPathSpecs(
      self, path_specs, find_specs=None, recurse_file_system=True,
      resolver_context=None):
    """Extracts path specification from a specific source.

    Args:
      path_specs (Optional[list[dfvfs.PathSpec]]): path specifications.
      find_specs (Optional[list[dfvfs.FindSpec]]): find specifications
          used in path specification extraction.
      recurse_file_system (Optional[bool]): True if extraction should
          recurse into a file system.
      resolver_context (Optional[dfvfs.Context]): resolver context.

    Yields:
      dfvfs.PathSpec: path specification of a file entry found in the source.
    """
    for path_spec in path_specs:
      for extracted_path_spec in self._ExtractPathSpecs(
          path_spec, find_specs=find_specs,
          recurse_file_system=recurse_file_system,
          resolver_context=resolver_context):
        yield extracted_path_spec