text:
/*jshint strict:false */
'Use strict';

// Use applicaion configuration module to register a new module
angular.module('sector', ['ciudad']);

redpajama_set_name: RedPajamaGithub


text:
classdef WBWickensTracking < WBTask
    properties
        trialTimer

        lineWidth = 2;
        r = 50;
        speed = 0.015; % initial speed
        speedChange = 0.001
        updateFreq = 1/30;
        performanceCheckFreq = 1/3;
        useMouse = 1;

        xS = 0;
        yS = 0;
        prevUpdateTime = 0;
        prevPerformanceCheck = 0;
        prevMouseCenter = 0;
        prevMX = 0;
        prevMY = 0;
        latestMovement = 0;

        winningCheck = 0;

        distance = [];
        prevInside = 1;
        Fs = 22050;
        tone = [];
    end

    properties (Dependent = true)
        currentDistance
    end

    methods
        function obj = WBWickensTracking(nm)
            obj@WBTask(nm);

            obj.trialTimer = WBTimer;

            dur = 0.05;
            obj.tone= 0.4*sin(linspace(0, dur*400*2*pi, round(dur*obj.Fs)));
        end % constructor

        function stop(this)
            stop@WBTask(this);
        end % stop

        function start(this)
            start@WBTask(this);

            this.nextTrial();
        end

        function update(this)
            %if (this.trialTimer.running & this.trialTimer.passed)
                %this.nextTrial();
            %end
            if (this.active)

                t = GetSecs;

                % keep the mouse from going offscreen
                if (this.prevMouseCenter+1 < t)
                    this.prevMouseCenter = t;
                    this.prevMX = this.canvas.width*0.5;
                    this.prevMY = this.canvas.height*0.5;
                    this.canvas.setMouse(this.prevMX, this.prevMY);
                end

                % keep track of accuracy over time
                if (this.prevPerformanceCheck+this.performanceCheckFreq < t)
                    this.prevPerformanceCheck = t;
                    %this.numSamples = this.numSamples + 1;
                    %if (this.isInside())
                        %this.inCircleSamples = this.inCircleSamples + 1;
                    %end
                    d = this.currentDistance;
                    this.distance = [this.distance d];
                    % generate event
                    this.eventBuffer.add([this.name ':update'], {{'distance' d} ...
                                                                 {'timestamp' t} ...
                                                                 {'x' this.xS-0.5*this.canvas.width} ...
                                                                 {'y' this.yS-0.5*this.canvas.height} ...
                                                                 {'speed' this.speed} ...
                                                                 {'movement' this.latestMovement} ...
                                                                });
                    inside = this.isInside();
                    if (~inside & inside ~= this.prevInside)
                        % play an annoying tone when you cross the circle threshold
                        sound(this.tone, this.Fs);

                        % task may be too difficult; change the movement speed a bit
                        this.speed = max(0.015, this.speed - this.speedChange*2);
                    %disp(['decreasing movement speed ' num2str(this.speed)]);
                    end
                    this.prevInside = inside;
                end

                if (this.winningCheck+3 < t)
                    % task may be too easy; increase movement speed a bit
                    this.speed = this.speed + this.speedChange;
                    this.winningCheck = t;
                    %disp(['increasing movement speed ' num2str(this.speed)]);
                end

                % update the screen at a constant rate
                if (this.prevUpdateTime+this.updateFreq < t)
                    this.prevUpdateTime = t;
                    this.updatePointLocation(t);
                    this.paint();
                end
            end
        end

        function nextTrial(this)
            if (this.active)
                this.trialStartTime = GetSecs;
                this.distance = [];

                this.xS = this.canvas.width*0.5;
                this.yS = this.canvas.height*0.5;

                this.prevMX = this.xS;
                this.prevMY = this.yS;

                this.paint();
            end
        end

        function paint(this)
            % blank the screen
            Screen('FillRect', this.canvas.area, 255, [0 0 this.canvas.width this.canvas.height]);
            xC = this.canvas.width*0.5;
            yC = this.canvas.height*0.5;

            % draw the target zone
            col = [150 0 0];
            if (this.isInside())
                col = [0 100 0];
            end

            Screen('FrameOval', this.canvas.area, col, [xC-this.r yC-this.r xC+this.r yC+this.r], this.lineWidth, this.lineWidth);
            crss = 25;
            lns = [0    0   -crss crss; ...
                  -crss crss 0    0];
            Screen('DrawLines', this.canvas.area, lns, 2, col, [xC yC]);

            % draw the tracking dot
            Screen('FillOval', this.canvas.area, [0 58 104], [this.xS-5 this.yS-5 this.xS+5 this.yS+5]);

            this.canvas.paint();
        end

        function mouseInput(this, x, y, buttons)
            if (this.active)
                dX = -(x - this.prevMX);
                dY = -(y - this.prevMY);

                move = sqrt(dX*dX + dY*dY);
                if (move > 500)
                    move = 9999;
                end
                this.latestMovement = move;

                this.eventBuffer.add([this.name ':movement'], {{'distance' move} ...
                                                             {'x' dX} ...
                                                             {'y' dY} ...
                                                            });

                if (abs(dX) < 200 & abs(dY) < 200)

                    this.xS = this.xS - dX;
                    this.yS = this.yS - dY;

                    % always keep the point inside the canvas area
                    this.xS = min(max(0, this.xS), this.canvas.width);
                    this.yS = min(max(0, this.yS), this.canvas.height);

                end
                    this.prevMX = x;
                    this.prevMY = y;
            end

        end

        function value = get.currentDistance(this)
            % translate to the center
            x = this.xS - this.canvas.width*0.5;
            y = this.yS - this.canvas.height*0.5;

            value = sqrt(x^2 + y^2);
        end

        function updatePointLocation(this, t)
            pi2 = pi*2;

            offH = 69*sin(pi2*0.08*t) + 32*sin(pi2*0.5*t) + 17*sin(pi2*0.3*t);
            offV = 55*sin(pi2*0.05*t) + 39*sin(pi2*0.2*t) + 24*sin(pi2*0.08*t);

            %disp(['offset: ' num2str(offH) ',' num2str(offV)]);
            x = round(this.xS + offH*this.speed);
            if (x > 0 & x < this.canvas.width)
                this.xS = x;
            end

            y = round(this.yS + offV*this.speed);
            if (y > 0 & y < this.canvas.height)
                this.yS = y;
            end

        end

    end % methods

    methods (Access = private)
        function bool = isInside(this)
        bool = 0;
            x = this.xS - this.canvas.width*0.5;
            y = this.yS - this.canvas.height*0.5;

            len = sqrt(x^2 + y^2);
            if (len < this.r)
                bool = 1;
            end

        end

    end % methods
end


text:
import pygame

"""
Monitors the users mouse and their selections
"""
class PickingHandler(object):
    SUCCESS_COLOR = (0,0,255)
    ERROR_COLOR = (255,0,0)

    def __init__(self, viewport, transmutation_manager, physics_manager):
        self.viewport = viewport
        self.transmutation_manager = transmutation_manager
        self.physics_manager = physics_manager
        self._user_selection_bound1 = None
        self._user_selection_bound2 = None

    def is_picked(self, actor, position):
        position = self.viewport.convert_position(position)
        return actor.get_rect().collidepoint(position)

    def tile_at_point(self, position, tile_size):
        position = self.viewport.convert_position(position)
        return (int(position[0] / tile_size), int(position[1] / tile_size))

    def start_user_selection(self, position, tile_size):
        self._user_selection_bound1 = self.tile_at_point(position, tile_size)

    def stop_user_selection(self):
        if self._user_selection_bounds is not None:
            pygame.event.post(pygame.event.Event(pygame.USEREVENT, {"bounds":self._user_selection_bounds}))
        self._user_selection_bound1 = None
        self._user_selection_bound2 = None

    @property
    def surface(self):
        if self._user_selection_bound1 is not None:
            return self.selection_surface
        else:
            return pygame.Surface((0,0))

    @property
    def position(self):
        if self._user_selection_bound1 is not None:
            return self._user_selection_position
        else:
            return (0,0)

    def _is_selection_space_filled(self, tile_size):
        px_selection_box = self.selection_surface.get_rect().move(self._user_selection_position)
        tile_selection_box = pygame.Rect(px_selection_box.left / tile_size, px_selection_box.top / tile_size, px_selection_box.width / tile_size, px_selection_box.height / tile_size)
        return self.physics_manager.is_space_filled(tile_selection_box)

    def get_points_used(self, tile_size):
        return self.transmutation_manager.get_points_required((self.selection_surface.get_width() / tile_size), (self.selection_surface.get_height() / tile_size))

    def update(self, delta, tile_size):
        if self._user_selection_bound1 is not None: #user can select right now
            new_bound2 = self.tile_at_point(pygame.mouse.get_pos(), tile_size)
            if new_bound2 != self._user_selection_bound2:
                self._user_selection_bound2 = new_bound2
                self._user_selection_position = (
                    min(self._user_selection_bound1[0], self._user_selection_bound2[0]) * tile_size,
                    min(self._user_selection_bound1[1], self._user_selection_bound2[1]) * tile_size
                )
                self.selection_surface = pygame.Surface((
                    abs(self._user_selection_bound2[0] - self._user_selection_bound1[0]) * tile_size,
                    abs(self._user_selection_bound2[1] - self._user_selection_bound1[1]) * tile_size
                    ))
                self.selection_surface.set_alpha(150)
            if self.selection_surface.get_width() == 0 or self.selection_surface.get_height() == 0 or self.get_points_used(tile_size) > self.transmutation_manager.current_points or self._is_selection_space_filled(tile_size):
                self.selection_surface.fill(PickingHandler.ERROR_COLOR)
                self._user_selection_bounds = None
            else:
                self.selection_surface.fill(PickingHandler.SUCCESS_COLOR)
                self._user_selection_bounds = self.selection_surface.get_rect().move(self._user_selection_position)


text:
////////////////////////////////////////////////////////////////////////////////
//
//                W R I T T E N   B Y   I M P E R A S   I G E N
//
//                             Version 20140731.0
//                          Mon Aug  4 13:35:18 2014
//
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////// Description /////////////////////////////////

// Microblaze Debug Module

/////////////////////////////////// Licensing //////////////////////////////////

// Open Source Apache 2.0

////////////////////////////////// Limitations /////////////////////////////////

// This model implements the registers but has no functional behavior

#include "pse.igen.h"
/////////////////////////////// Port Declarations //////////////////////////////

