text:
namespace chocolatey.infrastructure.app.services
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using configuration;
    using domain;
    using infrastructure.commands;
    using logging;
    using results;

    public sealed class RubyGemsService : ISourceRunner
    {
        private readonly ICommandExecutor _commandExecutor;
        private readonly INugetService _nugetService;
        private const string PACKAGE_NAME_TOKEN = "{{packagename}}";
        private const string EXE_PATH = "cmd.exe";
        private const string APP_NAME = "Ruby Gems";
        public const string RUBY_PORTABLE_PACKAGE = "ruby.portable";
        public const string RUBY_PACKAGE = "ruby";
        public const string PACKAGE_NAME_GROUP = "PkgName";
        public static readonly Regex InstallingRegex = new Regex(@"Fetching:", RegexOptions.Compiled);
        public static readonly Regex InstalledRegex = new Regex(@"Successfully installed", RegexOptions.Compiled);
        public static readonly Regex ErrorNotFoundRegex = new Regex(@"ERROR:  Could not find a valid gem", RegexOptions.Compiled);
        public static readonly Regex PackageNameFetchingRegex = new Regex(@"Fetching: (?<{0}>.*)\-".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled);
        public static readonly Regex PackageNameInstalledRegex = new Regex(@"Successfully installed (?<{0}>.*)\-".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled);
        public static readonly Regex PackageNameErrorRegex = new Regex(@"'(?<{0}>[^']*)'".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled);

        private readonly IDictionary<string, ExternalCommandArgument> _listArguments = new Dictionary<string, ExternalCommandArgument>(StringComparer.InvariantCultureIgnoreCase);
        private readonly IDictionary<string, ExternalCommandArgument> _installArguments = new Dictionary<string, ExternalCommandArgument>(StringComparer.InvariantCultureIgnoreCase);

        public RubyGemsService(ICommandExecutor commandExecutor, INugetService nugetService)
        {
            _commandExecutor = commandExecutor;
            _nugetService = nugetService;
            set_cmd_args_dictionaries();
        }

        /// <summary>
        ///   Set any command arguments dictionaries necessary for the service
        /// </summary>
        private void set_cmd_args_dictionaries()
        {
            set_list_dictionary(_listArguments);
            set_install_dictionary(_installArguments);
        }

        /// <summary>
        ///   Sets list dictionary
        /// </summary>
        private void set_list_dictionary(IDictionary<string, ExternalCommandArgument> args)
        {
            args.Add("_cmd_c_", new ExternalCommandArgument { ArgumentOption = "/c", Required = true });
            args.Add("_gem_", new ExternalCommandArgument { ArgumentOption = "gem", Required = true });
            args.Add("_action_", new ExternalCommandArgument {ArgumentOption = "list", Required = true});
        }

        /// <summary>
        ///   Sets install dictionary
        /// </summary>
        private void set_install_dictionary(IDictionary<string, ExternalCommandArgument> args)
        {
            args.Add("_cmd_c_", new ExternalCommandArgument {ArgumentOption = "/c", Required = true});
            args.Add("_gem_", new ExternalCommandArgument {ArgumentOption = "gem", Required = true});
            args.Add("_action_", new ExternalCommandArgument {ArgumentOption = "install", Required = true});
            args.Add("_package_name_", new ExternalCommandArgument
                {
                    ArgumentOption = "package name ",
                    ArgumentValue = PACKAGE_NAME_TOKEN,
                    QuoteValue = false,
                    UseValueOnly = true,
                    Required = true
                });

            args.Add("Force", new ExternalCommandArgument
                {
                    ArgumentOption = "-f ",
                    QuoteValue = false,
                    Required = false
                });

            args.Add("Version", new ExternalCommandArgument
                {
                    ArgumentOption = "--version ",
                    QuoteValue = false,
                    Required = false
                });
        }

        public SourceType SourceType
        {
            get { return SourceType.ruby; }
        }

        public void ensure_source_app_installed(ChocolateyConfiguration config, Action<PackageResult> ensureAction)
        {
            var runnerConfig = new ChocolateyConfiguration
                {
                    PackageNames = RUBY_PORTABLE_PACKAGE,
                    Sources = ApplicationParameters.PackagesLocation,
                    Debug = config.Debug,
                    Force = config.Force,
                    Verbose = config.Verbose,
                    CommandExecutionTimeoutSeconds = config.CommandExecutionTimeoutSeconds,
                    CacheLocation = config.CacheLocation,
                    RegularOutput = config.RegularOutput,
                    PromptForConfirmation = false,
                    AcceptLicense = true,
                    QuietOutput = true,
                };
            runnerConfig.ListCommand.LocalOnly = true;

            var localPackages = _nugetService.list_run(runnerConfig);

            if (!localPackages.Any(p => p.Name.is_equal_to(RUBY_PACKAGE) || p.Name.is_equal_to(RUBY_PORTABLE_PACKAGE)))
            {
                runnerConfig.Sources = ApplicationParameters.ChocolateyCommunityFeedSource;

                var prompt = config.PromptForConfirmation;
                config.PromptForConfirmation = false;
                _nugetService.install_run(runnerConfig, ensureAction.Invoke);
                config.PromptForConfirmation = prompt;
            }
        }

        public int count_run(ChocolateyConfiguration config)
        {
            throw new NotImplementedException("Count is not supported for this source runner.");
        }

        public void list_noop(ChocolateyConfiguration config)
        {
            var args = ExternalCommandArgsBuilder.build_arguments(config, _listArguments);
            this.Log().Info("Would have run '{0} {1}'".format_with(EXE_PATH.escape_curly_braces(), args.escape_curly_braces()));
        }

        public IEnumerable<PackageResult> list_run(ChocolateyConfiguration config)
        {
            var packageResults = new List<PackageResult>();
            var args = ExternalCommandArgsBuilder.build_arguments(config, _listArguments);

            Environment.ExitCode = _commandExecutor.execute(
                EXE_PATH,
                args,
                config.CommandExecutionTimeoutSeconds,
                stdOutAction: (s, e) =>
                    {
                        var logMessage = e.Data;
                        if (string.IsNullOrWhiteSpace(logMessage)) return;
                        if (!config.QuietOutput)
                        {
                            this.Log().Info(logMessage.escape_curly_braces());
                        }
                        else
                        {
                            this.Log().Debug(() => "[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces()));
                        }
                    },
                stdErrAction: (s, e) =>
                    {
                        if (string.IsNullOrWhiteSpace(e.Data)) return;
                        this.Log().Error(() => "{0}".format_with(e.Data.escape_curly_braces()));
                    },
                updateProcessPath: false
                );

            return packageResults;
        }

        public void install_noop(ChocolateyConfiguration config, Action<PackageResult> continueAction)
        {
            var args = ExternalCommandArgsBuilder.build_arguments(config, _installArguments);
            args = args.Replace(PACKAGE_NAME_TOKEN, config.PackageNames.Replace(';', ','));
            this.Log().Info("Would have run '{0} {1}'".format_with(EXE_PATH.escape_curly_braces(), args.escape_curly_braces()));
        }

        public ConcurrentDictionary<string, PackageResult> install_run(ChocolateyConfiguration config, Action<PackageResult> continueAction)
        {
            var packageResults = new ConcurrentDictionary<string, PackageResult>(StringComparer.InvariantCultureIgnoreCase);
            var args = ExternalCommandArgsBuilder.build_arguments(config, _installArguments);

            foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries))
            {
                var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageToInstall);
                var exitCode = _commandExecutor.execute(
                    EXE_PATH,
                    argsForPackage,
                    config.CommandExecutionTimeoutSeconds,
                    (s, e) =>
                        {
                            var logMessage = e.Data;
                            if (string.IsNullOrWhiteSpace(logMessage)) return;
                            this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces()));

                            if (InstallingRegex.IsMatch(logMessage))
                            {
                                var packageName = get_value_from_output(logMessage, PackageNameFetchingRegex, PACKAGE_NAME_GROUP);
                                var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null));
                                this.Log().Info(ChocolateyLoggers.Important, "{0}".format_with(packageName));
                                return;
                            }

                            //if (string.IsNullOrWhiteSpace(packageName)) return;

                            if (InstalledRegex.IsMatch(logMessage))
                            {
                                var packageName = get_value_from_output(logMessage, PackageNameInstalledRegex, PACKAGE_NAME_GROUP);
                                var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null));

                                results.Messages.Add(new ResultMessage(ResultType.Note, packageName));
                                this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName));
                            }
                        },
                    (s, e) =>
                        {
                            var logMessage = e.Data;
                            if (string.IsNullOrWhiteSpace(logMessage)) return;
                            this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces()));

                            var packageName = get_value_from_output(logMessage, PackageNameErrorRegex, PACKAGE_NAME_GROUP);

                            if (ErrorNotFoundRegex.IsMatch(logMessage))
                            {
                                var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null));
                                results.Messages.Add(new ResultMessage(ResultType.Error, packageName));
                            }
                        },
                    updateProcessPath: false
                    );

                if (exitCode != 0)
                {
                    Environment.ExitCode = exitCode;
                }
            }

            return packageResults;
        }

        public ConcurrentDictionary<string, PackageResult> upgrade_noop(ChocolateyConfiguration config, Action<PackageResult> continueAction)
        {
            this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement upgrade".format_with(APP_NAME));
            return new ConcurrentDictionary<string, PackageResult>(StringComparer.InvariantCultureIgnoreCase);
        }

        public ConcurrentDictionary<string, PackageResult> upgrade_run(ChocolateyConfiguration config, Action<PackageResult> continueAction, Action<PackageResult> beforeUpgradeAction)
        {
            throw new NotImplementedException("{0} does not implement upgrade".format_with(APP_NAME));
        }

        public void uninstall_noop(ChocolateyConfiguration config, Action<PackageResult> continueAction)
        {
            this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement uninstall".format_with(APP_NAME));
        }

        public ConcurrentDictionary<string, PackageResult> uninstall_run(ChocolateyConfiguration config, Action<PackageResult> continueAction)
        {
            throw new NotImplementedException("{0} does not implement uninstall".format_with(APP_NAME));
        }

        /// <summary>
        ///   Grabs a value from the output based on the regex.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <param name="regex">The regex.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <returns></returns>
        private static string get_value_from_output(string output, Regex regex, string groupName)
        {
            var matchGroup = regex.Match(output).Groups[groupName];
            if (matchGroup != null)
            {
                return matchGroup.Value;
            }

            return string.Empty;
        }
    }
}


