text:
/* eslint no-console: 0 */
'use strict';

const testConfig = require('../testConfig');
const fs = require('fs');

const CHROME_BINARY = require('puppeteer').executablePath();

/**
 * Given a preset key, return set set of common configuration keys for a given service, os, and browser
 * This is useful because testing services support a limited number of browser dimensions, which differs
 * between operating systems.
 * Note that config keys other than those implied by the preset (service, os, browser) are overriden by the
 * corresponding environment variables.
 * @param {string} preset A preset config key; see the switch statement for available presets.
 * @returns {Object} A config object with the following keys: OS, OS_VERSION, BROWSER, BROWSER_VERSION, SERVICE, WIDTH, HEIGHT
 */
function processPreset(preset) {
    const e = process.env;

    switch (preset) {
        case 'bs-win-chrome':
            return {
                OS: 'Windows',
                OS_VERSION: e.OS_VERSION || '10',
                BROWSER: 'chrome',
                BROWSER_VERSION: e.BROWSER_VERSION || 'latest',
                HEADLESS: e.HEADLESS || 'f',
                SERVICE: 'browserstack',
            };
        case 'bs-win-firefox':
            return {
                OS: 'Windows',
                OS_VERSION: e.OS_VERSION || '10',
                BROWSER: 'firefox',
                BROWSER_VERSION: e.BROWSER_VERSION || 'latest',
                HEADLESS: e.HEADLESS || 'f',
                SERVICE: 'browserstack',
            };
        case 'bs-mac-chrome':
            return {
                OS: 'OS X',
                OS_VERSION: e.OS_VERSION || 'Catalina',
                BROWSER: 'chrome',
                BROWSER_VERSION: e.BROWSER_VERSION || 'latest',
                HEADLESS: e.HEADLESS || 'f',
                SERVICE: 'browserstack',
            };
        case 'bs-mac-firefox':
            return {
                OS: 'OS X',
                OS_VERSION: e.OS_VERSION || 'Catalina',
                BROWSER: 'firefox',
                BROWSER_VERSION: e.BROWSER_VERSION || 'latest',
                HEADLESS: e.HEADLESS || 'f',
                SERVICE: 'browserstack',
            };
        case 'ss-firefox':
            // TODO: detect platform
            return {
                OS: null, // not used by selenium standalone -- it runs on the current host
                OS_VERSION: null,
                BROWSER: 'firefox',
                BROWSER_VERSION: null, // will use the installed browser on this host
                HEADLESS: e.HEADLESS || 't',
                SERVICE: 'selenium-standalone',
            };
        case 'ss-chrome':
            // TODO: detect platform
            return {
                OS: null, // not used by selenium standalone -- it runs on the current host
                OS_VERSION: null,
                BROWSER: 'chrome',
                BROWSER_VERSION: null, // will use the installed browser on this host
                HEADLESS: e.HEADLESS || 't',
                SERVICE: 'selenium-standalone',
            };
        case 'cd':
            // TODO: detect platform
            return {
                OS: null, // not used by chromedriver; it is run on the host, whatever it is
                OS_VERSION: null, // TODO: detect os version.
                BROWSER: 'chrome',
                BROWSER_VERSION: null, // will use the installed chrome on this host
                HEADLESS: e.HEADLESS || 't',
                SERVICE: 'chromedriver',
            };
        default:
            throw new Error(`Sorry, "${preset}" is not a preset`);
    }
}

function makeConfig() {
    const e = process.env;
    const preset = e.PRESET || 'cd';
    const presetConfig = processPreset(preset);

    const [width, height] = (() => {
        switch (e.PRESET_DIMENSIONS || 'sxga') {
            case 'xga':
                return [1024, 768];
            case 'sxga':
                return [1280, 1024];
            case 'hd':
                return [1920, 1080];
            default:
                throw new Error(`Not a valid PRESET_DIMENSIONS: "${e.PRESET_DIMENSIONS}"`);
        }
    })();

    return {
        ...presetConfig,
        WIDTH: e.WIDTH || width,
        HEIGHT: e.HEIGHT || height,
        // Note that these service configs are only used for browserstack.
        SERVICE_USER: e.SERVICE_USER || null,
        SERVICE_KEY: e.SERVICE_KEY || null,

        BASE_URL: e.BASE_URL || 'http://localhost:8888',
        ENV: e.ENV || 'ci',
        HEADLESS: e.HEADLESS || 't',
    };
}

const authToken = (() => {
    if (process.env.KBASE_TEST_TOKEN) {
        console.log('loading auth token from environment variable KBASE_TEST_TOKEN');
        return process.env.KBASE_TEST_TOKEN;
    } else if (
        testConfig &&
        testConfig.token &&
        testConfig.token.file &&
        fs.existsSync(testConfig.token.file)
    ) {
        console.log('loading auth token from file ' + testConfig.token.file);
        return fs.readFileSync(testConfig.token.file, 'utf-8').trim();
    } else {
        console.warn('continuing without valid test token');
        return 'fakeToken';
    }
})();

// Each wdio service supported requires an entry here, even
// if it doesn't have any specific configuration.
// TODO: The relation between selenium-standalone test drivers, as shown
// in the example below, and the installed browser is tricky.
//
// For testing services, we can supply the browser version for supported
// browsers. But for local or github based tests, the tests use whichever
// browser version is installed.
//
// It seems to be fine to have a newer driver for an older browser
// (although warnings may be printed when running tests), but it can be
// an error for a newer browse and older driver. This can happen if
// the selenium-standalone drivers are out of date, but the host is not.
//
// One way to keep this deterministic is to pin the drivers, as show in the
// example below (and the commented out "drivers" setting in the service configs),
// and at the same time pin the browser version in the host.
//
// The host browser can be pinned across testing environments by installing
// the required browsers via npm. E.g. puppeteer installs a local chrome binary, which
// can be specified as the Chrome binary. I could not find a similar method
// for installing Firefox, so gave up on that effort.
//
// The default behavior is to use the latest available, which should
// normally be what we want. However, this ability in selenium-standalone is
// relatively recent, and not yet implemented for Firefox (12/12/2020).
//
// Thus, we should keep the selenium-standalone dependency up to date to ensure
// the most recent version of Firefox is supported.
//

const serviceConfigs = {
    'selenium-standalone': {
        logPath: 'selenium-standalone-logs',
        // drivers
    },
    chromedriver: {},
    browserstack: {
        browserstackLocal: true,
        opts: {},
    },
};