plb_REG_dataT plb_REG_data;

handlesT handles;

/////////////////////////////// Diagnostic level ///////////////////////////////

// Test this variable to determine what diagnostics to output.
// eg. if (diagnosticLevel > 0) bhmMessage("I", "mdm", "Example");

Uns32 diagnosticLevel;

/////////////////////////// Diagnostic level callback //////////////////////////

static void setDiagLevel(Uns32 new) {
    diagnosticLevel = new;
}

//////////////////////////////// Bus Slave Ports ///////////////////////////////

static void installSlavePorts(void) {
    handles.plb = ppmCreateSlaveBusPort("plb", 65536);
    if (!handles.plb) {
        bhmMessage("E", "PPM_SPNC", "Could not connect port 'plb'");
    }

    ppmInstallReadCallback(readMemCB, (void*)0x0, handles.plb+0x0, 0x10000);
    ppmInstallWriteCallback(writeMemCB, (void*)0x0, handles.plb+0x0, 0x10000);
}

/////////////////////////////////// Net Ports //////////////////////////////////

static void installNetPorts(void) {
// To write to this net, use ppmWriteNet(handles.Interrupt, value);

    handles.Interrupt = ppmOpenNetPort("Interrupt");

}

////////////////////////////////// Constructor /////////////////////////////////

PPM_CONSTRUCTOR_CB(periphConstructor) {
    installSlavePorts();
    installNetPorts();
}

///////////////////////////////////// Main /////////////////////////////////////

int main(int argc, char *argv[]) {
    diagnosticLevel = 0;
    bhmInstallDiagCB(setDiagLevel);
    constructor();

    bhmWaitEvent(bhmGetSystemEvent(BHM_SE_END_OF_SIMULATION));
    destructor();
    return 0;
}


text:
#include "clusterlibinternal.h"

using namespace std;
using namespace boost;

namespace clusterlib {

const string &
RegisteredApplicationImpl::registeredName() const
{
    return CLString::REGISTERED_APPLICATION_NAME;
}

string
RegisteredApplicationImpl::generateKey(const string &parentKey,
                                       const string &name) const
{
    return NotifyableKeyManipulator::createApplicationKey(name);
}

bool
RegisteredApplicationImpl::isValidName(const string &name) const
{
    TRACE(CL_LOG, "isValidName");

    if ((name.compare(CLString::DEFAULT_CLI_APPLICATION)) &&
        (!NotifyableKeyManipulator::isValidNotifyableName(name))) {
        LOG_WARN(CL_LOG,
                 "isValidName: Illegal Application name %s",
                 name.c_str());
        return false;
    }
    else {
        return true;
    }
}

shared_ptr<NotifyableImpl>
RegisteredApplicationImpl::createNotifyable(
    const string &notifyableName,
    const string &notifyableKey,
    const shared_ptr<NotifyableImpl> &parent,
    FactoryOps &factoryOps) const
{
    return dynamic_pointer_cast<NotifyableImpl>(
        shared_ptr<ApplicationImpl>(new ApplicationImpl(&factoryOps,
                                                        notifyableKey,
                                                        notifyableName,
                                                        parent)));
}

vector<string>
RegisteredApplicationImpl::generateRepositoryList(
    const string &notifyableName,
    const string &notifyableKey) const
{
    vector<string> resVec;
    resVec.push_back(notifyableKey);
    resVec.push_back(
        NotifyableKeyManipulator::createGroupChildrenKey(notifyableKey));
    resVec.push_back(
        NotifyableKeyManipulator::createDataDistributionChildrenKey(
            notifyableKey));
    resVec.push_back(
        NotifyableKeyManipulator::createNodeChildrenKey(notifyableKey));

    return resVec;
}

bool
RegisteredApplicationImpl::isValidKey(const vector<string> &components,
                                      int32_t elements)
{
    TRACE(CL_LOG, "isValidKey");

    if (elements > static_cast<int32_t>(components.size())) {
        LOG_FATAL(CL_LOG,
                  "isValidKey: elements %" PRId32
                  " > size of components %" PRIuPTR,
                  elements,
                  components.size());
        throw InvalidArgumentsException("isValidKey: elements > size of "
                                        "components");
    }

    /*
     * Set to the full size of the vector.
     */
    if (elements == -1) {
        elements = components.size();
    }

    if (elements != CLNumericInternal::APP_COMPONENTS_COUNT) {
        return false;
    }

    if ((components.at(CLNumericInternal::CLUSTERLIB_INDEX) !=
         CLStringInternal::CLUSTERLIB) ||
        (components.at(CLNumericInternal::ROOT_INDEX) !=
         CLString::ROOT_DIR) ||
        (components.at(CLNumericInternal::APP_INDEX) !=
         CLString::APPLICATION_DIR)) {
        return false;
    }

    return true;
}

RegisteredApplicationImpl::RegisteredApplicationImpl(FactoryOps *factoryOps)
    : RegisteredNotifyableImpl(factoryOps)
{
    setRegisteredParentNameVec(
        vector<string>(1, CLString::REGISTERED_ROOT_NAME));
}

}	/* End of 'namespace clusterlib' */


text:
<?php

/**
 * @runTestsInSeparateProcesses
 */
class Test extends HTMLServerComponentTestCase
{

