text:
#include "arm_compute/runtime/NEON/functions/NEReduceMean.h"

#include "arm_compute/core/Error.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "arm_compute/runtime/NEON/NEScheduler.h"
#include "src/common/utils/Log.h"
#include "src/core/CPP/Validate.h"
#include "src/core/NEON/kernels/NEReductionOperationKernel.h"
#include "src/core/helpers/AutoConfiguration.h"

namespace arm_compute
{
namespace
{
Status validate_config(const ITensorInfo *input, const Coordinates &reduction_axis, bool keep_dims, const ITensorInfo *output)
{
    ARM_COMPUTE_UNUSED(keep_dims);
    ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output);
    ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(input);
    ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QASYMM8_SIGNED, DataType::QASYMM8, DataType::F16, DataType::F32);
    ARM_COMPUTE_RETURN_ERROR_ON(reduction_axis.num_dimensions() < 1);
    ARM_COMPUTE_RETURN_ERROR_ON(reduction_axis.num_dimensions() > input->num_dimensions());

    const unsigned int reduction_ops = reduction_axis.num_dimensions();
    const int          input_dims    = input->num_dimensions();
    Coordinates        axis_local    = reduction_axis;

    for(unsigned int i = 0; i < axis_local.num_dimensions(); ++i)
    {
        //axis: The dimensions to reduce. Must be in the range [-rank(input_tensor), rank(input_tensor)).
        ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] < (-static_cast<int>(input->num_dimensions())));
        ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] >= static_cast<int>(input->num_dimensions()));
    }

    if(output->tensor_shape().total_size() != 0)
    {
        // Only validate if not using auto_init for the output tensor
        TensorShape out_shape = input->tensor_shape();
        // Validate output_shape only if not using auto_init
        convert_negative_axis(axis_local, input_dims);
        std::sort(axis_local.begin(), axis_local.begin() + reduction_ops);
        for(unsigned int i = 0; i < reduction_ops; ++i)
        {
            ARM_COMPUTE_RETURN_ERROR_ON(axis_local[i] > 3);
            ARM_COMPUTE_RETURN_ERROR_ON(static_cast<unsigned int>(axis_local[i]) > input->num_dimensions() - 1);
            if(output->total_size() > 0 && keep_dims)
            {
                ARM_COMPUTE_RETURN_ERROR_ON(output->dimension(axis_local[i]) != 1);
            }
            if(keep_dims)
            {
                out_shape.set(axis_local[i], 1);
            }
            else
            {
                ARM_COMPUTE_RETURN_ERROR_ON(i > static_cast<unsigned int>(axis_local[i]));
                const unsigned int remove_index = axis_local[i] - i;
                ARM_COMPUTE_RETURN_ERROR_ON(remove_index >= out_shape.num_dimensions());
                out_shape.remove_dimension(remove_index);
            }
        }
        const TensorInfo out_info = input->clone()->set_tensor_shape(out_shape);
        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(output, &out_info);
        const bool requant = is_data_type_quantized(input->data_type()) && input->quantization_info() != output->quantization_info();
        if(requant)
        {
            TensorInfo input_no_quant(input->clone()->set_data_type(DataType::F32));
            NEDequantizationLayer::validate(input, &input_no_quant);
            TensorInfo output_no_quant(output->clone()->set_data_type(DataType::F32));
            NEQuantizationLayer::validate(&output_no_quant, output);
        }
    }
    return Status{};
}
} // namespace

NEReduceMean::~NEReduceMean() = default;

NEReduceMean::NEReduceMean(std::shared_ptr<IMemoryManager> memory_manager)
    : _memory_group(std::move(memory_manager)), _reduction_kernels(), _reduced_outs(), _reshape(), _dequant(), _requant(), _reduction_ops(), _keep_dims(), _do_requant(), _input_no_quant(),
      _output_no_quant()
{
}

Status NEReduceMean::validate(const ITensorInfo *input, const Coordinates &reduction_axis, bool keep_dims, const ITensorInfo *output)
{
    return validate_config(input, reduction_axis, keep_dims, output);
}

void NEReduceMean::configure(ITensor *input, const Coordinates &reduction_axis, bool keep_dims, ITensor *output)
{
    ARM_COMPUTE_LOG_PARAMS(input, reduction_axis, keep_dims, output);

    // Perform validate step
    ARM_COMPUTE_ERROR_THROW_ON(NEReduceMean::validate(input->info(), reduction_axis, keep_dims, output->info()));
    // Output auto inizialitation if not yet initialized
    const TensorShape output_shape = arm_compute::misc::shape_calculator::calculate_reduce_mean_shape(input->info(), reduction_axis, keep_dims);
    auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape));

    _do_requant    = is_data_type_quantized(input->info()->data_type()) && input->info()->quantization_info() != output->info()->quantization_info();
    _reduction_ops = reduction_axis.num_dimensions();
    _reduction_kernels.resize(_reduction_ops);
    _reduced_outs.resize(_reduction_ops - (keep_dims ? 1 : 0));
    _keep_dims = keep_dims;

    ITensor *tmp_input  = input;
    ITensor *tmp_output = output;
    if(_do_requant)
    {
        _memory_group.manage(&_input_no_quant);
        _memory_group.manage(&_output_no_quant);
        TensorInfo output_no_quant_info = input->info()->clone()->set_tensor_shape(output_shape);
        output_no_quant_info.set_data_type(DataType::F32);
        auto_init_if_empty(*_output_no_quant.info(), output_no_quant_info);
        auto_init_if_empty(*_input_no_quant.info(), input->info()->clone()->set_data_type(DataType::F32));
        _dequant.configure(input, &_input_no_quant);
        tmp_input  = &_input_no_quant;
        tmp_output = &_output_no_quant;
    }

    Coordinates axis_local = reduction_axis;
    const int   input_dims = tmp_input->info()->num_dimensions();

    convert_negative_axis(axis_local, input_dims);

    // Perform reduction for every axis
    for(int i = 0; i < _reduction_ops; ++i)
    {
        TensorShape out_shape = i == 0 ? tmp_input->info()->tensor_shape() : (&_reduced_outs[i - 1])->info()->tensor_shape();
        out_shape.set(axis_local[i], 1);
        auto in = (i == 0) ? tmp_input : (&_reduced_outs[i - 1]);

        if(i == _reduction_ops - 1 && keep_dims)
        {
            _reduction_kernels[i].configure(in, tmp_output, axis_local[i], ReductionOperation::MEAN_SUM);
        }
        else
        {
            _reduced_outs[i].allocator()->init(TensorInfo(out_shape, tmp_input->info()->num_channels(), tmp_input->info()->data_type(), tmp_input->info()->quantization_info()));
            _memory_group.manage(&_reduced_outs[i]);
            _reduction_kernels[i].configure(in, &_reduced_outs[i], axis_local[i], ReductionOperation::MEAN_SUM);
        }
    }

    // Allocate intermediate tensors
    for(int i = 0; i < _reduction_ops - (keep_dims ? 1 : 0); ++i)
    {
        _reduced_outs[i].allocator()->allocate();
    }

    // Configure reshape layer if we want to drop the dimensions
    if(!keep_dims)
    {
        TensorShape out_shape = tmp_input->info()->tensor_shape();
        // We have to sort the reduction axis vectors in order for remove_dimension
        // to work properly
        std::sort(axis_local.begin(), axis_local.begin() + _reduction_ops);
        for(int i = 0; i < _reduction_ops; ++i)
        {
            out_shape.remove_dimension(axis_local[i] - i);
        }
        auto_init_if_empty(*tmp_output->info(), tmp_input->info()->clone()->set_tensor_shape(out_shape));
        _reshape.configure(&_reduced_outs[_reduction_ops - 1], tmp_output);
    }
    if(_do_requant)
    {
        _requant.configure(&_output_no_quant, output);
        _input_no_quant.allocator()->allocate();
        _output_no_quant.allocator()->allocate();
    }
}

void NEReduceMean::run()
{
    MemoryGroupResourceScope scope_mg(_memory_group);
    if(_do_requant)
    {
        _dequant.run();
    }
    for(auto &kernel : _reduction_kernels)
    {
        kernel.run();
    }
    if(!_keep_dims)
    {
        _reshape.run();
    }
    if(_do_requant)
    {
        _requant.run();
    }
}
} // namespace arm_compute


text:
package com.thoughtworks.xstream.io;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;

/**
 * Provides implementation of stream parsers and writers to XStream.
 *
 * @author Joe Walnes
 * @author James Strachan
 */
public interface HierarchicalStreamDriver {

    /**
     * Create the HierarchicalStreamReader with the stream parser reading from the IO reader.
     *
     * @param in the {@link Reader} with the data to parse
     * @return the HierarchicalStreamReader
     */
    HierarchicalStreamReader createReader(Reader in);

    /**
     * Create the HierarchicalStreamReader with the stream parser reading from the input stream.
     *
     * @param in the {@link InputStream} with the data to parse
     * @since 1.1.3
     */
    HierarchicalStreamReader createReader(InputStream in);

    /**
     * Create the HierarchicalStreamReader with the stream parser reading from a URL.
     *
     * Depending on the parser implementation, some might take the URL as SystemId to resolve
     * additional references.
     *
     * @param in the {@link URL} defining the location with the data to parse
     * @return the HierarchicalStreamReader
     * @since 1.4
     */
    HierarchicalStreamReader createReader(URL in);

    /**
     * Create the HierarchicalStreamReader with the stream parser reading from a File.
     *
     * Depending on the parser implementation, some might take the file path as SystemId to
     * resolve additional references.
     *
     * @param in the {@link URL} defining the location with the data to parse
     * @return the HierarchicalStreamReader
     * @since 1.4
     */
    HierarchicalStreamReader createReader(File in);

    /**
     * Create the HierarchicalStreamWriter with the formatted writer.
     *
     * @param out the {@link Writer} to receive the formatted data
     * @return the HierarchicalStreamWriter
     */
    HierarchicalStreamWriter createWriter(Writer out);
    /**
     * Create the HierarchicalStreamWriter with the formatted writer.
     *
     * @param out the {@link OutputStream} to receive the formatted data
     * @return the HierarchicalStreamWriter
     * @since 1.1.3
     */
    HierarchicalStreamWriter createWriter(OutputStream out);

}

redpajama_set_name: RedPajamaGithub


text:
#include "EventCounterStore.h"
#include <qs/log/LogLevel.h>

namespace IAS {
namespace QS {
namespace Workers {
namespace Proc {
namespace EC {

/*************************************************************************/
EventCounterStore::EventCounterStore(){
	IAS_TRACER;
}
/*************************************************************************/
EventCounterStore::~EventCounterStore() throw(){
	IAS_TRACER;
}
/*************************************************************************/
void EventCounterStore::addEventCounter(const String& strName, EventCounter* pEventCounter){
	IAS_TRACER;

	Mutex::Locker locker(mutex);

	if(hmEventCounters.count(strName) > 0)
		IAS_THROW(AlreadyExists(String("cache: ")+strName));

	IAS_LOG(IAS::QS::LogLevel::INSTANCE.isInfo(),"EC: "<<strName);

	hmEventCounters[strName]=pEventCounter;
}
/*************************************************************************/
EventCounter* EventCounterStore::lookup(const String& strName){
	IAS_TRACER;

	Mutex::Locker locker(mutex);

	if(hmEventCounters.count(strName) == 0)
		IAS_THROW(ItemNotFoundException(String("event counter: ")+strName));

	return hmEventCounters.at(strName);

}
/*************************************************************************/

}
}
}
}
}