const testParams = makeConfig();

/**
 * Constructs a capabilities object for the current test configuration.
 * @param {Object} config - test configuration as provided in the environment
 * variables and defaults as set above.
 * @returns {Object} a capabilities object suitable for the wdio configuration.
 */
function makeCapabilities(config) {
    switch (config.SERVICE) {
        case 'chromedriver':
            return (() => {
                const args = [
                    '--disable-gpu',
                    '--no-sandbox',
                    `window-size=${config.WIDTH},${config.HEIGHT}`,
                ];
                if (config.HEADLESS === 't') {
                    args.push('--headless');
                }
                return {
                    browserName: 'chrome',
                    acceptInsecureCerts: true,
                    maxInstances: 1,
                    'goog:chromeOptions': {
                        args,
                        binary: CHROME_BINARY,
                    },
                };
            })();
        case 'selenium-standalone':
            switch (config.BROWSER) {
                case 'chrome':
                    return (() => {
                        const args = [
                            '--disable-gpu',
                            '--no-sandbox',
                            `window-size=${config.WIDTH},${config.HEIGHT}`,
                        ];
                        if (config.HEADLESS === 't') {
                            args.push('--headless');
                        }
                        return {
                            browserName: 'chrome',
                            acceptInsecureCerts: true,
                            maxInstances: 1,
                            'goog:chromeOptions': {
                                args,
                            },
                        };
                    })();
                case 'firefox':
                    return (() => {
                        const args = [`--width=${config.WIDTH}`, `--height=${config.HEIGHT}`];
                        if (config.HEADLESS === 't') {
                            args.push('--headless');
                        }
                        return {
                            browserName: 'firefox',
                            acceptInsecureCerts: true,
                            maxInstances: 1,
                            'moz:firefoxOptions': {
                                args,
                            },
                        };
                    })();
                default:
                    throw new Error(`Browser not supported "${config.BROWSER}"`);
            }
        case 'browserstack':
            // see https://www.browserstack.com/docs/automate/selenium/select-browsers-and-devices
            return {
                os: `${config.OS}`,
                os_version: `${config.OS_VERSION}`,
                browser: `${config.BROWSER}`,
                browser_version: `${config.BROWSER_VERSION}`,
                resolution: `${config.WIDTH}x${config.HEIGHT}`,
            };
    }
}

const CAPABILITIES = makeCapabilities(testParams);

console.log('Test Settings');
console.log('-----------------');
console.log('ENV             : ' + testParams.ENV);
console.log('BASE_URL        : ' + testParams.BASE_URL);
console.log('BROWSER         : ' + testParams.BROWSER);
console.log('BROWSER VERSION : ' + testParams.BROWSER_VERSION);
console.log('WIDTH           : ' + testParams.WIDTH);
console.log('HEIGHT          : ' + testParams.HEIGHT);
console.log('OS              : ' + testParams.OS);
console.log('OS VERSION      : ' + testParams.OS_VERSION);
console.log('HEADLESS        : ' + testParams.HEADLESS);
console.log('TEST SERVICE    : ' + testParams.SERVICE);
console.log('SERVICE USER    : ' + testParams.SERVICE_USER);
console.log('SERVICE KEY     : ' + (testParams.SERVICE_KEY ? 'set but hidden' : null));
console.log('-----------------');

const wdioConfig = {
    kbaseToken: authToken,
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: ['./test/integration/specs/**/*.js'],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    // capabilities: [{
    //     // maxInstances can get overwritten per capability. So if you have an in-house Selenium
    //     // grid with only 5 firefox instances available you can make sure that not more than
    //     // 5 instances get started at a time.
    //     maxInstances: 1,
    //     // 'goog:chromeOptions': {
    //     //     args: ['--disable-gpu', '--no-sandbox', 'headless']
    //     // },
    //     //
    //     browserName: 'chrome',
    //     acceptInsecureCerts: true
    //     // If outputDir is provided WebdriverIO can capture driver session logs
    //     // it is possible to configure which logTypes to include/exclude.
    //     // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
    //     // excludeDriverLogs: ['bugreport', 'server'],
    // }],
    capabilities: [CAPABILITIES],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'warn',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
    //     webdriver: 'info',
    //     '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: testParams.BASE_URL,
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 30000,
    //
    // Default timeout in milliseconds for request
    // if browser driver or grid doesn't send response
    connectionRetryTimeout: 120000,
    //
    // Default request retries count
    connectionRetryCount: 3,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: [[testParams.SERVICE, serviceConfigs[testParams.SERVICE]]],

    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'mocha',
    jasmineNodeOpts: {
        //
        // Jasmine default timeout
        defaultTimeoutInterval: 60000,
        //
        // The Jasmine framework allows interception of each assertion in order to log the state of the application
        // or website depending on the result. For example, it is pretty handy to take a screenshot every time
        // an assertion fails.
        expectationResultHandler: function (/*passed, assertion*/) {
            // do something
        },
    },
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Delay in seconds between the spec file retry attempts
    // specFileRetriesDelay: 0,
    //
    // Whether or not retried specfiles should be retried immediately or deferred to the end of the queue
    // specFileRetriesDeferred: false,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec'],

    //
    // Options to be passed to Mocha.
    // See the full list at http://mochajs.org/
    mochaOpts: {
        ui: 'bdd',
        timeout: 60000,
    },
    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed before a worker process is spawned and can be used to initialise specific service
     * for that worker as well as modify runtime environments in an async fashion.
     * @param  {String} cid      capability id (e.g 0-0)
     * @param  {[type]} caps     object containing capabilities for session that will be spawn in the worker
     * @param  {[type]} specs    specs to be run in the worker process
     * @param  {[type]} args     object that will be merged with the main configuration once worker is initialised
     * @param  {[type]} execArgv list of string arguments passed to the worker process
     */
    // onWorkerStart: function (cid, caps, specs, args, execArgv) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // before: function (capabilities, specs) {
    // },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },
    /**
     * Hook that gets executed before the suite starts
     * @param {Object} suite suite details
     */
    // beforeSuite: function (suite) {
    // },
    /**
     * Function to be executed before a test (in Mocha/Jasmine) starts.
     */
    // beforeTest: function (test, context) {
    // },
    /**
     * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
     * beforeEach in Mocha)
     */
    // beforeHook: function (test, context) {
    // },
    /**
     * Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
     * afterEach in Mocha)
     */
    // afterHook: function (test, context, { error, result, duration, passed, retries }) {
    // },
    /**
     * Function to be executed after a test (in Mocha/Jasmine).
     */
    // afterTest: function(test, context, { error, result, duration, passed, retries }) {
    // },

    /**
     * Hook that gets executed after the suite has ended
     * @param {Object} suite suite details
     */
    // afterSuite: function (suite) {
    // },
    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit. An error
     * thrown in the onComplete hook will result in the test run failing.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Object} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
     * Gets executed when a refresh happens.
     * @param {String} oldSessionId session ID of the old session
     * @param {String} newSessionId session ID of the new session
     */
    //onReload: function(oldSessionId, newSessionId) {
    //}
};

