Setup PHP code sniffer.
770244
public function setupPhpCodeSniffer()
    {
        $root_path = ProjectX::projectRoot();

        $this->taskWriteToFile("{$root_path}/phpcs.xml.dist")
            ->text($this->loadTemplateContents('phpcs.xml.dist'))
            ->place('PROJECT_ROOT', $this->getInstallRoot())
            ->run();

        $this->composer->addRequires([
            'squizlabs/php_codesniffer' => static::PHPCS_VERSION,
        ], true);

        return $this;
    }
1323052
public function setup() {
		$this->errorHandler = $errorHandler = \Asgard\Debug\ErrorHandler::register();
		if(php_sapi_name() !== 'cli')
			\Asgard\Debug\Debug::setFormat('html');

		register_shutdown_function([$this, 'shutdownFunction']);
		$this->addShutdownCallback([$errorHandler, 'shutdownFunction']);

		$compiledFile = $this->getCompiledFile();
		if($compiledFile && file_exists($compiledFile))
			include_once $compiledFile;

		return $this;
	}
1367009
private function configNormalize()
    {
        $this->debug->groupCollapsed(__METHOD__);
        $cfg = &$this->cfg;
        if (!isset($cfg['attribs']['id'])) {
            $cfg['attribs']['id'] = 'form-'.\str_replace(' ', '_', $cfg['name']);
        }
        if (!isset($cfg['attribs']['name'])) {
            $cfg['attribs']['name'] = \str_replace(' ', '_', $cfg['name']);
        }
        if (isset($cfg['fields'])) {
            $cfg['pages'] = array(
                $cfg['fields'],
            );
            unset($cfg['fields']);
        } elseif (!isset($cfg['pages'])) {
            $cfg['pages'] = array( array() );
        }
        if ($cfg['onComplete'] == 'log' && empty($cfg['logFile'])) {
            $callerInfo = Php::getCallerInfo();
            $dirname = \dirname($callerInfo['file']);
            $cfg['logFile'] = $dirname.DIRECTORY_SEPARATOR.$cfg['name'].'_log.csv';
        }
        /*
            we will use the callable defined in cfg
            if we have a method defined, define it in cfg
        */
        $methods = array(
            'buildAlerts',
            'buildOutput',
            'onComplete',
            'pre',
            'post',
        );
        foreach ($methods as $method) {
            if (\method_exists($this, $method)) {
                $cfg[$method] = array($this, $method);
            }
        }
        // $this->debug->log('cfg', $cfg);
        $this->debug->groupEnd();
    }
