text:
package org.dspace.app.xmlui.wing.element;

/**
 * A class representing a radio input control. Radio input controls allow the
 * user to select one value among many. If the user selects one value then all
 * other values are set to off.
 *
 * @author Scott Phillips
 */

import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;

public class Radio extends Field
{

    /**
     * Construct a new field.
     *
     * @param context
     *            (Required) The context this element is contained in, such as
     *            where to route SAX events and what i18n catalogue to use.
     *
     * @param name
     *            (Required) a non-unique local identifier used to differentiate
     *            the element from its siblings within an interactive division.
     *            This is the name of the field use when data is submitted back
     *            to the server.
     * @param rend
     *            (May be null) a rendering hint used to override the default
     *            display of the element.
     */
    protected Radio(WingContext context, String name, String rend)
            throws WingException
    {
        super(context, name, Field.TYPE_RADIO, rend);
        this.params = new Params(context);
    }

    /**
     * Enable the add operation for this field. When this is enabled the
     * front end will add a button to add more items to the field.
     *
     */
    public void enableAddOperation() throws WingException
    {
        this.params.enableAddOperation();
    }

    /**
     * Enable the delete operation for this field. When this is enabled then
     * the front end will provide a way for the user to select fields (probably
     * checkboxes) along with a submit button to delete the selected fields.
     *
     */
    public void enableDeleteOperation()throws WingException
    {
        this.params.enableDeleteOperation();
    }

    /**
     * Add an option.
     *
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     */
    public Option addOption(String returnValue)
            throws WingException
    {
        Option option = new Option(context, returnValue);
        options.add(option);

        return option;
    }

    /**
     * Add an option.
     *
     * @param selected
     *            (Required) Set the field as selected.
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     */
    public Option addOption(boolean selected, String returnValue)
            throws WingException
    {
        if (selected)
        {
            setOptionSelected(returnValue);
        }
        return addOption(returnValue);
    }

    /**
     * Add an option.
     *
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param characters
     *            (Required) The text to set as the visible option.
     */
    public void addOption(String returnValue, String characters) throws WingException
    {
        Option option = this.addOption(returnValue);
        option.addContent(characters);
    }

    /**
     * Add an option.
     *
     * @param selected
     *            (Required) Set the field as selected.
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param characters
     *            (Required) The text to set as the visible option.
     */
    public void addOption(boolean selected,String returnValue, String characters) throws WingException
    {
        if (selected)
        {
            setOptionSelected(returnValue);
        }
        addOption(returnValue,characters);
    }

    /**
     * Add an option.
     *
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param characters
     *            (Required) The text to set as the visible option.
     */
    public void addOption(int returnValue, String characters) throws WingException
    {
        Option option = this.addOption(String.valueOf(returnValue));
        option.addContent(characters);
    }

    /**
     * Add an option.
     *
     * @param selected
     *            (Required) Set the field as selected.
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param characters
     *            (Required) The text to set as the visible option.
     */
    public void addOption(boolean selected, int returnValue, String characters) throws WingException
    {
        if (selected)
        {
            setOptionSelected(returnValue);
        }
        addOption(returnValue,characters);
    }

    /**
     * Add an option.
     *
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param message
     *            (Required) The transalted text to set as the visible option.
     */
    public void addOption(String returnValue, Message message) throws WingException
    {
        Option option = this.addOption(returnValue);
        option.addContent(message);
    }

    /**
     * Add an option.
     *
     * @param selected
     *            (Required) Set the field as selected.
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param message
     *            (Required) The transalted text to set as the visible option.
     */
    public void addOption(boolean selected, String returnValue, Message message) throws WingException
    {
        if (selected)
        {
            setOptionSelected(returnValue);
        }
        addOption(returnValue,message);
    }

    /**
     * Add an option.
     *
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param message
     *            (Required) The transalted text to set as the visible option.
     */
    public void addOption(int returnValue, Message message) throws WingException
    {
        Option option = this.addOption(String.valueOf(returnValue));
        option.addContent(message);
    }

    /**
     * Add an option.
     *
     * @param selected
     *            (Required) Set the field as selected.
     * @param returnValue
     *            (Required) The value to be passed back if this option is
     *            selected.
     * @param message
     *            (Required) The transalted text to set as the visible option.
     */
    public void addOption(boolean selected, int returnValue, Message message) throws WingException
    {
        if (selected)
        {
            setOptionSelected(returnValue);
        }
        addOption(returnValue,message);
    }

    /**
     * Set the given option as selected.
     *
     * @param returnValue
     *            (Required) The return value of the option to be selected.
     */
    public void setOptionSelected(String returnValue) throws WingException
    {
        Value value = new Value(context,Value.TYPE_OPTION,returnValue);
        values.add(value);
    }

    /**
     * Set the given option as selected.
     *
     * @param returnValue
     *            (Required) The return value of the option to be selected.
     */
    public void setOptionSelected(int returnValue) throws WingException
    {
        Value value = new Value(context,Value.TYPE_OPTION,String.valueOf(returnValue));
        values.add(value);
    }

    /**
     * Add a field instance
     * @return instance
     */
    public Instance addInstance() throws WingException
    {
        Instance instance = new Instance(context);
        instances.add(instance);
        return instance;
    }
}


text:
handle = open('numbers.txt','r')

index = 0
while True:
    line = handle.readline()
    if len(line) == 0:
        break
    fields = line.split()
    numbers = [int(x) for x in fields]
    for number in numbers:
        print number,
        if index % 10 == 9:
            print
        index += 1

if index % 10 == 9:
    print

handle.close()

redpajama_set_name: RedPajamaGithub


text:
import {
    CreateAction, CreateVoidAction, AsyncActions, IdMap, toIdMap,
    Action, toArray, AsyncCrudActionType, deleteFromMap, AsyncActionType
} from "../../../util/redux.util";
import {Injectable} from "@angular/core";
import {AppState} from "../../../state.module";
import {Store} from "@ngrx/store";
import {ConfigService} from "../../../service/config.service";
import {Effect, Actions} from "@ngrx/effects";
import {SchemaRepository, Schema} from "../../../model/schema.repository";
import {AlertService} from "../../../service/alert.service";
import {Alert, AlertType} from "../../../model/alert";
import {memoize} from "../../../util/decorator";

export interface SchemaRepositoryState {
    repositories:IdMap<SchemaRepository>;
    schemas:IdMap<Schema>;
    mappingStrategies: string[];
}

export const SchemaRepositoryStateInit:SchemaRepositoryState = {
    repositories: {},
    schemas: {},
    mappingStrategies: []
};

@Injectable()
export class SchemaRepositoryEffects {
    constructor(
        private actions:AsyncActions,
        private configurationService:ConfigService,
        private alertService:AlertService,
        private actions$:Actions,
    ) {}

    @Effect() mappingstrategies = this.actions
        .handleEffect(SchemaRepositoryActions.MAPPING_STRATEGIES, () => this.configurationService.getMappingStrategies());

    @Effect() package = this.actions
        .handleEffect(SchemaRepositoryActions.SCHEMA.READ, () => this.configurationService.getSchemas());

    @Effect() detail = this.actions
        .handleEffect(SchemaRepositoryActions.REPOSITORY.READ, () => this.configurationService.getSchemaRepositories());

    @Effect() repositoryCreate = this.actions
        .handleEffect<SchemaRepository>(SchemaRepositoryActions.REPOSITORY.CREATE, ({payload}) => this.configurationService.createSchemaRepository(payload).map(r => payload));

    @Effect() repoSchemaDelete = this.actions
        .handleEffect<SchemaRepository>(SchemaRepositoryActions.REPOSITORY.DELETE, ({payload}) => this.configurationService.deleteComponent(payload.id).map(r => payload));

    @Effect() repoSchemaUpdate = this.actions
        .handleEffect<SchemaRepository>(SchemaRepositoryActions.REPOSITORY.UPDATE, ({payload}) => this.configurationService.updateSchemaRepository(payload).map(r => payload));

    @Effect() schemaCreate = this.actions
        .handleEffect<Schema>(SchemaRepositoryActions.SCHEMA.CREATE, ({payload}) => this.configurationService.createSchema(payload).map(r => payload));

    @Effect() schemaUpdate = this.actions
        .handleEffect<Schema>(SchemaRepositoryActions.SCHEMA.UPDATE, ({payload}) => this.configurationService.updateSchema(payload).map(r => payload));

    @Effect() schemaDelete = this.actions
        .handleEffect<Schema>(SchemaRepositoryActions.SCHEMA.DELETE, ({payload}) => this.configurationService.deleteComponent(payload.id).map(r => payload));

    @Effect({dispatch:false}) alerts = this.actions$.ofType(...Object.keys(Messages))
        .do((action) => {
            const [type, message] = Messages[action.type];
            this.alertService.add(new Alert(type, message((action as any).payload.id), true));
        })
}

@Injectable()
export class SchemaRepositoryActions {
    static SCHEMA = AsyncCrudActionType('SCHEMA');
    static REPOSITORY = AsyncCrudActionType('REPOSITORY')
    static MAPPING_STRATEGIES = AsyncActionType('MAPPING_STRATEGY');

    constructor(private store:Store<AppState>) {}

    fetchSchema() {
        this.store.dispatch(CreateVoidAction(SchemaRepositoryActions.SCHEMA.READ.FETCH))
    }

    fetchRepository() {
        this.store.dispatch(CreateVoidAction(SchemaRepositoryActions.REPOSITORY.READ.FETCH))
    }