wdioConfig.testParams = testParams;

// Only set the service if it is an online service; setting the
// user and key otherwise will trigger a warning or error.
if (testParams.SERVICE === 'browserstack') {
    wdioConfig.user = testParams.SERVICE_USER;
    wdioConfig.key = testParams.SERVICE_KEY;
}

exports.config = wdioConfig;


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Thelia\Core\Form\Type\Field\AddressIdType | Thelia 2 API</title>

            <link rel="stylesheet" type="text/css" href="../../../../../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../../../../../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../../../../../css/sami.css">

        <meta name="MobileOptimized" content="width">
        <meta name="HandheldFriendly" content="true">
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">

                <form id="search-form" action="../../../../../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Thelia 2 API

Classes

Namespaces

Interfaces

Traits

Index

Search

class

Thelia

Core

Form

Type

Field

AddressIdType

AddressIdType

    class
    AddressIdType        extends AbstractIdType

Class AddressIdType

Methods

                    __construct(
    TranslatorInterface $translator)

No description

from
    AbstractIdType

                    setDefaultOptions(
    OptionsResolverInterface $resolver)

No description

from
    AbstractIdType

                    getParent()

No description

from
    AbstractIdType

                    checkId($value,
    ExecutionContextInterface $context)

No description

from
    AbstractIdType

    string

                    getName()

Returns the name of this type.

Details

in
    AbstractIdType at line 34

    __construct(
    TranslatorInterface $translator)

Parameters

    TranslatorInterface
                $translator

in
    AbstractIdType at line 39

    setDefaultOptions(
    OptionsResolverInterface $resolver)

Parameters

    OptionsResolverInterface
                $resolver

in
    AbstractIdType at line 55

    getParent()

in
    AbstractIdType at line 60

    checkId($value,
    ExecutionContextInterface $context)

Parameters

                $value

    ExecutionContextInterface
                $context

at line 39

    string
    getName()

Returns the name of this type.

Return Value

    string
            The name of this type

        Generated by Sami, the API Documentation Generator.

redpajama_set_name: RedPajamaGithub


text:
package manifest

import (
	"context"
	"fmt"

	"github.com/google/kf/v2/pkg/apis/kf"
	kfapis "github.com/google/kf/v2/pkg/apis/kf"
	apivalidation "k8s.io/apimachinery/pkg/api/validation"
	v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/validation/field"

	"knative.dev/pkg/apis"
)

const (
	protocolHTTP2 = "http2"
	protocolHTTP  = "http"
	protocolTCP   = "tcp"
)

// Validate checks for errors in the Application's fields.
func (app *Application) Validate(ctx context.Context) (errs *apis.FieldError) {
	// validate container execution
	if app.Command != "" {
		if len(app.Args) > 0 {
			errs = errs.Also(apis.ErrMultipleOneOf("command", "args"))
		}

		if app.Entrypoint != "" {
			errs = errs.Also(apis.ErrMultipleOneOf("entrypoint", "command"))
		}
	}

	// validate buildpacks
	if len(app.Buildpacks) > 0 {
		if app.LegacyBuildpack != "" {
			errs = errs.Also(apis.ErrMultipleOneOf("buildpack", "buildpacks"))
		}
	}

	errs = errs.Also(app.Ports.Validate(ctx).ViaField("ports"))

	errs = errs.Also(app.Metadata.Validate(ctx).ViaField("metadata"))

	okRoutePorts := sets.NewInt(0) // 0 means default
	for _, port := range app.Ports {
		okRoutePorts.Insert(int(port.Port))
	}
	for i, route := range app.Routes {
		if !okRoutePorts.Has(int(route.AppPort)) {
			errs = errs.Also(apis.ErrInvalidValue("must match a declared port", "appPort").ViaFieldIndex("routes", i))
		}
	}

	// Check that the probe fields are mutually exclusive
	hasCFHealthChecks := app.hasCFHealthCheckFields()
	hasK8sHealthChecks := app.hasK8sHealthCheckFields()

	switch {
	case hasCFHealthChecks && hasK8sHealthChecks:
		errs = errs.Also(&apis.FieldError{Message: "startupProbe, livenessProbe, and readinessProbe can't be used with CF health check fields"})
	case hasK8sHealthChecks:
		errs = errs.Also(kf.ValidateContainerProbe(app.StartupProbe).ViaField("startupProbe"))
		errs = errs.Also(kf.ValidateContainerProbe(app.LivenessProbe).ViaField("livenessProbe"))
		errs = errs.Also(kf.ValidateContainerProbe(app.ReadinessProbe).ViaField("readinessProbe"))
	case hasCFHealthChecks:
		// NOTE: https://docs.cloudfoundry.org/devguide/deploy-apps/healthchecks.html#health_check_timeout
		// says that officially the max timeout is 180, but checking that would likely be a
		// major breaking change with Kf because Kf was built before K8s supported startup probes so
		// longer timeouts were necessary to ensure apps would start.

		if timeout := app.HealthCheckTimeout; timeout < 0 {
			errs = errs.Also(apis.ErrInvalidValue(timeout, "timeout", "health check timeout can't be negative"))
		}

		if timeout := app.HealthCheckInvocationTimeout; timeout < 0 {
			errs = errs.Also(apis.ErrInvalidValue(timeout, "health-check-invocation-timeout", "health check timeout can't be negative"))
		}

		if app.HealthCheckType != "http" && app.HealthCheckHTTPEndpoint != "" {
			errs = errs.Also(apis.ErrInvalidValue(
				app.HealthCheckHTTPEndpoint,
				"health-check-http-endpoint",
				`field can only be set if health-check-type is "http"`))
		}

		allowedHealthCheckTypes := sets.NewString("http", "port", "", "process", "none")
		if !allowedHealthCheckTypes.Has(app.HealthCheckType) {
			errs = errs.Also(apis.ErrInvalidValue(
				app.HealthCheckType,
				"health-check-type",
				fmt.Sprintf("valid values are: %q", allowedHealthCheckTypes.List()),
			))
		}
	}

	return
}