678607
def main():
    """"""
    parser = argparse.ArgumentParser(description='webBench is an alternative to ab in python')

    parser.add_argument('-n', dest='requests', type=int,
                        help='Number of requests to perform')
    parser.add_argument('-c', dest='concurrency', type=int,
                        help='Number of multiple requests to make at a time')
    parser.add_argument('-d', dest='strbody', type=str, default='',
                        help='String post body')
    parser.add_argument('-p', dest='postfile', type=str, default='',
                        help='File containing data to POST')
    parser.add_argument('-u', dest='putfile', type=str, default='',
                        help='File containing data to PUT')
    parser.add_argument('-v', dest='verbosity', type=int, default=0,
                        help='How much troubleshooting info to print')
    parser.add_argument('-H', dest='header', action='append', default=[],
                        help='Add Arbitrary header line, eg. "Accept-Encoding: gzip"\n'
                             'Inserted after all normal header lines. (repeatable)')
    parser.add_argument('-e', dest='csv', type=str, default='',
                        help='Output CSV file with percentages served')
    parser.add_argument('-m', dest='method', type=str, default='GET',
                        help='Method name')
    parser.add_argument('-Z', dest='ciphersuite', type=str, default='',
                        help='Specify SSL/TLS cipher suite (See openssl ciphers)')
    parser.add_argument('-t', dest='http_version', default='1.1',
                        help='Speofy HTTP versions (1.0, 1.1)')
    parser.add_argument('-f', dest='protocol', default='SSLv23',
                        help='Specify SSL/TLS protocol (SSLv23, SSLv2, SSLv3, TLSv1)')
    parser.add_argument('url', metavar="URL", type=str, help='URL of request')

    # args = parser.parse_args(["-c", "1", "-n", "1", "-v", "1", "-H",
    #                           "Content-Type: application/x-www-form-urlencoded;charset=utf-8",
    #                           "-H", "Host: upl.pa.dev",
    #                           "-H", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) "
    #                                 "Gecko/20100101 Firefox/47.0",
    #                           "-H", "Accept: application/json, text/plain, */*'",
    #                           "-H 'Accept-Language: en-US,en;q=0.5",
    #                           "-H", "Accept-Encoding: gzip, deflate, br",
    #                           "-H", "X-XSRF-TOKEN: f005bad9fcec4dec745917b37b8495154f8eed0ed4fa220f3df3be79"
    #                                 "b457a33c1f76696b6e33488d67cfa29d375d65c00813ca8b4c53cf39a3e7225d64610de7",
    #                           "-H", "Referer: https://upl.pa.dev/",
    #                           "-H", "Cookie: PHPSESSID=inhevvko89k92ls80skc7ii3h6; "
    #                                 "idpSAMLSessionID=e8342db3073f8320f5a4089a9adc6cf6; "
    #                                 "idpSAMLAuthToken=_b2a7d9935241b6b8862e2e393b26cc4d304e64c0b9; "
    #                                 "spSAMLSessionID=870b591c8ff5ffde5b1a3dc7bc981c1a; "
    #                                 "spSAMLAuthToken=_70f436ee6e64911a7fa6d03d0e3faa57b2d822b4c6; "
    #                                 "XSRF-TOKEN=f005bad9fcec4dec745917b37b8495154f8eed0ed4fa220f3d"
    #                                 "f3be79b457a33c1f76696b6e33488d67cfa29d375d65c00813ca8b4c53cf39a3"
    #                                 "e7225d64610de7; "
    #                                 "web_token=29380664226a1933f9c33684f5c81b5267cab4fcfb84ea44603d8d9b7"
    #                                 "8529b7d22fc47c7011a7abf69358ff1a7dcc63c924513ab71eb22381689864fb1724292",
    #                           "-H", "Connection: keep-alive",
    #                           "-p", "/tmp/test.body", "https://upl.pa.dev/webapi/workspacefile/getProperties"])
    args = parser.parse_args()

    if args.requests < args.concurrency:
        print "Requests should be bigger then concurrency"
        sys.exit(1)

    protocols = {
        'SSLv23': ssl.PROTOCOL_SSLv23,
        'SSLv2': ssl.PROTOCOL_SSLv2,
        'SSLv3': ssl.PROTOCOL_SSLv3,
        'TLSv1': ssl.PROTOCOL_TLSv1
    }

    arguments = []
    method = args.method
    port = 443 if 'https' in args.url else 80
    host = args.url[args.url.index("://") + 3:]
    uri = '/'
    body = ''
    headers = '\r\n'.join(args.header) if args.header else []
    if '/' in host:
        uri = '%s' % host[host.index("/"):]
        host = host[:host.index("/")]
    if args.strbody:
        body = args.strbody
        method = 'POST'
    if args.postfile:
        with open(args.postfile, 'r') as f:
            body = f.read().strip()
        method = 'POST'
    elif args.putfile:
        with open(args.putfile, 'r') as f:
            body = f.read().strip()
        method = 'PUT'
    protocol = ssl.PROTOCOL_SSLv23 if args.protocol not in protocols else protocols[args.protocol]
    print "Starting benchmark for:"
    print "%s %s %s" % (method, args.url, args.http_version)
    if args.verbosity:
        if headers:
            print " Headers: \n%s" % headers
            print
        if body:
            print "Body: \n%s" % body
    print
    p = Pool(args.concurrency)
    for each in range(args.requests):
        arguments.append(dict(host=host, port=port, uri=uri, headers=headers,
                              verbocity=True if args.verbosity else False,
                              body=body, method=method, http_version=args.http_version,
                              protocol=protocol))
    print "Staring test ... "
    result = []
    start = time.time()
    for each in p.imap_unordered(bench_wrapper, arguments):
        result.append(each)
        if start + 1 < time.time():
            start = time.time()
            print "Remaining %s requests ... " % (args.requests - len(result))
    if args.csv:
        with open(args.csv, 'w') as f:
            f.write("".join(result))
    print
    print
    if args.verbosity:
        print "".join(result)
        print
        print
    req_time = []
    connection_time = []
    processing_time = []
    for each in result:
        if ',' in each:
            tmp_res = each.split(',')
            req_time.append(float(tmp_res[1]))
            connection_time.append(float(tmp_res[3]))
            processing_time.append(float(tmp_res[5]))

    print 'Summary:'
    print 'Failed Requests: %s ' % (args.requests - len(req_time))
    print
    print "Percentile\tConnection,ms\tProcessing,ms\tTotal,ms"
    some_chart = sorted(req_time)
    le = len(some_chart)
    for per in [0.5, 0.66, 0.75, 0.80, 0.90, 0.95, 0.98, 0.99]:
        value = some_chart[int(per*float(le))]
        index = req_time.index(value)
        print "%s %%\t\t%s\t\t%s\t\t%s" % (per*100, connection_time[index], processing_time[index], req_time[index])
    print "%s %%\t\t%s\t\t%s\t\t%s" % (100, max(connection_time), max(processing_time), max(req_time))
    print