    fetchMappingStrategies() {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.MAPPING_STRATEGIES.FETCH))
    }

    createSchema(newGlobalSchema: Schema) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.SCHEMA.CREATE.FETCH, newGlobalSchema))
    }

    updateSchema(schema:Schema) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.SCHEMA.UPDATE.FETCH, schema))
    }

    deleteSchema(selected: Schema) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.SCHEMA.DELETE.FETCH, selected))
    }

    createRepository(newRepository: SchemaRepository) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.REPOSITORY.CREATE.FETCH, newRepository))
    }

    updateRepository(repository: SchemaRepository) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.REPOSITORY.UPDATE.FETCH, repository))
    }

    deleteRepository(repo:SchemaRepository) {
        this.store.dispatch(CreateAction(SchemaRepositoryActions.REPOSITORY.DELETE.FETCH, repo))
    }
}

type IMessages = IdMap<[AlertType, (id:string)=>string]>;
const Messages:IMessages = {
    [SchemaRepositoryActions.REPOSITORY.CREATE.SUCCESS]:['success', (id:string) => `Successfully created repository ${id}`],
    [SchemaRepositoryActions.REPOSITORY.DELETE.SUCCESS]:['success', (id:string) => `Successfully deleted repository ${id}`],
    [SchemaRepositoryActions.REPOSITORY.UPDATE.SUCCESS]:['success', (id:string) => `Successfully updated repository ${id}`],
    [SchemaRepositoryActions.SCHEMA.CREATE.SUCCESS]:['success', (id:string) => `Successfully created schema ${id}`],
    [SchemaRepositoryActions.SCHEMA.DELETE.SUCCESS]:['success', (id:string) => `Successfully deleted schema  ${id}`],
    [SchemaRepositoryActions.SCHEMA.UPDATE.SUCCESS]:['success', (id:string) => `Successfully updated schema  ${id}`],
    [SchemaRepositoryActions.REPOSITORY.CREATE.FAILED]:['danger', (id:string) => `Failed to create repository ${id}`],
    [SchemaRepositoryActions.REPOSITORY.DELETE.FAILED]:['danger', (id:string) => `Failed to delete repository ${id}`],
    [SchemaRepositoryActions.REPOSITORY.UPDATE.FAILED]:['danger', (id:string) => `Failed to update repository ${id}`],
    [SchemaRepositoryActions.SCHEMA.CREATE.FAILED]:['danger', (id:string) => `Failed to create schema ${id}`],
    [SchemaRepositoryActions.SCHEMA.DELETE.FAILED]:['danger', (id:string) => `Failed to delete schema ${id}`],
    [SchemaRepositoryActions.SCHEMA.UPDATE.FAILED]:['danger', (id:string) => `Failed to update schema ${id}`]
};

@Injectable()
export class SchemaRepositoryStateService {
    constructor(private store:Store<AppState>) {}

    get schemas() {
        return this.store.select(s => s.configuration.schemaRepository.schemas).map(toArray)
    }

    get repositories() {
        return this.store.select(s => s.configuration.schemaRepository.repositories).map(toArray)
    }

    get mappingStrategies() {
        return this.store.select(s => s.configuration.schemaRepository.mappingStrategies)
    }

    @memoize()
    getRepository(byId:string) {
        return this.store.select(s => s.configuration.schemaRepository.repositories[byId])
    }

    @memoize()
    getSchema(byId:string) {
        return this.store.select(s => s.configuration.schemaRepository.schemas[byId])
    }
}

export function reduce (state:SchemaRepositoryState = SchemaRepositoryStateInit, action:Action<any>): SchemaRepositoryState {
    switch(action.type) {
        case SchemaRepositoryActions.REPOSITORY.READ.SUCCESS: {
            const {payload:repos} = action as Action<SchemaRepository[]>;
            return ({
                ...state,
                repositories: toIdMap(repos, r => r.id)
            })

        }
        case SchemaRepositoryActions.SCHEMA.READ.SUCCESS: {
            const {payload:schemas} = action as Action<Schema[]>;
            return ({
                ...state,
                schemas: toIdMap(schemas, s => s.id)
            })
        }
        case SchemaRepositoryActions.SCHEMA.CREATE.SUCCESS: {
            return ({
                ...state,
                schemas: { ...state.schemas, [action.payload.id]: action.payload}
            })
        }
        case SchemaRepositoryActions.SCHEMA.UPDATE.SUCCESS: {
            return ({
                ...state,
                schemas: {...state.schemas, [action.payload.id]: action.payload}
            })
        }
        case SchemaRepositoryActions.SCHEMA.DELETE.SUCCESS: {
            return ({
                ...state,
                schemas: deleteFromMap(state.schemas, action.payload.id)
            })
        }
        case SchemaRepositoryActions.REPOSITORY.CREATE.SUCCESS: {
            return ({
                ...state,
                repositories: { ...state.repositories, [action.payload.id]: action.payload}
            })
        }
        case SchemaRepositoryActions.REPOSITORY.UPDATE.SUCCESS: {
            return ({
                ...state,
                repositories: { ...state.repositories, [action.payload.id]: action.payload}
            })
        }
        case SchemaRepositoryActions.REPOSITORY.DELETE.SUCCESS: {
            return ({
                ...state,
                repositories: deleteFromMap(state.repositories, action.payload.id)
            })
        }
        case SchemaRepositoryActions.MAPPING_STRATEGIES.SUCCESS: {
            return ({
                ...state,
                mappingStrategies: action.payload
            })
        }
    }
    return state;
}


text:
#ifndef __LIBSTUDIO_PCH_H__
#define __LIBSTUDIO_PCH_H__

#include <memory>
#include <list>
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>

#include <stdlib.h>
#ifdef _WIN32
#include <sdkddkver.h>
#include <process.h>
#else
#include <unistd.h>
#define _getpid getpid
#endif

namespace std
{
	inline std::ostream& operator << (std::ostream& o, const std::string& str)
	{
		return o << str.c_str();
	}
}

#endif //__LIBSTUDIO_PCH_H__


text:
import $ from 'jquery';
import stateCountry from '../common/state-country';
import nod from '../common/nod';
import utils from 'bigcommerce/stencil-utils';
import { Validators } from '../common/form-utils';

export default class ShippingEstimator {
    constructor($element) {
        this.$element = $element;

        this.$state = $('[data-field-type="State"]', this.$element);
        this.initFormValidation();
        this.bindStateCountryChange();
        this.bindEstimatorEvents();
    }

    initFormValidation() {
        this.shippingEstimator = 'form[data-shipping-estimator]';
        this.shippingValidator = nod({
            submit: `${this.shippingEstimator} .shipping-estimate-submit`,
        });

        $('.shipping-estimate-submit', this.$element).click((event) => {
            // When switching between countries, the state/region is dynamic
            // Only perform a check for all fields when country has a value
            // Otherwise areAll('valid') will check country for validity
            if ($(`${this.shippingEstimator} select[name="shipping-country"]`).val()) {
                this.shippingValidator.performCheck();
            }

            if (this.shippingValidator.areAll('valid')) {
                return;
            }

            event.preventDefault();
        });

        this.bindValidation();
        this.bindStateValidation();
        this.bindUPSRates();
    }

    bindValidation() {
        this.shippingValidator.add([
            {
                selector: `${this.shippingEstimator} select[name="shipping-country"]`,
                validate: (cb, val) => {
                    const countryId = Number(val);
                    const result = countryId !== 0 && !isNaN(countryId);

                    cb(result);
                },
                errorMessage: 'The \'Country\' field cannot be blank.',
            },
        ]);
    }

    bindStateValidation() {
        this.shippingValidator.add([
            {
                selector: $(`${this.shippingEstimator} select[name="shipping-state"]`),
                validate: (cb) => {
                    let result;

                    const $ele = $(`${this.shippingEstimator} select[name="shipping-state"]`);

                    if ($ele.length) {
                        const eleVal = $ele.val();

                        result = eleVal && eleVal.length && eleVal !== 'State/province';
                    }

                    cb(result);
                },
                errorMessage: 'The \'State/Province\' field cannot be blank.',
            },
        ]);
    }

    /**
     * Toggle between default shipping and ups shipping rates
     */
    bindUPSRates() {
        const UPSRateToggle = '.estimator-form-toggleUPSRate';

        $('body').on('click', UPSRateToggle, (event) => {
            const $estimatorFormUps = $('.estimator-form--ups');
            const $estimatorFormDefault = $('.estimator-form--default');

            event.preventDefault();

            $estimatorFormUps.toggleClass('u-hiddenVisually');
            $estimatorFormDefault.toggleClass('u-hiddenVisually');
        });
    }

    bindStateCountryChange() {
        let $last;

        // Requests the states for a country with AJAX
        stateCountry(this.$state, this.context, { useIdForStates: true }, (err, field) => {
            if (err) {
                alert(err);

                throw new Error(err);
            }

            const $field = $(field);

            if (this.shippingValidator.getStatus(this.$state) !== 'undefined') {
                this.shippingValidator.remove(this.$state);
            }

            if ($last) {
                this.shippingValidator.remove($last);
            }

            if ($field.is('select')) {
                $last = field;
                this.bindStateValidation();
            } else {
                $field.attr('placeholder', 'State/province');
                Validators.cleanUpStateValidation(field);
            }

            // When you change a country, you swap the state/province between an input and a select dropdown
            // Not all countries require the province to be filled
            // We have to remove this class when we swap since nod validation doesn't cleanup for us
            $(this.shippingEstimator).find('.form-field--success').removeClass('form-field--success');
        });
    }