// Validate implements apis.Validatable
func (a AppPortList) Validate(ctx context.Context) (errs *apis.FieldError) {
	seen := sets.NewInt()

	for i, port := range a {
		errs = errs.Also(port.Validate(ctx).ViaIndex(i))

		// ensure there are no duplicate port entries
		portInt := int(port.Port)
		if seen.Has(portInt) {
			errs = errs.Also(kfapis.ErrDuplicateValue(portInt, "port").ViaIndex(i))
		}
		seen.Insert(portInt)
	}

	return
}

// Validate implements apis.Validatable
func (a *AppPort) Validate(ctx context.Context) (errs *apis.FieldError) {
	// Validate port number
	errs = errs.Also(kfapis.ValidatePortNumberBounds(a.Port, "port"))

	// Validate protocol
	validProtocols := sets.NewString(protocolHTTP, protocolTCP, protocolHTTP2)
	if !validProtocols.Has(a.Protocol) {
		msg := fmt.Sprintf("must be one of: %v", validProtocols.List())
		errs = errs.Also(apis.ErrInvalidValue(msg, "protocol"))
	}

	return
}

// Validate implements apis.Validatable
func (a *ApplicationMetadata) Validate(ctx context.Context) (errs *apis.FieldError) {

	for _, err := range apivalidation.ValidateAnnotations(a.Annotations, field.NewPath("annotations")) {
		errs = errs.Also(&apis.FieldError{
			Message: err.ErrorBody(),
			Paths:   []string{err.Field},
		})
	}

	for _, err := range v1validation.ValidateLabels(a.Labels, field.NewPath("labels")) {
		errs = errs.Also(&apis.FieldError{
			Message: err.ErrorBody(),
			Paths:   []string{err.Field},
		})
	}

	return
}


text:
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Refactoring;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.PatternMatching;
using Mono.CSharp;
using ICSharpCode.NRefactory.Semantics;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{

	[IssueDescription ("Redundant 'partial' modifier in type declaration",
	                   Description = "Class is declared partial but has only one part",
	                   Category = IssueCategories.RedundanciesInDeclarations,
	                   Severity = Severity.Warning,
	                   AnalysisDisableKeyword = "PartialTypeWithSinglePart")]
	public class PartialTypeWithSinglePartIssue : GatherVisitorCodeIssueProvider
	{
		protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
		{
			return new GatherVisitor(context);
		}

		class GatherVisitor : GatherVisitorBase<PartialTypeWithSinglePartIssue>
		{
			public GatherVisitor(BaseRefactoringContext ctx)
				: base(ctx)
			{
			}

			public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
			{
				if (!typeDeclaration.HasModifier(Modifiers.Partial)) {
					//We still need to visit the children in search of partial nested types.
					base.VisitTypeDeclaration(typeDeclaration);
					return;
				}

				var resolveResult = ctx.Resolve(typeDeclaration) as TypeResolveResult;
				if (resolveResult == null)
					return;

				var typeDefinition = resolveResult.Type.GetDefinition();
				if (typeDefinition == null)
					return;

				if (typeDefinition.Parts.Count == 1) {
					var partialModifierToken = typeDeclaration.ModifierTokens.Single(modifier => modifier.Modifier == Modifiers.Partial);
					// there may be a disable comment before the partial token somewhere
					foreach (var child in typeDeclaration.Children.TakeWhile (child => child != partialModifierToken)) {
						child.AcceptVisitor(this);
					}
					AddIssue(new CodeIssue(partialModifierToken,
					         ctx.TranslateString("Partial class with single part"),
						GetFixAction(typeDeclaration, partialModifierToken)) { IssueMarker = IssueMarker.GrayOut });
				}
				base.VisitTypeDeclaration(typeDeclaration);
			}

			public override void VisitBlockStatement(BlockStatement blockStatement)
			{
				//We never need to visit the children of block statements
			}

			CodeAction GetFixAction(TypeDeclaration typeDeclaration, CSharpModifierToken partialModifierToken)
			{
				return new CodeAction(ctx.TranslateString("Remove 'partial'"), script => {
					script.ChangeModifier (typeDeclaration, typeDeclaration.Modifiers & ~Modifiers.Partial);
				}, partialModifierToken);
			}
		}
	}
}


text:
require 'spec_helper'

describe 'controller index' do
  context 'when a user requests a page' do
    it 'should respond with an ok status' do
      get '/'
      expect(last_response).to be_ok
    end

    it 'should contain a form to enter your route' do
      get '/'
      expect(last_response.body).to include("Welcome")
    end
  end
end


text:
<?php

    namespace frontend\models;

    use yii\base\Exception;
    use yii\db\ActiveRecord;
    use Yii;

    class Settings extends \yii\base\Model {

        /**
         * Возвращает значенеи конфигурационного параметра
         *
         * @param $key
         * @return string
         * @throws Exception
         */
        public function getConfigurationParamByKey($key){

            if( (int)(new \yii\db\Query())
                ->select('data')
                ->from('{{%settings}} comments')
                ->where([
                    'key' => $key
                ])->count() === 0 )

                throw new Exception("No such key ($key) stored in db");

            return (string)(new \yii\db\Query())
                ->select('data')
                ->from('{{%settings}} comments')
                ->where([
                    'key' => $key
                ])
                ->one()['data'];
        }

    }


text:
package org.ehcache.loaderwriter.writebehind;

import org.ehcache.spi.ServiceLocator;
import org.ehcache.spi.ServiceProvider;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.ehcache.spi.loaderwriter.WriteBehindConfiguration;
import org.ehcache.spi.loaderwriter.WriteBehindDecoratorLoaderWriterProvider;
import org.ehcache.spi.service.ServiceConfiguration;
import org.ehcache.spi.service.ServiceFactory;

/**
 * @author Abhilash
 *
 */
public class WriteBehindDecoratorLoaderWriterProviderFactory implements ServiceFactory<WriteBehindDecoratorLoaderWriterProvider> {