    /**
     *
     */
    public function testProccessHTML()
    {
        $fullFilename = $this->makeFile('component1.php', '<meta custom="value">text1');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<component src="file:' . $fullFilename . '"/>');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<meta custom="value">' . "\n" . 'text1';
        $this->assertTrue($result === $expectedResult);

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process(''
            . 'text0'
            . '<component src="file:' . $fullFilename . '"/>'
            . 'text2'
            . '');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<meta custom="value">'
            . 'text0'
            . 'text1'
            . 'text2'
            . '';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testAlias()
    {
        $fullFilename = $this->makeFile('component1.php', 'text1');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $compiler->addAlias('component1', 'file:' . $fullFilename);

        $expectedResult = '<!DOCTYPE html>' . "\n" . '' . "\n" . 'text1';

        $result = $compiler->process('<component src="file:' . $fullFilename . '" />');
        $this->assertTrue($result === $expectedResult);

        $result = $compiler->process('<component src="component1" />');
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testTags()
    {
        $fullFilename = $this->makeFile('component1.php', '<?= $component->value; ?>');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $compiler->addAlias('component1', 'file:' . $fullFilename);
        $compiler->addTag('mytag', 'file:' . $fullFilename);
        $compiler->addTag('my-tag', 'component1');

        $result = $compiler->process('<mytag value="text1"/>');
        $this->assertTrue($result === '<!DOCTYPE html>' . "\n" . '' . "\n" . 'text1');

        $result = $compiler->process('<my-tag value="text2"/>');
        $this->assertTrue($result === '<!DOCTYPE html>' . "\n" . '' . "\n" . 'text2');

        $result = $compiler->process('<mytag value="text1"/><my-tag value="text2"/><component src="component1" value="text3"/><component src="file:' . $fullFilename . '" value="text4"/>');
        $this->assertTrue($result === '<!DOCTYPE html>' . "\n" . '' . "\n" . 'text1text2text3text4');
    }

    /**
     *
     */
    public function testMakeComponent()
    {
        $fullFilename = $this->makeFile('component1.php', 'text1');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $component = $compiler->makeComponent(['var1' => '1'], 'hi');

        $expectedResult = '<component var1="1">hi</component>';
        $this->assertTrue((string) $component === $expectedResult);
    }

    /**
     *
     */
    public function testVariables()
    {
        $fullFilename = $this->makeFile('component1.php', '<?= $component->test1?><?= $test2?>');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $component = new \IvoPetkov\HTMLServerComponent();
        $component->src = 'file:' . $fullFilename;
        $component->test1 = '1';
        $result = $compiler->process($component, [
            'variables' => [
                'test2' => 2
            ]
        ]);
        $expectedResult = '<!DOCTYPE html>' . "\n" . '12';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testProccessRecursion()
    {
        $fullFilename1 = $this->makeFile('component1.php', '<meta custom="value1">text1');
        $fullFilename2 = $this->makeFile('component2.php', '<meta custom="value2"><component src="file:' . urlencode($fullFilename1) . '"></component>text2');
        $fullFilename3 = $this->makeFile('component3.php', '<meta custom="value3"><component src="file:' . urlencode($fullFilename2) . '"></component>text3');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<component src="file:' . $fullFilename3 . '"/>');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<meta custom="value3"><meta custom="value2"><meta custom="value1">' . "\n" . 'text1text2text3';
        $this->assertTrue($result === $expectedResult);

        $result = $compiler->process('<component src="file:' . $fullFilename3 . '"/>', ['recursive' => false]);
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<meta custom="value3">' . "\n" . '<component src="file:' . urlencode($fullFilename2) . '"></component>text3';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testProccessData()
    {

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<component src="data:base64,' . base64_encode('text1') . '" />');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '' . "\n" . 'text1';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testComponentInComponentInnerHTML()
    {

        $fullFilename1 = $this->makeFile('component1.php', 'text1');
        $fullFilename2 = $this->makeFile('component2.php', '<title>hi</title><?= $component->innerHTML;?>/head>');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<component src="file:' . $fullFilename2 . '"><component src="file:' . $fullFilename1 . '"/></component>');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<title>hi</title>' . "\n" . 'text1';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testComponentAttribute()
    {
        $fullFilename = $this->makeFile('component1.php', '<?php '
            . 'echo $component->test1;' // 1
            . '$component->test1 = "2";'
            . 'echo $component->test1;' // 2
            . 'echo $component->test2;' // null
            . 'echo (int)isset($component->test1);' // 1
            . 'unset($component->test1);'
            . 'echo (int)isset($component->test1);' // 0
            . '?>');

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $component = new \IvoPetkov\HTMLServerComponent();
        $component->src = 'file:' . $fullFilename;
        $component->test1 = '1';
        $result = $compiler->process($component);
        $expectedResult = '<!DOCTYPE html>' . "\n" . '1210';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testComponentSetAttributes()
    {

        $component = new \IvoPetkov\HTMLServerComponent();
        $component->setAttributes(['aTTR1' => 'value1', 'attr2' => 'value2']);
        $result = (string) $component;
        $expectedResult = '<component attr1="value1" attr2="value2"></component>';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testComponentRemoveAttributes()
    {

        $component = new \IvoPetkov\HTMLServerComponent();
        $component->setAttributes(['aTTR1' => 'value1', 'attr2' => 'value2', 'attr3' => 'value3']);
        $component->removeAttributes(['attr1', 'Attr3']);
        $result = (string) $component;
        $expectedResult = '<component attr2="value2"></component>';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testHeadContent()
    {

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<title>111</title><component src="data:base64,' . base64_encode('<title>222</title>') . '" />');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '<title>222</title>';
        $this->assertTrue($result === $expectedResult);
    }

    /**
     *
     */
    public function testDifferentComponentLocations()
    {

        $compiler = new \IvoPetkov\HTMLServerComponentsCompiler();
        $result = $compiler->process('<component src="data:base64,' . base64_encode('
1
') . '" /><component src="data:base64,' . base64_encode('
2
') . '" />');
        $expectedResult = '<!DOCTYPE html>' . "\n" . '
2

1
';
        $this->assertTrue($result === $expectedResult);
    }
}


text:
Command line User and Project Management
========================================

This module deals with management of users and projects using CMD3.

The code is located at:

* https://github.com/cloudmesh/management.git

**Assumptions:**

* Python 2.7.9 is installed
* virtual environment is installed and setup (for example, virtualenv ~/ENV -p <path to python version 2.7.9>)
* Cloudmesh is installed
* mongo server is running (fab server.start)

Clone the module for bson and build it::

    git clone https://github.com/martinkou/bson.git
    python setup.py install

Clone the project with::

    git clone https://github.com/cloudmesh/management.git

Change to the cloned directory::

    cd management

Setup the requirements with::

    python setup.py requirements

Install the module::

    python setup.py install

Install the YAML files::

    python setup.py yaml

If you are starting from scratch, the commands that needs to be run are listed below::

    git clone https://github.com/martinkou/bson.git
    python setup.py install
    pip install cloudmesh_base
    pip install cmd3
    pip install cloudmesh_database
    python setup.py requirements
    python setup.py install
    python setup.py yaml

.. note::

    The fields of the User and Project objects can be generated dynamically from the YAML file in the directory
    "etc/accounts". A default file for **user** is available under etc/accounts/cloudmesh_user.yaml and a default file for
    **project** is available under etc/accounts/cloudmesh_project.yaml. To add/remove fields, amend the YAML file as required. When
    you do "python setup.py yaml", the files are moved to "~/.cloudmesh/accounts" directory.

How to add/amend fields to the YAML file::

    * Amend the file(s) under etc/accounts/
    * The fields are listed under::
        cloudmesh:
            user:
                fields:
    * Each field is described as shown below::
        - <Field Name>:
            label: <Label for field>
            type: <Field type>
            required: <True/False>
            reference: <Reference field>[OPTIONAL]
            options:
                - option 1
                - option 2
                - option n

    * The field type can be: text, textarea, dropdown, password, list, checkbox, email
    * If any of the field, references to an existing field, "reference: " needs to be set to the existing field
    * If a field has options, "options: ", needs to be set as shown above
    * If the field is in [text, textarea, dropdown, password] and has a reference field, the field is mapped as a ListField[ReferenceField]
    * If the field is in [text, textarea, dropdown, password] and has options, the field is mapped as a ListField[StringField]
    * If the field is just in [text, textarea, dropdown, password], the field is mapped as a StringField
    * If the field is a checkbox, the field is mapped to a BooleanField
    * If the field is a email, the field is mapped to a EmailField
    * UUIDField() is being used to generate a Project ID and User ID

If you make any amendments to the file under "etc/accounts", follow the steps below::

    * python setup.py resetyaml
    * python setup.py regenfile (This regenerates the files base_user.py and base_project.py under cloudmesh_management)
    * python setup.py install

If everything is setup correctly, run the following command::

    cm management help

You should see the screen below::

    management: Command line for Administrators to manage users and projects

            Usage:
                management version
                management admin user generate [--count=N]
                management admin user list [USERNAME] [--format=FORMAT]
                management admin user add [YAMLFILE]
                management admin user delete [USERNAME]
                management admin user clear
                management admin user status USERNAME
                management admin user approve [USERNAME]
                management admin user activate [USERNAME]
                management admin user suspend [USERNAME]
                management admin user block [USERNAME]
                management admin user deny [USERNAME]
                management admin user assign [USERNAME] [ROLE]
                management admin user password USERNAME PASSWORD
                management admin user projects USERNAME
                management admin project generate [--count=N]
                management admin project list [PROJECTID] [--format=FORMAT]
                management admin project add [YAMLFILE]
                management admin project delete [PROJECTID]
                management admin project clear
                management admin project status [PROJECTID]
                management admin project activate [PROJECTID]
                management admin project deactivate [PROJECTID]
                management admin project close [PROJECTID]
                management admin project add [USERNAME] [PROJECTID] [ROLE]
                management admin project remove [USERNAME] [PROJECTID] [ROLE]
                management admin export [DATABASE] [COLLECTION] [--user=USERNAME] [--password=PASSWORD]
                management admin import [--file=FILENAME] [--dir=DIRNAME] [--db=DBNAME] [--collection=NAME]  [--user=USERNAME] [--password=PASSWORD]
                management committee setup
                management committee reviewer add [PROJECTID] [USERNAME]
                management committee reviewer remove [PROJECTID] [USERNAME]
                management committee list
                management committee project list [PROJECTID] [--format=FORMAT]
                management committee project status
                management committee project approve [PROJECTID]
                management committee project deny [PROJECTID]
                management committee project block [PROJECTID]
                management committee project activate [PROJECTID]
                management committee project close [PROJECTID]
                management committee project open [PROJECTID]
                management user apply [--user=USERFILE|--project=PROJECTFILE]
                management user configure [USERNAME]
                management user password
                management user status
                management user add-sshkey [FILENAME]

            Options:
                --format=json   Show the user details in json format

Workflow
========

User
    - User applies for an account using "cm management user apply --user=USERFILE
    - Configure user using "cm management user configure [USERNAME]

Admin
    - On getting notified (Notification is yet to be implemented), Check user status using "cm management admin user status"
    - Approve and activate the user using "cm management admin user approve USERNAME" and "cm management admin user activate USERNAME"
    - Assign a role if the user is other than a non-normal user using "cm management admin user assign [USERNAME] [ROLE]"

Committee
    - While setting up the system, set up a committee using the command "cm management committee setup"
    - On getting notified (Notification is yet to be implemented) about project approval request:
        - Approve a project using the command "cm management committee project approve [PROJECTID]"
        - Deny a project using the command "cm management committee project deny [PROJECTID]

Initialize the system
======================

Steps to initialize the system::

    cm management user configure [USERNAME]
        - This step puts an entry into the local hidden file under "**~/.cloudmesh/accounts/.config**"

Roles
=====

There are three roles at the moment in the system.

    User (user)
        General user
    Admin (admin)
        Role used to manage users like add/delete users, change user status, assign user role and assign password
    Reviewer (reviewer)
        Role used to add/remove reviewers, approve projects

Note::

    - When the system is installed, a super user named "super" is created with all the 3 roles assigned to it.
    - The Authorization is being imposed by a decorator function, which checks the roles assigned to the current user.
    - If the user has the required roles, the information is displayed else an error message is thrown.
    - The name of the current user is stored in a hidden configuration file under "**~/.cloudmesh/accounts/.config**"
    - This file can be used to store secret keys for the user later when authentication mechanism is being built.

Manage Users
============

To generate a list of users run::

    cm management user generate

To generate "n" number of users run::

    cm management user generate --count=n

To clear all the users within the database::

    cm management user clear

To set a password for a user::

    cm management user password <USERNAME> <PASSWORD>

.. note::

    The password is encrypted using sha256 encryption algorithm and the hash value is stored in Mongo.

To get a list of users run::

    cm management user list

To get detail about a particular user::

    cm management user list USERNAME

To add a user using a YAML file::

    cm management user add <PATH TO YAML FILE>

.. note::

    A sample YAML file is available in etc directory within managament

To amend a status of the user::

    * User will be in pending state by default
    * The commands to change the user status are cls explanatory

.. note::

    The state changes for a user is listed in the figure below:

.. figure:: docs/management_states.png

Manage Projects
===============

To generate a list of projects run::

    cm management project generate

To generate "n" number of dummy projects::

    cm management project generate --count=n

To clear the projects within the database::

    cm management project clear

To add a member to a project::

    cm management project add member <USERID> <PROJECTID> <ROLE>

.. note::

    The user roles are member, lead, alumni. When adding a user as a member or lead, the USERID should be available
    within the database. If not an error message would be displayed. An alumni need not be a valid user within the
    system. No check will be done against the alumni role. When you add a user as a lead or a member, user will be
    appended to the existing list accordingly.

To remove a member from a project::

    cm management project remove member <USERID> <PROJECTID>

To activate a project::

    cm management project activate <PROJECT ID>

To deactivate a project::

    cm management project deactivate <PROJECT ID>

To close a project::

    cm management project close <PROJECT ID>

Export/Import Collections
=========================

To export collection(s) from a database::

    cm management export <DATABASENAME> <COLLECTION NAME>

.. note::

    - To pass the username and password to access the database as parameters use --user=<USERNAME> and --password=<PASSWORD>. If the username and password is not passed, the system tried to get the details from the file, cloudmesh_server.yaml. If the details are not available in the yaml file, it tries to connect without them.

    - If <COLLECTION NAME> is not specified, the system tries to export all the non system collections to a json file and the file name would be the name of the collection.

To import data from json file into a database::

    cm management import --file=<FILE NAME> --db=<DATABASE NAME>

                        or

    cm management import --dir=<DIR NAME> --db=<DATABASE NAME>

.. note::

    - To pass the username and password to access the database as parameters use --user=<USERNAME> and --password=<PASSWORD>. If the username and password is not passed, the system tried to get the details from the file, cloudmesh_server.yaml. If the details are not available in the yaml file, it tries to connect without them.

    - A file name or a directory name needs to be passed as source of the data.

Yet to be done
==============

**Notification Mechanisms**
    When the user applies for an account/project, notification needs to be put in place to let the admin/reviewer know about the pending account/project request.

**Authentication and Security**
    Authentication and Security is yet to be done

**Add users in Bulk**
    At the moment, there is only an option to add single user from the yaml file. This needs to be extended to cover multiple users.

**Start mongo if mongo is not running while using the "cm management" commands**
    The file mongo.py has the code that is taken from mongo.py under **fabfile** directory in cloudmesh. This has three
    methods: "get_status", "start" and "stop". Need to understand the way cm works and where to hook these methods.


text:
import React from 'react'
import queryString from 'query-string'
import styled from 'styled-components'
import { Location } from 'history'

const Title = styled.div`
  font-size: 2em;
  font-weight: bold;
  margin-bottom: 0.2em;
`

const Error = ({ location }: { location: Location }) => (
  <div>
    <Title>Error</Title>
    {queryString.parse(location.search).text}
  </div>
)

export { Error }


text:
package de.akquinet.engineering.vaadin.demos.buffering;

import com.vaadin.data.Binder;
import com.vaadin.data.ValidationException;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import de.akquinet.engineering.vaadin.ComponentView;

import java.time.LocalDate;

/**
 * @author Axel Meier, akquinet engineering GmbH
 */
public class BufferingView implements View, ComponentView
{
    public static final String VIEW_NAME = "buffering";

    private final VerticalLayout rootLayout = new VerticalLayout();

    private boolean isBuffered = true;

    public BufferingView()
    {
        init();
    }

    private void init()
    {
        rootLayout.removeAllComponents();

        final TextField nameField = new TextField("Name");
        final TextField emailField = new TextField("Email");
        final TextField phoneField = new TextField("Phone");
        final DateField dateOfBirthField = new DateField("Birthday");

        final FormLayout formLayout = new FormLayout(nameField, emailField, phoneField, dateOfBirthField);

        final Contact contact = new Contact("John Doe", "john@doe.com", "555-123", LocalDate.of(1969, 7, 4));
        final Binder<Contact> binder = new Binder<>();
        binder.forField(nameField)
                .asRequired("name is mandatory")
                .bind(Contact::getName, Contact::setName);

        binder.forField(emailField)
                .withValidator(new EmailValidator("email is invalid"))
                .bind(Contact::getEmail, Contact::setEmail);

        binder.bind(phoneField, Contact::getPhoneNumber, Contact::setPhoneNumber);

        binder.forField(dateOfBirthField)
                .bind(Contact::getDateOfBirth, Contact::setDateOfBirth);

        if (isBuffered)
        {
            binder.readBean(contact);
        }
        else
        {
            // Loads the values from the person instance
            // Sets person to be updated when any bound field is updated
            binder.setBean(contact);
        }

        final Button saveButton = new Button("save", event ->
        {
            try
            {
                // write all or nothing depending on the validation
                binder.writeBean(contact);
            }
            catch (final ValidationException e)
            {
                Notification.show("validation error", Notification.Type.ERROR_MESSAGE);
            }
        });
        final Button cancelButton = new Button("cancel", event -> binder.readBean(contact));
        final Button showContactButton = new Button("showContact", event -> Notification.show(contact.toString()));
        final Button toggleBuffered = new Button();
        toggleBuffered.addClickListener(event ->
        {
            isBuffered = !isBuffered;
            init();
            updateToggleCaption(toggleBuffered);
        });
        updateToggleCaption(toggleBuffered);

        final HorizontalLayout buttonBar = new HorizontalLayout();
        buttonBar.addComponents(cancelButton, saveButton, showContactButton, toggleBuffered);
        rootLayout.addComponents(formLayout, buttonBar);
    }

    private void updateToggleCaption(final Button toggleBuffered)
    {
        toggleBuffered.setCaption("Buffered is " + (isBuffered ? "on" : "off"));
    }

    @Override
    public void enter(final ViewChangeListener.ViewChangeEvent event)
    {

    }

    @Override
    public Component getComponent()
    {
        return rootLayout;
    }
}


text:
'''
    Generic fake_wpilib launching script for RobotSnake

    -> This file is copied to all robots, and should not need to be
    modified at all
'''

import sys
import os.path

# setup the path correctly for the snake package to be loaded
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import snake

# directory that robot.py is located, relative to this file
# -> this automatically sets the path to a directory above, with the same
#    directory name that this file is in
robot_path = '../%s' % os.path.split(__file__)[1][:-3]

def run_tests(robot_module, myrobot):
    snake.launch_robot(robot_module, myrobot)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
org.omg.PortableServer (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

org.omg.PortableServer

接口

AdapterActivator

AdapterActivatorOperations

Current

CurrentOperations

ID_ASSIGNMENT_POLICY_ID

ID_UNIQUENESS_POLICY_ID

IdAssignmentPolicy

IdAssignmentPolicyOperations

IdUniquenessPolicy

IdUniquenessPolicyOperations

IMPLICIT_ACTIVATION_POLICY_ID

ImplicitActivationPolicy

ImplicitActivationPolicyOperations

LIFESPAN_POLICY_ID

LifespanPolicy

LifespanPolicyOperations

POA

POAManager

POAManagerOperations

POAOperations

REQUEST_PROCESSING_POLICY_ID

RequestProcessingPolicy

RequestProcessingPolicyOperations

SERVANT_RETENTION_POLICY_ID

ServantActivator

ServantActivatorOperations

ServantLocator

ServantLocatorOperations

ServantManager

ServantManagerOperations

ServantRetentionPolicy

ServantRetentionPolicyOperations

THREAD_POLICY_ID

ThreadPolicy

ThreadPolicyOperations

类

_ServantActivatorStub

_ServantLocatorStub

CurrentHelper

DynamicImplementation

ForwardRequestHelper

IdAssignmentPolicyValue

IdUniquenessPolicyValue

ImplicitActivationPolicyValue

LifespanPolicyValue

POAHelper

RequestProcessingPolicyValue

Servant

ServantActivatorHelper

ServantActivatorPOA

ServantLocatorHelper

ServantLocatorPOA

ServantRetentionPolicyValue

ThreadPolicyValue

异常

ForwardRequest


text:
from django.shortcuts import redirect
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.sites.models import Site, RequestSite
from django.contrib.auth.models import Group
from django.template.loader import render_to_string

from registration.models import RegistrationProfile

USER_FIELDS = ['username', 'email']

def moderate_user(strategy, details, user=None, *args, **kwargs):

    is_new = kwargs.get('is_new')

    # This user has authenticated but not yet moderated.
    if not is_new and not user.is_active:
        return redirect('register')

    if is_new:
        profile = RegistrationProfile.objects.create_profile(user)
        profile.verified = True
        profile.save()

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        # send a new user registration email explaining the next steps
        subject = render_to_string('registration/moderator_subject.txt', {
            'site': site
        })
        # no newlines
        subject = ''.join(subject.splitlines())
        message = render_to_string('registration/moderator_email.txt', {
            'site': site,
            'profile': profile
        })
        user.is_active = False
        moderators = (x[1] for x in settings.MANAGERS)
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, moderators)
        strategy.storage.user.changed(user)

        g = Group.objects.get(name='Consortium Members')
        g.user_set.add(user)
        g.save()


text:
package mesosphere.marathon.core.task.termination.impl

import akka.Done
import akka.actor.{ ActorRef, ActorSystem }
import mesosphere.marathon.MarathonSchedulerDriverHolder
import mesosphere.marathon.core.base.ConstantClock
import mesosphere.marathon.core.event.{ MesosStatusUpdateEvent, UnknownTaskTerminated }
import mesosphere.marathon.core.task.state.MarathonTaskStatus
import mesosphere.marathon.core.task.termination.TaskKillConfig
import mesosphere.marathon.core.task.tracker.TaskStateOpProcessor
import mesosphere.marathon.core.task.{ Task, TaskStateOp }
import mesosphere.marathon.state.{ PathId, Timestamp }
import mesosphere.marathon.test.{ MarathonTestHelper, Mockito }
import org.apache.mesos
import org.apache.mesos.SchedulerDriver
import org.mockito.ArgumentCaptor
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Millis, Span }
import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach, FunSuiteLike, GivenWhenThen, Matchers }
import org.slf4j.LoggerFactory

import scala.collection.JavaConverters._
import scala.concurrent.Promise
import scala.concurrent.duration._

class TaskKillServiceActorTest extends FunSuiteLike
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with GivenWhenThen
    with ScalaFutures
    with Matchers
    with Mockito {

  import TaskKillServiceActorTest.log

  test("Kill single known instance") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("a single, known running task")
    val task = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)

    When("the service is asked to kill that task")
    val promise = Promise[Done]()
    actor ! TaskKillServiceActor.KillTasks(Seq(task), promise)

    Then("a kill is issued to the driver")
    verify(f.driver, timeout(500)).killTask(task.taskId.mesosTaskId)

    When("a terminal status update is published via the event stream")
    f.publishStatusUpdate(task.taskId, mesos.Protos.TaskState.TASK_KILLED)

    Then("the promise is eventually completed successfully")
    promise.future.futureValue should be (Done)
  }

  test("Kill unknown task") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("an unknown taskId")
    val taskId = Task.Id.forRunSpec(PathId("/unknown"))

    When("the service is asked to kill that taskId")
    actor ! TaskKillServiceActor.KillUnknownTaskById(taskId)

    Then("a kill is issued to the driver")
    verify(f.driver, timeout(500)).killTask(taskId.mesosTaskId)

    When("a terminal status update is published via the event stream")
    f.publishUnknownTaskTerminated(taskId)

    Then("no more kills are issued")
    noMoreInteractions(f.driver)
  }

  test("Kill single known LOST task") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("a single, known running task")
    val task = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_LOST)

    When("the service is asked to kill that task")
    val promise = Promise[Done]()
    actor ! TaskKillServiceActor.KillTasks(Seq(task), promise)

    Then("NO kill is issued to the driver because the task is lost")
    noMoreInteractions(f.driver)

    And("the stateOpProcessor receives an expunge")
    verify(f.stateOpProcessor, timeout(500)).process(TaskStateOp.ForceExpunge(task.taskId))

    When("a terminal status update is published via the event stream")
    f.publishStatusUpdate(task.taskId, mesos.Protos.TaskState.TASK_KILLED)

    Then("the promise is eventually completed successfully")
    promise.future.futureValue should be (Done)
  }

  test("kill multiple instances at once") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("a list of tasks")
    val runningTask = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
    val lostTask = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_LOST)
    val stagingTask = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_STAGING)

    When("the service is asked to kill those tasks")
    val promise = Promise[Done]()
    actor ! TaskKillServiceActor.KillTasks(Seq(runningTask, lostTask, stagingTask), promise)

    Then("three kill requests are issued to the driver")
    verify(f.driver, timeout(500)).killTask(runningTask.taskId.mesosTaskId)
    verify(f.stateOpProcessor, timeout(500)).process(TaskStateOp.ForceExpunge(lostTask.taskId))
    verify(f.driver, timeout(500)).killTask(stagingTask.taskId.mesosTaskId)
    noMoreInteractions(f.driver)

    And("Eventually terminal status updates are published via the event stream")
    f.publishStatusUpdate(runningTask.taskId, mesos.Protos.TaskState.TASK_KILLED)
    f.publishStatusUpdate(lostTask.taskId, mesos.Protos.TaskState.TASK_LOST)
    f.publishStatusUpdate(stagingTask.taskId, mesos.Protos.TaskState.TASK_LOST)

    Then("the promise is eventually completed successfully")
    promise.future.futureValue should be (Done)
  }

  test("kill multiple tasks at once (empty list)") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("an empty list")
    val emptyList = Seq.empty[Task]

    When("the service is asked to kill those tasks")
    val promise = Promise[Done]()
    actor ! TaskKillServiceActor.KillTasks(emptyList, promise)

    Then("the promise is eventually completed successfully")
    promise.future.futureValue should be (Done)

    Then("no kill is issued")
    noMoreInteractions(f.driver)
  }