text:
addGoal clean
addGoal install

# Always update snapshots
# addArg "-U";
# Never download dependencies
# addArg "-o";

addDef "maven.javadoc.skip=true"


text:
<?php

namespace Illuminate\Tests\Bus;

use Carbon\CarbonImmutable;
use Illuminate\Bus\Batch;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\BatchFactory;
use Illuminate\Bus\DatabaseBatchRepository;
use Illuminate\Bus\PendingBatch;
use Illuminate\Bus\Queueable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Queue\Factory;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\PostgresConnection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\CallQueuedClosure;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use RuntimeException;

class BusBatchTest extends TestCase
{
    protected function setUp(): void
    {
        $db = new DB;

        $db->addConnection([
            'driver' => 'sqlite',
            'database' => ':memory:',
        ]);

        $db->bootEloquent();
        $db->setAsGlobal();

        $this->createSchema();

        $_SERVER['__finally.count'] = 0;
        $_SERVER['__then.count'] = 0;
        $_SERVER['__catch.count'] = 0;
    }

    /**
     * Setup the database schema.
     *
     * @return void
     */
    public function createSchema()
    {
        $this->schema()->create('job_batches', function ($table) {
            $table->string('id')->primary();
            $table->string('name');
            $table->integer('total_jobs');
            $table->integer('pending_jobs');
            $table->integer('failed_jobs');
            $table->text('failed_job_ids');
            $table->text('options')->nullable();
            $table->integer('cancelled_at')->nullable();
            $table->integer('created_at');
            $table->integer('finished_at')->nullable();
        });
    }

    /**
     * Tear down the database schema.
     *
     * @return void
     */
    protected function tearDown(): void
    {
        unset($_SERVER['__finally.batch']);
        unset($_SERVER['__then.batch']);
        unset($_SERVER['__catch.batch']);
        unset($_SERVER['__catch.exception']);

        $this->schema()->drop('job_batches');

        m::close();
    }

    public function test_jobs_can_be_added_to_the_batch()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $job = new class {
            use Batchable;
        };

        $secondJob = new class {
            use Batchable;
        };

        $thirdJob = function () {
        };

        $queue->shouldReceive('connection')->once()
                        ->with('test-connection')
                        ->andReturn($connection = m::mock(stdClass::class));

        $connection->shouldReceive('bulk')->once()->with(\Mockery::on(function ($args) use ($job, $secondJob) {
            return
                $args[0] == $job &&
                $args[1] == $secondJob &&
                $args[2] instanceof CallQueuedClosure
                && is_string($args[2]->batchId);
        }), '', 'test-queue');

        $batch = $batch->add([$job, $secondJob, $thirdJob]);

        $this->assertEquals(3, $batch->totalJobs);
        $this->assertEquals(3, $batch->pendingJobs);
        $this->assertTrue(is_string($job->batchId));
        $this->assertInstanceOf(CarbonImmutable::class, $batch->createdAt);
    }

    public function test_processed_jobs_can_be_calculated()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $batch->totalJobs = 10;
        $batch->pendingJobs = 4;

        $this->assertEquals(6, $batch->processedJobs());
        $this->assertEquals(60, $batch->progress());
    }

    public function test_successful_jobs_can_be_recorded()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $job = new class {
            use Batchable;
        };

        $secondJob = new class {
            use Batchable;
        };

        $queue->shouldReceive('connection')->once()
                        ->with('test-connection')
                        ->andReturn($connection = m::mock(stdClass::class));

        $connection->shouldReceive('bulk')->once();

        $batch = $batch->add([$job, $secondJob]);
        $this->assertEquals(2, $batch->pendingJobs);

        $batch->recordSuccessfulJob('test-id');
        $batch->recordSuccessfulJob('test-id');

        $this->assertInstanceOf(Batch::class, $_SERVER['__finally.batch']);
        $this->assertInstanceOf(Batch::class, $_SERVER['__then.batch']);

        $batch = $batch->fresh();
        $this->assertEquals(0, $batch->pendingJobs);
        $this->assertTrue($batch->finished());
        $this->assertEquals(1, $_SERVER['__finally.count']);
        $this->assertEquals(1, $_SERVER['__then.count']);
    }

    public function test_failed_jobs_can_be_recorded_while_not_allowing_failures()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue, $allowFailures = false);

        $job = new class {
            use Batchable;
        };

        $secondJob = new class {
            use Batchable;
        };

        $queue->shouldReceive('connection')->once()
                        ->with('test-connection')
                        ->andReturn($connection = m::mock(stdClass::class));

        $connection->shouldReceive('bulk')->once();

        $batch = $batch->add([$job, $secondJob]);
        $this->assertEquals(2, $batch->pendingJobs);

        $batch->recordFailedJob('test-id', new RuntimeException('Something went wrong.'));
        $batch->recordFailedJob('test-id', new RuntimeException('Something else went wrong.'));

        $this->assertInstanceOf(Batch::class, $_SERVER['__finally.batch']);
        $this->assertFalse(isset($_SERVER['__then.batch']));

        $batch = $batch->fresh();
        $this->assertEquals(2, $batch->pendingJobs);
        $this->assertEquals(2, $batch->failedJobs);
        $this->assertTrue($batch->finished());
        $this->assertTrue($batch->cancelled());
        $this->assertEquals(1, $_SERVER['__finally.count']);
        $this->assertEquals(1, $_SERVER['__catch.count']);
        $this->assertSame('Something went wrong.', $_SERVER['__catch.exception']->getMessage());
    }

    public function test_failed_jobs_can_be_recorded_while_allowing_failures()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue, $allowFailures = true);

        $job = new class {
            use Batchable;
        };

        $secondJob = new class {
            use Batchable;
        };

        $queue->shouldReceive('connection')->once()
                        ->with('test-connection')
                        ->andReturn($connection = m::mock(stdClass::class));

        $connection->shouldReceive('bulk')->once();

        $batch = $batch->add([$job, $secondJob]);
        $this->assertEquals(2, $batch->pendingJobs);

        $batch->recordFailedJob('test-id', new RuntimeException('Something went wrong.'));
        $batch->recordFailedJob('test-id', new RuntimeException('Something else went wrong.'));

        // While allowing failures this batch never actually completes...
        $this->assertFalse(isset($_SERVER['__then.batch']));

        $batch = $batch->fresh();
        $this->assertEquals(2, $batch->pendingJobs);
        $this->assertEquals(2, $batch->failedJobs);
        $this->assertFalse($batch->finished());
        $this->assertFalse($batch->cancelled());
        $this->assertEquals(1, $_SERVER['__catch.count']);
        $this->assertSame('Something went wrong.', $_SERVER['__catch.exception']->getMessage());
    }

    public function test_batch_can_be_cancelled()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $batch->cancel();

        $batch = $batch->fresh();

        $this->assertTrue($batch->cancelled());
    }

    public function test_batch_can_be_deleted()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $batch->delete();

        $batch = $batch->fresh();

        $this->assertNull($batch);
    }

    public function test_batch_state_can_be_inspected()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $this->assertFalse($batch->finished());
        $batch->finishedAt = now();
        $this->assertTrue($batch->finished());

        $batch->options['then'] = [];
        $this->assertFalse($batch->hasThenCallbacks());
        $batch->options['then'] = [1];
        $this->assertTrue($batch->hasThenCallbacks());

        $this->assertFalse($batch->allowsFailures());
        $batch->options['allowFailures'] = true;
        $this->assertTrue($batch->allowsFailures());

        $this->assertFalse($batch->hasFailures());
        $batch->failedJobs = 1;
        $this->assertTrue($batch->hasFailures());

        $batch->options['catch'] = [];
        $this->assertFalse($batch->hasCatchCallbacks());
        $batch->options['catch'] = [1];
        $this->assertTrue($batch->hasCatchCallbacks());

        $this->assertFalse($batch->cancelled());
        $batch->cancelledAt = now();
        $this->assertTrue($batch->cancelled());

        $this->assertTrue(is_string(json_encode($batch)));
    }

    public function test_chain_can_be_added_to_batch()
    {
        $queue = m::mock(Factory::class);

        $batch = $this->createTestBatch($queue);

        $chainHeadJob = new ChainHeadJob();

        $secondJob = new SecondTestJob();

        $thirdJob = new ThirdTestJob();

        $queue->shouldReceive('connection')->once()
            ->with('test-connection')
            ->andReturn($connection = m::mock(stdClass::class));

        $connection->shouldReceive('bulk')->once()->with(\Mockery::on(function ($args) use ($chainHeadJob, $secondJob, $thirdJob) {
            return
                $args[0] == $chainHeadJob
                && serialize($secondJob) == $args[0]->chained[0]
                && serialize($thirdJob) == $args[0]->chained[1];
        }), '', 'test-queue');

        $batch = $batch->add([
            [$chainHeadJob, $secondJob, $thirdJob],
        ]);

        $this->assertEquals(3, $batch->totalJobs);
        $this->assertEquals(3, $batch->pendingJobs);
        $this->assertEquals('test-queue', $chainHeadJob->chainQueue);
        $this->assertTrue(is_string($chainHeadJob->batchId));
        $this->assertTrue(is_string($secondJob->batchId));
        $this->assertTrue(is_string($thirdJob->batchId));
        $this->assertInstanceOf(CarbonImmutable::class, $batch->createdAt);
    }

    public function test_options_serialization_on_postgres()
    {
        $pendingBatch = (new PendingBatch(new Container, collect()))
            ->onQueue('test-queue');

        $connection = m::spy(PostgresConnection::class);

        $connection->shouldReceive('table')->andReturnSelf()
            ->shouldReceive('where')->andReturnSelf();

        $repository = new DatabaseBatchRepository(
            new BatchFactory(m::mock(Factory::class)), $connection, 'job_batches'
        );

        $repository->store($pendingBatch);

        $connection->shouldHaveReceived('insert')
            ->withArgs(function ($argument) use ($pendingBatch) {
                return unserialize(base64_decode($argument['options'])) === $pendingBatch->options;
            });
    }

    /**
     * @dataProvider serializedOptions
     */
    public function test_options_unserialize_on_postgres($serialize, $options)
    {
        $factory = m::mock(BatchFactory::class);

        $connection = m::spy(PostgresConnection::class);

        $connection->shouldReceive('table->where->first')
            ->andReturn($m = (object) [
                'id' => '',
                'name' => '',
                'total_jobs' => '',
                'pending_jobs' => '',
                'failed_jobs' => '',
                'failed_job_ids' => '[]',
                'options' => $serialize,
                'created_at' => null,
                'cancelled_at' => null,
                'finished_at' => null,
            ]);

        $batch = (new DatabaseBatchRepository($factory, $connection, 'job_batches'));

        $factory->shouldReceive('make')
            ->withSomeOfArgs($batch, '', '', '', '', '', '', $options);

        $batch->find(1);
    }

    /**
     * @return array
     */
    public function serializedOptions()
    {
        $options = [1, 2];

        return [
            [serialize($options), $options],
            [base64_encode(serialize($options)), $options],
        ];
    }

    protected function createTestBatch($queue, $allowFailures = false)
    {
        $repository = new DatabaseBatchRepository(new BatchFactory($queue), DB::connection(), 'job_batches');

        $pendingBatch = (new PendingBatch(new Container, collect()))
                            ->then(function (Batch $batch) {
                                $_SERVER['__then.batch'] = $batch;
                                $_SERVER['__then.count']++;
                            })
                            ->catch(function (Batch $batch, $e) {
                                $_SERVER['__catch.batch'] = $batch;
                                $_SERVER['__catch.exception'] = $e;
                                $_SERVER['__catch.count']++;
                            })
                            ->finally(function (Batch $batch) {
                                $_SERVER['__finally.batch'] = $batch;
                                $_SERVER['__finally.count']++;
                            })
                            ->allowFailures($allowFailures)
                            ->onConnection('test-connection')
                            ->onQueue('test-queue');

        return $repository->store($pendingBatch);
    }

    /**
     * Get a database connection instance.
     *
     * @return \Illuminate\Database\Connection
     */
    protected function connection()
    {
        return Model::getConnectionResolver()->connection();
    }

    /**
     * Get a schema builder instance.
     *
     * @return \Illuminate\Database\Schema\Builder
     */
    protected function schema()
    {
        return $this->connection()->getSchemaBuilder();
    }
}