  private volatile WriteBehindDecoratorLoaderWriter<?, ?> loaderWriter = null;

  @Override
  public WriteBehindDecoratorLoaderWriterProvider create(ServiceConfiguration<WriteBehindDecoratorLoaderWriterProvider> serviceConfiguration, ServiceLocator serviceLocator) {
    return new WriteBehindDecoratorLoaderWriterProvider() {

      @Override
      public void stop() {
        // no op

      }

      @Override
      public void start(ServiceConfiguration<?> config, ServiceProvider serviceProvider) {
        if (config != null) {
          throw new IllegalArgumentException("WriteBehind configuration must not be provided at CacheManager level");
        }
      }

      @Override
      public <K, V> WriteBehindDecoratorLoaderWriter<K, V> createWriteBehindDecoratorLoaderWriter(CacheLoaderWriter<K, V> cacheLoaderWriter, WriteBehindConfiguration configuration) {
        if (cacheLoaderWriter == null) {
          throw new NullPointerException("WriteBehind requires non null CacheLoaderWriter.");
        }
        loaderWriter = new WriteBehindDecoratorLoaderWriter<K, V>(cacheLoaderWriter, configuration);
        return (WriteBehindDecoratorLoaderWriter<K, V>)loaderWriter;
      }

      @Override
      public void releaseWriteBehindDecoratorCacheLoaderWriter(CacheLoaderWriter<?, ?> cacheLoaderWriter) {
        if(loaderWriter != null) loaderWriter.getWriteBehindQueue().stop();
      }
    };
  }

  @Override
  public Class<WriteBehindDecoratorLoaderWriterProvider> getServiceType() {
    return WriteBehindDecoratorLoaderWriterProvider.class;
  }

}


text:
using System.Runtime.CompilerServices;

namespace System.Runtime.Intrinsics.Arm
{
    /// <summary>
    /// This class provides access to the ARM AES hardware instructions via intrinsics
    /// </summary>
    [Intrinsic]
    [CLSCompliant(false)]
    public abstract class Aes : ArmBase
    {
        internal Aes() { }

        public static new bool IsSupported { get => IsSupported; }

        /// <summary>
        /// uint8x16_t vaesdq_u8 (uint8x16_t data, uint8x16_t key)
        ///   A32: AESD.8 Qd, Qm
        ///   A64: AESD Vd.16B, Vn.16B
        /// </summary>
        public static Vector128<byte> Decrypt(Vector128<byte> value, Vector128<byte> roundKey) => Decrypt(value, roundKey);

        /// <summary>
        /// uint8x16_t vaeseq_u8 (uint8x16_t data, uint8x16_t key)
        ///   A32: AESE.8 Qd, Qm
        ///   A64: AESE Vd.16B, Vn.16B
        /// </summary>
        public static Vector128<byte> Encrypt(Vector128<byte> value, Vector128<byte> roundKey) => Encrypt(value, roundKey);

        /// <summary>
        /// uint8x16_t vaesimcq_u8 (uint8x16_t data)
        ///   A32: AESIMC.8 Qd, Qm
        ///   A64: AESIMC Vd.16B, Vn.16B
        /// </summary>
        public static Vector128<byte> InverseMixColumns(Vector128<byte> value) => InverseMixColumns(value);

        /// <summary>
        /// uint8x16_t vaesmcq_u8 (uint8x16_t data)
        ///   A32: AESMC.8 Qd, Qm
        ///   A64: AESMC V>.16B, Vn.16B
        /// </summary>
        public static Vector128<byte> MixColumns(Vector128<byte> value) => MixColumns(value);
    }
}


text:
class AddSocietyFlagToAwards < ActiveRecord::Migration
  def change
    add_column :awards, :society, :boolean, null: false, default: false
  end
end


text:
#ifndef __CCWIDGETBASE_H__
#define __CCWIDGETBASE_H__

struct CCWidgetCallbacks
{
    CCWidgetCallbacks()
    {
        routine = NULL;
        parameter1 = parameter2 = NULL;
    }

    void run()
    {
        if( routine != NULL )
        {
            routine( parameter1, parameter2 );
        }
    }

    void (*routine)(void *parameter1, void *parameter2);
    void *parameter1, *parameter2;
};

struct CCScreenTouches;

class CCWidgetBase : public CCBaseType
{
public:
    CCWidgetBase();
    virtual void destruct();

    const bool inActiveSpace(const CCPoint &inPosition);
    const bool touchInActiveSpace(const CCScreenTouches &screenTouch);
    virtual const bool handleControls(const CCScreenTouches &screenTouch, const bool released=true);
    virtual const bool update(const CCTime &time);
	virtual const bool render(const bool foreground);

	inline const float getWidth() const { return size.width; }
	inline const float getHeight() const { return size.height; }
    inline const CCSize getSizeStart() { return sizeStart; }
    inline const CCPoint getPosition() { return position; }
    inline const CCPoint getTargetPosition() { return positionTarget; }

    void setPosition(const CCPoint &inPosition);
	void setPosition(const float x, const float y);
    void setTarget(const CCPoint &target);
	void setTarget(const float x, const float y);

    virtual void setSize(const CCSize &size, const bool correctAspect=true);
	void setSize(const float width, const float height, const bool correctAspect=true);
    void setSizeTarget(const CCSize &size, const bool correctAspect=true, const float speed=-1.0f);
	void setSizeTarget(const float width, const float height, const bool correctAspect=true, const float speed=-1.0f);

	inline const bool isInView() { return inView; }
	inline const bool interpolating() const
	{
		return moving() ||
		size.width != sizeTarget.width || size.height != sizeTarget.height ||
		( colour != NULL && colourTarget != NULL && colour->equals( *colourTarget ) == false );
	}

	inline const bool moving() const
	{
		return positionTarget.x != position.x || positionTarget.y != position.y;
	}

    virtual const CCWidgetBase* unHover() { return NULL; }

	// Update min/max
	virtual void refreshDimensions();

	inline const float getStartX() { return min.x; }
	inline const float getStartY() { return min.y; }
	inline const float getEndX() { return max.x; }
	inline const float getEndY() { return max.y; }

	inline const CCColour& getColour() { return *colour; }
	inline const float getTargetAlpha() { return colourTarget != NULL ? colourTarget->alpha : 1.0f; }

	void setColour(const CCColour &newColour);
	void setTargetColour(const CCColour &newColour);