    bindEstimatorEvents() {
        const $estimatorContainer = $('.shipping-estimator');
        const $estimatorForm = $('.estimator-form');

        $estimatorForm.on('submit', (event) => {
            const params = {
                country_id: $('[name="shipping-country"]', $estimatorForm).val(),
                state_id: $('[name="shipping-state"]', $estimatorForm).val(),
                city: $('[name="shipping-city"]', $estimatorForm).val(),
                zip_code: $('[name="shipping-zip"]', $estimatorForm).val(),
            };

            event.preventDefault();

            utils.api.cart.getShippingQuotes(params, 'cart/shipping-quotes', (err, response) => {
                $('.shipping-quotes').html(response.content);

                // bind the select button
                $('.select-shipping-quote').on('click', (clickEvent) => {
                    const quoteId = $('.shipping-quote:checked').val();

                    clickEvent.preventDefault();

                    utils.api.cart.submitShippingQuote(quoteId, () => {
                        location.reload();
                    });
                });
            });
        });

        $('.shipping-estimate-show').on('click', (event) => {
            event.preventDefault();

            $(event.currentTarget).hide();
            $estimatorContainer.removeClass('u-hiddenVisually');
            $('.shipping-estimate-hide').show();
        });

        $('.shipping-estimate-hide').on('click', (event) => {
            event.preventDefault();

            $estimatorContainer.addClass('u-hiddenVisually');
            $('.shipping-estimate-show').show();
            $('.shipping-estimate-hide').hide();
        });
    }
}


text:
#region Usings

using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Akavache;
using ModInstallation.Annotations;
using ModInstallation.Interfaces.Net;

#endregion

namespace ModInstallation.Implementations.Net
{
    public abstract class CachingWebClient : IWebClient
    {
        #region IWebClient Members

        public Task<string> GetStringAsync(Uri uri, CancellationToken token, TimeSpan? cacheDuration = null)
        {
            if (cacheDuration.HasValue)
            {
                return GetFromCache(uri, token, cacheDuration.Value);
            }

            return ActuallyGetStringAsync(uri, token);
        }

        public abstract Task DownloadAsync(Uri uri, string destination, Action<DownloadProgress> downloadReporter, CancellationToken token);

        #endregion

        [NotNull]
        protected abstract Task<string> ActuallyGetStringAsync([NotNull] Uri uri, CancellationToken token);

        [NotNull]
        private async Task<string> GetFromCache([NotNull] Uri uri, CancellationToken token, TimeSpan cacheDuration)
        {
            var cacheKey = uri.ToString();
            string content = null;
            try
            {
                content = await BlobCache.LocalMachine.GetObject<string>(cacheKey);
            }
            catch (KeyNotFoundException)
            {
                // Key is not in the cache
            }

            if (content != null)
            {
                return content;
            }

            content = await ActuallyGetStringAsync(uri, token);

            await BlobCache.LocalMachine.InsertObject(cacheKey, content, cacheDuration);

            return content;
        }
    }
}


text:
<?php

namespace Scalr\Modules\Platforms\Ec2\Observers;

use Scalr\Service\Aws\Ec2\DataType\CreateVolumeRequestData;
use \DBFarmRole;

class EbsObserver extends \EventObserver
{

    public $ObserverName = 'Elastic Block Storage';

    function __construct()
    {
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnBeforeInstanceLaunch()
     */
    public function OnBeforeInstanceLaunch(\BeforeInstanceLaunchEvent $event)
    {
        if ($event->DBServer->platform != \SERVER_PLATFORMS::EC2) {
            return;
        }
        $DBFarm = $event->DBServer->GetFarmObject();
        $DBFarmRole = $event->DBServer->GetFarmRoleObject();

        // Create EBS volume for MySQLEBS
        if (!$event->DBServer->IsSupported("0.6")) {
            // Only for old AMIs
            if ($DBFarmRole->GetRoleObject()->hasBehavior(\ROLE_BEHAVIORS::MYSQL) &&
                $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE) == \MYSQL_STORAGE_ENGINE::EBS) {

                $server = $event->DBServer;
                $masterServer = $DBFarm->GetMySQLInstances(true);
                $isMaster = !$masterServer || $masterServer[0]->serverId == $server->serverId;
                $farmMasterVolId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID);
                $createEbs = ($isMaster && !$farmMasterVolId);

                if ($createEbs) {
                    \Logger::getLogger(\LOG_CATEGORY::FARM)->info(
                        new \FarmLogMessage($event->DBServer->farmId, sprintf(
                            _("Need EBS volume for MySQL %s instance..."),
                            ($isMaster ? "Master" : "Slave")
                        ))
                    );

                    $req = new CreateVolumeRequestData(
                        $event->DBServer->GetProperty(\EC2_SERVER_PROPERTIES::AVAIL_ZONE),
                        $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_VOLUME_SIZE)
                    );
                    $aws = $event->DBServer->GetEnvironmentObject()->aws($DBFarmRole->CloudLocation);
                    $res = $aws->ec2->volume->create($req);

                    if (!empty($res->volumeId)) {
                        $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID, $res->volumeId, DBFarmRole::TYPE_LCL);
                        \Logger::getLogger(\LOG_CATEGORY::FARM)->info(
                            new \FarmLogMessage($event->DBServer->farmId, sprintf(
                                _("MySQL %S volume created. Volume ID: %s..."),
                                ($isMaster ? "Master" : "Slave"),
                                $res->volumeId
                            ))
                        );
                    }
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnFarmTerminated()
     */
    public function OnFarmTerminated(\FarmTerminatedEvent $event)
    {
        $this->Logger->info("Keep EBS volumes: {$event->KeepEBS}");
        if ($event->KeepEBS == 1) {
            return;
        }
        $this->DB->Execute("UPDATE ec2_ebs SET attachment_status=? WHERE farm_id=? AND ismanual='0'", array(
            \EC2_EBS_ATTACH_STATUS::DELETING,
            $this->FarmID
        ));
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnEBSVolumeAttached()
     */
    public function OnEBSVolumeAttached(\EBSVolumeAttachedEvent $event)
    {
        if ($event->DeviceName) {
            try {
                $DBEBSVolume = \DBEBSVolume::loadByVolumeId($event->VolumeID);

                $DBEBSVolume->serverId = $event->DBServer->serverId;
                $DBEBSVolume->deviceName = $event->DeviceName;
                $DBEBSVolume->attachmentStatus = \EC2_EBS_ATTACH_STATUS::ATTACHED;
                //$DBEBSVolume->isFsExists = 1;

                $DBEBSVolume->save();
            } catch (\Exception $e) {
            }
        }
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnEBSVolumeMounted()
     */
    public function OnEBSVolumeMounted(\EBSVolumeMountedEvent $event)
    {
        try {
            $DBEBSVolume = \DBEBSVolume::loadByVolumeId($event->VolumeID);

            $DBEBSVolume->mountStatus = \EC2_EBS_MOUNT_STATUS::MOUNTED;
            $DBEBSVolume->deviceName = $event->DeviceName;
            $DBEBSVolume->isFsExists = 1;

            $DBEBSVolume->save();
        } catch (\Exception $e) {}
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnHostUp()
     */
    public function OnHostUp(\HostUpEvent $event)
    {
        if ($event->DBServer->platform != \SERVER_PLATFORMS::EC2) return;
        // Scalarizr will attach and mount volumes by itself
        if ($event->DBServer->IsSupported("0.7.36")) {
            return;
        }

        $volumes = $this->DB->GetAll("SELECT volume_id FROM ec2_ebs WHERE farm_roleid=? AND server_index=?", array(
            $event->DBServer->farmRoleId,
            $event->DBServer->index
        ));

        $this->Logger->info(new \FarmLogMessage($this->FarmID, sprintf(
            _("Found %s volumes for server: %s"), count($volumes), $event->DBServer->serverId
        )));

        foreach ($volumes as $volume) {
            if ($volume['volume_id']) {

                $this->Logger->info(new \FarmLogMessage($this->FarmID, sprintf(
                    _("Preparing volume #%s for attaching to server: %s."),
                    $volume['volume_id'], $event->DBServer->serverId
                )));

                try {
                    $DBEBSVolume = \DBEBSVolume::loadByVolumeId($volume['volume_id']);

                    $DBEBSVolume->serverId = $event->DBServer->serverId;
                    $DBEBSVolume->attachmentStatus = \EC2_EBS_ATTACH_STATUS::ATTACHING;
                    $DBEBSVolume->mountStatus = ($DBEBSVolume->mount) ?
                        \EC2_EBS_MOUNT_STATUS::AWAITING_ATTACHMENT : \EC2_EBS_MOUNT_STATUS::NOT_MOUNTED;

                    $DBEBSVolume->save();
                } catch (\Exception $e) {
                    $this->Logger->fatal($e->getMessage());
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnHostInit()
     */
    public function OnHostInit(\HostInitEvent $event)
    {
        if ($event->DBServer->platform != \SERVER_PLATFORMS::EC2) {
            return;
        }

        $DBFarmRole = $event->DBServer->GetFarmRoleObject();

        if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_USE_EBS)) {
            if (!$this->DB->GetOne("
                    SELECT id FROM ec2_ebs
                    WHERE farm_roleid=? AND server_index=? AND ismanual='0'
                    LIMIT 1
                ", array(
                    $event->DBServer->farmRoleId,
                    $event->DBServer->index
                ))) {

                if (in_array($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_TYPE), array('standard','io1', 'gp2'))) {
                    $type = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_TYPE);
                } else {
                    $type = 'standard';
                }

                $DBEBSVolume = new \DBEBSVolume();
                $DBEBSVolume->attachmentStatus = \EC2_EBS_ATTACH_STATUS::CREATING;
                $DBEBSVolume->isManual = 0;
                $DBEBSVolume->ec2AvailZone = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_AVAIL_ZONE);
                $DBEBSVolume->ec2Region = $event->DBServer->GetProperty(\EC2_SERVER_PROPERTIES::REGION);
                $DBEBSVolume->farmId = $DBFarmRole->FarmID;
                $DBEBSVolume->farmRoleId = $DBFarmRole->ID;
                $DBEBSVolume->serverId = $event->DBServer->serverId;
                $DBEBSVolume->serverIndex = $event->DBServer->index;
                $DBEBSVolume->size = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_SIZE);
                $DBEBSVolume->type = $type;
                $DBEBSVolume->iops = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_IOPS);
                $DBEBSVolume->snapId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_SNAPID);
                $DBEBSVolume->isFsExists = ($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_SNAPID)) ? 1 : 0;
                $DBEBSVolume->mount = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_MOUNT);
                $DBEBSVolume->mountPoint = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_MOUNTPOINT);
                $DBEBSVolume->mountStatus = ($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_MOUNT)) ?
                    \EC2_EBS_MOUNT_STATUS::AWAITING_ATTACHMENT : \EC2_EBS_MOUNT_STATUS::NOT_MOUNTED;
                $DBEBSVolume->clientId = $event->DBServer->GetFarmObject()->ClientID;
                $DBEBSVolume->envId = $event->DBServer->envId;

                $DBEBSVolume->Save();
            }
        }
    }

    /**
     * {@inheritdoc}
     * @see EventObserver::OnHostDown()
     */
    public function OnHostDown(\HostDownEvent $event)
    {
        if ($event->DBServer->platform != \SERVER_PLATFORMS::EC2) {
            return;
        }
        if ($event->DBServer->IsRebooting()) {
            return;
        }
        $this->DB->Execute("
            UPDATE ec2_ebs
            SET attachment_status=?,
                mount_status=?,
                device='',
                server_id=''
            WHERE server_id=? AND attachment_status != ?
        ", array(
            \EC2_EBS_ATTACH_STATUS::AVAILABLE,
            \EC2_EBS_MOUNT_STATUS::NOT_MOUNTED,
            $event->DBServer->serverId,
            \EC2_EBS_ATTACH_STATUS::CREATING
        ));
    }
}