class ChainHeadJob implements ShouldQueue
{
    use Dispatchable, Queueable, Batchable;
}

class SecondTestJob implements ShouldQueue
{
    use Dispatchable, Queueable, Batchable;
}

class ThirdTestJob implements ShouldQueue
{
    use Dispatchable, Queueable, Batchable;
}


text:
Running the Wafflehaus.Nova tests
----------------------------

You will want both an installation of Python 2.6 and 2.7
to run all configured tests

1. Fork the repo and clone your fork:
	git clone <repository link>

2. Navigate to the new repo:
	cd wafflehaus.nova

3. Install virtualenv if you don't have it already:
	pip install virtualenv

4. Create a virtual environment in the .venv folder at the root of the repo:
	virtualenv --no-site-packages --distribute .venv --prompt="(WafflehausNovaEnv)"

5. Activate the virtual environment:
	source .venv/bin/activate

6. Install tox in the newly activated virtual environment:
	pip install tox

7. Now simply run the tox command:
	Note: this may take a bit of time the first time you execute it

	tox

	Note: subsequent runs of tox should be much faster

8. Exit out of the context of the virtual environment when you are finished:
	deactivate

Note: For subsequent test runs, simply have the virtual environment activated
and run the tox command from within the repo


text:
using UnityEngine;

namespace BeardPhantom.PhantomConsole
{
    /// <summary>
    /// Behavior and visuals settings for a console
    /// </summary>
    [CreateAssetMenu(menuName = "BeardPhantom/PhantomConsole/PhantomConsole Settings")]
    public class ConsoleSettings : ScriptableObject
    {
        /// <summary>
        /// Does the console start open when created
        /// </summary>
        [Header("General")]
        public bool StartOpen;

        /// <summary>
        /// Checked at console create time to see if the application command line arguments contain
        /// this value. If true, open the console when created.
        /// </summary>
        public string CommandLineOpenArg = "-console";

        /// <summary>
        /// Color used for default print
        /// </summary>
        [Header("Colors")]
        public Color DefaultPrintColor = Color.white;

        /// <summary>
        /// Color used when showing echo of submitted input
        /// </summary>
        public Color InputEchoPrintColor = new Color(0.75f, 0.75f, 0.75f);

        /// <summary>
        /// Color used for warning print
        /// </summary>
        public Color WarningPrintColor = new Color(1f, 0.5f, 0f);

        /// <summary>
        /// Color used for error print
        /// </summary>
        public Color ErrorPrintColor = Color.red;

        /// <summary>
        /// Input checked for opening/closing the console
        /// </summary>
        [Header("Input")]
        public KeyCode[] ToggleConsole =
        {
            KeyCode.BackQuote
        };

        /// <summary>
        /// Input checked for navigating backwards in the console input history
        /// </summary>
        public KeyCode[] InputHistoryBackwards =
        {
            KeyCode.UpArrow
        };

        /// <summary>
        /// Input checked for navigating forwads in the console input history
        /// </summary>
        public KeyCode[] InputHistoryForwards =
        {
            KeyCode.DownArrow
        };

        /// <summary>
        /// Input checked for navigating backwards in the console input history
        /// </summary>
        public KeyCode[] AutoCompleteBackwards =
        {
            KeyCode.UpArrow
        };

        /// <summary>
        /// Input checked for navigating forwads in the console input history
        /// </summary>
        public KeyCode[] AutoCompleteForwards =
        {
            KeyCode.DownArrow,
            KeyCode.Tab
        };

        /// <summary>
        /// Input checked for submitting input to the console
        /// </summary>
        public KeyCode[] SubmitInput =
        {
            KeyCode.Return,
            KeyCode.KeypadEnter
        };
    }
}


text:
from __future__ import absolute_import

from desktop.lib.scheduler.lib.api import Api

from oozie.views.editor2 import _submit_coordinator

class OozieApi(Api):

  def submit_schedule(self, request, coordinator, mapping):
    return _submit_coordinator(request, coordinator, mapping)


text:
id: 587d8254367417b2b2512c71
title: Remover itens de um conjunto na ES6
challengeType: 1
forumTopicId: 301713
dashedName: remove-items-from-a-set-in-es6
---

# --description--

Vamos praticar a remoção de itens de um conjunto da ES6 usando o método `delete`.

Primeiro, crie um conjunto (Set) da ES6:

```js
var set = new Set([1,2,3]);
```

Agora, remova um item do seu conjunto com o método `delete`.

```js
set.delete(1);
console.log([...set]) // should return [ 2, 3 ]
```

# --instructions--

Crie um conjunto com os números inteiros 1, 2, 3, 4 e 5.

Remova os valores 2 e 5. Então, retorne o conjunto.

# --hints--

O conjunto deve conter os valores 1, 3 e 4

```js
assert(
  (function () {
    var test = checkSet();
    return test.has(1) && test.has(3) && test.has(4) && test.size === 3;
  })()
);
```

# --seed--

## --seed-contents--

```js
function checkSet(){
  // Only change code below this line
  var set = null;

  // Only change code above this line
  return set;
}
```

# --solutions--

```js
function checkSet(){
var set = new Set([1,2,3,4,5]);
set.delete(2);
set.delete(5);
return set;}
```


text:
#ifndef TENSORFLOW_CC_FRAMEWORK_FUZZING_CC_OP_FUZZ_GEN_H_
#define TENSORFLOW_CC_FRAMEWORK_FUZZING_CC_OP_FUZZ_GEN_H_

#include "tensorflow/cc/framework/cc_op_gen_util.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {
namespace cc_op {

// String with single fuzzer file content.
string WriteSingleFuzzer(const OpInfo& op_info, bool is_fuzzable);

// Do we have all we need to create a fuzzer
bool OpFuzzingIsOk(const OpInfo& op_info);

}  // namespace cc_op
}  // namespace tensorflow

#endif  // TENSORFLOW_CC_FRAMEWORK_FUZZING_CC_OP_FUZZ_GEN_H_


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>TestGitProject</artifactId>
  <version>1.0</version>
  <packaging>jar</packaging>

  <name>TestGitProject</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
  </dependencies>
</project>


text:
package habier.pawnshop.commands.pawn;

import java.util.logging.Level;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import habier.pawnshop.database.PlayerData;
import habier.pawnshop.helpers.Log;
import habier.pawnshop.main.Configurer;
import habier.pawnshop.main.Lang;
import habier.pawnshop.main.PawnPlugin;

public final class PawnHelper {

	public static PlayerData getPlayerData(Player p) {
		PlayerData userData = PawnPlugin.PawnDB.getPlayerData(p.getUniqueId());

		if (userData == null) {
			p.sendMessage(Lang.DB_timeOut);
			Log.write(Level.SEVERE, p.getName() + " Cannot be found nor created in the DB");
			return null;
		}

		return userData;
	}

	public static boolean buyLimit(int number, int data) {
		if ((number + data) <= (Configurer.maxSell + Configurer.maxBuy))
			return true;

		return false;
	}

	public static boolean sellLimit(int number, int data) {
		if ((data - number) > -1)
			return true;

		return false;
	}

	public static void removeItems(Player p, int qty, Material material) {
		ItemStack[] inventory = p.getInventory().getContents();
		for (int i = 0; i < inventory.length && qty > 0; i++) {
			if (inventory[i] != null && inventory[i].getType() == material) {
				if (inventory[i].getAmount() <= qty) {
					qty -= inventory[i].getAmount();
					inventory[i] = null;
				} else {
					inventory[i].setAmount(inventory[i].getAmount() - qty);
					qty = 0;
				}
			}
		}
		p.getInventory().setContents(inventory);
		p.updateInventory();
	}

	public static int countInventoryFreeSpace(Inventory inv) {
		int freeSpace = 0;
		ItemStack[] inventory = inv.getContents();

		for (int i = 0; i < inventory.length; i++) {
			if (inventory[i] == null) {
				freeSpace++;
			}
		}
		return freeSpace;
	}

	public static boolean checkEnoughInventory(Inventory inv, int qty, Material material) {
		int freeSlots = countInventoryFreeSpace(inv);

		if ((qty + material.getMaxStackSize() - 1) / material.getMaxStackSize() > freeSlots)
			return false;

		return true;
	}

	public static void giveItems(Inventory inv, int number, Material targetItem) {
		while (number > targetItem.getMaxStackSize() - 1) {
			inv.addItem(new ItemStack(targetItem, targetItem.getMaxStackSize()));
			number -= targetItem.getMaxStackSize();
		}
		if (number > 0)
			inv.addItem(new ItemStack(targetItem, number));

	}
}


text:
angular.module('recipals').controller('registerController',
  ['$scope', '$location', 'AuthService',
  function ($scope, $location, AuthService) {
    //register function
    $scope.register = function () {
      if($scope.registerForm.password != $scope.registerForm.password2){
        $scope.error = true;
        $scope.errorMessage = 'Passwords do not match!';
        return false;
      }
      // initial values
      $scope.error = false;
      $scope.disabled = true;

      // call register from service
      AuthService.register($scope.registerForm.username, $scope.registerForm.password)
        // handle success
        .then(function () {
          $location.path('/login');
          $scope.disabled = false;
          $scope.registerForm = {};
        })
        // handle error
        .catch(function () {
          $scope.error = true;
          $scope.errorMessage = "Something went wrong!";
          $scope.disabled = false;
          $scope.registerForm = {};
        });

    };

}]);


text:
var express = require("express");
var app = express();

var fs = require('fs');
var path = require("path");
var bodyParser = require('body-parser');

var controllers = require('./controllers');

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

controllers.set(app);

app.listen(3000);


text:
package scouter.client.host.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

import scouter.client.host.views.NetStatView;

public class OpenNetStatAction extends Action {
	public final static String ID = OpenNetStatAction.class
			.getName();

	private final IWorkbenchWindow win;
	private int objHash;
	private int serverId;

	public OpenNetStatAction(IWorkbenchWindow win, String label,	int objHash, int serverId) {
		this.win = win;
		this.objHash = objHash;
		this.serverId = serverId;
		setText(label);
	}