	void setColourAlpha(const float alpha);
	void setTargetAlpha(const float target);
    void setTexture(const char *name, const CCResourceType resourceType);

	virtual const bool isDragged() { return false; }

	bool enabled;

	bool renderButton;		// Should we render our background button
	bool renderOutline;
	bool renderForeground;	// Are we rendering in the foreground

	float movementSpeed, resizeSpeed;

	bool distortEffect;		// Apply distortion effect?
	float distortAmount, distortSpeed;

	float colourSpeed;

	CCWidgetCallbacks onInterpolated;
	struct CCPrimitiveSquareUVs *customUVs;

protected:
	bool inView;

    CCPoint position, positionTarget;
    CCSize size, sizeTarget, sizeStart;

    CCPoint min, max;

	CCColour *colour, *colourTarget;
	int textureIndex;

    CCPoint distort, distortTarget;
};

void callback_widgetDisableOnInterpolated(void *parameter1, void *parameter2);

#endif // __CCWIDGETBASE_H__


text:
package org.apache.camel.component.bean;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;

/**
 * @version
 */
public class BeanInvokeWithNullBodyTest extends ContextTestSupport {

    public void testWithHelloWorld() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    public void testWithEmptyBody() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("");

        template.sendBody("direct:start", "");

        assertMockEndpointsSatisfied();
    }

    public void testWithNullBody() throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(1);
        getMockEndpoint("mock:result").message(0).body().isNull();

        template.sendBody("direct:start", null);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        jndi.bind("foo", new MyNullFooBean());
        return jndi;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").to("bean:foo").to("mock:result");
            }
        };
    }

    @SuppressWarnings("unused")
    private static class MyNullFooBean {

        public String doSomething(String s) {
            return s;
        }
    }
}


text:
using System;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.UI.ProgressMonitoring;

namespace Gallio.Icarus.Commands
{
    public class DelegateCommand : ICommand
    {
        public DelegateCommand(Action<IProgressMonitor> action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            Action = action;
        }

        public Action<IProgressMonitor> Action
        {
            get; private set;
        }

        public void Execute(IProgressMonitor progressMonitor)
        {
            Action(progressMonitor);
        }
    }
}


text:
viewModel.table = new Object()
let tbl = viewModel.table

tbl.data = ko.observableArray([])
tbl.currentTargetDimension = null

tbl.dimensions = ko.observableArray([])
tbl.dataPoints = ko.observableArray([])
tbl.enableDimensions = ko.observable(true)
tbl.enableDataPoints = ko.observable(true)

tbl.setMode = (what) => () => {
	tbl.mode(what)

	if (what == 'render') {
		tbl.refresh()
	}
}
tbl.mode = ko.observable('render')
tbl.computeDimensionDataPoint = (which, field) => {
	return ko.pureComputed({
		read: () => {
	        return tbl[which]().filter((d) => d.field() == field).length > 0
	    },
	    write: (value) => {
	    	let row = tbl[which]().find((d) => d.field() == field)
	    	if (app.isDefined(row)) {
	    		tbl[which].remove(row)
	    	} else {
	    		let option = (which == 'dataPoint') ? 'optionDataPoints' : 'optionDimensions'
	    		row = app.koMap(app.koUnmap(ra[option]).find((d) => d.field == field))
	    		tbl[which].push(row)
	    	}
	    },
	    owner: this
	})
}
tbl.getParam = () => {
	let dimensions = ko.mapping.toJS(tbl.dimensions)
		.filter((d) => (d.field != ''))
	let dataPoints = ko.mapping.toJS(tbl.dataPoints)
		.filter((d) => (d.field != '') && (d.field != ''))
		.map((d) => { return { field: d.field, name: d.name, aggr: 'sum' } })

	return rpt.wrapParam(dimensions, dataPoints)
}
tbl.refresh = () => {
	// pvt.data(DATATEMP_TABLE)
	app.ajaxPost(viewModel.appName + "report/summarycalculatedatapivot", tbl.getParam(), (res) => {
		tbl.data(res.Data)
		tbl.render()
	})
}
tbl.render = () => {
	let dimensions = app.koUnmap(tbl.dimensions)
		.filter((d) => (d.field != ''))
		.map((d) => { return { field: app.idAble(d.field), title: d.name } })
	let dataPoints = ko.mapping.toJS(tbl.dataPoints)
		.filter((d) => (d.field != '') && (d.field != ''))
		.map((d) => {
			return {
				field: app.idAble(d.field),
				headerTemplate: `<div class="align-right">${d.name}</div>`,
				format: '{0:n2}',
				attributes: { class: 'align-right' },
				isDataPoint: true
			}
		})

	let columns = dimensions.concat(dataPoints).map((d, i) => {
		d.format = '{0:n2}'

		if (i == 0) {
			d.footerTemplate = 'Total :'
		}

		if (app.isDefined(d.isDataPoint)) {
			d.aggregates = ['sum']
			d.footerTemplate = '
#= kendo.toString(sum, "n2") #
'
		}

		return d
	})

	let config = {
		dataSource: {
			data: tbl.data(),
			pageSize: 10,
            aggregate: [
				{ field: 'value1', aggregate: 'sum' },
				{ field: 'value2', aggregate: 'sum' },
				{ field: 'value3', aggregate: 'sum' }
			]
		},
		pageable: true,
		columns: columns
	}

	app.log('table', app.clone(config))
	$('.tabular-view').replaceWith(`<div class="tabular-view"></div>`)
	$('.tabular-view').kendoGrid(config)
}

$(() => {
	tbl.dimensions([
		app.koMap({ field: 'customer.branchname', name: 'Branch/RD' }),
		app.koMap({ field: 'product.name', name: 'Product' }),
		app.koMap({ field: 'customer.channelname', name: 'Product' })
	])
	tbl.dataPoints([
		app.koMap({ field: 'value1', name: o[`value1`] }),
		app.koMap({ field: 'value2', name: o[`value2`] }),
		app.koMap({ field: 'value3', name: o[`value3`] })
	])
	tbl.refresh()
})


text:
package org.spongepowered.api.data.type;

import org.spongepowered.api.entity.living.trader.Villager;
import org.spongepowered.api.registry.DefaultedRegistryValue;
import org.spongepowered.api.util.annotation.CatalogedBy;

/**
 * Represents a {@link Villager} profession. A profession defines the genre of
 * trade offers a trader may offer to a player.
 */