text:
class AddUpdateScheduleToUser < ActiveRecord::Migration
  def change
    add_column :users, :update_schedule, :string,  :null => false,  :default => ""
    add_column :users, :last_update_sent, :datetime
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
class NearwordModel extends CommonModel{
    protected $pk   = 'word_id';
    protected $tableName =  'pois_word';

}


text:
package odeint

//import "fmt"

// Euler implements the Euler stepper method. Euler is part of the Stepper
// interface.
type Euler struct {
	stepSize complex64
	system   System
}

// NewEuler returns a reference to a new Euler stepper method.
func NewEuler(stepSize complex64, system System) (r *Euler) {
	if real(stepSize) <= 0 && imag(stepSize) <= 0.0 {
		panic("NewEuler called with negative or null stepSize.")
	}
	if system.Function() == nil {
		panic("NewEuler called with nil system.Function.")
	}
	r = &Euler{stepSize: stepSize, system: system}
	return
}

// These methods are required by the interface Stepper

// Setter methods

// SetStep sets the state for the Euler stepper.
func (euler *Euler) SetStep(step complex64) error {
	euler.stepSize = step
	return nil
}

// SetState sets the state for the Euler stepper.
func (euler *Euler) SetState(state []complex64) error {
	euler.system.stateVector = state
	return nil
}

// Set sets the step size and System for the Euler stepper.
func (euler *Euler) Set(stepSize complex64, system System) error {
	//if stepSize <= 0 {
	if real(stepSize) <= 0 && imag(stepSize) <= 0.0 {
		return &Error{"Can't use negative or null step size for Euler stepper."}
	} else {
		euler.stepSize = stepSize
		euler.system = system
		return nil
	}
}

// Getter methods

// StepSize returns the step size of the method
func (euler *Euler) StepSize() complex64 {
	return euler.stepSize
}

// State returns the state of the Euler stepper.
func (euler *Euler) State() []complex64 {
	return euler.system.stateVector
}

// Step performs one step iteration call of the Midpoint stepper.
// It also updates the state of the Midpoint object.
//
// The mid-point method for the system,
// 		y = f(t, y)
// Consists of building the sequence of numbers t_n, y_n,
// following the recurrence,
// 		t_n+1 = t_n + dt
// 		ya_n = y_n + 0.5*dt*f(t_n, y_n) // First step
//		y_n+1 = y_n + dt*f(t_n, ya_n)   // Second step
func (euler *Euler) Step() ([]complex64, error) {

	newstate := make([]complex64, len(euler.system.stateVector))

	for i := 0; i < len(euler.system.stateVector); i++ {
		newstate[i] = euler.system.stateVector[i] + euler.stepSize*euler.system.Evaluate(euler.system.stateVector)[i]
	}

	euler.system.stateVector = newstate

	return newstate, nil
}


text:
* One page presentation for student organization in Czech republic
* No PHP, everything is static (HTML, Javascript)
* We use MaterializeCSS - http://materializecss.com/

* Pull requests are welcome!


text:
#include "precomp.hpp"

using namespace cv;

CvEMParams::CvEMParams() : nclusters(10), cov_mat_type(CvEM::COV_MAT_DIAGONAL),
    start_step(CvEM::START_AUTO_STEP), probs(0), weights(0), means(0), covs(0)
{
    term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON );
}

CvEMParams::CvEMParams( int _nclusters, int _cov_mat_type, int _start_step,
                        CvTermCriteria _term_crit, const CvMat* _probs,
                        const CvMat* _weights, const CvMat* _means, const CvMat** _covs ) :
                        nclusters(_nclusters), cov_mat_type(_cov_mat_type), start_step(_start_step),
                        probs(_probs), weights(_weights), means(_means), covs(_covs), term_crit(_term_crit)
{}

CvEM::CvEM() : logLikelihood(DBL_MAX)
{
}

CvEM::CvEM( const CvMat* samples, const CvMat* sample_idx,
            CvEMParams params, CvMat* labels ) : logLikelihood(DBL_MAX)
{
    train(samples, sample_idx, params, labels);
}

CvEM::~CvEM()
{
    clear();
}

void CvEM::clear()
{
    emObj.clear();
}

void CvEM::read( CvFileStorage* fs, CvFileNode* node )
{
    FileNode fn(fs, node);
    emObj.read(fn);
    set_mat_hdrs();
}

void CvEM::write( CvFileStorage* _fs, const char* name ) const
{
    FileStorage fs = _fs;
    if(name)
        fs << name << "{";
    emObj.write(fs);
    if(name)
        fs << "}";
    fs.fs.obj = 0;
}

double CvEM::calcLikelihood( const Mat &input_sample ) const
{
    return emObj.predict(input_sample)[0];
}

float
CvEM::predict( const CvMat* _sample, CvMat* _probs ) const
{
    Mat prbs0 = cvarrToMat(_probs), prbs = prbs0, sample = cvarrToMat(_sample);
    int cls = static_cast<int>(emObj.predict(sample, _probs ? _OutputArray(prbs) : cv::noArray())[1]);
    if(_probs)
    {
        if( prbs.data != prbs0.data )
        {
            CV_Assert( prbs.size == prbs0.size );
            prbs.convertTo(prbs0, prbs0.type());
        }
    }
    return (float)cls;
}

void CvEM::set_mat_hdrs()
{
    if(emObj.isTrained())
    {
        meansHdr = emObj.get<Mat>("means");
        int K = emObj.get<int>("nclusters");
        covsHdrs.resize(K);
        covsPtrs.resize(K);
        const std::vector<Mat>& covs = emObj.get<vector<Mat> >("covs");
        for(size_t i = 0; i < covsHdrs.size(); i++)
        {
            covsHdrs[i] = covs[i];
            covsPtrs[i] = &covsHdrs[i];
        }
        weightsHdr = emObj.get<Mat>("weights");
        probsHdr = probs;
    }
}

static
void init_params(const CvEMParams& src,
                 Mat& prbs, Mat& weights,
                 Mat& means, vector<Mat>& covsHdrs)
{
    prbs = src.probs;
    weights = src.weights;
    means = src.means;

    if(src.covs)
    {
        covsHdrs.resize(src.nclusters);
        for(size_t i = 0; i < covsHdrs.size(); i++)
            covsHdrs[i] = src.covs[i];
    }
}

bool CvEM::train( const CvMat* _samples, const CvMat* _sample_idx,
                  CvEMParams _params, CvMat* _labels )
{
    CV_Assert(_sample_idx == 0);
    Mat samples = cvarrToMat(_samples), labels0, labels;
    if( _labels )
        labels0 = labels = cvarrToMat(_labels);

    bool isOk = train(samples, Mat(), _params, _labels ? &labels : 0);
    CV_Assert( labels0.data == labels.data );

    return isOk;
}

int CvEM::get_nclusters() const
{
    return emObj.get<int>("nclusters");
}

const CvMat* CvEM::get_means() const
{
    return emObj.isTrained() ? &meansHdr : 0;
}

const CvMat** CvEM::get_covs() const
{
    return emObj.isTrained() ? (const CvMat**)&covsPtrs[0] : 0;
}

const CvMat* CvEM::get_weights() const
{
    return emObj.isTrained() ? &weightsHdr : 0;
}

const CvMat* CvEM::get_probs() const
{
    return emObj.isTrained() ? &probsHdr : 0;
}