	public void run() {
		if (win != null) {
			try {
				NetStatView view = (NetStatView) win.getActivePage().showView(NetStatView.ID,	"" + objHash, IWorkbenchPage.VIEW_ACTIVATE);
				if(view != null)
					view.setInput(serverId, objHash);
			} catch (PartInitException e) {
				MessageDialog.openError(win.getShell(), "Error", "Error opening view:" + e.getMessage());
			}
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13.Increasing_Sequence_of_Elements
{
    class IncreasingSequenceOfElements
    {
        static void Main(string[] args)
        {
            string[] arr = Console.ReadLine().Split(' ');

            int[] nums = new int[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                nums[i] = int.Parse(arr[i]);
            }
            int lastNum = int.MinValue;
            for (int i = 0; i < nums.Length; i++)
            {
                if (lastNum < nums[i])
                {
                    lastNum = nums[i];
                }
                else
                {
                    Console.WriteLine("No");
                    return;
                }
            }
            Console.WriteLine("Yes");
        }
    }
}


text:
slacker
=======

An unofficial simple Slack client for GTK2 using the Python WebKit library.

![Screenshot](screenshot.png?raw=true)

### Setup

The first time you run Slacker you'll be prompted to provide your team name as well as log-in credentials. From then on, Slacker should connect directly to your team.

> There is currently no way using the GUI to switch to a different team or log out of the service. Switching teams can be done by running `slacker TEAMNAME` from the command line.

### Requirements
* Python 3
* GTK2
* WebKit

### Installation

From git:
``` shell
git clone git@github.com:benfairless/slacker.git
# To install globally
sudo slacker/setup.sh install
# To install local to your user
slacker/setup.sh install
```

From tarball:
``` shell
curl -L https://github.com/benfairless/slacker/archive/master.tar.gz | tar xz
# To install globally
sudo slacker-master/setup.sh install
# To install local to your user
slacker-master/setup.sh install
```

### Notes

Cookies used for remembering your log-in details are stored in either `/usr/share/slacker/slacker.cookies` or `$HOME/.local/share/slacker/slacker.cookies` depending on whether you choose to install globally or local to your user.

### Credits
Slack icon from [Moka Icon Theme](http://mokaproject.com/moka-icon-theme/)


text:
package org.csstudio.swt.xygraph.dataprovider;

import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**A particular circular buffer. New arrived data will be appended to the tail of the buffer.
 * When buffer is full, the oldest data will be deleted when new data arrived.
 *
 * @author Xihui Chen
 */
public class CircularBuffer<T> extends AbstractCollection<T> {
	private int bufferSize =0;
	private T[] buffer;
	private int head;
	private int tail;
	private int count;

	public CircularBuffer(int bufferSize) {
		if(bufferSize <=0)
			throw new IllegalArgumentException("Buffer size must be larger than zero.");
		this.setBufferSize(bufferSize, true);
	}

	/** Add an element.
	 * @param element
	 */
	public synchronized boolean add(T element){
		if(tail == head && count == bufferSize) { //buffer is full
			buffer[tail] = element;
			head = (head + 1) % bufferSize;
			tail = (tail + 1) % bufferSize;
			return true;
		}
		else{//buffer is not full
			buffer[tail] = element;
			tail = (tail + 1) % bufferSize;
			count++;
			return true;
		}
	}

	/**Get element
	 * @param index the index of the element in the buffer.
	 * @return the element. null if the data at the index doesn't exist.
	 */
	public synchronized T getElement(int index){
		if(index < count)
			return buffer[(head + index) % bufferSize];
		else
			return null;
	}

	/**Get head element
	 * @return the head element. null if the buffer is empty.
	 */
	public synchronized T getHead(){
		if(count > 0)
			return buffer[head];
		else
			return null;
	}

	/**Get tail element
	 * @return the tail element. null if the buffer is empty.
	 */
	public synchronized T getTail(){
		if(count > 0)
			return buffer[(head+count-1)%bufferSize];
		else
			return null;
	}

	/**
	 * clear the buffer;
	 */
	public synchronized void clear(){
		head = 0;
		tail = 0;
		count = 0;
	}

	/**Set the buffer size.
	 * @param bufferSize the bufferSize to set
	 * @param clear clear the buffer if true. Otherwise keep the exist data;
	 * Extra data on the end would be omitted if the new bufferSize is less
	 * than the exist data count.
	 */
	@SuppressWarnings("unchecked")
	public synchronized void setBufferSize(int bufferSize, boolean clear) {
		assert bufferSize > 0;
		if(this.bufferSize != bufferSize){
			if(clear){//clear
				buffer = (T[]) new Object[bufferSize];
				clear();
			}else{// keep the exist data
				T[] tempBuffer = (T[]) toArray();
				buffer = (T[]) new Object[bufferSize];
				for(int i=0; i<Math.min(bufferSize, count); i++){
					buffer[i] = tempBuffer[i];
				}
				count = Math.min(bufferSize, count);
				head =0;
				tail = count%bufferSize;
			}
			this.bufferSize = bufferSize;
		}
	}

	/**
	 * @return the bufferSize
	 */
	public synchronized int getBufferSize() {
		return bufferSize;
	}

	public Iterator<T> iterator() {
		return new Iterator<T>(){
			private int index=0;

			public boolean hasNext() {
				return index < count;
			}
			public T next() {
				if(!hasNext())
					throw new NoSuchElementException();
				return buffer[(head+index++)%bufferSize];
			}
			public void remove() {}
		};
	}

	@Override
	public int size() {
		return count;
	}

}


text:
AESTable
=

Simple and easy implementation of the AES encryption algorithm. It uses static table definitions for key generation and extension. The project does not follow official AES guidelines and can therefore not be used in other projects as a base.


text:
<?php

namespace SMW;

use SMWInfolink;
use SMWQueryProcessor;

use Parser;
use Html;
use Title;

/**
 * Class that provides the {{#concept}} parser function
 *
 * @license GNU GPL v2+
 * @since   1.9
 *
 * @author Markus Krötzsch
 * @author Jeroen De Dauw
 * @author mwjames
 */
class ConceptParserFunction {

	/**
	 * @var ParserData
	 */
	private $parserData;

	/**
	 * @var MessageFormatter
	 */
	private $messageFormatter;

	/**
	 * @since 1.9
	 *
	 * @param ParserData $parserData
	 * @param MessageFormatter $messageFormatter
	 */
	public function __construct( ParserData $parserData, MessageFormatter $messageFormatter ) {
		$this->parserData = $parserData;
		$this->messageFormatter = $messageFormatter;
	}

	/**
	 * Parse parameters, return concept information box and update the
	 * ParserOutput with the concept object
	 *
	 * @since 1.9
	 *
	 * @param array $params
	 *
	 * @return string|null
	 */
	public function parse( array $rawParams ) {
		$this->parserData->getOutput()->addModules( 'ext.smw.style' );

		$title = $this->parserData->getTitle();
		$property = new DIProperty( '_CONC' );

		if ( !( $title->getNamespace() === SMW_NS_CONCEPT ) ) {
			return $this->messageFormatter->addFromKey( 'smw_no_concept_namespace' )->getHtml();
		} elseif ( count( $this->parserData->getSemanticData()->getPropertyValues( $property ) ) > 0 ) {
			return $this->messageFormatter->addFromKey( 'smw_multiple_concepts' )->getHtml();
		}

		// Remove parser object from parameters array
		if( isset( $rawParams[0] ) && $rawParams[0] instanceof Parser ) {
			array_shift( $rawParams );
		}

		// Use first parameter as concept (query) string
		$conceptQuery = array_shift( $rawParams );

		// Use second parameter, if any as a description
		$conceptDocu = array_shift( $rawParams );

		$query = $this->buildQuery( $conceptQuery );

		$conceptQueryString = $query->getDescription()->getQueryString();

		$this->parserData->getSemanticData()->addPropertyObjectValue(
			$property,
			new DIConcept(
				$conceptQueryString,
				$conceptDocu,
				$query->getDescription()->getQueryFeatures(),
				$query->getDescription()->getSize(),
				$query->getDescription()->getDepth()
			)
		);

		$this->messageFormatter
			->addFromArray( $query->getErrors() )
			->addFromArray( $this->parserData->getErrors() );

		$this->parserData->pushSemanticDataToParserOutput();

		if ( $this->messageFormatter->exists() ) {
			return $this->messageFormatter->getHtml();
		}

		return $this->buildConceptInfoBox( $title, $conceptQueryString, $conceptDocu );
	}

	private function buildConceptInfoBox( Title $title, $queryString, $documentation ) {
		return Html::rawElement( 'div', array( 'class' => 'smwfact' ),
			Html::rawElement( 'span', array( 'class' => 'smwfactboxhead' ),
				wfMessage( 'smw_concept_description', $title->getText() )->inContentLanguage()->text() ) .
			Html::rawElement( 'span', array( 'class' => 'smwrdflink' ), $this->getRdfLink( $title )->getWikiText() ) .
			Html::element( 'br', array() ) .
			Html::element( 'p', array( 'class' => 'concept-documenation' ), $documentation ? $documentation : '' ) .
			Html::rawElement( 'pre', array(), str_replace( '[', '[', $queryString ) ) .
			Html::element( 'br', array() )
		);
	}

	private function getRdfLink( Title $title ) {
		return SMWInfolink::newInternalLink(
			wfMessage( 'smw_viewasrdf' )->inContentLanguage()->text(),
			$title->getPageLanguage()->getNsText( NS_SPECIAL ) . ':ExportRDF/' . $title->getPrefixedText(), 'rdflink'
		);
	}

	private function buildQuery( $conceptQueryString ) {
		$rawParams = array( $conceptQueryString );

		list( $query, ) = SMWQueryProcessor::getQueryAndParamsFromFunctionParams(
			$rawParams,
			SMW_OUTPUT_WIKI,
			SMWQueryProcessor::CONCEPT_DESC,
			false
		);

		return $query;
	}

}


text:
/* eslint no-multi-assign:0, no-mixed-operators:0 */

(function () {
    'use strict';

    angular
        .module('users')
        .controller('ChangeProfilePictureController', ChangeProfilePictureController);

    ChangeProfilePictureController.$inject = ['$timeout', 'Authentication', 'Upload', 'Notification'];

    function ChangeProfilePictureController($timeout, Authentication, Upload, Notification) {
        var vm = this;

        vm.user = Authentication.user;
        vm.progress = 0;

        vm.upload = function (dataUrl) {

            Upload.upload({
                url: '/api/users/picture',
                data: {
                    newProfilePicture: dataUrl
                }
            }).then(function (response) {
                $timeout(function () {
                    onSuccessItem(response.data);
                });
            }, function (response) {
                if (response.status > 0) onErrorItem(response.data);
            }, function (evt) {
                vm.progress = parseInt(100.0 * evt.loaded / evt.total, 10);
            });
        };

        // Called after the user has successfully uploaded a new picture
        function onSuccessItem(response) {
            // Show success message
            Notification.success({ message: ' Successfully changed profile picture' });

            // Populate user object
            vm.user = Authentication.user = response;

            // Reset form
            vm.fileSelected = false;
            vm.progress = 0;
        }

        // Called after the user has failed to upload a new picture
        function onErrorItem(response) {
            vm.fileSelected = false;
            vm.progress = 0;

            // Show error message
            Notification.error({ message: response.message, title: ' Failed to change profile picture' });
        }
    }
}());


text:
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_list %}

{% if not is_popup %}
{% block breadcrumbs %}

  {% trans 'Home' %}
  › Management pages
  › Site statistics

{% endblock %}
{% endif %}

{% block coltype %}flex{% endblock %}

{% block content %}

    {% for groupname, groupitems in statsitems.items %}

{{ groupname }}

        {% for key, val in groupitems.items %}

            {{ key }}
            {{ val }}

        {% endfor %}

    {% endfor %}

{% endblock %}


text:
Brakeman.load_brakeman_dependency 'multi_json'
require 'brakeman/report/initializers/multi_json'

class Brakeman::Report::JSON < Brakeman::Report::Base
  def generate_report
    errors = tracker.errors.map{|e| { :error => e[:error], :location => e[:backtrace][0] }}

    warnings = convert_to_hashes all_warnings

    ignored = convert_to_hashes ignored_warnings

    scan_info = {
      :app_path => tracker.app_path,
      :rails_version => rails_version,
      :security_warnings => all_warnings.length,
      :start_time => tracker.start_time.to_s,
      :end_time => tracker.end_time.to_s,
      :duration => tracker.duration,
      :checks_performed => checks.checks_run.sort,
      :number_of_controllers => tracker.controllers.length,
      # ignore the "fake" model
      :number_of_models => tracker.models.length - 1,
      :number_of_templates => number_of_templates(@tracker),
      :ruby_version => RUBY_VERSION,
      :brakeman_version => Brakeman::Version
    }

    report_info = {
      :scan_info => scan_info,
      :warnings => warnings,
      :ignored_warnings => ignored,
      :errors => errors
    }

    MultiJson.dump(report_info, :pretty => true)
  end

  def convert_to_hashes warnings
    warnings.map do |w|
      hash = w.to_hash
      hash[:file] = warning_file w
      hash
    end.sort_by { |w| w[:file] }
  end
end


text:
import * as Enums from '../enums/index';
import * as Models from './index';

/**
 * Regions
 * @export
 * @interface FilingRegionModel
 */
 export interface FilingRegionModel {
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   id?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   filingId?: number;
    /**
     * @type {string}
     * @memberof FilingRegionModel
     */
   country?: string;
    /**
     * @type {string}
     * @memberof FilingRegionModel
     */
   region?: string;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   salesAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   taxableAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   taxAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   taxDueAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   collectAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   totalRemittanceAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   nonTaxableAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   consumerUseTaxAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   consumerUseNonTaxableAmount?: number;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   consumerUseTaxableAmount?: number;
    /**
     * @type {Date}
     * @memberof FilingRegionModel
     */
   approveDate?: Date;
    /**
     * @type {Date}
     * @memberof FilingRegionModel
     */
   startDate?: Date;
    /**
     * @type {Date}
     * @memberof FilingRegionModel
     */
   endDate?: Date;
    /**
     * @type {boolean}
     * @memberof FilingRegionModel
     */
   hasNexus?: boolean;
    /**
     * @type {Enums.FilingStatusId}
     * @memberof FilingRegionModel
     */
   status?: Enums.FilingStatusId;
    /**
     * @type {Models.FilingReturnModel[]}
     * @memberof FilingRegionModel
     */
   returns: Models.FilingReturnModel[];
    /**
     * @type {Models.FilingsCheckupSuggestedFormModel[]}
     * @memberof FilingRegionModel
     */
   suggestReturns: Models.FilingsCheckupSuggestedFormModel[];
    /**
     * @type {Date}
     * @memberof FilingRegionModel
     */
   createdDate?: Date;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   createdUserId?: number;
    /**
     * @type {Date}
     * @memberof FilingRegionModel
     */
   modifiedDate?: Date;
    /**
     * @type {number}
     * @memberof FilingRegionModel
     */
   modifiedUserId?: number;
 }


text:
describe('TestEmployeeController', function() {

  let $controller;

  beforeEach(module('myApp'));

  beforeEach(inject(function(_$controller_) {
    $controller = _$controller_;
  }));

  it('should initiate with 0 employees', function() {
    let controller = $controller('EmployeeController', {$scope:{}});

    expect(controller.employees.length).toEqual(0);
  });

  it('should have 1 employee when a new employee is added', function() {
    let controller = $controller('EmployeeController', {$scope:{}});

    controller.addEmployee({ "employeeId" : 1, "name" : "Daan", "age" : 20, "salary" : 200000 });

    expect(controller.employees.length).toEqual(1);
  });

  it('should have 1 employee after adding 2 employees and removing 1 employee', function() {
    let controller = $controller('EmployeeController', {$scope:{}});

    controller.addEmployee({ "employeeId" : 1, "name" : "Daan", "age" : 20, "salary" : 200000 });
    controller.addEmployee({ "employeeId" : 2, "name" : "Jos", "age" : 40, "salary" : 400000 });

    controller.removeEmployee(1);

    expect(controller.employees.length).toEqual(1);
  });

  it('should return id 3 when employees with id 1 and 2 exist', function() {
    let controller = $controller('EmployeeController', {$scope:{}});

    controller.addEmployee({ "employeeId" : 1, "name" : "Daan", "age" : 20, "salary" : 200000 });
    controller.addEmployee({ "employeeId" : 2, "name" : "Jos", "age" : 40, "salary" : 400000 });

    expect(controller.employeeId).toEqual(3);
  });

});


text:
import importlib
from itertools import chain
import logging
import os
from pkg_resources import resource_filename
import sys

from api import Module, BaseGroovyModule
from common import TreeHelpersMixin, ReadersMixin, LoggerMixin

logger = logging.getLogger(__name__)

def load_py_modules(*paths):
    """:returns: modules from modules-directory"""

    py_modules = []
    logger.debug('Loading modules from {}'.format(', '.join(paths)))
    abspaths = [os.path.abspath(path) for path in paths]

    for path in abspaths:
        try:
            sys.path.insert(0, path)

            for item in os.listdir(path):
                itempath = os.path.join(path, item)

                if os.path.isfile(os.path.join(itempath, '__init__.py')):
                    logger.info("Importing {itempath}".format(**locals()))
                    py_modules.append(importlib.import_module(item))

                if itempath.endswith('.py'):
                    logger.info("Importing {itempath}".format(**locals()))
                    py_modules.append(importlib.import_module(item[:-3]))
        finally:
            sys.path.pop(0)

    return py_modules

def extract_jimmy_modules(*py_modules):
    """:returns: Jimmy modules found in imported .py modules"""

    modules = []

    for py_module in py_modules:
        logger.debug('Looking for modules in py_module "{}"'.format(py_module.__name__))

        for itemname in dir(py_module):
            if itemname.startswith('_'):
                continue

            item = getattr(py_module, itemname)

            if not isinstance(item, type):
                continue

            if item is Module:
                continue

            if item is BaseGroovyModule:
                continue

            if issubclass(item, Module):
                logger.info('Found module: "{}"'.format(item.__name__))
                modules.append(item)

    return modules

def load_modules(*paths):
    return extract_jimmy_modules(*load_py_modules(*paths))

class Runner(TreeHelpersMixin, ReadersMixin, LoggerMixin):
    schema_rel_path = 'schema.yaml'

    @property
    def schema_path(self):
        """:returns: absolute path for configuration schema"""

        return os.path.join(os.path.dirname(__file__), self.schema_rel_path)

    def __init__(self, conf_path, pipeline_name, env_name):
        self.conf_path = conf_path
        self.pipeline_name = pipeline_name
        self.env_name = env_name

        self.ctx = {
            'modules': [],
            'config': {},
            'results': {},
            'env': {}
        }

        self.steps = []

    # --- ctx shortcuts ---

    @property
    def config(self):
        return self.ctx['config']

    @property
    def modules(self):
        return self.ctx['modules']

    @property
    def env(self):
        return self.ctx['env']

    # --- main workflow related methods ---

    def run(self):
        self.read_conf()
        self.build_steps()
        self.set_env()
        self.load_modules()
        self.execute_steps()

    def read_conf(self):
        """Read jimmy yaml configuration file and validate it using schema"""

        self.config.update(self.yaml_reader.read(self.conf_path))
        schema = self.yaml_reader.read(self.schema_path)
        try:
            self.jsonschema_validator.validate(self.config, schema)
        except self.jsonschema_validator.ValidationError as e:
            self.logger.error('Config is not valid: "{}", path: "{}"'.format(e.message, '.'.join(map(str, e.path))))

    def build_steps(self):
        """Build pipeline, steps from jimmy yaml configuration file"""

        pipeline = self._tree_read(self.config, ['pipelines', self.pipeline_name])

        config = self.config

        if not pipeline:
            self.logger.error('No such pipeline {}').format(self.pipeline_name)

        self.logger.info('Pipeline is: \n{}'.format(self.yaml_renderer.render(pipeline)))

        self.logger.info('Building pipeline steps')
        for step in chain(
                self._tree_read(self.config, ['setup'], []),
                self._tree_read(pipeline, ['steps'], []),
                self._tree_read(config, ['teardown'], []),
        ):
            step_name = step['name']

            inject = {}
            for k, v in chain(
                    self._tree_read(config, ['defaults', 'inject'], {}).iteritems(),
                    self._tree_read(config, ['defaults', 'inject', step_name], {}).iteritems(),
                    self._tree_read(pipeline, ['inject'], {}).iteritems(),
                    self._tree_read(step, ['inject'], {}).iteritems()
            ):
                inject[k] = v

            params = {}
            for k, v in chain(
                    self._tree_read(config, ['defaults', 'params'], {}).iteritems(),
                    self._tree_read(config, ['defaults', 'params', step_name], {}).iteritems(),
                    self._tree_read(pipeline, ['params'], {}).iteritems(),
                    self._tree_read(step, ['params'], {}).iteritems()
            ):
                if k not in inject:
                    params[k] = v

            _step = {'name': step_name}
            if inject:
                _step['inject'] = inject
            if params:
                _step['params'] = params

            self.steps.append(_step)
        self.logger.debug('Pipeline steps will be: \n{}'.format(self.yaml_renderer.render(pipeline)))

    def set_env(self):
        """Setup environment"""

        self.logger.debug('Setup env')
        self.ctx['env'].update(self._tree_read(self.config, ['envs', self.env_name], {}))

    def get_default_modules_path(self):
        """Get default moduless"""

        resource_package = __name__
        modules_dir = '../modules'
        default_modules_path = os.path.abspath(resource_filename(resource_package, modules_dir))

        return default_modules_path

    def load_modules(self):
        """Loading modules"""

        self.logger.info('Loading Modules')
        module_paths = self._tree_read(self.config, ['module-directories'], [])
        if self._tree_read(self.config, ['include-default-modules'], True):
            module_paths.append(self.get_default_modules_path())
        self.modules.extend([p() for p in load_modules(*module_paths)])

    def execute_steps(self):
        """Execute pipeline steps and invoke modules for each step"""

        self.logger.debug('Executing pipeline "{}"'.format(self.pipeline_name))

        for step in self.steps:
            step_name = step['name']
            self.logger.info('Executing step "{}"'.format(step_name))

            for module in self.modules:
                if hasattr(module, step_name) and not module.skip:
                    params = self._tree_read(step, ['params'], {})
                    injections = {
                        key: self._tree_read(self.ctx, ctx_path)
                        for key, ctx_path
                        in self._tree_read(step, ['inject'], {}).iteritems()
                    }

                    kwargs = {}

                    kwargs.update(params)
                    kwargs.update(injections)

                    self.logger.debug('Invoking module "{}"'.format(module.__class__.__name__))
                    try:
                        value = getattr(module, step_name)(**kwargs)
                        if value:
                            self._tree_update(self.ctx, ['results', step_name], value)
                    except StandardError as e:
                        self.logger.error(e)
                        raise


text:
<?php

declare(strict_types=1);

/*
 * This file is part of Contao Manager.
 *
 * (c) Contao Association
 *
 * @license LGPL-3.0-or-later
 */

namespace Contao\ManagerApi;

use Contao\ManagerApi\Command\AboutCommand;
use Contao\ManagerApi\Command\IntegrityCheckCommand;
use Contao\ManagerApi\Command\ProcessRunnerCommand;
use Contao\ManagerApi\Command\TaskAbortCommand;
use Contao\ManagerApi\Command\TaskDeleteCommand;
use Contao\ManagerApi\Command\TaskUpdateCommand;
use Contao\ManagerApi\Command\UpdateCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ApiApplication extends Application
{
    /**
     * @var ApiKernel
     */
    private $kernel;

    /**
     * @var bool
     */
    private $commandsRegistered = false;

    public function __construct(ApiKernel $kernel)
    {
        $this->kernel = $kernel;

        parent::__construct('Contao Manager', $kernel->getVersion());

        $this->getDefinition()->addOption(new InputOption('disable-events', null, InputOption::VALUE_NONE, 'Disables the event dispatcher.'));
    }

    /**
     * Gets the Kernel associated with this Console.
     */
    public function getKernel(): ApiKernel
    {
        return $this->kernel;
    }

    public function doRun(InputInterface $input, OutputInterface $output): int
    {
        $this->registerCommands();

        if ('self-update' !== $this->getCommandName($input)
            && !$input->hasParameterOption(['--disable-events'], true)
        ) {
            $this->setDispatcher($this->kernel->getContainer()->get('event_dispatcher'));
        }

        return (int) parent::doRun($input, $output);
    }

    protected function getDefaultCommands(): array
    {
        $commands = parent::getDefaultCommands();

        $commands[] = (new Command('composer'))->setDescription('Run Composer within Contao Manager');

        return $commands;
    }

    private function registerCommands(): void
    {
        if ($this->commandsRegistered) {
            return;
        }

        $this->commandsRegistered = true;

        $this->kernel->boot();

        $container = $this->kernel->getContainer();

        $this->add($container->get(ProcessRunnerCommand::class)->setName('run'));
        $this->add($container->get(AboutCommand::class));
        $this->add($container->get(IntegrityCheckCommand::class));
        $this->add($container->get(TaskAbortCommand::class));
        $this->add($container->get(TaskDeleteCommand::class));
        $this->add($container->get(TaskUpdateCommand::class));
        $this->add($container->get(UpdateCommand::class));

        if (!\Phar::running(false) && $container->has('console.command_loader')) {
            $this->setCommandLoader($container->get('console.command_loader'));
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class BasicTower : MonoBehaviour {
	public GameObject rangeIndicator;
	public GameObject bullet;
	public float bulletSpeed = 100f;
	public float fireRate = 1.0f;
	public  float fireRadius = 5.0f;
		public static float increase = 0.0f;
	bool once = false;
	// Use this for initialization
	bool once1 = false;
	void Start ()
	{
		InvokeRepeating("SpawnBullet",fireRate,fireRate);
	}

	void SpawnBullet()

	{
		GameObject target = null;

		foreach(Collider col in Physics.OverlapSphere(transform.position, fireRadius))
		{
			if(col.tag == "Enemy")
			{
				target = col.gameObject;
				break;
			}
		}

		if(target != null)
		{
			GameObject newBullet = Instantiate(bullet,transform.position,bullet.transform.rotation) as GameObject;
			newBullet.rigidbody.AddForce((target.transform.position - transform.position).normalized*bulletSpeed,ForceMode.VelocityChange);
		}
	}

	// Update is called once per frame
	void Update ()
	{
		//fireRadius = fireRadius+increase*(fireRadius/100);
		if(once1 == false){
			fireRadius = fireRadius*GUIControllerFireEmblem.ranger;
			once1 = true;}
	}
	void OnMouseEnter(){

			GameObject rangeFinder = Instantiate(rangeIndicator, transform.position, Quaternion.identity) as GameObject;
			StoreRange.rangee= fireRadius;

	}
	void OnMouseExit(){

		Destroy(GameObject.FindWithTag("Range"));
		Destroy(GameObject.FindWithTag("Range"));

	}

}


text:
package br.edu.ufsj.dcomp.manageBeans;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.edu.ufsj.dcomp.consulta.ConsultaDAO;
import br.edu.ufsj.dcomp.prescricoes.Prescricoes;
import br.edu.ufsj.dcomp.prescricoes.PrescricoesDAO;
import br.edu.ufsj.dcomp.servlet.ManageBeanInterface;

public class PrescricoesBean implements ManageBeanInterface {

	@Override
	public void listar(HttpServletRequest req, HttpServletResponse res) throws Exception {

		PrescricoesDAO fsd = new PrescricoesDAO();
		List<Prescricoes> lista = new ArrayList<Prescricoes>();
		lista = fsd.listar();
		req.setAttribute("lista", lista);
		RequestDispatcher rd = req.getRequestDispatcher("/app/prescricoes/lista.jsp");
		rd.forward(req, res);

	}

	@Override
	public String novo(HttpServletRequest req, HttpServletResponse res) throws Exception {

		Prescricoes fs = new Prescricoes();
		ConsultaDAO consulta = new ConsultaDAO();

		fs.setPrescricao_id(Integer.parseInt(req.getParameter("prescricaoId")));
		fs.setConsulta(consulta.selectByConsultaId(Integer.parseInt(req.getParameter("consultaId"))));
		fs.setDescricao(req.getParameter("descricao"));
		fs.setExige_retencao(req.getParameter("exigeRetencao"));
		// TODO: Verificar como tratar datas
		Calendar date = Calendar.getInstance();
		try {
			date.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(req.getParameter("dataHoraEmissao")));
			fs.setData_hora_emissao(date);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		PrescricoesDAO fsd = new PrescricoesDAO();
		try {
			fsd.insert(fs);
			return "sucesso";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public String excluir(HttpServletRequest req, HttpServletResponse res) throws Exception {

		Prescricoes fs = new Prescricoes();
		fs.setPrescricao_id(Integer.parseInt(req.getParameter("prescricaoId")));

		PrescricoesDAO fsd = new PrescricoesDAO();
		try {
			fsd.delete(fs);
			return "sucesso";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void editar(HttpServletRequest req, HttpServletResponse res) throws Exception {

		PrescricoesDAO fsd = new PrescricoesDAO();
		int prescricao_id = Integer.parseInt(req.getParameter("prescricaoId"));

		Prescricoes fs = fsd.selectById(prescricao_id);

		if (fs != null) {
			req.setAttribute("obj", fs);
			RequestDispatcher rd = req.getRequestDispatcher("/app/prescricoes/formEdicao.jsp");
			rd.forward(req, res);
		}

	}

	@Override
	public String alterar(HttpServletRequest req, HttpServletResponse res) throws Exception {

		Prescricoes fs = new Prescricoes();
		ConsultaDAO consulta = new ConsultaDAO();

		fs.setPrescricao_id(Integer.parseInt(req.getParameter("prescricaoId")));
		fs.setConsulta(consulta.selectByConsultaId(Integer.parseInt(req.getParameter("consultaId"))));
		fs.setDescricao(req.getParameter("descricao"));
		fs.setExige_retencao(req.getParameter("exigeRetencao"));
		// TODO: Verificar como tratar datas
		Calendar date = Calendar.getInstance();
		try {
			date.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(req.getParameter("dataHoraEmissao")));
			fs.setData_hora_emissao(date);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		PrescricoesDAO fsd = new PrescricoesDAO();
		try {
			fsd.update(fs);
			return "sucesso";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


text:
@interface PodsDummy_Pods_smsGate : NSObject
@end
@implementation PodsDummy_Pods_smsGate
@end


text:
function Test() { }
var test = new Test();


text:
class Extension;
class Profile;

typedef struct _GtkAccelGroup GtkAccelGroup;
typedef struct _GdkEventKey GdkEventKey;

// The ExtensionKeybindingRegistryGtk is the GTK specialization of the
// ExtensionKeybindingRegistry class that handles turning keyboard shortcuts
// into events that get sent to the extension.

// ExtensionKeybindingRegistryGtk is a class that handles GTK-specific
// implemenation of the Extension Keybinding shortcuts (keyboard accelerators).
// Note: It keeps track of browserAction and pageAction commands, but does not
// route the events to them -- that is handled elsewhere. This class registers
// the accelerators on behalf of the extensions and routes the commands to them
// via the BrowserEventRouter.
class ExtensionKeybindingRegistryGtk
    : public extensions::ExtensionKeybindingRegistry {
 public:
  ExtensionKeybindingRegistryGtk(Profile* profile, gfx::NativeWindow window);
  virtual ~ExtensionKeybindingRegistryGtk();

  // Whether this class has any registered keyboard shortcuts that correspond
  // to |event|.
  gboolean HasPriorityHandler(const GdkEventKey* event) const;

 protected:
  // Overridden from ExtensionKeybindingRegistry:
  virtual void AddExtensionKeybinding(const Extension* extension) OVERRIDE;
  virtual void RemoveExtensionKeybinding(const Extension* extension) OVERRIDE;

 private:
  // The accelerator handler for when the extension command shortcuts are
  // struck.
  CHROMEG_CALLBACK_3(ExtensionKeybindingRegistryGtk, gboolean, OnGtkAccelerator,
                     GtkAccelGroup*, GObject*, guint, GdkModifierType);

  // Weak pointer to the our profile. Not owned by us.
  Profile* profile_;

  // The browser window the accelerators are associated with.
  gfx::NativeWindow window_;

  // The accelerator group used to handle accelerators, owned by this object.
  GtkAccelGroup* accel_group_;

  // Maps a GTK accelerator to a string pair (extension id, command name) for
  // commands that have been registered. Unlike its Views counterpart, this map
  // contains browserAction and pageAction commands (but does not route those
  // events), so that we can query priority handlers in HasPriorityHandler(...).
  typedef std::map< ui::AcceleratorGtk,
                    std::pair<std::string, std::string> > EventTargets;
  EventTargets event_targets_;

  // The content notification registrar for listening to extension events.
  content::NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionKeybindingRegistryGtk);
};

#endif  // CHROME_BROWSER_UI_GTK_EXTENSIONS_EXTENSION_KEYBINDING_REGISTRY_GTK_H_


text:
package bookshop2.supplier.incoming.shipBooks;

import org.aries.tx.Transactional;

import bookshop2.ShipmentFailedMessage;

public interface ShipmentFailedHandler extends Transactional {

	public void shipmentFailed(ShipmentFailedMessage shipmentFailedMessage);

}


text:
package com.streamsets.datacollector.execution.executor;

import com.streamsets.datacollector.main.SlaveRuntimeModule;
import com.streamsets.datacollector.util.Configuration;
import com.streamsets.dc.execution.manager.standalone.ResourceManager;
import com.streamsets.pipeline.lib.executor.SafeScheduledExecutorService;
import dagger.Module;
import dagger.Provides;

import javax.inject.Named;
import javax.inject.Singleton;

/**
 * Provides separate singleton instances of SafeScheduledExecutorService for running pipelines in cluster mode.
 */
@Module(injects = SafeScheduledExecutorService.class, library = true, includes = {SlaveRuntimeModule.class})
public class SlaveExecutorModule {

  @Provides
  @Singleton
  @Named("runnerExecutor")
  public SafeScheduledExecutorService provideRunnerExecutor(Configuration configuration) {
    return new SafeScheduledExecutorService(
      ExecutorModule.getRunnerSize(configuration),
      "runner"
    );
  }

  @Provides
  @Singleton
  @Named("runnerStopExecutor")
  public SafeScheduledExecutorService provideRunnerStopExecutor(Configuration configuration) {
    return new SafeScheduledExecutorService(
      ExecutorModule.getRunnerStopSize(configuration),
      "runnerStop"
    );

    // We don't explicitly set thread expiration for stop executor in slave as it's allowed to run only one pipeline.
  }

  @Provides
  @Singleton
  @Named("eventHandlerExecutor")
  public SafeScheduledExecutorService provideEventExecutor(Configuration configuration) {
    return new SafeScheduledExecutorService(
      ExecutorModule.getEventSize(configuration),
      "eventHandlerExecutor"
    );
  }

  @Provides
  @Singleton
  @Named("supportBundleExecutor")
  public SafeScheduledExecutorService provideSupportBundleExecutor(Configuration configuration) {
    return new SafeScheduledExecutorService(
      ExecutorModule.getBundleSize(configuration),
      "supportBundleExecutor"
    );
  }

  @Provides
  @Singleton
  ResourceManager provideResourceManager(Configuration configuration) {
    return new ResourceManager(configuration);
  }
}


text:
import { ElementAbstract } from 'gluebert/element';

/**
 * Class represents BallElement
 * @extends ElementAbstract
 */
class BallElement extends ElementAbstract {

    /**
     * Create new BallElement
     * @param {object} data
     * @param {HTMLElement} template - shadow dom template reference
     */
    constructor(data, template) {
        super(data, template);

        this._numberElement = (this._template) ? this._template.querySelector('slot') : null;
        this._ballElement = (this._template) ? this._template.querySelector('.ball') : null;
        this._number = this._data.number;

    }

    /**
     * binds data to element context
     */
    bindData() {
        if(this._numberElement) {
            this._numberElement.textContent = this._number;
        }

        if(this._ballElement) {
            if(this._number % 2 === 0) {
                this._ballElement.classList.add('even');
            } else {
                this._ballElement.classList.add('odd');
            }
        }
    }

}

export {
    BallElement,
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<package packagerversion="1.9.1" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
    http://pear.php.net/dtd/tasks-1.0.xsd
    http://pear.php.net/dtd/package-2.0
    http://pear.php.net/dtd/package-2.0.xsd">
  <name>${project.name}</name>
  <channel>${project.channel}</channel>
  <summary>Simple Comet Service.</summary>
  <description>
    Watch for changes and respond to long poll requests.
  </description>
  <lead>
    <name>Nate Russell</name>
    <user>njr03304</user>
    <email>njr03304@gmail.com</email>
    <active>yes</active>
  </lead>
  <date>${build.date}</date>
  <time>${build.time}</time>
  <version>
    <release>${project.version}</release>
    <api>${project.majorVersion}.${project.minorVersion}</api>
  </version>
  <stability>
    <release>${project.stability}</release>
    <api>stable</api>
  </stability>
  <license>WTFPL2</license>
  <notes>
    No notes.
  </notes>
  <contents>
    <dir baseinstalldir="/" name="/">
${contents}
    </dir>
  </contents>
  <dependencies>
    <required>
      <php>
        <min>5.3.0</min>
      </php>
      <pearinstaller>
        <min>1.9.4</min>
      </pearinstaller>
      <package>
        <name>Autoloader</name>
        <channel>pear.phix-project.org</channel>
        <min>3.0.0</min>
        <max>3.999.9999</max>
      </package>
    </required>
  </dependencies>
  <phprelease />
  <changelog>
    <release>
      <version>
        <release>X.Y.Z</release>
        <api>X.Y</api>
      </version>
      <stability>
        <release>stable</release>
        <api>stable</api>
      </stability>
      <date>Your release date</date>
      <license>All rights reserved</license>
      <notes>
      </notes>
    </release>
  </changelog>
</package>
<!-- vim: set tabstop=2 shiftwidth=2 expandtab: -->


text:
		<title>Speech Test</title>

Hello World


text:
namespace FluentMigrator.Runner.Generators.Oracle
{
    public interface IOracle12CGenerator : IOracleGenerator
    {
    }
}


text:
#define _RTW_STA_MGT_C_

#include <osdep_service.h>
#include <drv_types.h>
#include <recv_osdep.h>
#include <xmit_osdep.h>
#include <mlme_osdep.h>
#include <sta_info.h>
#include <linux/vmalloc.h>

static void _rtw_init_stainfo(struct sta_info *psta)
{
	memset((u8 *)psta, 0, sizeof(struct sta_info));

	 spin_lock_init(&psta->lock);
	INIT_LIST_HEAD(&psta->list);
	INIT_LIST_HEAD(&psta->hash_list);
	_rtw_init_queue(&psta->sleep_q);
	psta->sleepq_len = 0;

	_rtw_init_sta_xmit_priv(&psta->sta_xmitpriv);
	_rtw_init_sta_recv_priv(&psta->sta_recvpriv);

#ifdef CONFIG_88EU_AP_MODE

	INIT_LIST_HEAD(&psta->asoc_list);

	INIT_LIST_HEAD(&psta->auth_list);

	psta->expire_to = 0;

	psta->flags = 0;

	psta->capability = 0;

	psta->bpairwise_key_installed = false;

	psta->nonerp_set = 0;
	psta->no_short_slot_time_set = 0;
	psta->no_short_preamble_set = 0;
	psta->no_ht_gf_set = 0;
	psta->no_ht_set = 0;
	psta->ht_20mhz_set = 0;

	psta->under_exist_checking = 0;

	psta->keep_alive_trycnt = 0;

#endif	/*  CONFIG_88EU_AP_MODE */

}

u32	_rtw_init_sta_priv(struct	sta_priv *pstapriv)
{
	struct sta_info *psta;
	s32 i;

	pstapriv->pallocated_stainfo_buf = vzalloc(sizeof(struct sta_info) * NUM_STA + 4);

	if (!pstapriv->pallocated_stainfo_buf)
		return _FAIL;

	pstapriv->pstainfo_buf = pstapriv->pallocated_stainfo_buf + 4 -
		((size_t)(pstapriv->pallocated_stainfo_buf) & 3);

	_rtw_init_queue(&pstapriv->free_sta_queue);

	spin_lock_init(&pstapriv->sta_hash_lock);

	pstapriv->asoc_sta_count = 0;
	_rtw_init_queue(&pstapriv->sleep_q);
	_rtw_init_queue(&pstapriv->wakeup_q);

	psta = (struct sta_info *)(pstapriv->pstainfo_buf);

	for (i = 0; i < NUM_STA; i++) {
		_rtw_init_stainfo(psta);

		INIT_LIST_HEAD(&(pstapriv->sta_hash[i]));

		list_add_tail(&psta->list, get_list_head(&pstapriv->free_sta_queue));

		psta++;
	}

#ifdef CONFIG_88EU_AP_MODE

	pstapriv->sta_dz_bitmap = 0;
	pstapriv->tim_bitmap = 0;

	INIT_LIST_HEAD(&pstapriv->asoc_list);
	INIT_LIST_HEAD(&pstapriv->auth_list);
	spin_lock_init(&pstapriv->asoc_list_lock);
	spin_lock_init(&pstapriv->auth_list_lock);
	pstapriv->asoc_list_cnt = 0;
	pstapriv->auth_list_cnt = 0;

	pstapriv->auth_to = 3; /*  3*2 = 6 sec */
	pstapriv->assoc_to = 3;
	pstapriv->expire_to = 3; /*  3*2 = 6 sec */
	pstapriv->max_num_sta = NUM_STA;
#endif

	return _SUCCESS;
}

inline int rtw_stainfo_offset(struct sta_priv *stapriv, struct sta_info *sta)
{
	int offset = (((u8 *)sta) - stapriv->pstainfo_buf)/sizeof(struct sta_info);

	if (!stainfo_offset_valid(offset))
		DBG_88E("%s invalid offset(%d), out of range!!!", __func__, offset);

	return offset;
}

inline struct sta_info *rtw_get_stainfo_by_offset(struct sta_priv *stapriv, int offset)
{
	if (!stainfo_offset_valid(offset))
		DBG_88E("%s invalid offset(%d), out of range!!!", __func__, offset);

	return (struct sta_info *)(stapriv->pstainfo_buf + offset * sizeof(struct sta_info));
}

u32	_rtw_free_sta_priv(struct	sta_priv *pstapriv)
{
	struct list_head *phead, *plist;
	struct sta_info *psta = NULL;
	struct recv_reorder_ctrl *preorder_ctrl;
	int	index;

	if (pstapriv) {
		/*	delete all reordering_ctrl_timer		*/
		spin_lock_bh(&pstapriv->sta_hash_lock);
		for (index = 0; index < NUM_STA; index++) {
			phead = &(pstapriv->sta_hash[index]);
			plist = phead->next;

			while (phead != plist) {
				int i;
				psta = container_of(plist, struct sta_info , hash_list);
				plist = plist->next;

				for (i = 0; i < 16; i++) {
					preorder_ctrl = &psta->recvreorder_ctrl[i];
					del_timer_sync(&preorder_ctrl->reordering_ctrl_timer);
				}
			}
		}
		spin_unlock_bh(&pstapriv->sta_hash_lock);
		/*===============================*/

		if (pstapriv->pallocated_stainfo_buf)
			vfree(pstapriv->pallocated_stainfo_buf);
	}

	return _SUCCESS;
}

struct	sta_info *rtw_alloc_stainfo(struct sta_priv *pstapriv, u8 *hwaddr)
{
	s32	index;
	struct list_head *phash_list;
	struct sta_info	*psta;
	struct __queue *pfree_sta_queue;
	struct recv_reorder_ctrl *preorder_ctrl;
	int i = 0;
	u16  wRxSeqInitialValue = 0xffff;

	pfree_sta_queue = &pstapriv->free_sta_queue;

	spin_lock_bh(&(pfree_sta_queue->lock));

	if (list_empty(&pfree_sta_queue->queue)) {
		spin_unlock_bh(&pfree_sta_queue->lock);
		psta = NULL;
	} else {
		psta = container_of((&pfree_sta_queue->queue)->next, struct sta_info, list);
		list_del_init(&(psta->list));
		spin_unlock_bh(&pfree_sta_queue->lock);
		_rtw_init_stainfo(psta);
		memcpy(psta->hwaddr, hwaddr, ETH_ALEN);
		index = wifi_mac_hash(hwaddr);
		RT_TRACE(_module_rtl871x_sta_mgt_c_, _drv_info_, ("rtw_alloc_stainfo: index=%x", index));
		if (index >= NUM_STA) {
			RT_TRACE(_module_rtl871x_sta_mgt_c_, _drv_err_, ("ERROR => rtw_alloc_stainfo: index >= NUM_STA"));
			psta = NULL;
			goto exit;
		}
		phash_list = &(pstapriv->sta_hash[index]);

		spin_lock_bh(&(pstapriv->sta_hash_lock));

		list_add_tail(&psta->hash_list, phash_list);

		pstapriv->asoc_sta_count++;

		spin_unlock_bh(&pstapriv->sta_hash_lock);

/*  Commented by Albert 2009/08/13 */
/*  For the SMC router, the sequence number of first packet of WPS handshake will be 0. */
/*  In this case, this packet will be dropped by recv_decache function if we use the 0x00 as the default value for tid_rxseq variable. */
/*  So, we initialize the tid_rxseq variable as the 0xffff. */

		for (i = 0; i < 16; i++)
			memcpy(&psta->sta_recvpriv.rxcache.tid_rxseq[i], &wRxSeqInitialValue, 2);

		RT_TRACE(_module_rtl871x_sta_mgt_c_, _drv_info_,
			 ("alloc number_%d stainfo  with hwaddr = %pM\n",
			 pstapriv->asoc_sta_count, hwaddr));

		init_addba_retry_timer(pstapriv->padapter, psta);

		/* for A-MPDU Rx reordering buffer control */
		for (i = 0; i < 16; i++) {
			preorder_ctrl = &psta->recvreorder_ctrl[i];

			preorder_ctrl->padapter = pstapriv->padapter;

			preorder_ctrl->enable = false;

			preorder_ctrl->indicate_seq = 0xffff;
			preorder_ctrl->wend_b = 0xffff;
			preorder_ctrl->wsize_b = 64;/* 64; */

			_rtw_init_queue(&preorder_ctrl->pending_recvframe_queue);

			rtw_init_recv_timer(preorder_ctrl);
		}

		/* init for DM */
		psta->rssi_stat.UndecoratedSmoothedPWDB = (-1);
		psta->rssi_stat.UndecoratedSmoothedCCK = (-1);

		/* init for the sequence number of received management frame */
		psta->RxMgmtFrameSeqNum = 0xffff;
	}

exit:
	return psta;
}

/*  using pstapriv->sta_hash_lock to protect */
u32	rtw_free_stainfo(struct adapter *padapter, struct sta_info *psta)
{
	int i;
	struct __queue *pfree_sta_queue;
	struct recv_reorder_ctrl *preorder_ctrl;
	struct	sta_xmit_priv	*pstaxmitpriv;
	struct	xmit_priv	*pxmitpriv = &padapter->xmitpriv;
	struct	sta_priv *pstapriv = &padapter->stapriv;

	if (psta == NULL)
		goto exit;

	pfree_sta_queue = &pstapriv->free_sta_queue;

	pstaxmitpriv = &psta->sta_xmitpriv;

	spin_lock_bh(&pxmitpriv->lock);

	rtw_free_xmitframe_queue(pxmitpriv, &psta->sleep_q);
	psta->sleepq_len = 0;

	rtw_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->vo_q.sta_pending);

	list_del_init(&(pstaxmitpriv->vo_q.tx_pending));

	rtw_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->vi_q.sta_pending);

	list_del_init(&(pstaxmitpriv->vi_q.tx_pending));

	rtw_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->bk_q.sta_pending);

	list_del_init(&(pstaxmitpriv->bk_q.tx_pending));

	rtw_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->be_q.sta_pending);

	list_del_init(&(pstaxmitpriv->be_q.tx_pending));

	spin_unlock_bh(&pxmitpriv->lock);

	list_del_init(&psta->hash_list);
	RT_TRACE(_module_rtl871x_sta_mgt_c_, _drv_err_, ("\n free number_%d stainfo  with hwaddr=0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x\n", pstapriv->asoc_sta_count , psta->hwaddr[0], psta->hwaddr[1], psta->hwaddr[2], psta->hwaddr[3], psta->hwaddr[4], psta->hwaddr[5]));
	pstapriv->asoc_sta_count--;

	/*  re-init sta_info; 20061114 */
	_rtw_init_sta_xmit_priv(&psta->sta_xmitpriv);
	_rtw_init_sta_recv_priv(&psta->sta_recvpriv);

	del_timer_sync(&psta->addba_retry_timer);

	/* for A-MPDU Rx reordering buffer control, cancel reordering_ctrl_timer */
	for (i = 0; i < 16; i++) {
		struct list_head *phead, *plist;
		struct recv_frame *prhdr;
		struct recv_frame *prframe;
		struct __queue *ppending_recvframe_queue;
		struct __queue *pfree_recv_queue = &padapter->recvpriv.free_recv_queue;

		preorder_ctrl = &psta->recvreorder_ctrl[i];

		del_timer_sync(&preorder_ctrl->reordering_ctrl_timer);

		ppending_recvframe_queue = &preorder_ctrl->pending_recvframe_queue;

		spin_lock_bh(&ppending_recvframe_queue->lock);

		phead =		get_list_head(ppending_recvframe_queue);
		plist = phead->next;

		while (!list_empty(phead)) {
			prhdr = container_of(plist, struct recv_frame, list);
			prframe = (struct recv_frame *)prhdr;

			plist = plist->next;

			list_del_init(&(prframe->list));

			rtw_free_recvframe(prframe, pfree_recv_queue);
		}

		spin_unlock_bh(&ppending_recvframe_queue->lock);
	}

	if (!(psta->state & WIFI_AP_STATE))
		rtw_hal_set_odm_var(padapter, HAL_ODM_STA_INFO, psta, false);

#ifdef CONFIG_88EU_AP_MODE

	spin_lock_bh(&pstapriv->auth_list_lock);
	if (!list_empty(&psta->auth_list)) {
		list_del_init(&psta->auth_list);
		pstapriv->auth_list_cnt--;
	}
	spin_unlock_bh(&pstapriv->auth_list_lock);

	psta->expire_to = 0;

	psta->sleepq_ac_len = 0;
	psta->qos_info = 0;

	psta->max_sp_len = 0;
	psta->uapsd_bk = 0;
	psta->uapsd_be = 0;
	psta->uapsd_vi = 0;
	psta->uapsd_vo = 0;
	psta->has_legacy_ac = 0;

	pstapriv->sta_dz_bitmap &= ~BIT(psta->aid);
	pstapriv->tim_bitmap &= ~BIT(psta->aid);

	if ((psta->aid > 0) && (pstapriv->sta_aid[psta->aid - 1] == psta)) {
		pstapriv->sta_aid[psta->aid - 1] = NULL;
		psta->aid = 0;
	}

	psta->under_exist_checking = 0;

#endif	/*  CONFIG_88EU_AP_MODE */

	spin_lock_bh(&(pfree_sta_queue->lock));
	list_add_tail(&psta->list, get_list_head(pfree_sta_queue));
	spin_unlock_bh(&pfree_sta_queue->lock);

exit:

	return _SUCCESS;
}

/*  free all stainfo which in sta_hash[all] */
void rtw_free_all_stainfo(struct adapter *padapter)
{
	struct list_head *plist, *phead;
	s32	index;
	struct sta_info *psta = NULL;
	struct	sta_priv *pstapriv = &padapter->stapriv;
	struct sta_info *pbcmc_stainfo = rtw_get_bcmc_stainfo(padapter);

	if (pstapriv->asoc_sta_count == 1)
		return;

	spin_lock_bh(&pstapriv->sta_hash_lock);

	for (index = 0; index < NUM_STA; index++) {
		phead = &(pstapriv->sta_hash[index]);
		plist = phead->next;

		while (phead != plist) {
			psta = container_of(plist, struct sta_info, hash_list);

			plist = plist->next;

			if (pbcmc_stainfo != psta)
				rtw_free_stainfo(padapter, psta);
		}
	}
	spin_unlock_bh(&pstapriv->sta_hash_lock);
}

/* any station allocated can be searched by hash list */
struct sta_info *rtw_get_stainfo(struct sta_priv *pstapriv, u8 *hwaddr)
{
	struct list_head *plist, *phead;
	struct sta_info *psta = NULL;
	u32	index;
	u8 *addr;
	u8 bc_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

	if (hwaddr == NULL)
		return NULL;

	if (IS_MCAST(hwaddr))
		addr = bc_addr;
	else
		addr = hwaddr;

	index = wifi_mac_hash(addr);

	spin_lock_bh(&pstapriv->sta_hash_lock);

	phead = &(pstapriv->sta_hash[index]);
	plist = phead->next;

	while (phead != plist) {
		psta = container_of(plist, struct sta_info, hash_list);

		if ((!memcmp(psta->hwaddr, addr, ETH_ALEN)) == true) {
			/*  if found the matched address */
			break;
		}
		psta = NULL;
		plist = plist->next;
	}

	spin_unlock_bh(&pstapriv->sta_hash_lock);
	return psta;
}

u32 rtw_init_bcmc_stainfo(struct adapter *padapter)
{
	struct sta_info		*psta;
	u32 res = _SUCCESS;
	unsigned char bcast_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
	struct	sta_priv *pstapriv = &padapter->stapriv;

	psta = rtw_alloc_stainfo(pstapriv, bcast_addr);

	if (psta == NULL) {
		res = _FAIL;
		RT_TRACE(_module_rtl871x_sta_mgt_c_, _drv_err_, ("rtw_alloc_stainfo fail"));
		goto exit;
	}

	/*  default broadcast & multicast use macid 1 */
	psta->mac_id = 1;

exit:
	return res;
}

struct sta_info *rtw_get_bcmc_stainfo(struct adapter *padapter)
{
	struct sta_info		*psta;
	struct sta_priv		*pstapriv = &padapter->stapriv;
	u8 bc_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
	 psta = rtw_get_stainfo(pstapriv, bc_addr);
	return psta;
}

u8 rtw_access_ctrl(struct adapter *padapter, u8 *mac_addr)
{
	u8 res = true;
#ifdef CONFIG_88EU_AP_MODE
	struct list_head *plist, *phead;
	struct rtw_wlan_acl_node *paclnode;
	u8 match = false;
	struct sta_priv *pstapriv = &padapter->stapriv;
	struct wlan_acl_pool *pacl_list = &pstapriv->acl_list;
	struct __queue *pacl_node_q = &pacl_list->acl_node_q;

	spin_lock_bh(&(pacl_node_q->lock));
	phead = get_list_head(pacl_node_q);
	plist = phead->next;
	while (phead != plist) {
		paclnode = container_of(plist, struct rtw_wlan_acl_node, list);
		plist = plist->next;

		if (!memcmp(paclnode->addr, mac_addr, ETH_ALEN)) {
			if (paclnode->valid) {
				match = true;
				break;
			}
		}
	}
	spin_unlock_bh(&pacl_node_q->lock);

	if (pacl_list->mode == 1)/* accept unless in deny list */
		res = (match) ? false : true;
	else if (pacl_list->mode == 2)/* deny unless in accept list */
		res = (match) ? true : false;
	else
		 res = true;

#endif

	return res;
}