445900
def run(self, *args):
        """"""

        params = self.parser.parse_args(args)

        code = self.add(params.source, params.email, params.name, params.username,
                        params.uuid, params.matching, params.interactive)

        return code
851083
public static function debug()
    {
        $vars = func_get_args();

        $cloner = new VarCloner();

        $dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper();

        $dumper->setStyles([
            'default' => 'background-color:#fff; color:#FF8400; line-height:1.2em; 
                font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; 
                white-space: pre-wrap; position:relative; z-index:99999; word-break: normal',
            'num' => 'font-weight:bold; color:#1299DA',
            'const' => 'font-weight:bold',
            'str' => 'color:#111111',
            'note' => 'color:#1299DA',
            'ref' => 'color:#A0A0A0',
            'public' => 'color:blue',
            'protected' => 'color:#111',
            'private' => 'color:#478',
            'meta' => 'color:#B729D9',
            'key' => 'color:#212',
            'index' => 'color:#1200DA',
        ]);

        $handler = function ($vars) use ($cloner, $dumper) {
            if (!is_array($vars)) {
                $vars = [$vars];
            }

            foreach ($vars as $var) {
                $dumper->dump($cloner->cloneVar($var));
            }
        };

        call_user_func_array($handler, [$vars]);
    }
398562
protected function setup()
    {
        // Check if a valid access token exists.
        if (!$this->accessToken || $this->accessToken->expired()) {
            // Refresh is successful unless explicitly set to false.
            $refreshSuccess = true;

            // Check if a valid refresh token exists.
            if ($this->refreshToken && $this->refreshToken->getToken()) {
                // Attempt to use the refresh token.
                try {
                    $this->refresh();
                } catch (RequestException $e) {
                    // Check if the exception is due to an HTTP 403.
                    if ($e->getCode() == 403) {
                        $response = $e->getResponse();
                        $json = json_decode($response->getBody());
                        $body = $json->{'nl.divide.iq'};

                        // Check if the error is indeed a "TokenExpired" error,
                        // as expected.
                        if ($body->answer == 'TokenExpired') {
                            // Token is expired; refreshing unsuccessful.
                            $refreshSuccess = false;
                        } else {
                            // Unexpected error. Pass it up the stack. This
                            // might be a "TokenEmpty" error, but that would
                            // still be unexpected, because the token value was
                            // checked beforehand.
                            throw $e;
                        }
                    } else {
                        // Unexpected error. Pass it up the stack.
                        throw $e;
                    }
                }
            } else {
                // There is no refresh token to use; refreshing unsuccessful.
                $refreshSuccess = false;
            }

            // If refreshing failed, login from scratch and then authenticate.
            if (!$refreshSuccess) {
                $this->login()->authenticate();
            }
        }

        // Request the settings if needed.
        if (!$this->settings) {
            $response = $this->client->get('settings', [
                'headers' => ['Authentication' => $this->accessToken->getToken()],
            ]);

            $json = json_decode($response->getBody());
            $body = $json->{'nl.divide.iq'};
            $services = [];
            foreach ($body->services as $service) {
                $services[] = $service->code;
            }

            // Create new settings object.
            $this->settings = new Settings($services, $body->settings_updated);
        }
    }
332341
public function initAndConfigure()
    {
        /*********************************************************
         * initialize the CURL session
        *********************************************************/
        $ch = curl_init($this->url);

        if (version_compare(PHP_VERSION, '5.1.3', '>=')) {
            //only avaible in php5
            curl_setopt_array($ch, $this->_curlOptions);
        } else {
            foreach ($this->_curlOptions as $key => $value) {
                curl_setopt($ch, $key, $value);
            }
        }

        /*********************************************************
         * Set SSL configuration
        *********************************************************/
        if ($this->caCertPath) {
            if ($this->validateCN) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            } else {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            }
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
            curl_setopt($ch, CURLOPT_CAINFO, $this->caCertPath);
            phpCAS::trace('CURL: Set CURLOPT_CAINFO ' . $this->caCertPath);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        }

        /*********************************************************
         * Configure curl to capture our output.
        *********************************************************/
        // return the CURL output into a variable
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // get the HTTP header with a callback
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, '_curlReadHeaders'));

        /*********************************************************
         * Add cookie headers to our request.
        *********************************************************/
        if (count($this->cookies)) {
            $cookieStrings = array();
            foreach ($this->cookies as $name => $val) {
                $cookieStrings[] = $name.'='.$val;
            }
            curl_setopt($ch, CURLOPT_COOKIE, implode(';', $cookieStrings));
        }

        /*********************************************************
         * Add any additional headers
        *********************************************************/
        if (count($this->headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        }

        /*********************************************************
         * Flag and Body for POST requests
        *********************************************************/
        if ($this->isPost) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postBody);
        }

        return $ch;
    }