text:
#include <shogun/lib/common.h>
#include <shogun/kernel/ShiftInvariantKernel.h>
#include <shogun/distance/CustomDistance.h>

using namespace shogun;

CShiftInvariantKernel::CShiftInvariantKernel() : CKernel(0)
{
	register_params();
}

CShiftInvariantKernel::CShiftInvariantKernel(CFeatures *l, CFeatures *r) : CKernel(l, r, 0)
{
	register_params();
	init(l, r);
}

CShiftInvariantKernel::~CShiftInvariantKernel()
{
	cleanup();
	SG_UNREF(m_distance);
}

bool CShiftInvariantKernel::init(CFeatures* l, CFeatures* r)
{
	REQUIRE(m_distance, "The distance instance cannot be NULL!\n");
	CKernel::init(l,r);
	m_distance->init(l, r);
	return init_normalizer();
}

void CShiftInvariantKernel::precompute_distance()
{
	REQUIRE(m_distance, "The distance instance cannot be NULL!\n");
	REQUIRE(m_distance->init(lhs, rhs), "Could not initialize the distance instance!\n");

	SGMatrix<float32_t> dist_mat=m_distance->get_distance_matrix<float32_t>();
	if (m_precomputed_distance==NULL)
	{
		m_precomputed_distance=new CCustomDistance();
		SG_REF(m_precomputed_distance);
	}

	if (lhs==rhs)
		m_precomputed_distance->set_triangle_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols);
	else
		m_precomputed_distance->set_full_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols);
}

void CShiftInvariantKernel::cleanup()
{
	SG_UNREF(m_precomputed_distance);
	m_precomputed_distance=NULL;
	CKernel::cleanup();
	m_distance->cleanup();
}

EDistanceType CShiftInvariantKernel::get_distance_type() const
{
	REQUIRE(m_distance, "The distance instance cannot be NULL!\n");
	return m_distance->get_distance_type();
}

float64_t CShiftInvariantKernel::distance(int32_t a, int32_t b) const
{
	REQUIRE(m_distance, "The distance instance cannot be NULL!\n");
	if (m_precomputed_distance!=NULL)
		return m_precomputed_distance->distance(a, b);
	else
		return m_distance->distance(a, b);
}

void CShiftInvariantKernel::register_params()
{
	SG_ADD((CSGObject**) &m_distance, "m_distance", "Distance to be used.");
	SG_ADD((CSGObject**) &m_precomputed_distance, "m_precomputed_distance", "Precomputed istance to be used.");

	m_distance=NULL;
	m_precomputed_distance=NULL;
}

void CShiftInvariantKernel::set_precomputed_distance(CCustomDistance* precomputed_distance)
{
	REQUIRE(precomputed_distance, "The precomputed distance instance cannot be NULL!\n");
	SG_REF(precomputed_distance);
	SG_UNREF(m_precomputed_distance);
	m_precomputed_distance=precomputed_distance;
}

CCustomDistance* CShiftInvariantKernel::get_precomputed_distance() const
{
	REQUIRE(m_precomputed_distance, "The precomputed distance instance cannot be NULL!\n");
	SG_REF(m_precomputed_distance);
	return m_precomputed_distance;
}


text:
namespace extensions {

namespace {

absl::optional<ChromeContentVerifierDelegate::VerifyInfo::Mode>&
GetModeForTesting() {
  static absl::optional<ChromeContentVerifierDelegate::VerifyInfo::Mode>
      testing_mode;
  return testing_mode;
}

const char kContentVerificationExperimentName[] =
    "ExtensionContentVerification";

}  // namespace

ChromeContentVerifierDelegate::VerifyInfo::VerifyInfo(Mode mode,
                                                      bool is_from_webstore,
                                                      bool should_repair)
    : mode(mode),
      is_from_webstore(is_from_webstore),
      should_repair(should_repair) {}

// static
ChromeContentVerifierDelegate::VerifyInfo::Mode
ChromeContentVerifierDelegate::GetDefaultMode() {
  if (GetModeForTesting())
    return *GetModeForTesting();
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

#if BUILDFLAG(PLATFORM_CFM)
  if (command_line->HasSwitch(
          extensions::switches::kDisableAppContentVerification)) {
    return VerifyInfo::Mode::NONE;
  }
#endif  // BUILDFLAG(PLATFORM_CFM)

  VerifyInfo::Mode experiment_value;
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  experiment_value = VerifyInfo::Mode::ENFORCE_STRICT;
#else
  experiment_value = VerifyInfo::Mode::NONE;
#endif
  const std::string group =
      base::FieldTrialList::FindFullName(kContentVerificationExperimentName);
  if (group == "EnforceStrict")
    experiment_value = VerifyInfo::Mode::ENFORCE_STRICT;
  else if (group == "Enforce")
    experiment_value = VerifyInfo::Mode::ENFORCE;
  else if (group == "Bootstrap")
    experiment_value = VerifyInfo::Mode::BOOTSTRAP;
  else if (group == "None")
    experiment_value = VerifyInfo::Mode::NONE;

  // The field trial value that normally comes from the server can be
  // overridden on the command line, which we don't want to allow since
  // malware can set chrome command line flags. There isn't currently a way
  // to find out what the server-provided value is in this case, so we
  // conservatively default to the strictest mode if we detect our experiment
  // name being overridden.
  if (command_line->HasSwitch(::switches::kForceFieldTrials)) {
    std::string forced_trials =
        command_line->GetSwitchValueASCII(::switches::kForceFieldTrials);
    if (forced_trials.find(kContentVerificationExperimentName) !=
        std::string::npos)
      experiment_value = VerifyInfo::Mode::ENFORCE_STRICT;
  }

  VerifyInfo::Mode cmdline_value = VerifyInfo::Mode::NONE;
  if (command_line->HasSwitch(::switches::kExtensionContentVerification)) {
    std::string switch_value = command_line->GetSwitchValueASCII(
        ::switches::kExtensionContentVerification);
    if (switch_value == ::switches::kExtensionContentVerificationBootstrap)
      cmdline_value = VerifyInfo::Mode::BOOTSTRAP;
    else if (switch_value == ::switches::kExtensionContentVerificationEnforce)
      cmdline_value = VerifyInfo::Mode::ENFORCE;
    else if (switch_value ==
             ::switches::kExtensionContentVerificationEnforceStrict)
      cmdline_value = VerifyInfo::Mode::ENFORCE_STRICT;
    else
      // If no value was provided (or the wrong one), just default to enforce.
      cmdline_value = VerifyInfo::Mode::ENFORCE;
  }

  // We don't want to allow the command-line flags to eg disable enforcement
  // if the experiment group says it should be on, or malware may just modify
  // the command line flags. So return the more restrictive of the 2 values.
  return std::max(experiment_value, cmdline_value);
}

// static
void ChromeContentVerifierDelegate::SetDefaultModeForTesting(
    absl::optional<VerifyInfo::Mode> mode) {
  DCHECK(!GetModeForTesting() || !mode)
      << "Verification mode already overridden, unset it first.";
  GetModeForTesting() = mode;
}

ChromeContentVerifierDelegate::ChromeContentVerifierDelegate(
    content::BrowserContext* context)
    : context_(context), default_mode_(GetDefaultMode()) {}

ChromeContentVerifierDelegate::~ChromeContentVerifierDelegate() {
}

ContentVerifierDelegate::VerifierSourceType
ChromeContentVerifierDelegate::GetVerifierSourceType(
    const Extension& extension) {
  const VerifyInfo info = GetVerifyInfo(extension);
  if (info.mode == VerifyInfo::Mode::NONE)
    return VerifierSourceType::NONE;
  if (info.is_from_webstore)
    return VerifierSourceType::SIGNED_HASHES;
  return VerifierSourceType::UNSIGNED_HASHES;
}

ContentVerifierKey ChromeContentVerifierDelegate::GetPublicKey() {
  return ContentVerifierKey(kWebstoreSignaturesPublicKey,
                            kWebstoreSignaturesPublicKeySize);
}

GURL ChromeContentVerifierDelegate::GetSignatureFetchUrl(
    const std::string& extension_id,
    const base::Version& version) {
  // TODO(asargent) Factor out common code from the extension updater's
  // ManifestFetchData class that can be shared for use here.
  std::string id_part = "id=" + extension_id;
  std::string version_part = "v=" + version.GetString();
  std::string x_value = base::EscapeQueryParamValue(
      base::JoinString({"uc", "installsource=signature", id_part, version_part},
                       "&"),
      true);
  std::string query = "response=redirect&x=" + x_value;

  GURL base_url = extension_urls::GetWebstoreUpdateUrl();
  GURL::Replacements replacements;
  replacements.SetQueryStr(query);
  return base_url.ReplaceComponents(replacements);
}

std::set<base::FilePath> ChromeContentVerifierDelegate::GetBrowserImagePaths(
    const extensions::Extension* extension) {
  return ExtensionsClient::Get()->GetBrowserImagePaths(extension);
}

void ChromeContentVerifierDelegate::VerifyFailed(
    const std::string& extension_id,
    ContentVerifyJob::FailureReason reason) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(context_);
  const Extension* extension =
      registry->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
  if (!extension)
    return;