  test("kill multiple instances subsequently") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("multiple tasks")
    val task1 = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
    val task2 = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
    val task3 = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)

    val promise1 = Promise[Done]()
    val promise2 = Promise[Done]()
    val promise3 = Promise[Done]()

    When("the service is asked subsequently to kill those tasks")
    actor ! TaskKillServiceActor.KillTasks(Seq(task1), promise1)
    actor ! TaskKillServiceActor.KillTasks(Seq(task2), promise2)
    actor ! TaskKillServiceActor.KillTasks(Seq(task3), promise3)

    Then("exactly 3 kills are issued to the driver")
    verify(f.driver, timeout(500)).killTask(task1.taskId.mesosTaskId)
    verify(f.driver, timeout(500)).killTask(task2.taskId.mesosTaskId)
    verify(f.driver, timeout(500)).killTask(task3.taskId.mesosTaskId)
    noMoreInteractions(f.driver)

    And("Eventually terminal status updates are published via the event stream")
    f.publishStatusUpdate(task1.taskId, mesos.Protos.TaskState.TASK_KILLED)
    f.publishStatusUpdate(task2.taskId, mesos.Protos.TaskState.TASK_KILLED)
    f.publishStatusUpdate(task3.taskId, mesos.Protos.TaskState.TASK_KILLED)

    Then("the promises are eventually are completed successfully")
    promise1.future.futureValue should be (Done)
    promise2.future.futureValue should be (Done)
    promise3.future.futureValue should be (Done)
  }

  test("killing tasks is throttled (single requests)") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("multiple tasks")
    val tasks: Map[Task.Id, Task] = (1 to 10).map { index =>
      val task = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
      task.taskId -> task
    }(collection.breakOut)

    When("the service is asked to kill those tasks")
    tasks.values.foreach { task =>
      actor ! TaskKillServiceActor.KillTasks(Seq(task), Promise[Done]())
    }

    Then("5 kills are issued immediately to the driver")
    val captor: ArgumentCaptor[mesos.Protos.TaskID] = ArgumentCaptor.forClass(classOf[mesos.Protos.TaskID])
    verify(f.driver, timeout(5000).times(5)).killTask(captor.capture())
    reset(f.driver)

    And("after receiving terminal messages for the requested kills, 5 additional tasks are killed")
    captor.getAllValues.asScala.foreach { id =>
      val taskId = Task.Id(id)
      tasks.get(taskId).foreach { task =>
        f.publishStatusUpdate(task.taskId, mesos.Protos.TaskState.TASK_KILLED)
      }
    }

    verify(f.driver, timeout(500).times(5)).killTask(any)
    noMoreInteractions(f.driver)
  }

  test("killing tasks is throttled (batch request)") {
    val f = new Fixture
    val actor = f.createTaskKillActor()

    Given("multiple tasks")
    val tasks: Map[Task.Id, Task] = (1 to 10).map { index =>
      val task = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
      task.taskId -> task
    }(collection.breakOut)

    When("the service is asked to kill those tasks")
    val promise = Promise[Done]()
    actor ! TaskKillServiceActor.KillTasks(tasks.values, promise)

    Then("5 kills are issued immediately to the driver")
    val captor: ArgumentCaptor[mesos.Protos.TaskID] = ArgumentCaptor.forClass(classOf[mesos.Protos.TaskID])
    verify(f.driver, timeout(5000).times(5)).killTask(captor.capture())
    reset(f.driver)

    And("after receiving terminal messages for the requested kills, 5 additional tasks are killed")
    captor.getAllValues.asScala.foreach { id =>
      val taskId = Task.Id(id)
      tasks.get(taskId).foreach { task =>
        f.publishStatusUpdate(task.taskId, mesos.Protos.TaskState.TASK_KILLED)
      }
    }

    verify(f.driver, timeout(2000).times(5)).killTask(any)
    noMoreInteractions(f.driver)
  }

  test("kills will be retried") {
    val f = new Fixture
    val actor = f.createTaskKillActor(f.retryConfig)

    Given("a single, known running task")
    val task = f.mockTask(Task.Id.forRunSpec(f.appId), f.now(), mesos.Protos.TaskState.TASK_RUNNING)
    val promise = Promise[Done]()

    When("the service is asked to kill that task")
    actor ! TaskKillServiceActor.KillTasks(Seq(task), promise)

    Then("a kill is issued to the driver")
    verify(f.driver, timeout(500)).killTask(task.taskId.mesosTaskId)

    When("no statusUpdate is received and we reach the future")
    f.clock.+=(10.seconds)

    Then("the service will eventually retry")
    verify(f.driver, timeout(1000)).killTask(task.taskId.mesosTaskId)
  }

  private[this] implicit var actorSystem: ActorSystem = _
  private[this] var actor: ActorRef = _
  private[this] var actorCounter: Int = 0

  override protected def beforeAll(): Unit = {
    actorSystem = ActorSystem()
  }

  override protected def afterAll(): Unit = {
    actorSystem.terminate()
  }

  override protected def afterEach(): Unit = {
    actorSystem.stop(actor)
  }

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(timeout = scaled(Span(4000, Millis)))

  class Fixture {
    import scala.concurrent.duration._

    val appId = PathId("/test")
    val driver = mock[SchedulerDriver]
    val driverHolder: MarathonSchedulerDriverHolder = {
      val holder = new MarathonSchedulerDriverHolder
      holder.driver = Some(driver)
      holder
    }
    val defaultConfig: TaskKillConfig = new TaskKillConfig {
      override lazy val killChunkSize: Int = 5
      override lazy val killRetryTimeout: FiniteDuration = 10.minutes
    }
    val retryConfig: TaskKillConfig = new TaskKillConfig {
      override lazy val killChunkSize: Int = 5
      override lazy val killRetryTimeout: FiniteDuration = 500.millis
    }
    val stateOpProcessor: TaskStateOpProcessor = mock[TaskStateOpProcessor]
    val clock = ConstantClock()

    def createTaskKillActor(config: TaskKillConfig = defaultConfig): ActorRef = {
      actorCounter += 1
      actor = actorSystem.actorOf(TaskKillServiceActor.props(driverHolder, stateOpProcessor, config, clock), s"TaskKillService-$actorCounter")
      actor
    }

    def mockTask(taskId: Task.Id, stagedAt: Timestamp, mesosState: mesos.Protos.TaskState): Task.LaunchedEphemeral = {
      val mesosStatus: mesos.Protos.TaskStatus = MarathonTestHelper.statusForState(taskId.idString, mesosState)
      MarathonTestHelper.mininimalTask(taskId.idString, stagedAt, Some(mesosStatus))
    }

    def now(): Timestamp = Timestamp(0)
    def publishStatusUpdate(taskId: Task.Id, state: mesos.Protos.TaskState): Unit = {
      val appId = taskId.runSpecId
      val statusUpdateEvent =
        MesosStatusUpdateEvent(
          slaveId = "", taskId = taskId, taskStatus = state.toString, message = "", appId = appId, host = "",
          ipAddresses = None, ports = Nil, version = "version"
        )
      log.info("publish {} on the event stream", statusUpdateEvent)
      actorSystem.eventStream.publish(statusUpdateEvent)
    }

    def publishUnknownTaskTerminated(taskId: Task.Id): Unit = {
      val event = UnknownTaskTerminated(taskId, taskId.runSpecId, MarathonTaskStatus.Killed)
      log.info("publish {} on the event stream", event)
      actorSystem.eventStream.publish(event)
    }

  }
}