266858
function _setupDebugHelpers() {
        window.ld = LiveDevelopment;
        window.i = Inspector;
        window.report = function report(params) { window.params = params; console.info(params); };
    }
70523
protected function setUp(): void
    {
        parent::setUp();

        $nextToken = $this->tokens[$this->stackPos + 1];
        $prevToken = $this->tokens[$this->stackPos - 1];

        $this->nextIsWhitespace = $nextToken['code'] === T_WHITESPACE;
        $this->prevIsWhitespace = $prevToken['code'] === T_WHITESPACE;
    }
1270115
def setup_stream_handlers(conf):
    """"""
    class StdoutFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.DEBUG, logging.INFO)

    log.handlers = []

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.WARNING)
    stdout_handler.addFilter(StdoutFilter())
    if conf.debug:
        stdout_handler.setLevel(logging.DEBUG)
    elif conf.verbose:
        stdout_handler.setLevel(logging.INFO)
    else:
        stdout_handler.setLevel(logging.WARNING)
    log.addHandler(stdout_handler)

    stderr_handler = logging.StreamHandler(sys.stderr)
    msg_format = "%(levelname)s: %(message)s"
    stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
    stderr_handler.setLevel(logging.WARNING)
    log.addHandler(stderr_handler)
713676
function _dochecks()
    {
        // Check availability of %F
        if (sprintf('%.1F', 1.0) != '1.0')
            $this->Error('This version of PHP is not supported');
        // Check availability of mbstring
        if (!function_exists('mb_strlen'))
            $this->Error('mbstring extension is not available');
        // Check mbstring overloading
        if (ini_get('mbstring.func_overload') & 2)
            $this->Error('mbstring overloading must be disabled');
        // Ensure runtime magic quotes are disabled
        if (get_magic_quotes_runtime())
            @set_magic_quotes_runtime(0);
    }
860324
public static function setupGlobalVariables(): void
	{
		$_SERVER = array_intersect_key($_SERVER, array_flip([
			'PHP_SELF',
			'SCRIPT_NAME',
			'SERVER_ADDR',
			'SERVER_SOFTWARE',
			'HTTP_HOST',
			'DOCUMENT_ROOT',
			'OS',
			'argc',
			'argv',
		]));
		$_SERVER['REQUEST_TIME'] = 1234567890;
		$_ENV = $_GET = $_POST = [];
	}
1117109
def setup_handler(context):
    

    if context.readDataFile("bika.lims_various.txt") is None:
        return

    logger.info(" [BEGIN]")

    portal = context.getSite()

    # Run Installers
    remove_default_content(portal)
    hide_navbar_items(portal)
    reindex_content_structure(portal)
    setup_groups(portal)
    setup_catalog_mappings(portal)
    setup_core_catalogs(portal)

    # Setting up all LIMS catalogs defined in catalog folder
    setup_catalogs(portal, getCatalogDefinitions())

    # Run after all catalogs have been setup
    setup_auditlog_catalog(portal)

    logger.info(" [DONE]")
870628
def _setup_helper():
    """"""
    base = os.path.abspath(os.path.dirname(__file__))
    helper = os.path.join(base, "helper.sh")
    with open(helper) as fh:
        click.echo(fh.read())
602342
public function init() {
        if (VERBOSE) echo 'INIT:' ,PHP_EOL;
        if (VERBOSE) echo ' CONNECTING API' ,PHP_EOL;
        $this->api->auth();
        if (VERBOSE) echo ' API CONNECTED' ,PHP_EOL;
        if (VERBOSE) echo ' CONNECTING SQL' ,PHP_EOL;
        $this->db->connect();
        if (VERBOSE) echo ' SQL CONNECTED' ,PHP_EOL;
        if (VERBOSE) echo ' CHECKING PATHS' ,PHP_EOL;
        if (DEBUG) echo '  CHECKING TMP DIR AT : '.$this->tmp_dir ,PHP_EOL;
        if (!file_exists($this->tmp_dir)) {
            throw new Exception("Path for 'tmp_dir' not found at '".$this->tmp_dir."'!");
        }
        if (DEBUG) echo '  CHECKING DUMP DIR AT : '.$this->dumps_dir ,PHP_EOL;
        if (!file_exists($this->dumps_dir)) {
            throw new Exception("Path for 'dumps_dir' not found at '".$this->dumps_dir."'!");
        }
        if (VERBOSE) echo ' PATHS FOUND' ,PHP_EOL;
    }
1333588
def setup(self, app):
        """"""
        super().setup(app)

        self.enabled = len(self.cfg.backends)

        self.default = self.cfg.default
        if not self.default and self.enabled:
            self.default = self.cfg.backends[0][0]

        self.backends_hash = {name: parse.urlparse(loc) for (name, loc) in self.cfg.backends}
        if self.default and self.default not in self.backends_hash:
            raise PluginException('Backend not found: %s' % self.default)