  ExtensionSystem* system = ExtensionSystem::Get(context_);
  if (!system->extension_service()) {
    // Some tests will add an extension to the registry, but there are no
    // subsystems.
    return;
  }

  ExtensionService* service = system->extension_service();
  CorruptedExtensionReinstaller* corrupted_extension_reinstaller =
      service->corrupted_extension_reinstaller();

  const VerifyInfo info = GetVerifyInfo(*extension);

  SYSLOG(WARNING) << "Corruption detected in extension " << extension_id
                  << " installed at: " << extension->path().value()
                  << ", from webstore: " << info.is_from_webstore
                  << ", corruption reason: " << reason
                  << ", should be repaired: " << info.should_repair
                  << ", extension location: " << extension->location();

  if (reason == ContentVerifyJob::MISSING_ALL_HASHES) {
    // If the failure was due to hashes missing, only "enforce_strict" would
    // disable the extension, but not "enforce".
    if (info.mode != VerifyInfo::Mode::ENFORCE_STRICT)
      return;

    // If a non-webstore extension has no computed hashes for content
    // verification, leave it as is for now.
    // See https://crbug.com/958794#c22 for more details.
    // TODO(https://crbug.com/1044572): Schedule the extension for reinstall.
    if (!info.is_from_webstore) {
      if (!base::Contains(would_be_reinstalled_ids_, extension_id)) {
        corrupted_extension_reinstaller->RecordPolicyReinstallReason(
            CorruptedExtensionReinstaller::PolicyReinstallReason::
                NO_UNSIGNED_HASHES_FOR_NON_WEBSTORE_SKIP);
        would_be_reinstalled_ids_.insert(extension_id);
      }
      return;
    }
  }

  const bool should_disable = info.mode >= VerifyInfo::Mode::ENFORCE;
  // Configuration when we should repair extension, but not disable it, is
  // invalid.
  DCHECK(!info.should_repair || should_disable);

  if (!should_disable) {
    if (!base::Contains(would_be_disabled_ids_, extension_id)) {
      UMA_HISTOGRAM_BOOLEAN("Extensions.CorruptExtensionWouldBeDisabled", true);
      would_be_disabled_ids_.insert(extension_id);
    }
    return;
  }

  if (info.should_repair) {
    if (corrupted_extension_reinstaller->IsReinstallForCorruptionExpected(
            extension_id))
      return;
    corrupted_extension_reinstaller->ExpectReinstallForCorruption(
        extension_id,
        info.is_from_webstore
            ? CorruptedExtensionReinstaller::PolicyReinstallReason::
                  CORRUPTION_DETECTED_WEBSTORE
            : CorruptedExtensionReinstaller::PolicyReinstallReason::
                  CORRUPTION_DETECTED_NON_WEBSTORE,
        extension->location());
    service->DisableExtension(extension_id, disable_reason::DISABLE_CORRUPTED);
    // Attempt to reinstall.
    corrupted_extension_reinstaller->NotifyExtensionDisabledDueToCorruption();
    return;
  }

  DCHECK(should_disable);
  service->DisableExtension(extension_id, disable_reason::DISABLE_CORRUPTED);
  ExtensionPrefs::Get(context_)->IncrementPref(
      extensions::kCorruptedDisableCount);
  UMA_HISTOGRAM_BOOLEAN("Extensions.CorruptExtensionBecameDisabled", true);
  UMA_HISTOGRAM_ENUMERATION("Extensions.CorruptExtensionDisabledReason", reason,
                            ContentVerifyJob::FAILURE_REASON_MAX);
}

void ChromeContentVerifierDelegate::Shutdown() {}

bool ChromeContentVerifierDelegate::IsFromWebstore(
    const Extension& extension) const {
  // Use the InstallVerifier's |IsFromStore| method to avoid discrepancies
  // between which extensions are considered in-store.
  // See https://crbug.com/766806 for details.
  if (!InstallVerifier::IsFromStore(extension, context_)) {
    // It's possible that the webstore update url was overridden for testing
    // so also consider extensions with the default (production) update url
    // to be from the store as well. Therefore update URL is compared with
    // |GetDefaultWebstoreUpdateUrl|, not the |GetWebstoreUpdateUrl| used by
    // |IsWebstoreUpdateUrl|.
    ExtensionManagement* extension_management =
        ExtensionManagementFactory::GetForBrowserContext(context_);
    if (extension_management->GetEffectiveUpdateURL(extension) !=
        extension_urls::GetDefaultWebstoreUpdateUrl()) {
      return false;
    }
  }
  return true;
}

ChromeContentVerifierDelegate::VerifyInfo
ChromeContentVerifierDelegate::GetVerifyInfo(const Extension& extension) const {
  ManagementPolicy* management_policy =
      ExtensionSystem::Get(context_)->management_policy();

  // Magement policy may be not configured in some tests.
  bool should_repair = management_policy &&
                       management_policy->ShouldRepairIfCorrupted(&extension);
  bool is_from_webstore = IsFromWebstore(extension);

#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (ExtensionAssetsManagerChromeOS::IsSharedInstall(&extension)) {
    return VerifyInfo(VerifyInfo::Mode::ENFORCE_STRICT, is_from_webstore,
                      should_repair);
  }
#endif

  if (should_repair)
    return VerifyInfo(default_mode_, is_from_webstore, should_repair);

  if (!extension.is_extension() && !extension.is_legacy_packaged_app())
    return VerifyInfo(VerifyInfo::Mode::NONE, is_from_webstore, should_repair);
  if (!Manifest::IsAutoUpdateableLocation(extension.location()))
    return VerifyInfo(VerifyInfo::Mode::NONE, is_from_webstore, should_repair);
  if (!is_from_webstore)
    return VerifyInfo(VerifyInfo::Mode::NONE, is_from_webstore, should_repair);

  return VerifyInfo(default_mode_, is_from_webstore, should_repair);
}

}  // namespace extensions


text:
// Code generated by go-swagger; DO NOT EDIT.

package storage

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// NewSplitStatusCollectionGetParams creates a new SplitStatusCollectionGetParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewSplitStatusCollectionGetParams() *SplitStatusCollectionGetParams {
	return &SplitStatusCollectionGetParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewSplitStatusCollectionGetParamsWithTimeout creates a new SplitStatusCollectionGetParams object
// with the ability to set a timeout on a request.
func NewSplitStatusCollectionGetParamsWithTimeout(timeout time.Duration) *SplitStatusCollectionGetParams {
	return &SplitStatusCollectionGetParams{
		timeout: timeout,
	}
}

// NewSplitStatusCollectionGetParamsWithContext creates a new SplitStatusCollectionGetParams object
// with the ability to set a context for a request.
func NewSplitStatusCollectionGetParamsWithContext(ctx context.Context) *SplitStatusCollectionGetParams {
	return &SplitStatusCollectionGetParams{
		Context: ctx,
	}
}

// NewSplitStatusCollectionGetParamsWithHTTPClient creates a new SplitStatusCollectionGetParams object
// with the ability to set a custom HTTPClient for a request.
func NewSplitStatusCollectionGetParamsWithHTTPClient(client *http.Client) *SplitStatusCollectionGetParams {
	return &SplitStatusCollectionGetParams{
		HTTPClient: client,
	}
}