object TaskKillServiceActorTest {
  val log = LoggerFactory.getLogger(getClass)
}


text:
<?php

if ( class_exists( 'Tribe__Events__Filterbar__Filter' ) ) { // avoid a fatal error with older versions of filterbar

class Tribe__Events__Pro__Geo_Loc_Filter extends Tribe__Events__Filterbar__Filter {
	public $type = 'select';

	/**
	 * Default values for the distance filter (regardless of the actual unit of measure).
	 *
	 * @var array
	 */
	protected $distances = array( 5, 10, 25, 50, 100, 250 );

	protected function get_values() {
		$distances = array();
		$steps     = apply_filters( 'geoloc-values-for-filters', $this->distances );
		$unit      = tribe_get_option( 'geoloc_default_unit', 'miles' );

		switch ( $unit ) {
			case 'miles':
				$unit = __( 'Miles', 'tribe-events-calendar-pro' );
				break;
			case 'kms':
				$unit = __( 'Kilometers', 'tribe-events-calendar-pro' );
				break;
		}

		foreach ( $steps as $value ) {
			$distances[] = array(
				'name'  => sprintf( __( '%d %s', 'tribe-events-calendar-pro' ), $value, $unit ),
				'value' => $value,
			);
		}

		return $distances;
	}

	public function get_admin_form() {
		$title = $this->get_title_field();
		$type  = $this->get_type_field();

		return $title . $type;
	}

	protected function get_type_field() {
		$name  = $this->get_admin_field_name( 'type' );
		$field = sprintf( __( 'Type: %s %s', 'tribe-events-calendar-pro' ),
			sprintf( '<input type="radio" name="%s" value="select" %s /> %s',
				$name,
				checked( $this->type, 'select', false ),
				__( 'Dropdown', 'tribe-events-calendar-pro' )
			),
			sprintf( '<input type="radio" name="%s" value="radio" %s /> %s',
				$name,
				checked( $this->type, 'radio', false ),
				__( 'Radio Buttons', 'tribe-events-calendar-pro' )
			)
		);

		return '
' . $field . '
';
	}

	protected function setup_query_filters() {
		if ( $this->currentValue ) {
			add_filter( 'tribe_geoloc_geofence', array( $this, 'setup_geofence_in_query' ) );
		}
	}

	/**
	 * Alter the geofence size if necessary.
	 *
	 * Any corrections to the unit of measure that may be required will take place
	 * in Tribe__Events__Pro__Geo_Loc::get_geofence_size().
	 *
	 * @param $distance
	 *
	 * @return mixed
	 */
	public function setup_geofence_in_query( $distance ) {
		return ! empty( $this->currentValue ) ? $this->currentValue : $distance;
	}
}

}


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
Table of Contents