@CatalogedBy(ProfessionTypes.class)
public interface ProfessionType extends DefaultedRegistryValue {

}


text:
package org.elasticsearch.xpack.core.termsenum.rest;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xpack.core.termsenum.action.TermsEnumAction;
import org.elasticsearch.xpack.core.termsenum.action.TermsEnumRequest;

import java.io.IOException;
import java.util.List;

import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;

public class RestTermsEnumAction extends BaseRestHandler {

    @Override
    public List<Route> routes() {
        return List.of(new Route(GET, "/{index}/_terms_enum"), new Route(POST, "/{index}/_terms_enum"));
    }

    @Override
    public String getName() {
        return "term_enum_action";
    }

    @Override
    public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
        try (XContentParser parser = request.contentOrSourceParamParser()) {
            TermsEnumRequest termEnumRequest = TermsEnumAction.fromXContent(
                parser,
                Strings.splitStringByCommaToArray(request.param("index"))
            );
            return channel -> client.execute(TermsEnumAction.INSTANCE, termEnumRequest, new RestToXContentListener<>(channel));
        }
    }

}


text:
package org.diorite.impl.command.defaults;

import java.util.Objects;
import java.util.regex.Pattern;

import org.diorite.impl.command.SystemCommandImpl;
import org.diorite.Server;
import org.diorite.chat.ChatPosition;
import org.diorite.command.CommandPriority;

public class SayCmd extends SystemCommandImpl
{
    public SayCmd()
    {
        super("say", Pattern.compile("(say)(:(?<type>[a-z0-9]+)|)", Pattern.CASE_INSENSITIVE), CommandPriority.LOW);
        this.setCommandExecutor((sender, command, label, matchedPattern, args) -> {
            ChatPosition chatPosition;
            try
            {
                chatPosition = ChatPosition.getByEnumName(matchedPattern.group("type"));
                if (chatPosition == null)
                {
                    chatPosition = ChatPosition.CHAT;
                }
            } catch (IllegalStateException | IllegalArgumentException e)
            {
                chatPosition = ChatPosition.CHAT;
            }
            if (Objects.equals(chatPosition, ChatPosition.ACTION))
            {
                sender.getServer().sendConsoleSimpleColoredMessage(Server.PREFIX_MSG + args.asText());
            }
            sender.getServer().broadcastSimpleColoredMessage(chatPosition, Server.PREFIX_MSG + args.asText());
        });
    }
}


text:
import { IndexInterface, DocumentInterface } from "./type.js";
//import { promise as Promise } from "./polyfill.js";
import { is_function, is_object, is_string } from "./common.js";

export default function(prototype){

    register(prototype, "add");
    register(prototype, "append");
    register(prototype, "search");
    register(prototype, "update");
    register(prototype, "remove");
}

function register(prototype, key){

    prototype[key + "Async"] = function(){

        /** @type {IndexInterface|DocumentInterface} */
        const self = this;
        const args = /*[].slice.call*/(arguments);
        const arg = args[args.length - 1];
        let callback;

        if(is_function(arg)){

            callback = arg;
            delete args[args.length - 1];
        }

        const promise = new Promise(function(resolve){

            setTimeout(function(){

                self.async = true;
                const res = self[key].apply(self, args);
                self.async = false;
                resolve(res);
            });
        });

        if(callback){

            promise.then(callback);
            return this;
        }
        else{

            return promise;
        }
    };
}


text:
from django.core import validators as core_validators
from django.utils.translation import ugettext as _

from taiga.base.api import serializers
from taiga.base.api import validators
from taiga.base.exceptions import ValidationError

import re

class BaseRegisterValidator(validators.Validator):
    full_name = serializers.CharField(max_length=256)
    email = serializers.EmailField(max_length=255)
    username = serializers.CharField(max_length=255)
    password = serializers.CharField(min_length=4)

    def validate_username(self, attrs, source):
        value = attrs[source]
        validator = core_validators.RegexValidator(re.compile('^[\w.-]+$'), _("invalid username"), "invalid")

        try:
            validator(value)
        except ValidationError:
            raise ValidationError(_("Required. 255 characters or fewer. Letters, numbers "
                                    "and /./-/_ characters'"))
        return attrs

class PublicRegisterValidator(BaseRegisterValidator):
    pass

class PrivateRegisterForNewUserValidator(BaseRegisterValidator):
    token = serializers.CharField(max_length=255, required=True)

class PrivateRegisterForExistingUserValidator(validators.Validator):
    username = serializers.CharField(max_length=255)
    password = serializers.CharField(min_length=4)
    token = serializers.CharField(max_length=255, required=True)


text:
//============================================================================
//
//	Copyright (c) 1999-2015 . All Rights Reserved.
//
//----------------------------------------------------------------------------
//
//	Fichero: Log.java  1.0 30/08/99
//
//
//	Descripción: Clase log. Imprime mensajes logging y de depuración en stdout.
//
// 	Authors:
//		 Alejandro García-Domínguez (alejandro.garcia.dominguez@gmail.com)
//		 Antonio Berrocal Piris (antonioberrocalpiris@gmail.com)
//
//  Historial:
//  07.04.2015 Changed licence to Apache 2.0
//
//  This file is part of PTMF
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//----------------------------------------------------------------------------

package ptmf;

import java.io.*;

/**
 * Clase Log. Imprime mensajes logging y de depuración en stdout.
 * @version 1.0
 * @author M. Alejandro García Domínguez
 * (alejandro.garcia.dominguez@gmail.com)

 *			   Antonio Berrocal Piris
 */

public class Log extends PrintStream {

  static OutputStream logfile;
  static PrintStream  oldStdout;
  static PrintStream  oldStderr;
  static boolean      bPantalla = false;