/*
SplitStatusCollectionGetParams contains all the parameters to send to the API endpoint

	for the split status collection get operation.

	Typically these are written to a http.Request.
*/
type SplitStatusCollectionGetParams struct {

	/* Fields.

	   Specify the fields to return.
	*/
	FieldsQueryParameter []string

	/* MaxRecords.

	   Limit the number of records returned.
	*/
	MaxRecordsQueryParameter *int64

	/* OrderBy.

	   Order results by specified fields and optional [asc|desc] direction. Default direction is 'asc' for ascending.
	*/
	OrderByQueryParameter []string

	/* PendingSplits.

	   Filter by pending_splits
	*/
	PendingSplitsQueryParameter *int64

	/* ReturnRecords.

	   The default is true for GET calls.  When set to false, only the number of records is returned.

	   Default: true
	*/
	ReturnRecordsQueryParameter *bool

	/* ReturnTimeout.

	   The number of seconds to allow the call to execute before returning.  When iterating over a collection, the default is 15 seconds.  ONTAP returns earlier if either max records or the end of the collection is reached.

	   Default: 15
	*/
	ReturnTimeoutQueryParameter *int64

	/* SvmName.

	   Filter by svm.name
	*/
	SVMNameQueryParameter *string

	/* SvmUUID.

	   Filter by svm.uuid
	*/
	SVMUUIDQueryParameter *string

	/* UnsplitCloneSize.

	   Filter by unsplit_clone_size
	*/
	UnsplitCloneSizeQueryParameter *int64

	/* VolumeName.

	   Filter by volume.name
	*/
	VolumeNameQueryParameter *string

	/* VolumeUUID.

	   Filter by volume.uuid
	*/
	VolumeUUIDQueryParameter *string

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the split status collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *SplitStatusCollectionGetParams) WithDefaults() *SplitStatusCollectionGetParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the split status collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *SplitStatusCollectionGetParams) SetDefaults() {
	var (
		returnRecordsQueryParameterDefault = bool(true)

		returnTimeoutQueryParameterDefault = int64(15)
	)

	val := SplitStatusCollectionGetParams{
		ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
		ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
	}

	val.timeout = o.timeout
	val.Context = o.Context
	val.HTTPClient = o.HTTPClient
	*o = val
}

// WithTimeout adds the timeout to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithTimeout(timeout time.Duration) *SplitStatusCollectionGetParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithContext(ctx context.Context) *SplitStatusCollectionGetParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithHTTPClient(client *http.Client) *SplitStatusCollectionGetParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithFieldsQueryParameter adds the fields to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithFieldsQueryParameter(fields []string) *SplitStatusCollectionGetParams {
	o.SetFieldsQueryParameter(fields)
	return o
}

// SetFieldsQueryParameter adds the fields to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetFieldsQueryParameter(fields []string) {
	o.FieldsQueryParameter = fields
}

// WithMaxRecordsQueryParameter adds the maxRecords to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithMaxRecordsQueryParameter(maxRecords *int64) *SplitStatusCollectionGetParams {
	o.SetMaxRecordsQueryParameter(maxRecords)
	return o
}

// SetMaxRecordsQueryParameter adds the maxRecords to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetMaxRecordsQueryParameter(maxRecords *int64) {
	o.MaxRecordsQueryParameter = maxRecords
}

// WithOrderByQueryParameter adds the orderBy to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithOrderByQueryParameter(orderBy []string) *SplitStatusCollectionGetParams {
	o.SetOrderByQueryParameter(orderBy)
	return o
}

// SetOrderByQueryParameter adds the orderBy to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetOrderByQueryParameter(orderBy []string) {
	o.OrderByQueryParameter = orderBy
}

// WithPendingSplitsQueryParameter adds the pendingSplits to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithPendingSplitsQueryParameter(pendingSplits *int64) *SplitStatusCollectionGetParams {
	o.SetPendingSplitsQueryParameter(pendingSplits)
	return o
}

// SetPendingSplitsQueryParameter adds the pendingSplits to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetPendingSplitsQueryParameter(pendingSplits *int64) {
	o.PendingSplitsQueryParameter = pendingSplits
}

// WithReturnRecordsQueryParameter adds the returnRecords to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithReturnRecordsQueryParameter(returnRecords *bool) *SplitStatusCollectionGetParams {
	o.SetReturnRecordsQueryParameter(returnRecords)
	return o
}

// SetReturnRecordsQueryParameter adds the returnRecords to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
	o.ReturnRecordsQueryParameter = returnRecords
}

// WithReturnTimeoutQueryParameter adds the returnTimeout to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *SplitStatusCollectionGetParams {
	o.SetReturnTimeoutQueryParameter(returnTimeout)
	return o
}

// SetReturnTimeoutQueryParameter adds the returnTimeout to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
	o.ReturnTimeoutQueryParameter = returnTimeout
}

// WithSVMNameQueryParameter adds the svmName to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithSVMNameQueryParameter(svmName *string) *SplitStatusCollectionGetParams {
	o.SetSVMNameQueryParameter(svmName)
	return o
}

// SetSVMNameQueryParameter adds the svmName to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetSVMNameQueryParameter(svmName *string) {
	o.SVMNameQueryParameter = svmName
}

// WithSVMUUIDQueryParameter adds the svmUUID to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithSVMUUIDQueryParameter(svmUUID *string) *SplitStatusCollectionGetParams {
	o.SetSVMUUIDQueryParameter(svmUUID)
	return o
}

// SetSVMUUIDQueryParameter adds the svmUuid to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetSVMUUIDQueryParameter(svmUUID *string) {
	o.SVMUUIDQueryParameter = svmUUID
}

// WithUnsplitCloneSizeQueryParameter adds the unsplitCloneSize to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithUnsplitCloneSizeQueryParameter(unsplitCloneSize *int64) *SplitStatusCollectionGetParams {
	o.SetUnsplitCloneSizeQueryParameter(unsplitCloneSize)
	return o
}

// SetUnsplitCloneSizeQueryParameter adds the unsplitCloneSize to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetUnsplitCloneSizeQueryParameter(unsplitCloneSize *int64) {
	o.UnsplitCloneSizeQueryParameter = unsplitCloneSize
}

// WithVolumeNameQueryParameter adds the volumeName to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithVolumeNameQueryParameter(volumeName *string) *SplitStatusCollectionGetParams {
	o.SetVolumeNameQueryParameter(volumeName)
	return o
}

// SetVolumeNameQueryParameter adds the volumeName to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetVolumeNameQueryParameter(volumeName *string) {
	o.VolumeNameQueryParameter = volumeName
}

// WithVolumeUUIDQueryParameter adds the volumeUUID to the split status collection get params
func (o *SplitStatusCollectionGetParams) WithVolumeUUIDQueryParameter(volumeUUID *string) *SplitStatusCollectionGetParams {
	o.SetVolumeUUIDQueryParameter(volumeUUID)
	return o
}

// SetVolumeUUIDQueryParameter adds the volumeUuid to the split status collection get params
func (o *SplitStatusCollectionGetParams) SetVolumeUUIDQueryParameter(volumeUUID *string) {
	o.VolumeUUIDQueryParameter = volumeUUID
}