-   [10 Rules of Good Studying](#10-rules-of-good-studying)
-   [10 Rules of Bad Studying](#10-rules-of-bad-studying)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
These rules form a synthesis of some of the main ideas of the
course--they are excerpted from the book *A Mind for Numbers: How to
Excel in Math and Science (Even if You Flunked Algebra)*, by Barbara
Oakley, Penguin, July, 2014. Feel free to copy these rules and
redistribute them, as long as you keep the original wording and this
citation.

10 Rules of Good Studying
=========================

1.  **Use recall**. After you read a page, look away and recall the
    main ideas. Highlight very little, and never highlight anything you
    haven't put in your mind first by recalling. Try recalling main
    ideas when you are walking to class or in a different room from
    where you originally learned it. An ability to recall—to generate
    the ideas from inside yourself—is one of the key indicators of
    good learning.
2.  **Test yourself**. On everything. All the time. Flash cards are
    your friend.
3.  **Chunk your problems**. Chunking is understanding and practicing
    with a problem solution so that it can all come to mind in a flash.
    After you solve a problem, rehearse it. Make sure you can solve it
    cold—every step. Pretend it's a song and learn to play it over and
    over again in your mind, so the information combines into one smooth
    chunk you can pull up whenever you want.
4.  **Space your repetition**. Spread out your learning in any subject a
    little every day, just like an athlete. Your brain is like a
    muscle—it can handle only a limited amount of exercise on one
    subject at a time.
5.  **Alternate different problem-solving techniques during your
    practice**. Never practice too long at any one session using only
    one problem-solving technique—after a while, you are just mimicking
    what you did on the previous problem. Mix it up and work on
    different types of problems. This teaches you both how and when to
    use a technique. (Books generally are not set up this way, so you'll
    need to do this on your own.) After every assignment and test, go
    over your errors, make sure you understand why you made them, and
    then rework your solutions. To study most effectively, handwrite
    (don't type) a problem on one side of a flash card and the solution
    on the other. (Handwriting builds stronger neural structures in
    memory than typing.) You might also photograph the card if you want
    to load it into a study app on your smartphone. Quiz yourself
    randomly on different types of problems. Another way to do this is
    to randomly flip through your book, pick out a problem, and see
    whether you can solve it cold.
6.  **Take breaks**. It is common to be unable to solve problems or
    figure out concepts in math or science the first time you
    encounter them. This is why a little study every day is much better
    than a lot of studying all at once. When you get frustrated with a
    math or science problem, take a break so that another part of your
    mind can take over and work in the background.
7.  **Use explanatory questioning and simple analogies**. Whenever you
    are struggling with a concept, think to yourself, How can I explain
    this so that a ten-year-old could understand it? Using an analogy
    really helps, like saying that the flow of electricity is like the
    flow of water. Don't just think your explanation—say it out loud or
    put it in writing. The additional effort of speaking and writing
    allows you to more deeply encode (that is, convert into neural
    memory structures) what you are learning.
8.  **Focus**. Turn off all interrupting beeps and alarms on your phone
    and computer, and then turn on a timer for twenty-five minutes.
    Focus intently for those twenty-five minutes and try to work as
    diligently as you can. After the timer goes off, give yourself a
    small, fun reward. A few of these sessions in a day can really move
    your studies forward. Try to set up times and places where
    studying—not glancing at your computer or phone—is just something
    you naturally do.
9.  **Eat your frogs first**. Do the hardest thing earliest in the day,
    when you are fresh.
10. **Make a mental contrast**. Imagine where you've come from and
    contrast that with the dream of where your studies will take you.
    Post a picture or words in your workspace to remind you of
    your dream. Look at that when you find your motivation lagging. This
    work will pay off both for you and those you love!

10 Rules of Bad Studying
========================

Excerpted from *A Mind for Numbers: How to Excel in Math and Science
(Even if You Flunked Algebra)*, by Barbara Oakley, Penguin, July, 2014

Avoid these techniques—they can waste your time even while they fool you
into thinking you're learning!

1.  **Passive rereading—sitting passively and running your eyes back
    over a page**. Unless you can prove that the material is moving into
    your brain by recalling the main ideas without looking at the page,
    rereading is a waste of time.
2.  **Letting highlights overwhelm you**. Highlighting your text can
    fool your mind into thinking you are putting something in your
    brain, when all you're really doing is moving your hand. A little
    highlighting here and there is okay—sometimes it can be helpful in
    flagging important points. But if you are using highlighting as a
    memory tool, make sure that what you mark is also going into
    your brain.
3.  **Merely glancing at a problem's solution and thinking you know how
    to do it**. This is one of the worst errors students make
    while studying. You need to be able to solve a problem step-by-step,
    without looking at the solution.
4.  **Waiting until the last minute to study**. Would you cram at the
    last minute if you were practicing for a track meet? Your brain is
    like a muscle—it can handle only a limited amount of exercise on one
    subject at a time.
5.  **Repeatedly solving problems of the same type that you already know
    how to solve**. If you just sit around solving similar problems
    during your practice, you're not actually preparing for a test—it's
    like preparing for a big basketball game by just practicing
    your dribbling.
6.  **Letting study sessions with friends turn into chat sessions**.
    Checking your problem solving with friends, and quizzing one another
    on what you know, can make learning more enjoyable, expose flaws in
    your thinking, and deepen your learning. But if your joint study
    sessions turn to fun before the work is done, you're wasting your
    time and should find another study group.
7.  **Neglecting to read the textbook before you start working
    problems**. Would you dive into a pool before you knew how to swim?
    The textbook is your swimming instructor—it guides yolready know how
    to solve. If you just sit around solving similar problems during
    your practice, you're not actually preparing for a test—it's like
    preparing for a big basketball game by just practicing
    your dribbling.
8.  **Not checking with your instructors or classmates to clear up
    points of confusion**. Professors are used to lost students coming
    in for guidance—it's our job to help you. The students we worry
    about are the ones who don't come in. Don't be one of
    those students.
9.  **Thinking you can learn deeply when you are being constantly
    distracted**. Every tiny pull toward an instant message or
    conversation means you have less brain power to devote to learning.
    Every tug of interrupted attention pulls out tiny neural roots
    before they can grow.
10. **Not getting enough sleep**. Your brain pieces together
    problem-solving techniques when you sleep, and it also practices and
    repeats whatever you put in mind before you go to sleep. Prolonged
    fatigue allows toxins to build up in the brain that disrupt the
    neural connections you need to think quickly and well. If you don't
    get a good sleep before a test, NOTHING ELSE YOU HAVE DONE
    WILL MATTER.


text:
const pad = require("./pad");
module.exports = function padLeft(str, length, padString) {
  return pad(str, length, false, padString);
}


text:
% SET    Set object properties.
%    SET(H,'PropertyName',PropertyValue) sets the value of the specified
%    property for the graphics object with handle H.  H can be a vector of
%    handles, in which case SET sets the properties' values for all objects
%    of H.
%
%    SET(H,a) where a is a structure whose field names are object property
%    names, sets the properties named in each field name with the values
%    contained in the structure.
%
%    SET(H,pn,pv) sets the named properties specified in the cell array of
%    strings pn to the corresponding values in the cell array pv for all
%    objects specified in H.  The cell array pn must be 1-by-N, but the cell
%    array pv can be M-by-N where M is equal to length(H) so that each
%    object will be updated with a different set of values for the list of
%    property names contained in pn.
%
%    SET(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
%    sets multiple property values with a single statement.  Note that it
%    is permissible to use property/value string pairs, structures, and
%    property/value cell array pairs in the same call to SET.
%
%    A = SET(H, 'PropertyName')
%    SET(H,'PropertyName')
%    returns or displays the possible values for the specified property of
%    the object with handle H.  The returned array is a cell array of
%    possible value strings or an empty cell array if the property does not
%    have a finite set of possible string values.
%
%    A = SET(H)
%    SET(H)
%    returns or displays the names of the user-settable properties and
%    their possible values for the object with handle H.  The return value
%    is a structure whose field names are the user-settable property names
%    of H, and whose values are cell arrays of possible property values or
%    empty cell arrays.
%
%    The default value for an object property can be set on any of an
%    object's ancestors by setting the PropertyName formed by concatenating
%    the string 'Default', the object type, and the property name.  For
%    example, to set the default color of text objects to red in the current
%    figure window:
%
%       set(gcf,'DefaultTextColor','red')
%
%    Defaults can not be set on a descendant of the object, or on the
%    object itself - for example, a value for 'DefaultAxesColor' can not
%    be set on an axes or an axes child, but can be set on a figure or on
%    the root.
%
%    Three strings have special meaning for PropertyValues:
%      'default' - use default value (from nearest ancestor)
%      'factory' - use factory default value
%      'remove'  - remove default value.
%
%    See also GET, RESET, DELETE, GCF, GCA, FIGURE, AXES.
%
%    Reference page in Doc Center
%       doc set
%
%    Other functions named set
%
%       abstvar/set      editline/set        scribehgobj/set
%       arrowline/set    editrect/set        serial/set
%       axischild/set    figobj/set          splanar/set
%       axisobj/set      generic/set         timer/set
%       axistext/set     instrument/set      timeseries/set
%       COM/set          RandStream/set      ts/set
%       dataset/set      scribehandle/set    tscollection/set
%       dsge/set
%


text:
APatrolPoint::APatrolPoint()
{
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.Test.Utilities;
using System.IO;

namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
    internal static class ActiveStatementTestHelpers
    {
        internal static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfos(
            string[] markedSources,
            string extension = ".cs",
            int[]? methodRowIds = null,
            Guid[]? modules = null,
            int[]? methodVersions = null,
            int[]? ilOffsets = null,
            ActiveStatementFlags[]? flags = null)
        {
            IEnumerable<(TextSpan Span, int Id, SourceText Text, string DocumentName, DocumentId DocumentId)> EnumerateAllSpans()
            {
                var sourceIndex = 0;
                foreach (var markedSource in markedSources)
                {
                    var documentName = Path.Combine(TempRoot.Root, TestWorkspace.GetDefaultTestSourceDocumentName(sourceIndex, extension));
                    var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId(), documentName);
                    var text = SourceText.From(markedSource);

                    foreach (var (span, id) in ActiveStatementsDescription.GetActiveSpans(markedSource))
                    {
                        yield return (span, id, text, documentName, documentId);
                    }

                    sourceIndex++;
                }
            }

            IEnumerable<ManagedActiveStatementDebugInfo> Enumerate()
            {
                var moduleId = new Guid("00000000-0000-0000-0000-000000000001");
                var threadId = new Guid("00000000-0000-0000-0000-000000000010");

                var index = 0;
                foreach (var (span, id, text, documentName, documentId) in EnumerateAllSpans().OrderBy(s => s.Id))
                {
                    yield return new ManagedActiveStatementDebugInfo(
                        new ManagedInstructionId(
                            new ManagedMethodId(
                                (modules != null) ? modules[index] : moduleId,
                                new ManagedModuleMethodId(
                                    token: 0x06000000 | (methodRowIds != null ? methodRowIds[index] : index + 1),
                                    version: (methodVersions != null) ? methodVersions[index] : 1)),
                            ilOffset: (ilOffsets != null) ? ilOffsets[index] : 0),
                        documentName: documentName,
                        sourceSpan: text.Lines.GetLinePositionSpan(span).ToSourceSpan(),
                        flags: (flags != null) ? flags[index] : ((id == 0 ? ActiveStatementFlags.IsLeafFrame : ActiveStatementFlags.IsNonLeafFrame) | ActiveStatementFlags.MethodUpToDate));

                    index++;
                }
            }

            return Enumerate().ToImmutableArray();
        }

        public static string Delete(string src, string marker)
        {
            while (true)
            {
                var startStr = "/*delete" + marker;
                var endStr = "*/";
                var start = src.IndexOf(startStr);
                if (start == -1)
                {
                    return src;
                }

                var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length;
                src = src.Substring(0, start) + src.Substring(end);
            }
        }

        /// <summary>
        /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/.
        /// </summary>
        public static string InsertNewLines(string src, string marker)
        {
            while (true)
            {
                var startStr = "/*insert" + marker + "[";
                var endStr = "*/";

                var start = src.IndexOf(startStr);
                if (start == -1)
                {
                    return src;
                }

                var startOfLineCount = start + startStr.Length;
                var endOfLineCount = src.IndexOf(']', startOfLineCount);
                var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount));

                var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length;

                src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end);
            }
        }

        public static string Update(string src, string marker)
            => InsertNewLines(Delete(src, marker), marker);

        public static string InspectActiveStatement(ActiveStatement statement)
            => $"{statement.Ordinal}: {statement.Span} flags=[{statement.Flags}] pdid={statement.PrimaryDocumentId.DebugName} docs=[{string.Join(",", statement.DocumentIds.Select(d => d.DebugName))}]";

        public static string InspectActiveStatementAndInstruction(ActiveStatement statement)
            => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay();

        public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text)
            => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'";

        public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update)
            => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}";

        public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions)
            => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}");

        public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r)
            => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}";

        public static string GetFirstLineText(LinePositionSpan span, SourceText text)
            => text.Lines[span.Start.Line].ToString().Trim();
    }
}