using namespace cv;

CvEM::CvEM( const Mat& samples, const Mat& sample_idx, CvEMParams params )
{
    train(samples, sample_idx, params, 0);
}

bool CvEM::train( const Mat& _samples, const Mat& _sample_idx,
                 CvEMParams _params, Mat* _labels )
{
    CV_Assert(_sample_idx.empty());
    Mat prbs, weights, means, logLikelihoods;
    std::vector<Mat> covshdrs;
    init_params(_params, prbs, weights, means, covshdrs);

    emObj = EM(_params.nclusters, _params.cov_mat_type, _params.term_crit);
    bool isOk = false;
    if( _params.start_step == EM::START_AUTO_STEP )
        isOk = emObj.train(_samples,
                           logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
    else if( _params.start_step == EM::START_E_STEP )
        isOk = emObj.trainE(_samples, means, covshdrs, weights,
                            logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
    else if( _params.start_step == EM::START_M_STEP )
        isOk = emObj.trainM(_samples, prbs,
                            logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
    else
        CV_Error(CV_StsBadArg, "Bad start type of EM algorithm");

    if(isOk)
    {
        logLikelihood = sum(logLikelihoods).val[0];
        set_mat_hdrs();
    }

    return isOk;
}

float
CvEM::predict( const Mat& _sample, Mat* _probs ) const
{
    return static_cast<float>(emObj.predict(_sample, _probs ? _OutputArray(*_probs) : cv::noArray())[1]);
}

int CvEM::getNClusters() const
{
    return emObj.get<int>("nclusters");
}

Mat CvEM::getMeans() const
{
    return emObj.get<Mat>("means");
}

void CvEM::getCovs(vector<Mat>& _covs) const
{
    _covs = emObj.get<vector<Mat> >("covs");
}

Mat CvEM::getWeights() const
{
    return emObj.get<Mat>("weights");
}

Mat CvEM::getProbs() const
{
    return probs;
}

/* End of file. */


text:
<?php

namespace DrSlump\Protobuf\Compiler\Command;

use DrSlump\Protobuf;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ProtocGenPhpCommand extends Command
{
    protected $isWin;

    protected function configure()
    {
        $this
        ->setDescription('Protobuf-PHP ' . Protobuf\Protobuf::VERSION . ' by Ivan -DrSlump- Montes')
        ->addOption(
            'out',
            'o',
            InputOption::VALUE_REQUIRED,
            'destination directory for generated files',
            './'
        )
        ->addOption(
            'include',
            'i',
            InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
            'define an include path (can be repeated)'
        )
        ->addOption(
            'json',
            'j',
            InputOption::VALUE_NONE,
            'turn on ProtoJson Javascript file generation'
        )
        ->addOption(
            'protoc',
            null,
            InputOption::VALUE_REQUIRED,
            'protoc compiler executable path',
            'protoc'
        )
        ->addOption(
            'skip-imported',
            null,
            InputOption::VALUE_NONE,
            'do not generate imported proto files'
        )
        ->addOption(
            'comments',
            null,
            InputOption::VALUE_NONE,
            'port .proto comments to generated code'
        )
        ->addOption(
            'insertions',
            null,
            InputOption::VALUE_NONE,
            'generate @@protoc insertion points'
        )
        ->addOption(
            'define',
            'D',
            InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
            'define a generator option (ie: -Dmultifile -Dsuffix=pb.php)'
        )
        ->addArgument(
            'protos',
            InputArgument::IS_ARRAY,
            'proto files'
        );
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->isWin = ('WIN' === strtoupper(substr(PHP_OS, 0, 3)));

        if (count($input->getArgument('protos'))) {
            if ($this->isWin) {
                $this->setName($this->getName() . '.bat');
            }
            return $this->executeProtoc($input, $output);
        // Attempt to compile data from stdin
        } else {
            return $this->executeCompile($input, $output);
        }
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function executeProtoc(InputInterface $input, OutputInterface $output)
    {
        $protocBin = $input->getOption('protoc');

        // Check if protoc is available
        exec("$protocBin --version", $out, $return);

        if (0 !== $return && 1 !== $return) {
            $output->writeln("<error>Unable to find the protoc command.");
            $output->writeln("       Please make sure it's installed and available in the path.</error>");
            return 1;
        }

        if (!preg_match('/[0-9\.]+/', $out[0], $m)) {
            $output->writeln("<error>Unable to get protoc command version.");
            $output->writeln("       Please make sure it's installed and available in the path.</error>");
            return 1;
        }

        if (version_compare($m[0], '2.3.0') < 0) {
            $output->writeln("<error>The protoc command in your system is too old.");
            $output->writeln("       Minimum version required is 2.3.0 but found {$m[0]}.</error>");
            return 1;
        }

        $cmd[] = $protocBin;
        $cmd[] = '--plugin=protoc-gen-php=' . escapeshellarg($this->getName());

        // Include paths
        $cmd[] = '--proto_path=' . escapeshellarg(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'protos');
        if ($input->hasOption('include')) {
            foreach($input->getOption('include') as $include) {
                $include = realpath($include);
                $cmd[] = '--proto_path=' . escapeshellarg($include);
            }
        }

        // Convert proto files to absolute paths
        $protos = array();
        foreach ($input->getArgument('protos') as $proto) {
            $realpath = realpath($proto);
            if (FALSE === $realpath) {
                $output->writeln("<error>: File '$proto' does not exist</error>");
                return 1;
            }

            $protos[] = $realpath;
        }

        // Protoc will pass custom arguments to the plugin if they are given
        // before a colon character. ie: --php_out="foo=bar:/path/to/plugin"
        // We make use of it to pass arguments encoded as an URI query string

        $args = array();
        if ($input->getOption('comments')) {
            $args['comments'] = 1;
            // Protos are only needed for comments right now
            $args['protos'] = $protos;
        }
        if ($input->getOption('verbose')) {
            $args['verbose'] = 1;
        }
        if ($input->getOption('json')) {
            $args['json'] = 1;
        }
        if ($input->getOption('skip-imported')) {
            $args['skip-imported'] = 1;
        }
        if (count($input->getOption('define'))) {
            $args['options'] = array();
            foreach($input->getOption('define') as $define) {
                $parts = explode('=', $define);
                $parts = array_filter(array_map('trim', $parts));
                if (count($parts) === 1) {
                    $parts[1] = 1;
                }
                $args['options'][$parts[0]] = $parts[1];
            }
        }
        if ($input->getOption('insertions')) {
            $args['options']['insertions'] = 1;
        }

        $cmd[] = '--php_out=' .
                 escapeshellarg(
                     http_build_query($args, '', '&') .
                     ':' .
                     $input->getOption('out')
                 );

        // Add the chosen proto files to generate
        foreach ($protos as $proto) {
            $cmd[] = escapeshellarg($proto);
        }

        $cmdStr = implode(' ', $cmd);

        $output->writeln("Generating protos with protoc -- $cmdStr");

        // Run command with stderr redirected to stdout
        exec($cmdStr . ' 2>&1', $stdout, $return);

        if ($return !== 0) {
            $output->writeln('<error>' . join("\n", $stdout) .'</error >');
            $output->writeln('');
            $output->writeln('<error>protoc exited with an error (' . $return . ') when executed with: </error>');
            $output->writeln('');
            $output->writeln('<error>  ' . implode(" \\\n    ", $cmd) . '</error>');
        } else {
            $output->writeln(join("\n", $stdout));
        }
        return $return;
    }

    /**
     * @return string
     */
    protected function getStdIn() {

        $stdin = '';

        // PHP doesn't implement non-blocking stdin on Windows
        // https://bugs.php.net/bug.php?id=34972
        if ($this->isWin) {
            // Open STDIN in non-blocking mode
            stream_set_blocking(STDIN, FALSE);

            // Loop until STDIN is closed or we've waited too long for data
            $cnt = 0;
            while (!feof(STDIN) && $cnt++ < 10) {
                // give protoc some time to feed the data
                usleep(10000);
                // read the bytes
                $bytes = fread(STDIN, 1024);
                if (strlen($bytes)) {
                    $cnt = 0;
                    $stdin .= $bytes;
                }
            }
        } else {
            $bytes = '';
            while (!feof(STDIN)) {
                $bytes .= fread(STDIN, 8192);
            }

            $stdin = $bytes;
        }

        return $stdin;
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function executeCompile(InputInterface $input, OutputInterface $output) {
        try {
            // Create a compiler interface
            $comp = new Protobuf\Compiler();

            echo $comp->compile($this->getStdIn());
            return 0;
        } catch(\Exception $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');
            $output->writeln('<error>' . $e->getTraceAsString() . '<error>');

            return 255;
        }
    }
}


text:
from __future__ import absolute_import, print_function

import os
import tempfile
import glob

from distutils.errors import DistutilsFileError
import distutils.file_util

from numpy.testing import dec

from scipy.weave import catalog

def slow(t):
    """Replacement for numpy.testing.dec.slow for weave."""
    t.slow = True
    if ('RUN_WEAVE_TESTS' in os.environ and
                bool(os.environ['RUN_WEAVE_TESTS'])):
        t.__test__ = True
    else:
        t.__test__ = False

    return t

dec.slow = slow

def remove_whitespace(in_str):
    out = in_str.replace(" ","")
    out = out.replace("\t","")
    out = out.replace("\n","")
    return out

###################################################
# mainly used by catalog tests
###################################################

def temp_catalog_files(prefix=''):
    # might need to add some more platform specific catalog file
    # suffixes to remove.  The .pag was recently added for SunOS
    d = catalog.default_dir()
    f = catalog.os_dependent_catalog_name()
    return glob.glob(os.path.join(d,prefix+f+'*'))

def clear_temp_catalog():
    """Remove any catalog from the temp dir."""
    backup_dir = tempfile.mkdtemp()
    for file in temp_catalog_files():
        move_file(file,backup_dir)

    return backup_dir

def restore_temp_catalog(backup_dir):
    """Remove any catalog from the temp dir"""
    cat_dir = catalog.default_dir()
    for file in os.listdir(backup_dir):
        file = os.path.join(backup_dir,file)
        d,f = os.path.split(file)
        dst_file = os.path.join(cat_dir, f)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        move_file(file,dst_file)

    os.rmdir(backup_dir)

def empty_temp_dir():
    """Create a sub directory in the temp directory for use in tests"""
    d = catalog.default_dir()
    for i in range(10000):
        new_d = os.path.join(d,tempfile.gettempprefix()[1:-1]+repr(i))
        if not os.path.exists(new_d):
            os.mkdir(new_d)
            break
    return new_d

def cleanup_temp_dir(d):
    """Remove a directory created by empty_temp_dir().

    This should probably catch some errors.

    """
    files = map(lambda x,d=d: os.path.join(d,x),os.listdir(d))
    for i in files:
        try:
            if os.path.isdir(i):
                cleanup_temp_dir(i)
            else:
                os.remove(i)
        except OSError:
            # failed to remove file for whatever reason (maybe it is a DLL
            # Python is currently using)
            pass
    try:
        os.rmdir(d)
    except OSError:
        pass

class TempdirBlitz():
    """A context manager to create a tempdir and make blitz() use it.

    Also cleans up the tempdir on exit.  Usage::

        with TempdirBlitz():
            weave.blitz(expr)

    When using blitz without this contextmanager, it tends to litter .so and
    .cpp files all over the dir from which tests are run.

    """
    def __init__(self):
        self._entered = False

    def __enter__(self):
        self._entered = True
        self.module_location = empty_temp_dir()
        self._old_env = os.environ.get('PYTHONCOMPILED', None)
        os.environ['PYTHONCOMPILED'] = self.module_location

    def __exit__(self, *exc_info):
        if not self._entered:
            raise RuntimeError("Cannot exit %r without entering first" % self)

        if self._old_env is None:
            os.environ.pop('PYTHONCOMPILED')
        else:
            os.environ['PYTHONCOMPILED'] = self._old_env

        cleanup_temp_dir(self.module_location)

# from distutils -- old versions had bug, so copying here to make sure
# a working version is available.
def move_file(src, dst,
               verbose=0,
               dry_run=0):
    """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
    be moved into it with the same name; otherwise, 'src' is just renamed
    to 'dst'.  Return the new full name of the file.

    Handles cross-device moves on Unix using 'copy_file()'.  What about
    other systems???
    """
    from os.path import exists, isfile, isdir, basename, dirname
    import errno

    if verbose:
        print("moving %s -> %s" % (src, dst))

    if dry_run:
        return dst

    if not isfile(src):
        raise DistutilsFileError("can't move '%s': not a regular file" % src)

    if isdir(dst):
        dst = os.path.join(dst, basename(src))
    elif exists(dst):
        raise DistutilsFileError("can't move '%s': destination '%s' already "
                                    "exists" % (src, dst))

    if not isdir(dirname(dst)):
        raise DistutilsFileError("can't move '%s': destination '%s' not a "
                                    "valid path" % (src, dst))

    copy_it = 0
    try:
        os.rename(src, dst)
    except os.error as xxx_todo_changeme1:
        (num, msg) = xxx_todo_changeme1.args
        if num == errno.EXDEV:
            copy_it = 1
        else:
            raise DistutilsFileError("couldn't move '%s' to '%s': %s" %
                                        (src, dst, msg))

    if copy_it:
        distutils.file_util.copy_file(src, dst)
        try:
            os.unlink(src)
        except os.error as xxx_todo_changeme:
            (num, msg) = xxx_todo_changeme.args
            try:
                os.unlink(dst)
            except os.error:
                pass
            raise DistutilsFileError("couldn't move '%s' to '%s' by copy/delete: "
                            "delete '%s' failed: %s" % (src, dst, src, msg))

    return dst

def debug_print(*arg):
    # Set to true to enable printing debug / benchmark info when running
    # these tests
    WEAVE_DEBUG = False
    if WEAVE_DEBUG:
        print(*arg)


text:
// -*- c++ -*-

/* $Id$ */

/* Copyright (C) 2002 The gtkmm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <glibmm/utility.h>

void Glib::append_canonical_typename(std::string& dest, const char* type_name)
{
  const std::string::size_type offset = dest.size();
  dest += type_name;

  std::string::iterator p = dest.begin() + offset;
  const std::string::iterator pend = dest.end();

  for(; p != pend; ++p)
  {
    if(!(g_ascii_isalnum(*p) || *p == '_' || *p == '-'))
      *p = '+';
  }
}


text:
var _taskname='[article] ';
var _ = require('underscore');

exports.task = function(task, done) {
  console.log(_taskname + "inside fetching articles for feed:"+task.input);
  // lets say we got these random # of articles
  var n = task.id.lastIndexOf('#');
  var subtaskid = n>0?(task.id.slice(n+1)+'.'):'';
  _.each(_.range(Math.floor(Math.random()*10+1)), function(id) {
    task.output.push({id:subtaskid+id, input:'article #'+id});
  });
  console.log(_taskname+ 'Following articles to be fetched:');
  console.log(task.output);
  done();
};


text:
.. image:: http://nikolaskama.me/content/images/2017/02/kickthemout_small.png

KickThemOut
============

`KickThemOut <https://nikolaskama.me/kickthemoutproject/>`_ - **Kick Devices Off Your Network**

A tool to kick devices out of your network and enjoy all the bandwidth for yourself.
It allows you to select specific or all devices and ARP spoofs them off your local area network.

Compatible with Python 2.6 & 2.7.

Authors: `Nikolaos Kamarinakis <mailto:nikolaskam@gmail.com>`_  & `David Schütz <mailto:xdavid@protonmail.com>`_.

.. image:: https://travis-ci.org/k4m4/kickthemout.svg?branch=master
    :target: https://travis-ci.org/k4m4/kickthemout
.. image:: https://img.shields.io/badge/license-MIT-blue.svg
    :target: https://github.com/k4m4/kickthemout/blob/master/LICENSE
.. image:: https://img.shields.io/badge/made%20with-%3C3-red.svg
    :target: https://nikolaskama.me/kickthemoutproject
.. image:: https://img.shields.io/github/stars/k4m4/kickthemout.svg
    :target: https://github.com/k4m4/kickthemout/stargazers

-------------

Debian Installation
----------------------

You can download KickThemOut by cloning the `Git Repo <https://github.com/k4m4/kickthemout>`_ and simply installing its requirements::

    $ sudo apt-get update && sudo apt-get install nmap

    $ git clone https://github.com/k4m4/kickthemout.git

    $ cd kickthemout/

    $ sudo python -m pip install -r requirements.txt

MacOS Installation
----------------------

If you would like to install KickThemOut on a Mac, please run the following::

    $ sudo python -m pip install pcapy

    $ brew install libdnet scapy nmap

**Keep in mind** that you might be asked to run some commands after executing the previous step. Moving on::

    $ git clone https://github.com/k4m4/kickthemout.git

    $ cd kickthemout/

    $ sudo python -m pip install -r requirements.txt

**NOTE**: You need to have `Homebrew <http://brew.sh/>`_ installed before running the Mac OS installation.

Demo
-----

Here's a short demo:

.. image:: https://nikolaskama.me/content/images/2017/01/kickthemout_asciinema.png
   :target: https://asciinema.org/a/98200?autoplay=1&loop=1

(For more demos click `here <https://asciinema.org/~k4m4>`_.)

Developers
-----------

* Nikolaos Kamarinakis - `@nikolaskama <https://twitter.com/nikolaskama>`_
* David Schütz - `@xdavidhu <https://twitter.com/xdavidhu>`_

Disclaimer
-----------

KickThemOut is provided as is under the MIT Licence (as stated below).
It is built for educational purposes only. If you choose to use it otherwise, the developers will not be held responsible.
In brief, do not use it with evil intent.

License
--------

Copyright (c) 2017 by `Nikolaos Kamarinakis <mailto:nikolaskam@gmail.com>`_ & `David Schütz <mailto:xdavid@protonmail.com>`_. Some rights reserved.

KickThemOut is under the terms of the `MIT License <https://www.tldrlegal.com/l/mit>`_, following all clarifications stated in the `license file <https://raw.githubusercontent.com/k4m4/kickthemout/master/LICENSE>`_.

For more information head over to the `official project page <https://nikolaskama.me/kickthemoutproject/>`_.
You can also go ahead and email me anytime at **nikolaskam{at}gmail{dot}com** or David at **xdavid{at}protonmail{dot}com**.


text:
require_relative '../c7000/storage_pool'

module OneviewSDK
  module API600
    module Synergy
      # Storage pool resource implementation for API 600 Synergy
      class StoragePool < OneviewSDK::API600::C7000::StoragePool
      end
    end
  end
end


text:
namespace MumbleSharp
{
    /// <summary>
    /// Indicates the state of a conection to a mumble server
    /// </summary>
    public enum ConnectionStates
    {
        Disconnecting,
        Disconnected,

        Connecting,
        Connected
    }
}


text:
import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {isLoaded as isInfoLoaded} from '../reducers/info';
import {isLoaded as isAuthLoaded} from '../reducers/auth';
import {load as loadInfo} from '../actions/infoActions';
import * as authActions from '../actions/authActions';
import {load as loadAuth} from '../actions/authActions';
import {createTransitionHook} from '../universalRouter';
import {requireServerCss} from '../util';

const styles = __CLIENT__ ? require('./App.scss') : requireServerCss(require.resolve('./App.scss'));

class App extends Component {
  static propTypes = {
    user: PropTypes.object,
    logout: PropTypes.func
  }

  static contextTypes = {
    router: PropTypes.object.isRequired,
    store: PropTypes.object.isRequired
  };

  componentWillMount() {
    const {router, store} = this.context;
    this.transitionHook = createTransitionHook(store);
    router.addTransitionHook(this.transitionHook);
  }

  componentWillUnmount() {
    const {router, store} = this.context;
    router.removeTransitionHook(this.transitionHook);
  }

  handleLogout(event) {
    event.preventDefault();
    this.props.logout();
  }

  render() {
    const {user} = this.props;
    return (
      <div className={styles.app}>
          {this.props.children}
      </div>
    );
  }
}

@connect(state => ({
  user: state.auth.user
}))
export default
class AppContainer {
  static propTypes = {
    user: PropTypes.object,
    dispatch: PropTypes.func.isRequired
  }

  static fetchData(store) {
    const promises = [];
    if (!isInfoLoaded(store.getState())) {
      promises.push(store.dispatch(loadInfo()));
    }
    if (!isAuthLoaded(store.getState())) {
      promises.push(store.dispatch(loadAuth()));
    }
    return Promise.all(promises);
  }

  render() {
    const { user, dispatch } = this.props;
    return <App user={user} {...bindActionCreators(authActions, dispatch)}>
      {this.props.children}
    </App>;
  }
}


text:
var Util = require("../../util");

function list (options, callback) {
    var self = this;

    var url = Util.createUrl.apply(self, ["subscriptions", options]);
    var reqOptions = {
        url: url,
    };

    self.Client.request(reqOptions, callback);
}

function insert (options, callback) {

    // get self
    var self = this

        // create the request url
      , url = Util.createUrl.apply(self, ["subscriptions", {
            part:   options.part,
            fields: options.fields
        }])

        // create the request options
      , reqOptions = {
           uri: url,
           method: "POST",
           json: options.requestBody
       };

    // submit request and callback
    self.Client.request(reqOptions, callback);
}

function deleteItem (options, callback) {

    // get self
    var self = this

        // create the request url
      , url = Util.createUrl.apply(self, ["subscriptions", {
            id:   options.id
        }])

        // create the request options
      , reqOptions = {
           uri: url,
           method: "DELETE"
       };

    // submit request and callback
    self.Client.request(reqOptions, callback);
}

module.exports = {
    list: list,
    insert: insert,
    delete: deleteItem
};


text:
package org.bouncycastle.openpgp.test;

import java.security.Security;
import java.util.Enumeration;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import org.bouncycastle.PrintTestResult;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.test.SimpleTestResult;

public class AllTests
    extends TestCase
{
    public void testPGP()
    {
        Security.addProvider(new BouncyCastleProvider());

        org.bouncycastle.util.test.Test[] tests = RegressionTest.tests;

        for (int i = 0; i != tests.length; i++)
        {
            SimpleTestResult  result = (SimpleTestResult)tests[i].perform();

            if (!result.isSuccessful())
            {
                fail(result.toString());
            }
        }
    }

    public static void main (String[] args)
    {
        PrintTestResult.printResult( junit.textui.TestRunner.run(suite()));
    }

    public static Test suite()
    {
        TestSuite suite = new TestSuite("OpenPGP Tests");

        suite.addTestSuite(AllTests.class);
        suite.addTestSuite(DSA2Test.class);
        suite.addTestSuite(PGPUnicodeTest.class);

        return new BCTestSetup(suite);
    }

    static class BCTestSetup
        extends TestSetup
    {
        public BCTestSetup(Test test)
        {
            super(test);
        }

        protected void setUp()
        {
            Security.addProvider(new BouncyCastleProvider());
        }

        protected void tearDown()
        {
            Security.removeProvider("BC");
        }
    }
}


text:
[![Build Status](https://travis-ci.org/blablacar/redis-client.png)](https://travis-ci.org/blablacar/redis-client)

This library provides a simple Redis connection wrapper.

## Installation

The recommended way to install this library is through
[Composer](http://getcomposer.org/). Require the `blablacar/redis-client` package
into your `composer.json` file:

```json
{
    "require": {
        "blablacar/redis-client": "@stable"
    }
}
```

**Protip:** you should browse the
[`blablacar/redis-client`](https://packagist.org/packages/blablacar/redis-client)
page to choose a stable version to use, avoid the `@stable` meta constraint.

## Usage

Create a Client and you're done!

```php
$client = new \Blablacar\Redis\Client('127.0.0.1', 6379); // Default values
$client->set('foobar', 42); // Return 1
```

For more information about Redis extension see the
[nicolasff/phpredis](https://github.com/nicolasff/phpredis).

## License

Blablacar Redis client is released under the MIT License. See the bundled
LICENSE file for details.


text:
import React from 'react';
import styled, { keyframes } from 'styled-components';

import Layout from 'components/layout';

import Headers from 'molecules/headers';

import Information from 'molecules/information-section';
import CareerSummary from 'molecules/career-summary-section';
import SkillSet from 'molecules/skill-set-section';
import Interests from 'molecules/interests-section';
import CareerHistory from 'organisms/career-history-section';
import Projects from 'organisms/projects-section';
import Education from 'organisms/education-section';

import PrintStyles from 'styles/print';
import { MainContextProvider } from 'src/contexts/main';

const slideInBckCenter = keyframes`
  0% {
    transform: translateZ(600px);
    opacity: 0;
  }
  100% {
    transform: translateZ(0);
    opacity: 1;
  }
`;

const CV = styled.main`
  max-width: 79.8rem;
  width: 100%;

  padding: 0 1.6rem;
  margin: 0 auto;

  animation: ${slideInBckCenter} 0.7s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;

  @media print {
    margin: 0;
    padding: 0;
    max-width: 100%;
  }
`;

const IndexPage = () => {
  return (
    <Layout>
      <MainContextProvider>
        <Headers />
        <PrintStyles />
        <CV>
          <Information />
          <CareerSummary />
          <SkillSet />
          <CareerHistory />
          <Projects />
          <Education />
          <Interests />
        </CV>
      </MainContextProvider>
    </Layout>
  );
};

export default IndexPage;


text:
import net from 'net';
import { Inbound, Outbound } from './defs';
import { DNSCache, logger } from '../utils';
import {
  ACL_PAUSE_RECV,
  ACL_PAUSE_SEND,
  ACL_RESUME_RECV,
  ACL_RESUME_SEND,
} from '../core/acl';

const MAX_BUFFERED_SIZE = 512 * 1024; // 512KB

export class TcpInbound extends Inbound {

  _socket = null;

  constructor(props) {
    super(props);
    this._socket = this._conn;
    this._socket.on('error', this.onError);
    this._socket.on('data', this.onReceive);
    this._socket.on('drain', this.onDrain);
    this._socket.on('timeout', this.onTimeout);
    this._socket.on('end', this.onHalfClose);
    this._socket.on('close', this.onClose);
    this._socket.setNoDelay(true);
    this._socket.setKeepAlive(true);
    this._socket.setTimeout(this._config.timeout);
  }

  get name() {
    return 'tcp:inbound';
  }

  get bufferSize() {
    return this._socket ? this._socket.bufferSize : 0;
  }

  get writable() {
    return this._socket && !this._socket.destroyed && this._socket.writable;
  }

  write(buffer) {
    if (this.writable) {
      this._socket.write(buffer);
    }
  }

  onError = (err) => {
    logger.warn(`[${this.name}] [${this.remote}] ${err.message}`);
    this.emit('_error', err);
  };

  onReceive = (buffer) => {
    this.emit('data', buffer);
    // throttle receiving data to reduce memory grow:
    // https://github.com/blinksocks/blinksocks/issues/60
    // https://nodejs.org/dist/latest/docs/api/net.html#net_socket_buffersize
    const outbound = this.getOutbound();
    if (outbound && outbound.bufferSize > MAX_BUFFERED_SIZE) {
      logger.debug(`[${this.name}] [${this.remote}] recv paused due to inbound.bufferSize=${outbound.bufferSize} >= ${MAX_BUFFERED_SIZE}`);
      this.pause();
      outbound.once('drain', () => {
        logger.debug(`[${this.name}] [${this.remote}] resume to recv`);
        this.resume();
      });
    }
  };

  onDrain = () => {
    this.emit('drain');
  };

  onTimeout = () => {
    logger.warn(`[${this.name}] [${this.remote}] timeout: no I/O on the connection for ${this._config.timeout / 1e3}s`);
    this.onClose();
  };

  onHalfClose = () => {
    const outbound = this.getOutbound();
    if (outbound && outbound.end) {
      outbound.end();
    }
  };

  onClose = () => {
    this.close();
    const outbound = this.getOutbound();
    if (outbound && outbound.close) {
      outbound.close();
      this.setOutbound(null);
    }
  };

  pause() {
    if (this._socket && !this._socket.destroyed) {
      this._socket.pause();
    }
  }

  resume() {
    if (this._socket && !this._socket.destroyed) {
      this._socket.resume();
    }
  }

  end() {
    this._socket && this._socket.end();
  }

  close() {
    const doClose = () => {
      if (this._socket) {
        this._socket.destroy();
        this._socket = null;
      }
      if (!this._destroyed) {
        this._destroyed = true;
        this.emit('close');
      }
    };
    if (this.bufferSize > 0) {
      this.once('drain', doClose);
    } else {
      doClose();
    }
  }

  onBroadcast(action) {
    switch (action.type) {
      case ACL_PAUSE_RECV:
        this.pause();
        break;
      case ACL_RESUME_RECV:
        this.resume();
        break;
      default:
        break;
    }
  }

}

export class TcpOutbound extends Outbound {

  _socket = null;

  get name() {
    return 'tcp:outbound';
  }

  get bufferSize() {
    return this._socket ? this._socket.bufferSize : 0;
  }

  get writable() {
    return this._socket && !this._socket.destroyed && this._socket.writable;
  }

  write(buffer) {
    if (this.writable) {
      this._socket.write(buffer);
    }
  }

  onError = (err) => {
    logger.warn(`[${this.name}] [${this.remote}] ${err.message}`);
    this.emit('_error', err);
  };

  onReceive = (buffer) => {
    this.emit('data', buffer);
    // throttle receiving data to reduce memory grow:
    // https://github.com/blinksocks/blinksocks/issues/60
    // https://nodejs.org/dist/latest/docs/api/net.html#net_socket_buffersize
    const inbound = this.getInbound();
    if (inbound && inbound.bufferSize > MAX_BUFFERED_SIZE) {
      logger.debug(`[${this.name}] [${this.remote}] recv paused due to inbound.bufferSize=${inbound.bufferSize} >= ${MAX_BUFFERED_SIZE}`);
      this.pause();
      inbound.once('drain', () => {
        logger.debug(`[${this.name}] [${this.remote}] resume to recv`);
        this.resume();
      });
    }
  };

  onDrain = () => {
    this.emit('drain');
  };

  onTimeout = () => {
    logger.warn(`[${this.name}] [${this.remote}] timeout: no I/O on the connection for ${this._config.timeout / 1e3}s`);
    this.onClose();
  };

  onHalfClose = () => {
    const inbound = this.getInbound();
    if (inbound && inbound.end) {
      inbound.end();
    }
  };

  onClose = () => {
    this.close();
    const inbound = this.getInbound();
    if (inbound && inbound.close) {
      inbound.close();
      this.setInbound(null);
    }
  };

  pause() {
    if (this._socket && !this._socket.destroyed) {
      this._socket.pause();
    }
  }

  resume() {
    if (this._socket && !this._socket.destroyed) {
      this._socket.resume();
    }
  }

  end() {
    this._socket && this._socket.end();
  }

  close() {
    const doClose = () => {
      if (this._socket) {
        this._socket.destroy();
        this._socket = null;
      }
      if (!this._destroyed) {
        this._destroyed = true;
        this.emit('close');
      }
    };
    if (this.bufferSize > 0) {
      this.once('drain', doClose);
    } else {
      doClose();
    }
  }

  onBroadcast(action) {
    switch (action.type) {
      case ACL_PAUSE_SEND:
        this.pause();
        break;
      case ACL_RESUME_SEND:
        this.resume();
        break;
      default:
        break;
    }
  }

  async connect(host, port, force = false) {
    return new Promise(async (resolve) => {
      if (!this._socket || force) {
        let targetHost, targetPort;
        try {
          const { is_server, server_host, server_port, server_pathname } = this._config;
          if (is_server) {
            targetHost = host;
            targetPort = port;
          } else {
            targetHost = server_host;
            targetPort = server_port;
          }
          // close alive connection before create a new one
          if (this._socket && !this._socket.destroyed) {
            this._socket.destroy();
            this._socket.removeAllListeners();
          }
          this._socket = await this._connect({ host: targetHost, port: targetPort, pathname: server_pathname });
          this._socket.on('connect', resolve);
          this._socket.on('error', this.onError);
          this._socket.on('end', this.onHalfClose);
          this._socket.on('close', this.onClose);
          this._socket.on('timeout', this.onTimeout);
          this._socket.on('data', this.onReceive);
          this._socket.on('drain', this.onDrain);
          this._socket.setNoDelay(true);
          this._socket.setKeepAlive(true);
          this._socket.setTimeout(this._config.timeout);
        } catch (err) {
          logger.error(`[${this.name}] [${this.remote}] cannot connect to ${targetHost}:${targetPort}, ${err.message}`);
          this.emit('_error', err);
          this.onClose();
        }
      } else {
        resolve();
      }
    });
  }

  async _connect({ host, port }) {
    const ip = await DNSCache.get(host);
    logger.info(`[${this.name}] [${this.remote}] connecting to tcp://${host}:${port}` + (net.isIP(host) ? '' : ` resolved=${ip}`));
    return net.connect({ host: ip, port });
  }

}


text:
require File.expand_path("helper", File.dirname(__FILE__))
require "lint/hyper_log_log"

class TestCommandsOnHyperLogLog < Test::Unit::TestCase

  include Helper::Client
  include Lint::HyperLogLog

  def test_pfmerge
    target_version "2.8.9" do
      r.pfadd "foo", "s1"
      r.pfadd "bar", "s2"

      assert_equal true, r.pfmerge("res", "foo", "bar")
      assert_equal 2, r.pfcount("res")
    end
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="com.b2international.snowowl.server.console.RemoteJobsCommandProvider">
   <implementation class="com.b2international.snowowl.server.console.RemoteJobsCommandProvider"/>
   <service>
      <provide interface="org.eclipse.osgi.framework.console.CommandProvider"/>
   </service>
</scr:component>


text:
class PreviousExamScore < ApplicationRecord
  belongs_to :student
  belongs_to :exam
  belongs_to :grading_level
end


text:
package com.braintreepayments.api;

import static android.app.Activity.RESULT_OK;
import static com.braintreepayments.api.BraintreeRequestCodes.THREE_D_SECURE;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isNull;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.Intent;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.ActivityResultRegistry;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;

import com.cardinalcommerce.cardinalmobilesdk.models.CardinalActionCode;
import com.cardinalcommerce.cardinalmobilesdk.models.ValidateResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public class ThreeDSecureV2UnitTest {

    private FragmentActivity activity;
    private ThreeDSecureV1BrowserSwitchHelper browserSwitchHelper;
    private ThreeDSecureListener listener;
    private Lifecycle lifecycle;

    private Configuration threeDSecureEnabledConfig;
    private ThreeDSecureRequest basicRequest;

    @Before
    public void setup() {
        activity = mock(FragmentActivity.class);
        browserSwitchHelper = mock(ThreeDSecureV1BrowserSwitchHelper.class);
        listener = mock(ThreeDSecureListener.class);

        threeDSecureEnabledConfig = new TestConfigurationBuilder()
                .threeDSecureEnabled(true)
                .cardinalAuthenticationJWT("cardinal_authentication_jwt")
                .buildConfiguration();

        ThreeDSecureV2TextBoxCustomization textBoxCustomization = new ThreeDSecureV2TextBoxCustomization();
        textBoxCustomization.setBorderWidth(12);

        ThreeDSecureV2UiCustomization v2UiCustomization = new ThreeDSecureV2UiCustomization();
        v2UiCustomization.setTextBoxCustomization(textBoxCustomization);

        basicRequest = new ThreeDSecureRequest();
        basicRequest.setNonce("a-nonce");
        basicRequest.setAmount("1.00");
        basicRequest.setVersionRequested(ThreeDSecureRequest.VERSION_2);
        basicRequest.setV2UiCustomization(v2UiCustomization);

        ActivityResultRegistry resultRegistry = mock(ActivityResultRegistry.class);
        when(activity.getActivityResultRegistry()).thenReturn(resultRegistry);

        lifecycle = mock(Lifecycle.class);
        when(activity.getLifecycle()).thenReturn(lifecycle);
    }

    @Test
    public void prepareLookup_returnsValidLookupJSONString() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("fake-df")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();

        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);

        ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class);
        sut.prepareLookup(activity, basicRequest, callback);

        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
        verify(callback).onResult(same(basicRequest), captor.capture(), (Exception) isNull());

        String clientData = captor.getValue();
        JSONObject lookup = new JSONObject(clientData);
        assertEquals("encoded_auth_fingerprint", lookup.getString("authorizationFingerprint"));
        assertEquals(lookup.getString("braintreeLibraryVersion"), "Android-" + BuildConfig.VERSION_NAME);
        assertEquals(lookup.getString("dfReferenceId"), "fake-df");
        assertEquals(lookup.getString("nonce"), "a-nonce");

        JSONObject clientMetaData = lookup.getJSONObject("clientMetadata");
        assertEquals(clientMetaData.getString("requestedThreeDSecureVersion"), "2");
        assertEquals(clientMetaData.getString("sdkVersion"), "Android/" + BuildConfig.VERSION_NAME);
    }

    @Test
    public void prepareLookup_returnsValidLookupJSONString_whenCardinalSetupFails() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .error(new Exception("cardinal error"))
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();

        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class);
        sut.prepareLookup(activity, basicRequest, callback);

        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
        verify(callback).onResult(same(basicRequest), captor.capture(), (Exception) isNull());

        String clientData = captor.getValue();
        JSONObject lookup = new JSONObject(clientData);
        assertEquals("encoded_auth_fingerprint", lookup.getString("authorizationFingerprint"));
        assertEquals(lookup.getString("braintreeLibraryVersion"), "Android-" + BuildConfig.VERSION_NAME);
        assertEquals(lookup.getString("nonce"), "a-nonce");
        assertFalse(lookup.has("dfReferenceId"));

        JSONObject clientMetaData = lookup.getJSONObject("clientMetadata");
        assertEquals(clientMetaData.getString("requestedThreeDSecureVersion"), "2");
        assertEquals(clientMetaData.getString("sdkVersion"), "Android/" + BuildConfig.VERSION_NAME);
    }

    @Test
    public void prepareLookup_initializesCardinal() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("fake-df")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class);
        sut.prepareLookup(activity, basicRequest, callback);

        verify(cardinalClient).initialize(same(activity), same(threeDSecureEnabledConfig), same(basicRequest), any(CardinalInitializeCallback.class));
    }

    @Test
    public void prepareLookup_withoutCardinalJWT_postsException() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();
        Configuration configuration = new TestConfigurationBuilder()
                .threeDSecureEnabled(true)
                .buildConfiguration();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(configuration)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class);
        sut.prepareLookup(activity, basicRequest, callback);

        ArgumentCaptor<Exception> captor = ArgumentCaptor.forClass(Exception.class);
        verify(callback).onResult((ThreeDSecureRequest) isNull(), (String) isNull(), captor.capture());

        assertTrue(captor.getValue() instanceof BraintreeException);
        assertEquals(captor.getValue().getMessage(), "Merchant is not configured for 3DS 2.0. " +
                "Please contact Braintree Support for assistance.");
    }

    @Test
    public void performVerification_initializesCardinal() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("df-reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);
        sut.performVerification(activity, basicRequest, mock(ThreeDSecureResultCallback.class));

        verify(cardinalClient).initialize(same(activity), same(threeDSecureEnabledConfig), same(basicRequest), any(CardinalInitializeCallback.class));
    }

    @Test
    public void performVerification_whenCardinalSetupCompleted_sendsAnalyticEvent() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("df-reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);
        sut.performVerification(activity, basicRequest, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.cardinal-sdk.init.setup-completed");
    }

    @Test
    public void performVerification_whenCardinalSetupFailed_sendsAnalyticEvent() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .error(new Exception("cardinal error"))
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);
        sut.performVerification(activity, basicRequest, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.cardinal-sdk.init.setup-failed");
    }

    @Test
    public void continuePerformVerification_whenAuthenticatingWithCardinal_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);
        sut.addObserver(activity, lifecycle);
        sut.observer.activityLauncher = mock(ActivityResultLauncher.class);

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);
        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult);

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.started");
    }

    @Test
    public void continuePerformVerification_whenChallengeIsPresented_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .returnUrlScheme("sample-return-url://")
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);
        when(browserSwitchHelper.getUrl(anyString(), anyString(), any(ThreeDSecureRequest.class), any(ThreeDSecureLookup.class))).thenReturn("https://example.com");

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_LOOKUP_RESPONSE);
        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult);

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.challenge-presented.true");
    }

    @Test
    public void continuePerformVerification_whenChallengeIsNotPresented_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_LOOKUP_RESPONSE_NO_ACS_URL);
        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult);

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.challenge-presented.false");
    }

    @Test
    public void continuePerformVerification_whenChallengeIsNotPresented_returnsResult() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_LOOKUP_RESPONSE_NO_ACS_URL);
        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult);

        verify(listener).onThreeDSecureSuccess(threeDSecureResult);
    }

    @Test
    public void continuePerformVerification_when3DSVersionIsVersion2_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);
        sut.addObserver(activity, lifecycle);
        sut.observer.activityLauncher = mock(ActivityResultLauncher.class);

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);
        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult);

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.3ds-version.2.1.0");
    }

    @Test
    public void continuePerformVerification_whenObserverIsNull_startsActivity() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder()
                .successReferenceId("reference-id")
                .build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(threeDSecureEnabledConfig)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(null, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);

        sut.continuePerformVerification(activity, basicRequest, threeDSecureResult, mock(ThreeDSecureResultCallback.class));

        verify(activity).startActivityForResult(any(Intent.class), any(Integer.class));
    }

    @Test
    public void performVerification_withoutCardinalJWT_postsException() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        Configuration configuration = new TestConfigurationBuilder()
                .threeDSecureEnabled(true)
                .buildConfiguration();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder()
                .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN))
                .configuration(configuration)
                .build();
        when(braintreeClient.canPerformBrowserSwitch(activity, THREE_D_SECURE)).thenReturn(true);

        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));
        sut.setListener(listener);

        ThreeDSecureResultCallback callback = mock(ThreeDSecureResultCallback.class);
        sut.performVerification(activity, basicRequest, callback);

        ArgumentCaptor<Exception> captor = ArgumentCaptor.forClass(Exception.class);
        verify(callback).onResult((ThreeDSecureResult) isNull(), captor.capture());
        assertTrue(captor.getValue() instanceof BraintreeException);
        assertEquals(captor.getValue().getMessage(), "Merchant is not configured for 3DS 2.0. " +
                "Please contact Braintree Support for assistance.");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationReportsSuccess_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();
        ThreeDSecureAPI threeDSecureAPI = mock(ThreeDSecureAPI.class);

        final ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) {
                ThreeDSecureResultCallback callback = (ThreeDSecureResultCallback) invocation.getArguments()[2];
                callback.onResult(threeDSecureResult, null);
                return null;
            }
        }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureResult.class), (String) isNull(), any(ThreeDSecureResultCallback.class));

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, threeDSecureAPI);

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.SUCCESS);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);
        data.putExtra(ThreeDSecureActivity.EXTRA_THREE_D_SECURE_RESULT, threeDSecureResult);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.cardinal-sdk.action-code.success");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.liability-shifted.true");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.liability-shift-possible.true");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.completed");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationReportsSuccess_whenResultWithError_sendsAnalytics() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();
        ThreeDSecureAPI threeDSecureAPI = mock(ThreeDSecureAPI.class);

        final ThreeDSecureResult threeDSecureResult = mock(ThreeDSecureResult.class);
        when(threeDSecureResult.hasError()).thenReturn(true);
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) {
                ThreeDSecureResultCallback callback = (ThreeDSecureResultCallback) invocation.getArguments()[2];
                callback.onResult(threeDSecureResult, null);
                return null;
            }
        }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureResult.class), (String) isNull(), any(ThreeDSecureResultCallback.class));

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, threeDSecureAPI);

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.SUCCESS);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);
        data.putExtra(ThreeDSecureActivity.EXTRA_THREE_D_SECURE_RESULT, threeDSecureResult);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        braintreeClient.sendAnalyticsEvent("three-d-secure.verification-flow.upgrade-payment-method.failure.returned-lookup-nonce");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.completed");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationReportsSuccess_whenAuthenticateJWTReturnsError_sendsAnalytics() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();
        ThreeDSecureAPI threeDSecureAPI = mock(ThreeDSecureAPI.class);

        final ThreeDSecureResult threeDSecureResult = mock(ThreeDSecureResult.class);
        final Exception exception = new Exception("error");

        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) {
                ThreeDSecureResultCallback callback = (ThreeDSecureResultCallback) invocation.getArguments()[2];
                callback.onResult(null, exception);
                return null;
            }
        }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureResult.class), (String) isNull(), any(ThreeDSecureResultCallback.class));

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, threeDSecureAPI);

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.SUCCESS);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);
        data.putExtra(ThreeDSecureActivity.EXTRA_THREE_D_SECURE_RESULT, threeDSecureResult);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        braintreeClient.sendAnalyticsEvent("three-d-secure.verification-flow.upgrade-payment-method.errored");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.completed");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationReportsNoAction_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.NOACTION);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);
        data.putExtra(ThreeDSecureActivity.EXTRA_THREE_D_SECURE_RESULT, threeDSecureResult);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.completed");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.cardinal-sdk.action-code.noaction");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationReportsFailure_sendsAnalyticsEvent() throws JSONException {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ThreeDSecureResult threeDSecureResult = ThreeDSecureResult.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE);

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.FAILURE);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);
        data.putExtra(ThreeDSecureActivity.EXTRA_THREE_D_SECURE_RESULT, threeDSecureResult);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.completed");
        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.cardinal-sdk.action-code.failure");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationIsCanceled_sendsAnalyticsEventAndReturnsExceptionToCallback() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.CANCEL);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);

        ThreeDSecureResultCallback threeDSecureResultCallback = mock(ThreeDSecureResultCallback.class);
        sut.onActivityResult(RESULT_OK, data, threeDSecureResultCallback);

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.canceled");

        ArgumentCaptor<BraintreeException> captor = ArgumentCaptor.forClass(BraintreeException.class);
        verify(threeDSecureResultCallback).onResult((ThreeDSecureResult) isNull(), captor.capture());

        BraintreeException exception = captor.getValue();
        assertEquals("User canceled 3DS.", exception.getMessage());
        assertTrue(exception instanceof UserCanceledException);
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationErrors_sendsAnalyticsEvent() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.ERROR);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.failed");
    }

    @Test
    public void onActivityResult_whenCardinalCardVerificationTimeout_sendsAnalyticsEvent() {
        CardinalClient cardinalClient = new MockCardinalClientBuilder().build();

        BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build();
        ThreeDSecureClient sut = new ThreeDSecureClient(activity, lifecycle, braintreeClient, cardinalClient, browserSwitchHelper, new ThreeDSecureAPI(braintreeClient));

        ValidateResponse validateResponse = mock(ValidateResponse.class);
        when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.TIMEOUT);

        Intent data = new Intent();
        data.putExtra(ThreeDSecureActivity.EXTRA_VALIDATION_RESPONSE, validateResponse);

        sut.onActivityResult(RESULT_OK, data, mock(ThreeDSecureResultCallback.class));

        verify(braintreeClient).sendAnalyticsEvent("three-d-secure.verification-flow.failed");
    }
}


text:
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.RecoveryServices;
    using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The properties of an update mobility service request.
    /// </summary>
    public partial class UpdateMobilityServiceRequestProperties
    {
        /// <summary>
        /// Initializes a new instance of the
        /// UpdateMobilityServiceRequestProperties class.
        /// </summary>
        public UpdateMobilityServiceRequestProperties()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// UpdateMobilityServiceRequestProperties class.
        /// </summary>
        /// <param name="runAsAccountId">The CS run as account Id.</param>
        public UpdateMobilityServiceRequestProperties(string runAsAccountId = default(string))
        {
            RunAsAccountId = runAsAccountId;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the CS run as account Id.
        /// </summary>
        [JsonProperty(PropertyName = "runAsAccountId")]
        public string RunAsAccountId { get; set; }

    }
}


text:
package me.kazik24.mtdm;

import java.util.ArrayList;

public class RepositoryDeserializationMap {

	private final ArrayList<Object> list;

	public RepositoryDeserializationMap(int capacity){
		list = new ArrayList<>(capacity);
	}
	public RepositoryDeserializationMap(){this(512);}

	public void putRepository(Object h){
		if(h == null) return;
		list.add(h);
	}
	public Object find(int key){
		if(key < 0 && key >= list.size()) return null;
		return list.get(key);
	}
	public void clear(){list.clear();}
}


text:
<?php
declare(strict_types=1);

namespace Cake\Log\Engine;

use Cake\Log\Formatter\DefaultFormatter;

/**
 * Array logger.
 *
 * Collects log messages in memory. Intended primarily for usage
 * in testing where using mocks would be complicated. But can also
 * be used in scenarios where you need to capture logs in application code.
 */
class ArrayLog extends BaseLog
{
    /**
     * Default config for this class
     *
     * @var array<string, mixed>
     */
    protected $_defaultConfig = [
        'levels' => [],
        'scopes' => [],
        'formatter' => [
            'className' => DefaultFormatter::class,
            'includeDate' => false,
        ],
    ];

    /**
     * Captured messages
     *
     * @var array<string>
     */
    protected $content = [];

    /**
     * Implements writing to the internal storage.
     *
     * @param mixed $level The severity level of log you are making.
     * @param string $message The message you want to log.
     * @param array $context Additional information about the logged message
     * @return void success of write.
     * @see \Cake\Log\Log::$_levels
     */
    public function log($level, $message, array $context = [])
    {
        $message = $this->_format($message, $context);
        $this->content[] = $this->formatter->format($level, $message, $context);
    }

    /**
     * Read the internal storage
     *
     * @return array<string>
     */
    public function read(): array
    {
        return $this->content;
    }

    /**
     * Reset internal storage.
     *
     * @return void
     */
    public function clear(): void
    {
        $this->content = [];
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp" >
    <solid android:color="@color/white"/>
    <stroke
        android:width="0.5dp"
        android:color="@color/grey_50" />
    <corners android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:topRightRadius="5dp"
        android:topLeftRadius="5dp"/>
</shape>


text:
<?php

namespace Umulmrum\Holiday\Formatter;

use Umulmrum\Holiday\Helper\DateProvider;
use Umulmrum\Holiday\Helper\DateProviderInterface;
use Umulmrum\Holiday\Model\Holiday;
use Umulmrum\Holiday\Model\HolidayList;
use Umulmrum\Holiday\Translator\NullTranslator;
use Umulmrum\Holiday\Translator\TranslatorInterface;

final class ICalendarFormatter implements HolidayFormatterInterface
{
    public const LINE_ENDING = "\r\n";

    /**
     * @var TranslatorInterface
     */
    private $translator;
    /**
     * @var DateProviderInterface
     */
    private $dateProvider;

    public function __construct(TranslatorInterface $translator = null, DateProviderInterface $dateProvider = null)
    {
        $this->translator = $translator ?? new NullTranslator();
        $this->dateProvider = $dateProvider ?? new DateProvider();
    }

    /**
     * {@inheritdoc}
     */
    public function format(Holiday $holiday): string
    {
        return $this->getEvent($holiday);
    }

    /**
     * {@inheritdoc}
     */
    public function formatList(HolidayList $holidayList)
    {
        $result = [];

        $result[] = $this->getHeader();
        foreach ($holidayList->getList() as $holiday) {
            $result[] = $this->getEvent($holiday);
        }
        $result[] = $this->getFooter();

        return \implode(self::LINE_ENDING, $result).self::LINE_ENDING;
    }

    public function getHeader(): string
    {
        return implode(self::LINE_ENDING, [
            'BEGIN:VCALENDAR',
            'VERSION:2.0',
            'PRODID:umulmrum/holiday',
            'CALSCALE:GREGORIAN',
        ]);
    }

    private function getEvent(Holiday $holiday): string
    {
        $dtstamp = $this->dateProvider->getCurrentDate();

        return implode(self::LINE_ENDING, [
            'BEGIN:VEVENT',
            sprintf('UID:%s-%s', $holiday->getName(), $holiday->getSimpleDate()),
            sprintf('DTSTAMP:%s', $dtstamp->format('Ymd\THis\ZO')),
            sprintf('CREATED:%s', $dtstamp->format('Ymd\THis\ZO')),
            'SUMMARY:'.$this->translator->translateName($holiday),
            'DTSTART;VALUE=DATE:'.$holiday->getDate()->format('Ymd'),
            'END:VEVENT',
        ]);
    }

    public function getFooter(): string
    {
        return 'END:VCALENDAR';
    }
}