  /** Niveles de depuración */
  public static final int TODO            = 0xFFFFFFFF;
  public static final int IDGL            = 0x00000001;
  public static final int TPDU            = 0x00000002;
  public static final int TPDU_CGL        = 0x00000004;
  public static final int TPDU_DATOS      = 0x00000008;
  public static final int TEMPORIZADOR    = 0x00000010;
  public static final int CGL             = 0x00000020;
  public static final int SOCKET          = 0x00000040;
  public static final int CANAL_MULTICAST = 0x00000080;
  public static final int CANAL_UNICAST   = 0x00000090;
  public static final int ACK             = 0x00000100;
  public static final int TPDU_NORMAL     = 0x00000200;
  public static final int NACK            = 0x00000400;
  public static final int HACK            = 0x00000800;
  public static final int HSACK           = 0x00001000;
  public static final int MACK            = 0x00002000;
  public static final int CGLOCALES       = 0x00004000;
  public static final int ID_SOCKETS_EMISORES   = 0x00008000;
  public static final int TABLA_ASENTIMIENTOS = 0x00020000;
  public static final int VENTANA         = 0x00080000;
  public static final int DATOS_THREAD    = 0x00100000;
  public static final int TPDU_RTX        = 0x00200000;
  public static final int DATOS_USUARIO   = 0x00800000;
  public static final int HNACK           = 0x01000000;
  public static final int ID_SOCKET       = 0x02000000;
  public static final int ID_SOCKETINPUTSTREAM  = 0x03000000;

  private static boolean DEBUG = true;
  private static int NIVEL_DEPURACION = 0;

  //==========================================================================
  /**
   * Constructor.
   * @param ps Un objeto PrintStream.
   */
  Log(PrintStream ps) {
    super(ps);
  }

  //==========================================================================
  /**
   * Método debug
   * @param nivel Nivel de depuración
   * @param mn Nombre del método
   * @param msg Mensaje
   */
  public static void debug(int nivel,String mn,String msg) {

    if(DEBUG)
    {
      //log(null,"Nivel: "+NIVEL_DEPURACION+" nivel:"+nivel);
      if ((NIVEL_DEPURACION & nivel) == nivel)
      {
        log(mn,msg);
      }
    }
  }

  //==========================================================================
  /**
   * Método log
   * @param mn Nombre del método
   * @param msg Mensaje
   */
  public static void log(String mn,String msg) {

   if(mn != null)
     System.out.println("["+mn+"] "+msg);
   else
     System.out.println(msg);

  }

  //==========================================================================
  /**
   * Método log
   * @param mn Nombre del método
   * @param msg Mensaje
   */
  public static void log(int iNivel,String mn,String msg) {

  /*
   switch(iNivel)
   {
    case 0xFFFFFFFF:
      sNivel =  TODO;
      break;
    case 0x00000001:
      sNivel = IDGL;

  case 0x00000002:

  TPDU            =

case 0x00000004:

  TPDU            =

  case 0x00000008:
  TPDU_DATOS      =
  case 0x00000010:
  TEMPORIZADOR    =
  case 0x00000020:
  CGL             =
  case 0x00000040:
  SOCKET          =
  case 0x00000080:
  CANAL_MULTICAST             =

case
  ACK             = 0x00000100;
  TPDU_NORMAL     = 0x00000200;
  NACK            = 0x00000400;
  HACK            = 0x00000800;
  HSACK           = 0x00001000;
  MACK            = 0x00002000;
  CGLOCALES       = 0x00004000;
  ID_SOCKETS_EMISORES   = 0x00008000;
  TABLA_ASENTIMIENTOS = 0x00020000;
  VENTANA         = 0x00080000;
  DATOS_THREAD    = 0x00100000;
  TPDU_RTX        = 0x00200000;
  DATOS_USUARIO   = 0x00800000;
  HNACK           = 0x01000000;
  ID_SOCKET       = 0x02000000;

   }
*/
   if(mn != null)
   {
     System.out.println("["+iNivel+"]"+" {"+mn+"} "+msg);
   }
   else
   {
     System.out.println("["+iNivel+"] "+msg);
   }
  }
  //==========================================================================
  /**
   * Método exit
   * @param int Código de salida
   */
  public static void exit(int codigo) {
    System.exit(-1);
  }

  //==========================================================================
  /**
   * Este método establece el nivel de depuración
   * @param int Nivel de depuración.
   *

   * <IL>Si se requiere todos los niveles: NIVEL_TODOS </IL>
   * <IL>Cualquier nivel se puede poner como combinación OR a nivel de bits "||"
   *   de cualquier nivel. Por ejemplo: IDGL | DATOS </IL>
   *

   */
  public static void setNivelDepuracion(int nivel)
  {
     NIVEL_DEPURACION = nivel;

     if (nivel == 0)
     {
       DEBUG = false;
     }
  }

  //==========================================================================
  /**
   * Este método obtiene el nivel de depuración
   * @return Nivel de depuración.
   */
  public static int getNivelDepuracion()
  {
    return NIVEL_DEPURACION;
  }

  //==========================================================================
  /**
   * Este método activa/desactiva la DEPUIRACIÓN
   * @param boolean depuracion
   */
  public static void setDepuracion(boolean depuracion)
  {
    DEBUG = depuracion;
  }

  //==========================================================================
  /**
   * Logging a un fichero. redirecciona la salida estandar y la de error
   * a un fichero.
   * @param f Fichero
   * @param pantalla Indica si la información debe de imprimirse en la pantalla también.
   */
   public static void logToFile(String f, boolean bpantalla) throws IOException {

      // Almacenar los flujos antiguos.
      oldStdout = System.out;
      oldStderr = System.err;

      // Crear/Abrir el fichero.
      logfile = new PrintStream(new BufferedOutputStream( new FileOutputStream(f)));

      if (logfile != null)
      {
       // Comenzar el redireccionamiento.
       System.setOut(new Log(System.out));
       System.setErr(new Log(System.err));

       bPantalla = bpantalla;
      }
    }

  //==========================================================================
  /**
   * Parar el Logging a un fichero. Redirecciona la salida estandar y la de error
   * a sus opciones por defecto.
   */
    public static void reset() {

      System.setOut(oldStdout);
      System.setErr(oldStderr);
      bPantalla = false;
      try
      {

        logfile.close();

      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }

  //==========================================================================
  /**
   * Sobreescribir write de PrintStream.
   */
  public void write(int b) {
    try
    {
      logfile.write(b);

      if (bPantalla)
       oldStdout.write(b);
    }
    catch (Exception e)
    {
       e.printStackTrace();
       setError();
    }
    super.write(b);
  }

  //==========================================================================
  /**
   * Sobreescribir write de PrintStream.
   */
   public void write(byte buf[], int off, int len) {
      try
      {
        logfile.write(buf, off, len);

        if (bPantalla)
         oldStdout.write(buf,off,len);

      }
      catch (Exception e)
      {
            e.printStackTrace();
            setError();
      }

      super.write(buf, off, len);
    }
}