text:
<?php

namespace Cloudflare\Organizations\Firewall\AccessRules;

use Cloudflare\Api;
use Cloudflare\Organizations;
use Cloudflare\Organizations\Firewall;

/**
 * CloudFlare API wrapper
 *
 * Organization-level Firewall access rule
 *
 * @author James Bell <james@james-bell.co.uk>
 *
 * @version 1
 */
class Rules extends Api
{
    /**
     * List access rules (permission needed: #organization:read)
     * Search, sort, and filter IP/country access rules
     *
     * @param string      $organization_id
     * @param string|null $mode                 The action to apply to a matched request
     * @param string|null $configuration_target The rule configuration target
     * @param string|null $configuration_value  Search by IP, range, or country code
     * @param int|null    $page                 Page number of paginated results
     * @param int|null    $per_page             Number of rules per page
     * @param string|null $order                Field to order rules by
     * @param string|null $direction            Direction to order rules
     * @param string|null $match                Whether to match all search requirements or at least one (any)
     */
    public function rules($organization_id, $mode = null, $configuration_target = null, $configuration_value = null, $page = null, $per_page = null, $order = null, $direction = null, $match = null)
    {
        $data = [
            'mode'                 => $mode,
            'configuration_target' => $configuration_target,
            'configuration_value'  => $configuration_value,
            'page'                 => $page,
            'per_page'             => $per_page,
            'order'                => $order,
            'direction'            => $direction,
            'match'                => $match,
        ];

        return $this->get('organizations/'.$organization_id.'/firewall/access_rules/rules', $data);
    }

    /**
     * Create access rule (permission needed: #organization:edit)
     * Make a new IP, IP range, or country access rule for all zones owned by the organization.
     * Note: If you would like to create an access rule that applies to a specific zone only, use the zone firewall endpoints.
     *
     * @param string      $organization_id
     * @param string      $mode            The action to apply to a matched request
     * @param object      $configuration   Rule configuration
     * @param string|null $notes           A personal note about the rule. Typically used as a reminder or explanation for the rule.
     */
    public function create($organization_id, $mode, $configuration, $notes = null)
    {
        $data = [
            'mode'          => $mode,
            'configuration' => $configuration,
            'notes'         => $notes,
        ];

        return $this->post('organizations/'.$organization_id.'/firewall/access_rules/rules', $data);
    }

    /**
     * Update access rule (permission needed: #organization:edit)
     * Update rule state and/or configuration. This will be applied across all zones owned by the organization.
     *
     * @param string      $organization_id
     * @param string      $identifier
     * @param string|null $mode            The action to apply to a matched request
     * @param object|null $configuration   Rule configuration
     * @param string|null $notes           A personal note about the rule. Typically used as a reminder or explanation for the rule.
     */
    public function update($organization_id, $identifier, $mode = null, $configuration = null, $notes = null)
    {
        $data = [
            'mode'          => $mode,
            'configuration' => $configuration,
            'notes'         => $notes,
        ];

        return $this->patch('organizations/'.$organization_id.'/firewall/access_rules/rules/'.$identifier, $data);
    }