// WriteToRequest writes these params to a swagger request
func (o *SplitStatusCollectionGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.FieldsQueryParameter != nil {

		// binding items for fields
		joinedFields := o.bindParamFields(reg)

		// query array param fields
		if err := r.SetQueryParam("fields", joinedFields...); err != nil {
			return err
		}
	}

	if o.MaxRecordsQueryParameter != nil {

		// query param max_records
		var qrMaxRecords int64

		if o.MaxRecordsQueryParameter != nil {
			qrMaxRecords = *o.MaxRecordsQueryParameter
		}
		qMaxRecords := swag.FormatInt64(qrMaxRecords)
		if qMaxRecords != "" {

			if err := r.SetQueryParam("max_records", qMaxRecords); err != nil {
				return err
			}
		}
	}

	if o.OrderByQueryParameter != nil {

		// binding items for order_by
		joinedOrderBy := o.bindParamOrderBy(reg)

		// query array param order_by
		if err := r.SetQueryParam("order_by", joinedOrderBy...); err != nil {
			return err
		}
	}

	if o.PendingSplitsQueryParameter != nil {

		// query param pending_splits
		var qrPendingSplits int64

		if o.PendingSplitsQueryParameter != nil {
			qrPendingSplits = *o.PendingSplitsQueryParameter
		}
		qPendingSplits := swag.FormatInt64(qrPendingSplits)
		if qPendingSplits != "" {

			if err := r.SetQueryParam("pending_splits", qPendingSplits); err != nil {
				return err
			}
		}
	}

	if o.ReturnRecordsQueryParameter != nil {

		// query param return_records
		var qrReturnRecords bool

		if o.ReturnRecordsQueryParameter != nil {
			qrReturnRecords = *o.ReturnRecordsQueryParameter
		}
		qReturnRecords := swag.FormatBool(qrReturnRecords)
		if qReturnRecords != "" {

			if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
				return err
			}
		}
	}

	if o.ReturnTimeoutQueryParameter != nil {

		// query param return_timeout
		var qrReturnTimeout int64

		if o.ReturnTimeoutQueryParameter != nil {
			qrReturnTimeout = *o.ReturnTimeoutQueryParameter
		}
		qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
		if qReturnTimeout != "" {

			if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
				return err
			}
		}
	}

	if o.SVMNameQueryParameter != nil {

		// query param svm.name
		var qrSvmName string

		if o.SVMNameQueryParameter != nil {
			qrSvmName = *o.SVMNameQueryParameter
		}
		qSvmName := qrSvmName
		if qSvmName != "" {

			if err := r.SetQueryParam("svm.name", qSvmName); err != nil {
				return err
			}
		}
	}

	if o.SVMUUIDQueryParameter != nil {

		// query param svm.uuid
		var qrSvmUUID string

		if o.SVMUUIDQueryParameter != nil {
			qrSvmUUID = *o.SVMUUIDQueryParameter
		}
		qSvmUUID := qrSvmUUID
		if qSvmUUID != "" {

			if err := r.SetQueryParam("svm.uuid", qSvmUUID); err != nil {
				return err
			}
		}
	}

	if o.UnsplitCloneSizeQueryParameter != nil {

		// query param unsplit_clone_size
		var qrUnsplitCloneSize int64

		if o.UnsplitCloneSizeQueryParameter != nil {
			qrUnsplitCloneSize = *o.UnsplitCloneSizeQueryParameter
		}
		qUnsplitCloneSize := swag.FormatInt64(qrUnsplitCloneSize)
		if qUnsplitCloneSize != "" {

			if err := r.SetQueryParam("unsplit_clone_size", qUnsplitCloneSize); err != nil {
				return err
			}
		}
	}

	if o.VolumeNameQueryParameter != nil {

		// query param volume.name
		var qrVolumeName string

		if o.VolumeNameQueryParameter != nil {
			qrVolumeName = *o.VolumeNameQueryParameter
		}
		qVolumeName := qrVolumeName
		if qVolumeName != "" {

			if err := r.SetQueryParam("volume.name", qVolumeName); err != nil {
				return err
			}
		}
	}

	if o.VolumeUUIDQueryParameter != nil {

		// query param volume.uuid
		var qrVolumeUUID string

		if o.VolumeUUIDQueryParameter != nil {
			qrVolumeUUID = *o.VolumeUUIDQueryParameter
		}
		qVolumeUUID := qrVolumeUUID
		if qVolumeUUID != "" {

			if err := r.SetQueryParam("volume.uuid", qVolumeUUID); err != nil {
				return err
			}
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// bindParamSplitStatusCollectionGet binds the parameter fields
func (o *SplitStatusCollectionGetParams) bindParamFields(formats strfmt.Registry) []string {
	fieldsIR := o.FieldsQueryParameter

	var fieldsIC []string
	for _, fieldsIIR := range fieldsIR { // explode []string

		fieldsIIV := fieldsIIR // string as string
		fieldsIC = append(fieldsIC, fieldsIIV)
	}

	// items.CollectionFormat: "csv"
	fieldsIS := swag.JoinByFormat(fieldsIC, "csv")

	return fieldsIS
}

// bindParamSplitStatusCollectionGet binds the parameter order_by
func (o *SplitStatusCollectionGetParams) bindParamOrderBy(formats strfmt.Registry) []string {
	orderByIR := o.OrderByQueryParameter

	var orderByIC []string
	for _, orderByIIR := range orderByIR { // explode []string

		orderByIIV := orderByIIR // string as string
		orderByIC = append(orderByIC, orderByIIV)
	}

	// items.CollectionFormat: "csv"
	orderByIS := swag.JoinByFormat(orderByIC, "csv")

	return orderByIS
}


text:
"""Tests for methods in the cloud_taskqueue_services."""

from __future__ import annotations

import datetime
import json

from core.domain import taskqueue_services
from core.platform.taskqueue import cloud_taskqueue_services
from core.tests import test_utils

from google.api_core import retry as retry_lib
from google.cloud import tasks_v2
from google.protobuf import timestamp_pb2
from typing import Any, Dict, Optional

class CloudTaskqueueServicesUnitTests(test_utils.TestBase):
    """Tests for cloud_taskqueue_services."""

    class Response:
        """Mock for the response object that is returned from a Cloud
        Tasks query.
        """

        def __init__(self, name: str) -> None:
            self.name = name

    def test_http_task_scheduled_immediately_sends_correct_request(
            self
    ) -> None:
        queue_name = 'queue'
        dummy_url = '/task/dummy_handler'
        payload = {
            'fn_identifier': (
                taskqueue_services.FUNCTION_ID_DELETE_EXPS_FROM_USER_MODELS),
            'args': [['1', '2', '3']],
            'kwargs': {}
        }
        task_name = 'task1'

        # Here we use type Any because this method mocks the behaviour of
        # cloud_taskqueue_services.CLIENT.create_task and in 'create_task'
        # task is defined as Dict[str, Any].
        def mock_create_task(
                parent: str,
                task: Dict[str, Any],
                retry: Optional[retry_lib.Retry] = None
        ) -> CloudTaskqueueServicesUnitTests.Response:
            self.assertIsInstance(retry, retry_lib.Retry)
            self.assertEqual(
                parent,
                u'projects/dev-project-id/locations/us-central1/queues/queue')
            self.assertEqual(
                task,
                {
                    'app_engine_http_request': {
                        'http_method': tasks_v2.types.HttpMethod.POST,
                        'relative_uri': dummy_url,
                        'headers': {
                            'Content-type': 'application/json'
                        },
                        'body': json.dumps(payload).encode()
                    },
                    'name': task_name
                }
            )
            return self.Response(task_name)

        with self.swap(
            cloud_taskqueue_services.CLIENT, 'create_task', mock_create_task):
            cloud_taskqueue_services.create_http_task(
                queue_name, dummy_url, payload=payload, task_name=task_name)

    def test_http_task_scheduled_for_later_sends_correct_request(self) -> None:
        queue_name = 'queue'
        dummy_url = '/task/dummy_handler'
        payload = {
            'fn_identifier': (
                taskqueue_services.FUNCTION_ID_DELETE_EXPS_FROM_USER_MODELS),
            'args': [['1', '2', '3']],
            'kwargs': {}
        }
        # Create Timestamp protobuf.
        datetime_to_execute_task = (
            datetime.datetime.utcnow() + datetime.timedelta(seconds=20))
        timestamp = timestamp_pb2.Timestamp()
        timestamp.FromDatetime(datetime_to_execute_task)
        task_name = 'task1'

        # Here we use type Any because this method mocks the behaviour of
        # cloud_taskqueue_services.CLIENT.create_task and in 'create_task'
        # task is defined as Dict[str, Any].
        def mock_create_task(
                parent: str,
                task: Dict[str, Any],
                retry: Optional[retry_lib.Retry] = None
        ) -> CloudTaskqueueServicesUnitTests.Response:
            self.assertIsInstance(retry, retry_lib.Retry)
            self.assertEqual(
                parent,
                u'projects/dev-project-id/locations/us-central1/queues/queue')
            self.assertEqual(
                task,
                {
                    'app_engine_http_request': {
                        'http_method': tasks_v2.types.HttpMethod.POST,
                        'relative_uri': dummy_url,
                        'headers': {
                            'Content-type': 'application/json'
                        },
                        'body': json.dumps(payload).encode()
                    },
                    'schedule_time': timestamp,
                    'name': task_name
                }
            )
            return self.Response(task_name)

        with self.swap(
            cloud_taskqueue_services.CLIENT, 'create_task', mock_create_task):
            cloud_taskqueue_services.create_http_task(
                queue_name, dummy_url, payload=payload,
                scheduled_for=datetime_to_execute_task, task_name=task_name)


text:
package mediabrowser.apiinteraction.connectionmanager;

import mediabrowser.apiinteraction.ApiClient;
import mediabrowser.apiinteraction.EmptyResponse;

import java.util.ArrayList;

public class ApiClientLogoutResponse extends EmptyResponse {

    private final ArrayList<Integer> _doneList;
    private int _count;
    private EmptyResponse _response;
    private ConnectionManager _connectionManager;
    private ApiClient _apiClient;

    public ApiClientLogoutResponse(ArrayList<Integer> doneList, int count, EmptyResponse response, ConnectionManager connectionManager, ApiClient apiClient) {
        this._doneList = doneList;
        this._count = count;
        this._response = response;
        this._connectionManager = connectionManager;
        this._apiClient = apiClient;
    }

    @Override
    public void onResponse() {

        onResponse(true);
    }

    public void onResponse(boolean wasSignedOut) {

        if (wasSignedOut) {
            _connectionManager.OnLocalUserSignout(_apiClient);
        }
        synchronized (_doneList) {

            _doneList.add(0);

            if (_doneList.size() >= _count) {
                _response.onResponse();
            }
        }

    }

    @Override
    public void onError(Exception ex) {

        onResponse();
    }
}


text:
- [About](#about)
 - [Features](#features)
 - [Installation](#installation)
 - [Quick Start](#quick-start)
 - [Mapping](#mapping)
 - [Settings](#settings)
 - [Interactions with other plugins](#interactions-with-other-plugins)
 - [Highlight](#highlight)
 - *[FAQ](#faq)*
 - *[Known Issues](#known-issues)*
 - [Changelog](#changelog)
 - [Contributing](#contributing)
 - [Credit](#credit)

###Contributors
- [eapache](https://github.com/eapache)
- [aschrab](https://github.com/aschrab)
- [kristijanhusak](https://github.com/kristijanhusak)
- [faceleg](https://github.com/faceleg)

## About
[There](https://github.com/paradigm/vim-multicursor) [have](https://github.com/felixr/vim-multiedit) [been](https://github.com/hlissner/vim-multiedit) [many](https://github.com/adinapoli/vim-markmultiple) [attempts](https://github.com/AndrewRadev/multichange.vim) at bringing Sublime Text's awesome [multiple selection][sublime-multiple-selection] feature into Vim, but none so far have been in my opinion a faithful port that is simplistic to use, yet powerful and intuitive enough for an existing Vim user. [vim-multiple-cursors] is yet another attempt at that.

### It's great for quick refactoring
![Example1](assets/example1.gif?raw=true)

### Add a cursor to each line of your visual selection
![Example2](assets/example2.gif?raw=true)

### Do it backwards too! This is not just a replay of the above gif :)
![Example3](assets/example3.gif?raw=true)

### Add multiple cursors using regexes
![Example4](assets/example4.gif?raw=true)

To see what keystrokes are used for the above example, see [this issue](https://github.com/terryma/vim-multiple-cursors/issues/39).

## Features
- Live update in Insert mode
- One key to rule it all! See [Quick Start](#quick-start) on what the key does in different scenarios
- Works in Normal, Insert, and Visual mode for any commands (including
  multi-key commands, assuming you set `g:multicursor_insert_maps` and
  `g:multicursor_normal_maps`; see Settings below for details)

## Installation
Install using [Pathogen], [Vundle], [Neobundle], or your favorite Vim package manager.
Requires vim 7.4 or later for full functionality.

## Quick Start
Out of the box, all you need to know is a single key `Ctrl-n`. Pressing the key in Normal mode highlights the current word under the cursor in Visual mode and places a virtual cursor at the end of it. Pressing it again finds the next occurrence and places another virtual cursor at the end of the visual selection. If you select multiple lines in Visual mode, pressing the key puts a virtual cursor at every line and leaves you in Normal mode.

After you've marked all your locations with `Ctrl-n`, you can change the visual selection with normal Vim motion commands in Visual mode. You could go to Normal mode by pressing `v` and wield your motion commands there. Single key command to switch to Insert mode such as `c` or `s` from Visual mode or `i`, `a`, `I`, `A` in Normal mode should work without any issues.

At any time, you can press `<Esc>` to exit back to regular Vim.

Two additional keys are also mapped:
- `Ctrl-p` in Visual mode will remove the current virtual cursor and go back to the previous virtual cursor location. This is useful if you are trigger happy with `Ctrl-n` and accidentally went too far.
- `Ctrl-x` in Visual mode will remove the current virtual cursor and skip to the next virtual cursor location. This is useful if you don't want the current selection to be a candidate to operate on later.

You can also add multiple cursors using a regular expression. The command `MultipleCursorsFind` accepts a range and a pattern, and it will create a virtual cursor at the end of every match within the range. If no range is passed in, then it defaults to the entire buffer.

**NOTE:** If at any time you have lingering cursors on screen, you can press `Ctrl-n` in Normal mode and it will remove all prior cursors before starting a new one.

## Mapping
Out of the box, only the single key `Ctrl-n` is mapped in regular Vim's Normal mode and Visual mode to provide the functionality mentioned above. `Ctrl-n`, `Ctrl-p`, `Ctrl-x`, and `<Esc>` are mapped in the special multicursor mode once you've added at least one virtual cursor to the buffer. If you don't like the plugin taking over your favorite key bindings, you can turn off the default with
```viml
let g:multi_cursor_use_default_mapping=0
```

You can then map the 'next', 'previous', 'skip', and 'exit' keys like the following:
```viml
" Default mapping
let g:multi_cursor_next_key='<C-n>'
let g:multi_cursor_prev_key='<C-p>'
let g:multi_cursor_skip_key='<C-x>'
let g:multi_cursor_quit_key='<Esc>'
```

By default, the 'next' key is also used to enter multicursor mode. If you want to use a different key to start multicursor mode than for selecting the next location, do like the following:
```viml
" Map start key separately from next key
let g:multi_cursor_start_key='<F6>'
```

Note that when multicursor mode is started, it selects current word with boundaries, i.e. it behaves like `*`. If you want to avoid word boundaries in Normal mode (as `g*` does) but still have old behaviour up your sleeve, you can do the following:
```viml
let g:multi_cursor_start_key='<C-n>'
let g:multi_cursor_start_word_key='g<C-n>'
```
In this configuration `<C-n>` will start multicursor mode without word boundaries (but only in Normal mode, as it does not make much sense to use it in Visual mode). Old behaviour with word boundaries is still available using `g<C-n>`.

**IMPORTANT:** Please note that currently only single keystrokes and special keys can be mapped. This means that a mapping like `<Leader>n` will NOT work correctly. For a list of special keys that are supported, see `help :key-notation`

**NOTE:** Please make sure to always map something to `g:multi_cursor_quit_key`, otherwise you'll have a tough time quitting from multicursor mode.

**NOTE:** Prior to version 1.3, the recommended way to map the keys is using the expression quote syntax in Vim, using something like `"\<C-n>"` or `"\<Esc>"` (see h: expr-quote). After 1.3, the recommended way is to use a raw string like above. If your key mappings don't appear to work, give the new syntax a try.

## Settings
Currently there are four additional global settings one can tweak:

### ```g:multi_cursor_exit_from_visual_mode``` (Default: 1)
If set to 0, then pressing `g:multi_cursor_quit_key` in _Visual_ mode will not quit and delete all existing cursors. This is useful if you want to press Escape and go back to Normal mode, and still be able to operate on all the cursors.

### ```g:multi_cursor_exit_from_insert_mode``` (Default: 1)
If set to 0, then pressing `g:multi_cursor_quit_key` in _Insert_ mode will not quit and delete all existing cursors. This is useful if you want to press Escape and go back to Normal mode, and still be able to operate on all the cursors.

### ```g:multi_cursor_insert_maps``` (Default: `{}`)
Any key in this map (values are ignored) will cause multi-cursor _Insert_ mode
to pause for `timeoutlen` waiting for map completion just like normal vim.
Otherwise keys mapped in insert mode are ignored when multiple cursors are
active. For example, setting it to `{'\':1}` will make insert-mode mappings
beginning with the default leader key work in multi-cursor mode. You have to
manually set this because vim doesn't provide a way to see which keys *start*
mappings.

### ```g:multi_cursor_normal_maps``` (Default: `{}`)
Any key in this map (values are ignored) will cause multi-cursor _Normal_ mode
to pause for map completion just like normal vim. Otherwise keys mapped in
normal mode will "fail to replay" when multiple cursors are active. For example,
setting it to `{'d':1}` will make normal-mode mappings beginning with `d` (such
as `dw` to delete a word) work in multi-cursor mode. You have to
manually set this because vim doesn't provide a way to see which keys *start*
mappings; setting it to include motion commands like `j` can break things.

### Interactions with other plugins

### ```Multiple_cursors_before/Multiple_cursors_after``` (Default: `nothing`)

Other plugins may trigger on keypresses when in insert mode. These plugins
generally provide a means to toggle their active state. These hooks allow
the user to provide functions in their .vimrc to do this when multiple-cursor-mode
is entered.

For example, if you are using [Neocomplete](https://github.com/Shougo/neocomplete.vim),
add this to your vimrc to prevent conflict:

```viml
" Called once right before you start selecting multiple cursors
function! Multiple_cursors_before()
  if exists(':NeoCompleteLock')==2
    exe 'NeoCompleteLock'
  endif
endfunction

" Called once only when the multiple selection is canceled (default <Esc>)
function! Multiple_cursors_after()
  if exists(':NeoCompleteUnlock')==2
    exe 'NeoCompleteUnlock'
  endif
endfunction
```

With this locking and unlocking we prevent neocomplete to trigger it's function calls until we are finished with multiple cursors editing.

### Highlight
The plugin uses the highlight group `multiple_cursors_cursor` and `multiple_cursors_visual` to highlight the virtual cursors and their visual selections respectively. You can customize them by putting something similar like the following in your vimrc:

```viml
" Default highlighting (see help :highlight and help :highlight-link)
highlight multiple_cursors_cursor term=reverse cterm=reverse gui=reverse
highlight link multiple_cursors_visual Visual
```

## FAQ

**Q** CTRL+n doesn't seem to work in gVIM?

**A** Try setting `set selection=inclusive` in your `~/.gvimrc`

## Known Issues
- Select mode is not implemented
- I and A do not work in Visual mode yet (See #55)

 Single key command to switch to Insert mode such as c or s from Visual mode or i, a, I, A in Normal mode should work without any issues. **NOTE**: vim's Visual block mode also supports I and A commands, however they do not work in this plugin's Visual mode at the moment. For now, to use I and A, switch to normal mode by pressing v first.

## Changelog
See [CHANGELOG.md](CHANGELOG.md)

## Contributing
As one can see, there're still many issues to be resolved, patches and suggestions are always welcome! A list of open feature requests can be found [here](../../issues?labels=enhancement&state=open).

Running the test suite requires ruby and rake as well as vim of course. On Mac
OS, [MacVim](https://code.google.com/p/macvim/) is known to work.

## Credit
Obviously inspired by Sublime Text's [multiple selection][sublime-multiple-selection] feature, also encouraged by Emac's [multiple cursors][emacs-multiple-cursors] implementation by Magnar Sveen

[vim-multiple-cursors]:http://github.com/terryma/vim-multiple-cursors
[sublime-multiple-selection]:http://www.sublimetext.com/docs/2/multiple_selection_with_the_keyboard.html
[Pathogen]:http://github.com/tpope/vim-pathogen
[Vundle]:http://github.com/gmarik/vundle
[Neobundle]:http://github.com/Shougo/neobundle.vim
[emacs-multiple-cursors]:https://github.com/magnars/multiple-cursors.el

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/terryma/vim-multiple-cursors/trend.png)](https://bitdeli.com/free "Bitdeli Badge")