    /**
     * Delete access rule (permission needed: #organization:edit)
     * Remove an access rule so it is no longer evaluated during requests. This will apply to all zones owned by the organization
     *
     * @param string $organization_id
     * @param string $identifier
     */
    public function delete_rule($organization_id, $identifier)
    {
        return $this->delete('organizations/'.$organization_id.'/firewall/access_rules/rules/'.$identifier);
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace Microsoft.Owin.Builder
{
    internal static class Constants
    {
        internal const string BuilderAddConversion = "builder.AddSignatureConversion";
        internal const string BuilderDefaultApp = "builder.DefaultApp";

        internal const string Invoke = "Invoke";
        internal const string Initialize = "Initialize";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<tool name="peer_assessment">
    <properties>
        <property
            name="section"
            value="basic" />
    </properties>
</tool>


text:
depot_git="/var/www/git/"
depot_site="/var/www/site/"
nom_user=$1

###Creation du fichier en cours.
cd $depot_site
sudo git clone $depot_git$nom_projet
sudo ./index.sh $nom_user
sudo ./vhost.sh $nom_user
sudo ./addfqdn.sh $nom_user


text:
sleep 15

# Where the user has the backup saved
backupDir=$1

if test "$1" == "" ; then
  echo "USAGE: $0 <backup directory>"
	exit
else

	vol_name="$(mount | tail -1 | cut -d' ' -f3)"

	# Echo the name of the last volume mounted

	# List the contents of $vol_name
	# ls -l $vol_name

	flashName=${vol_name:9}

	# We can have different files for different flashdrives
	# So when we plug in the flashdrive named ATIVA, we'll sync all files from FlashTransfer/ATIVA to the flashdrive

	#HDDsrc="/Users/isabella/Documents/FlashTransfer/$flashName"
	HDDsrc=$backupDir

	# Check if we already have a backup
	# If we don't print error
	# If we do, sync it
	if [ ! -d $HDDsrc ]; then
	 	echo -e "\n\nNo backup for this flash drive found.\nExiting..."
	else
		echo -e "\n\nCopying all files and directories\n=================================\n$HDDsrc   --to-->   $vol_name/$flashName\n\n"
		# add -q for quiet mode
		rsync -av --delete --progress --exclude=".*" $HDDsrc $vol_name
	fi

	echo -e "\n\n=====BACKUP COMPLETE====="

	#beep when finished
	echo -en "\007"
fi

# diskutil unmount vol_name


text:
<?php
/*
	Plugin Name: WP Redis
	Plugin URI: http://github.com/pantheon-systems/wp-redis/
	Description: WordPress Object Cache using Redis. Requires the PhpRedis extension (https://github.com/phpredis/phpredis).
	Version: 0.2.2
	Author: Pantheon, Josh Koenig, Matthew Boynes, Daniel Bachhuber Alley Interactive
	Author URI: https://pantheon.io/
*/
/*  This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


text:
namespace CSBackend
{
	namespace Windows
	{
		namespace WindowsFileUtils
		{
			//--------------------------------------------------------
			//--------------------------------------------------------
			BOOL WindowsCreateDirectory(LPCTSTR in_directory, LPSECURITY_ATTRIBUTES in_securityAttributes)
			{
				return CreateDirectory(in_directory, in_securityAttributes);
			}
			//--------------------------------------------------------
			//--------------------------------------------------------
			BOOL WindowsCopyFile(LPCTSTR in_sourceFilename, LPCTSTR in_destinationFilename, BOOL in_failIfExists)
			{
				return CopyFile(in_sourceFilename, in_destinationFilename, in_failIfExists);
			}
			//--------------------------------------------------------
			//--------------------------------------------------------
			BOOL WindowsDeleteFile(LPCTSTR in_filename)
			{
				return DeleteFile(in_filename);
			}
			//--------------------------------------------------------
			//--------------------------------------------------------
			BOOL WindowsRemoveDirectory(LPCTSTR in_directory)
			{
				return RemoveDirectory(in_directory);
			}
			//--------------------------------------------------------
			//--------------------------------------------------------
			HANDLE WindowsFindFirstFile(LPCTSTR in_directory, LPWIN32_FIND_DATA in_findFileData)
			{
				return FindFirstFile(in_directory, in_findFileData);
			}
			//--------------------------------------------------------
			//--------------------------------------------------------
			BOOL WindowsFindNextFile(HANDLE in_previousFile, LPWIN32_FIND_DATA in_findFileData)
			{
				return FindNextFile(in_previousFile, in_findFileData);
			}
		}
	}
}

#endif


text:
<!DOCTYPE html>

<meta charset='utf-8'>
<title>Crosswalk_CopyAndPaste_SelectAll_Copy</title>
<link rel="author" title="Intel" href="http://www.intel.com">

Test steps:

Launch app "web_support_copyandpaste_tests"

Copy all text in the "Select fields" field

Paste the text content in the "Paste fields" input box

  * Note: Copy/Paste option could be launched by long press or hotkey Ctrl+C/Ctrl+V

Expected Output:

The "web_support_copyandpaste_tests" web app is launched successfully.

Copy the text successfully and interface display normal

Text is pasted into the "Paste fields" field and the content is correctly


text:
function [ AUC_raw, AUC_filtered, AUC_interp, ...
    s_perf_data, ...
    filtered_data, ...
    interp_data ] = computePRData ( perf_data )
%% COMPUTEPRDATA plot the performance data for a precision/recall plot
% perf_data     the performance data matrix Nx11, each row contains a
%               threshold/score
% type          0 for classification, 1 for regression
% AUC_raw       the area under the curve (unfilterd data)
% AUC_filtered  the area under the curve (max-filterd data)
% AUC_interp    the area under the curve (interpolated data)
% s_perf_data   the raw performance data, sorted by recall
% filtered_data the max-filtered data matrix

% remove all NaN's from the precision and recall
nanindices = find(isnan(perf_data(:,3)) == 1);
perf_data(nanindices, :) = [];

% sort performance data by recall
s_perf_data = sortrows(perf_data, 2);
start = zeros(1,size(perf_data, 2));
start(3) = 1; % set the precision at recall 0 to 1.
s_perf_data = vertcat(start, s_perf_data(2:end,:));

%% interpolate the data
% get the max at each recall value
recalls = unique(s_perf_data(:,2));
filtered_data = zeros(length(recalls),2);
for recall_idx = 1 : length(recalls)
    recall_ = recalls(recall_idx);
    filtered_data(recall_idx, 1) = recall_;
    max_precision_ = max(s_perf_data(s_perf_data(:,2) == recall_, 3));
    filtered_data(recall_idx, 2) = max_precision_;
end

% search for interpolated points
ctr2 = 1;
nextIndex = -1;
interp_data = zeros(1,2);
previous = [0 1]; % start at 0,1
for recall_idx = 2 : length(recalls)
    % skip some elements
    if (recall_idx < nextIndex)
        continue;
    end

    %fprintf('recall_idx = %d\n', recall_idx);

    prev_recall_ = previous(1);
    prev_precision_ = previous(2);

    recall_ = filtered_data(recall_idx, 1);
    precision_ = filtered_data(recall_idx, 2);

    % starting from the current recall index
    % search for the next precision being equal or higher than the current
    next_max = max(...
        filtered_data(...
            filtered_data(:,1) >= recall_ &...
            filtered_data(:,2) >= precision_...
            , 2));
    prc_idx = find(filtered_data(:,2) == next_max, 1, 'last');

    max_precision_ = filtered_data(prc_idx, 2);

    % set the points
    interp_data(ctr2, 1) = prev_recall_;
    interp_data(ctr2, 2) = max_precision_;
    interp_data(ctr2+1, 1) = filtered_data(prc_idx, 1);
    interp_data(ctr2+1, 2) = max_precision_;

    % jump to the prc_idx
    nextIndex = prc_idx+1;
    % remember the previous recall
    previous = [filtered_data(prc_idx, 1), max_precision_];

    % increase counter
    ctr2 = ctr2 + 2;
end

% remove all information but recall and precision
s_perf_data = [s_perf_data(:,2), s_perf_data(:,3)];

%% compute the AUC
AUC_interp = trapz(interp_data(:,1), interp_data(:,2));
AUC_filtered = trapz(filtered_data(:,1), filtered_data(:,2));
AUC_raw = trapz(s_perf_data(:,1), s_perf_data(:,2));

return;
end


text:
require 'spec_helper'
require 'support/admin_abilities_in_mission_mode'
require 'support/admin_coordinator_shared_abilities'

describe 'abilities for users' do

  context 'for a coordinator' do
    before(:all) do
      @user = create(:user, :name => 'self', :role_name => 'coordinator')
      @user2 = create(:user, :name => 'other')
    end

    it_behaves_like 'admin or coordinator shared abilities'

    context 'in mission mode' do
      before(:all) do
        @ability = Ability.new(user: @user, mode: 'mission', mission: get_mission)
      end

      it 'should not allow adminify self or others' do
        expect(@ability).not_to be_able_to(:adminify, @user)
        expect(@ability).not_to be_able_to(:adminify, @user2)
      end

      it 'should not allow changing own assignments' do
        expect(@ability).not_to be_able_to(:change_assignments, @user)
      end
    end
  end

  context 'for an admin user' do

    before(:all) do
      @user = create(:user, :admin => true)
      @user2 = create(:user, :name => 'other')
    end

    it_behaves_like 'admin or coordinator shared abilities'

    context 'in mission mode' do

      context 'when assigned to mission' do
        it_behaves_like 'admin abilities in mission mode'
      end

      context 'when not assigned to mission' do
        before { @user.assignments.destroy_all }
        it_behaves_like 'admin abilities in mission mode'
      end
    end

    context 'in admin mode' do
      before(:all) do
        @ability = Ability.new(user: @user, mode: 'admin')
      end

      it 'should allow index and create' do
        expect(@ability).to be_able_to(:index, User)
        expect(@ability).to be_able_to(:create, User)
      end

      context 'for self' do
        it 'should allow show, edit, and chg assignments' do
          expect(@ability).to be_able_to(:show, @user)
          expect(@ability).to be_able_to(:update, @user)
          expect(@ability).to be_able_to(:change_assignments, @user)
        end

        it 'should disallow other actions' do
          expect(@ability).not_to be_able_to(:adminify, @user)
        end
      end

      context 'for other user' do
        it 'should allow all actions' do
          expect(@ability).to be_able_to(:show, @user2)
          expect(@ability).to be_able_to(:update, @user2)
          expect(@ability).to be_able_to(:change_assignments, @user2)
          expect(@ability).to be_able_to(:adminify, @user2)
        end
      end
    end
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Unit tests for BuildWarningEventArgs</summary>
//-----------------------------------------------------------------------

using System;

using Microsoft.Build.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Build.UnitTests
{
    /// <summary>
    /// Verify the functioning of the BuildWarningEventArgs class.
    /// </summary>
    [TestClass]
    public class BuildWarningEventArgs_Tests
    {
        /// <summary>
        /// Default event to use in tests.
        /// </summary>
        private BuildWarningEventArgs _baseWarningEvent = new BuildWarningEventArgs("Subcategory", "Code", "File", 1, 2, 3, 4, "Message", "HelpKeyword", "sender");

        /// <summary>
        /// Trivially exercise event args default ctors to boost Frameworks code coverage
        /// </summary>
        [TestMethod]
        public void EventArgsCtors()
        {
            BuildWarningEventArgs buildWarningEvent = new BuildWarningEventArgs2();
            buildWarningEvent = new BuildWarningEventArgs("Subcategory", "Code", "File", 1, 2, 3, 4, "Message", "HelpKeyword", "sender");
            buildWarningEvent = new BuildWarningEventArgs("Subcategory", "Code", "File", 1, 2, 3, 4, "Message", "HelpKeyword", "sender", DateTime.Now);
            buildWarningEvent = new BuildWarningEventArgs("Subcategory", "Code", "File", 1, 2, 3, 4, "{0}", "HelpKeyword", "sender", DateTime.Now, "Message");
            buildWarningEvent = new BuildWarningEventArgs(null, null, null, 1, 2, 3, 4, null, null, null);
            buildWarningEvent = new BuildWarningEventArgs(null, null, null, 1, 2, 3, 4, null, null, null, DateTime.Now);
            buildWarningEvent = new BuildWarningEventArgs(null, null, null, 1, 2, 3, 4, null, null, null, DateTime.Now, null);
        }

        /// <summary>
        /// Trivially exercise getHashCode.
        /// </summary>
        [TestMethod]
        public void TestGetHashCode()
        {
            _baseWarningEvent.GetHashCode();
        }

        /// <summary>
        /// Create a derrived class so that we can test the default constructor in order to increase code coverage and
        /// verify this code path does not cause any exceptions.
        /// </summary>
        private class BuildWarningEventArgs2 : BuildWarningEventArgs
        {
            /// <summary>
            /// Default constructor
            /// </summary>
            public BuildWarningEventArgs2()
                : base()
            {
            }
        }
    }
}


text:
package gui;

import java.awt.BorderLayout;
import java.awt.Frame;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

/**
 * Finestra della GUI principale, da cui si può accedere a tutte le funzioni del sistema.
 * E' leggermente diversa in base se l'utente è un amministratore o meno.
 */
@SuppressWarnings("serial")
public class Client extends JFrame {

	private String user;
	private boolean admin;

	/**
	 * Crea la finestra e inizializza tutti i suoi componenti.
	 * @param user L'username dell'utente loggato.
	 * @param admin Flag che indica se l'utente loggato è un amministratore.
	 */
	public Client(String user, boolean admin) {

		super();

		setIconImage(new ImageIcon("icon.png").getImage());
		setTitle("Sistema Schede Descrittive");
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		setExtendedState(Frame.MAXIMIZED_BOTH);
		getContentPane().setLayout(new BorderLayout());

		this.user = user;
		this.admin = admin;

		BarraMenu menu = new BarraMenu(this);
		setJMenuBar(menu);
	}

	/**
	 * Metodo get dell'username.
	 * @return L'username dell'utente loggato.
	 */
	String getUser() {
		return user;
	}

	/**
	 * Metodo get del flag admin.
	 * @return true se l'utente loggato è un amministratore, false altrimenti.
	 */
	boolean getAdmin() {
		return admin;
	}
}


text:
package com.tian.sort;

public class SelectionSort {

	public void selectSort(int[] data) {

	}

	public static void main(String[] args) {

	}

}