text:
<?php

namespace PaymentSuite\RedsysBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;

use PaymentSuite\PaymentCoreBundle\DependencyInjection\Abstracts\AbstractPaymentSuiteConfiguration;

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration extends AbstractPaymentSuiteConfiguration
{
    const GATEWAY_TERMINAL = '001';

    const GATEWAY_URL = 'https://sis.redsys.es/sis/realizarPago';

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('redsys');

        $rootNode
            ->children()
                ->scalarNode('merchant_code')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('secret_key')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('terminal')
                    ->defaultValue(self::GATEWAY_TERMINAL)
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('url')
                    ->defaultValue(self::GATEWAY_URL)
                ->end()
                ->append($this->addRouteConfiguration('payment_success'))
                ->append($this->addRouteConfiguration('payment_failure'))
            ->end();

        $this->addSettingsProviderConfiguration($rootNode);

        return $treeBuilder;
    }

    /**
     * {@inheritdoc}
     */
    protected function setDefaultSettings(array $config): array
    {
        $config['merchant_code'] = '999888777';
        $config['secret_key'] = 'dummy-key';
        $config['terminal'] = self::GATEWAY_TERMINAL;

        return $config;
    }
}


text:
django.cascade = django.cascade || {};

django.jQuery(function($) {
	'use strict';

	var url = new URL(window.location.href);
	var $sel_shared_glossary = $('#id_shared_glossary');
	if ($sel_shared_glossary.length === 0)
		return;

	// create class handling the SharableGlossaryMixin
	django.cascade.SharableGlossaryMixin = ring.create({
		constructor: function() {
			this.$super();

			if ($sel_shared_glossary.children('option').length > 1) {
				// set the value for 'Shared Settings' to that one provided by the URL
				if (url.searchParams.has('glossary')) {
					$sel_shared_glossary.val(url.searchParams.get('glossary'));
				}
				// add event handler to select box for 'Shared Settings'
				$sel_shared_glossary.change(this.toggleSharedGlossary);
			} else {
				// remove the select box to choose from 'Shared Settings', since it doesn't contain any options
				$('.field-shared_glossary').remove();
			}
		},
		toggleSharedGlossary: function(event) {
			var glossary = event.target.value;

			if (glossary) {
				url.searchParams.set('glossary', glossary);
				window.location.href = url.href;
			} else {
				url.searchParams.set('glossary', '');
				window.location.href = url.href;
			}
		}
	});
});

redpajama_set_name: RedPajamaGithub


text:
"""Benchmark tests for sqlite datastore."""

from grr.lib import data_store_test
from grr.lib import flags
from grr.lib import test_lib

from grr.lib.data_stores import sqlite_data_store_test

class SqliteDataStoreBenchmarks(sqlite_data_store_test.SqliteTestMixin,
                                data_store_test.DataStoreBenchmarks):
  """Benchmark the SQLite data store abstraction."""

class SqliteDataStoreCSVBenchmarks(sqlite_data_store_test.SqliteTestMixin,
                                   data_store_test.DataStoreCSVBenchmarks):
  """Benchmark the SQLite data store abstraction."""

def main(args):
  test_lib.main(args)

if __name__ == "__main__":
  flags.StartMain(main)


text:
id: Skip to content
section: components
---

## Accessibility
For information regarding accessibility, visit the [skip to content accessibility](/components/skip-to-content/accessibility) tab.


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef KMENUSLOTS_H
#define KMENUSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QList>
#include <QtCore/QString>

#include <KDEUI/KMenu>

#include "qt4xhb_common.h"
#include "qt4xhb_macros.h"
#include "qt4xhb_signals.h"

class KMenuSlots: public QObject
{
  Q_OBJECT
  public:
  KMenuSlots(QObject *parent = 0);
  ~KMenuSlots();
  public slots:
  void aboutToShowContextMenu( KMenu * menu, QAction * menuAction, QMenu * ctxMenu );
};

#endif /* KMENUSLOTS_H */


text:
module Elm.Compiler.Module
    ( Interface, Interfaces
    , ModuleName.Raw
    , nameToPath
    , nameToString, nameFromString
    , hyphenate, dehyphenate
    , RawForJson(RawForJson), fromJson
    , defaultImports
    , interfaceAliasedTypes
    , ModuleName.Canonical(..), qualifiedVar
    )
  where

import qualified Data.Aeson as Json
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Text as Text
import System.FilePath ((</>))

import qualified AST.Module as Module
import qualified AST.Module.Name as ModuleName
import qualified Elm.Compiler.Imports as Imports
import qualified Elm.Compiler.Type as Type
import qualified Elm.Compiler.Type.Extract as Extract
import qualified Generate.JavaScript.Variable as Gen

-- INTERFACES

type Interface = Module.Interface

type Interfaces = Module.Interfaces

interfaceAliasedTypes :: Interface -> Map.Map String Type.Type
interfaceAliasedTypes interface =
    Map.map Extract.toAliasedType (Module.iTypes interface)

-- NAMES

newtype RawForJson = RawForJson ModuleName.Raw

fromJson :: RawForJson -> ModuleName.Raw
fromJson (RawForJson raw) =
  raw

qualifiedVar :: ModuleName.Canonical -> String -> String
qualifiedVar =
  Gen.qualified

defaultImports :: [ModuleName.Raw]
defaultImports =
    map fst Imports.defaults

-- STRING CONVERSIONS for RAW NAMES

nameToPath :: ModuleName.Raw -> FilePath
nameToPath names =
  List.foldl1 (</>) names

nameToString :: ModuleName.Raw -> String
nameToString names =
  List.intercalate "." names

nameFromString :: String -> Maybe ModuleName.Raw
nameFromString =
  fromString '.'

hyphenate :: ModuleName.Raw -> String
hyphenate names =
  List.intercalate "-" names

dehyphenate :: String -> Maybe ModuleName.Raw
dehyphenate =
  fromString '-'

fromString :: Char -> String -> Maybe ModuleName.Raw
fromString sep raw =
    mapM isLegit names
  where
    names =
        filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)

    isLegit name =
        case name of
            [] -> Nothing
            char:rest ->
                if Char.isUpper char && all legitChar rest
                    then Just name
                    else Nothing

    legitChar char =
        Char.isAlphaNum char || char `elem` "_'"

-- JSON for NAME

instance Json.ToJSON RawForJson where
  toJSON (RawForJson name) =
    Json.toJSON (nameToString name)

instance Json.FromJSON RawForJson where
  parseJSON (Json.String text) =
    let
      rawString =
        Text.unpack text
    in
      case nameFromString rawString of
        Nothing ->
          fail (rawString ++ " is not a valid module name")

        Just name ->
          return (RawForJson name)

  parseJSON _ =
    fail "expecting the module name to be a string"


text:
namespace GitVersion;

public interface IGitVersionExecutor
{
    int Execute(GitVersionOptions gitVersionOptions);
}


text:
"""Test module for starting the broker."""

import os
from tempfile import mkdtemp
from shutil import rmtree

import unittest

if __name__ == "__main__":
    import utils
    utils.import_depends()

from .test_restart import TestBrokerReStart

class TestBrokerStart(TestBrokerReStart):

    def testclonetemplateking(self):
        if self.config.has_option("unittest", "template_base"):
            source = self.config.get("unittest", "template_base")
        else:
            source = None

        if not source:
            source = os.path.join(self.config.get("broker", "srcdir"),
                                  "tests/templates")

        dest = self.config.get("broker", "kingdir")
        rmtree(dest, ignore_errors=True)

        env = {}
        env["PATH"] = os.environ.get("PATH", "")
        git = self.config.lookup_tool("git")
        if source.startswith("git://"):
            # Easy case - just clone the source repository
            start = os.environ.get('AQD_UNITTEST_TEMPLATE_ALTERNATE_PROD')
            if not start and \
               self.config.has_option("unittest", "template_alternate_prod"):
                start = self.config.get("unittest", "template_alternate_prod").strip()

            if not start:
                start = "prod"

            self.run_command([git, "clone", "--bare", "--branch", start,
                              "--single-branch", source, dest], env=env)
            if start != "prod":
                self.run_command([git, "branch", "-m", start, "prod"],
                                 env=env, cwd=dest)
        else:
            # The source is just a directory somewhere. Create a temporary git
            # repository which we can then clone
            tmpdir = mkdtemp()
            self.run_command(["rsync", "-aH", source + "/", tmpdir + "/"],
                             env=env)
            self.run_command([git, "init"], cwd=tmpdir, env=env)
            self.run_command([git, "add", "-A"], cwd=tmpdir, env=env)
            self.run_command([git, "commit", "-m", "Initial commit"],
                             cwd=tmpdir, env=env)

            # Create the prod branch
            self.run_command([git, "checkout", "-b", "prod"], cwd=tmpdir, env=env)

            self.run_command([git, "clone", "--bare", tmpdir, dest], env=env)
            rmtree(tmpdir, ignore_errors=True)

        if self.config.has_option("broker", "trash_branch"):
            trash_branch = self.config.get("broker", "trash_branch")
            self.run_command([git, "branch", trash_branch, "prod"],
                             env=env, cwd=dest)

        # Set the default branch
        self.run_command([git, "symbolic-ref", "HEAD", "refs/heads/prod"],
                         env=env, cwd=dest)

    def testdisabletemplatetests(self):
        kingdir = self.config.get("broker", "kingdir")
        rundir = self.config.get("broker", "rundir")
        git = self.config.lookup_tool("git")
        env = {}
        env["PATH"] = os.environ.get("PATH", "")

        tempdir = mkdtemp(prefix="fixup", dir=rundir)

        self.run_command([git, "clone", "--shared", kingdir, "template-king",
                          "--branch", "prod"], cwd=tempdir, env=env)

        repodir = os.path.join(tempdir, "template-king")
        if os.path.exists(os.path.join(repodir, "t", "Makefile")):
            self.run_command([git, "rm", "-f", os.path.join("t", "Makefile")],
                             cwd=repodir, env=env)
            self.run_command([git, "commit", "-m", "Removed t/Makefile"],
                             cwd=repodir, env=env)

            for branch in ['prod']:
                self.run_command([git, "push", "origin", "prod:%s" % branch],
                                 cwd=repodir, env=env)

        rmtree(tempdir, ignore_errors=True)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestBrokerStart)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
package solutions.alterego.androidbound.example.support.nestedrvs.viewmodel;

public class RecyclerViewItem {

    private String mName;

    private String mImageUrl;

    public RecyclerViewItem(String name, String imageUrl) {
        mName = name;
        mImageUrl = imageUrl;
    }

    public String getName() {
        return mName;
    }

    public String getImageUrl() {
        return mImageUrl;
    }

    public void setName(String name) {
        mName = name;
    }

    public void setImageUrl(String imageUrl) {
        mImageUrl = imageUrl;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof RecyclerViewItem)) {
            return false;
        }
        final RecyclerViewItem other = (RecyclerViewItem) o;
        if (!other.canEqual((Object) this)) {
            return false;
        }
        final Object this$mName = this.getName();
        final Object other$mName = other.getName();
        if (this$mName == null ? other$mName != null : !this$mName.equals(other$mName)) {
            return false;
        }
        final Object this$mImageUrl = this.getImageUrl();
        final Object other$mImageUrl = other.getImageUrl();
        if (this$mImageUrl == null ? other$mImageUrl != null : !this$mImageUrl.equals(other$mImageUrl)) {
            return false;
        }
        return true;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $mName = this.getName();
        result = result * PRIME + ($mName == null ? 43 : $mName.hashCode());
        final Object $mImageUrl = this.getImageUrl();
        result = result * PRIME + ($mImageUrl == null ? 43 : $mImageUrl.hashCode());
        return result;
    }

    protected boolean canEqual(Object other) {
        return other instanceof RecyclerViewItem;
    }

    public String toString() {
        return "RecyclerViewItem(mName=" + this.getName() + ", mImageUrl=" + this.getImageUrl() + ")";
    }
}


text:
package org.zaproxy.zap.model;

import org.parosproxy.paros.Constant;
import org.parosproxy.paros.network.HttpMessage;

/**
 * Default implementation of {@code TextHttpMessageLocation}.
 *
 * @since 2.4.0
 */
public class DefaultTextHttpMessageLocation implements TextHttpMessageLocation {

    private final Location location;
    private final int start;
    private final int end;
    private final String value;

    public DefaultTextHttpMessageLocation(Location location, int position) {
        if (location == null) {
            throw new IllegalArgumentException("Parameter location must not be null");
        }
        if (position < 0) {
            throw new IllegalArgumentException("Parameter position must be greater or equal to zero.");
        }
        this.location = location;
        this.start = position;
        this.end = position;
        this.value = "";
    }

    public DefaultTextHttpMessageLocation(Location location, int start, int end, String value) {
        if (location == null) {
            throw new IllegalArgumentException("Parameter location must not be null");
        }
        if (start < 0) {
            throw new IllegalArgumentException("Parameter start must be greater or equal to zero.");
        }
        if (end < 0) {
            throw new IllegalArgumentException("Parameter end must be greater or equal to zero.");
        }
        if (start > end) {
            throw new IllegalArgumentException("Parameter end must be greater than start.");
        }
        if (value == null) {
            throw new IllegalArgumentException("Parameter value must not be null.");
        }
        this.location = location;
        this.start = start;
        this.end = end;
        this.value = value;
    }

    @Override
    public Location getLocation() {
        return location;
    }

    @Override
    public Class<HttpMessage> getTargetMessageClass() {
        return HttpMessage.class;
    }

    @Override
    public String getDescription() {
        StringBuffer description = new StringBuffer(25);
        switch (location) {
        case REQUEST_HEADER:
        case RESPONSE_HEADER:
            description.append(Constant.messages.getString("messagelocation.http.text.location.header"));
            break;
        case REQUEST_BODY:
        case RESPONSE_BODY:
            description.append(Constant.messages.getString("messagelocation.http.text.location.body"));
            break;
        default:
            description.append(Constant.messages.getString("messagelocation.http.text.location.unknown"));
        }

        description.append(" [").append(start);
        if (start != end) {
            description.append(", ").append(end);
        }
        description.append(']');

        return description.toString();
    }

    @Override
    public String getValue() {
        return value;
    }

    @Override
    public int getStart() {
        return start;
    }

    @Override
    public int getEnd() {
        return end;
    }

    @Override
    public boolean overlaps(MessageLocation otherLocation) {
        if (!(otherLocation instanceof HttpMessageLocation)) {
            return true;
        }

        HttpMessageLocation otherHttpMessageLocation = (HttpMessageLocation) otherLocation;
        if (location != otherHttpMessageLocation.getLocation()) {
            return false;
        }

        if (!(otherHttpMessageLocation instanceof TextHttpMessageLocation)) {
            return true;
        }

        TextHttpMessageLocation otherTextLocation = (TextHttpMessageLocation) otherHttpMessageLocation;
        if (start == otherTextLocation.getStart()) {
            return (start == end) ? end == otherTextLocation.getEnd() : false;
        }
        if (start < otherTextLocation.getStart()) {
            return end > otherTextLocation.getStart();
        }
        return start < otherTextLocation.getEnd();
    }

    @Override
    public int compareTo(MessageLocation otherLocation) {
        if (!(otherLocation instanceof HttpMessageLocation)) {
            return 1;
        }

        HttpMessageLocation otherHttpMessageLocation = (HttpMessageLocation) otherLocation;
        if (location != otherHttpMessageLocation.getLocation()) {
            if (location.ordinal() > otherHttpMessageLocation.getLocation().ordinal()) {
                return 1;
            } else if (location.ordinal() < otherHttpMessageLocation.getLocation().ordinal()) {
                return -1;
            }
        }

        if (!(otherHttpMessageLocation instanceof TextHttpMessageLocation)) {
            return 1;
        }

        TextHttpMessageLocation otherTextLocation = (TextHttpMessageLocation) otherHttpMessageLocation;
        if (start > otherTextLocation.getStart()) {
            return 1;
        } else if (start < otherTextLocation.getStart()) {
            return -1;
        }

        if (end > otherTextLocation.getEnd()) {
            return 1;
        } else if (end < otherTextLocation.getEnd()) {
            return -1;
        }

        int result = value.compareTo(otherHttpMessageLocation.getValue());
        if (result != 0) {
            return result;
        }

        // make sure (x.compareTo(y)==0) == (x.equals(y))
        return (otherHttpMessageLocation instanceof DefaultTextHttpMessageLocation) ? 0 : 1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + end;
        result = prime * result + ((location == null) ? 0 : location.hashCode());
        result = prime * result + start;
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        DefaultTextHttpMessageLocation other = (DefaultTextHttpMessageLocation) obj;
        if (end != other.end) {
            return false;
        }
        if (location != other.location) {
            return false;
        }
        if (start != other.start) {
            return false;
        }
        if (value == null) {
            if (other.value != null) {
                return false;
            }
        } else if (!value.equals(other.value)) {
            return false;
        }
        return true;
    }

}


text:
"use strict";

exports._enableAnalytics = function () {
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.1.0";
  analytics.load("nnJaunzB3C3F4YOyYx8ZIgoHXf8KZ4uS");
  analytics.page()
  }}();
};

exports._identify = function (userId) {
  return function (traits) {
    return function () {
      if (window.analytics) window.analytics.identify(userId, traits);
    };
  };
};

exports._track = function (event) {
  return function (props) {
    return function () {
      if (window.analytics) window.analytics.track(event, props);
    };
  };
};


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Elastic.Clients.Elasticsearch.Requests;

/// <summary>
///     Each Request type holds a static instance of this class which creates cached builders for each
///     of the defined urls in the json spec.
/// </summary>
internal class ApiUrls
{
	private static readonly RouteValues EmptyRouteValues = new();
	private readonly string _errorMessageSuffix;

	/// <summary>
	///     If the spec only defines a single non parameterizable route this allows us to shortcircuit and avoid hitting
	///     the cached string builders.
	/// </summary>
	private readonly string _fixedUrl;

	/// <summary> Only intended to be created once per request and stored in a static </summary>
	internal ApiUrls(string[] routes)
	{
		if (routes == null || routes.Length == 0)
			throw new ArgumentException("urls is null or empty", nameof(routes));
		if (routes.Length == 1 && !routes[0].Contains("{"))
			_fixedUrl = routes[0];
		else
		{
			foreach (var route in routes)
			{
				var bracketsCount = route.Count(c => c.Equals('{'));
				if (Routes == null)
					Routes = new Dictionary<int, List<UrlLookup>>();
				if (Routes.ContainsKey(bracketsCount))
					Routes[bracketsCount].Add(new UrlLookup(route));
				else
					Routes.Add(bracketsCount, new List<UrlLookup> {new(route)});
			}
		}

		_errorMessageSuffix = string.Join(",", routes);

		// received multiple urls without brackets we resolve to first
		if (Routes == null)
			_fixedUrl = routes[0];
	}

	/// <summary>
	///     Creates a lookup for number of parts <=> list of routes with that number of parts.
	///     <see cref="UrlLookup.Matches" /> allows us to quickly find the right url to use in the list.
	/// </summary>
	public Dictionary<int, List<UrlLookup>> Routes { get; }

	public (string ResolvedUrl, string UrlTemplate) Resolve(RouteValues routeValues, IElasticsearchClientSettings settings)
	{
		if (_fixedUrl != null)
			return (_fixedUrl, _fixedUrl);

		var resolved = routeValues.Resolve(settings);

		if (!Routes.TryGetValue(resolved.Count, out var routes))
			throw new Exception($"No route taking {resolved.Count} parameters{_errorMessageSuffix}");

		if (routes.Count == 1)
			return (routes[0].ToUrl(resolved), routes[0].Route);

		//find the first url with N parts that has all provided named parts
		foreach (var u in routes)
		{
			if (u.Matches(resolved))
				return (u.ToUrl(resolved), u.Route);
		}

		throw new Exception($"No route taking {routeValues.Count} parameters{_errorMessageSuffix}");
	}
}


text:
import com.github.jeanadrien.gatling.mqtt.Predef._
import io.gatling.core.Predef._

import scala.concurrent.duration._

/**
  *
  */
class MqttScenarioExample extends Simulation {

    val mqttConf = mqtt.host("tcp://localhost:1883")

    val scn = scenario("MQTT Test")
        .exec(connect)
        .exec(subscribe("myTopic"))
        .during(30 seconds) {
            pace(1 second).exec(publish("myTopic", "myPayload"))
        }

    setUp(
        scn.inject(rampUsers(10) over (10 seconds)))
        .protocols(mqttConf)
}


text:
<?php

namespace Columbus\securityWebBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;

class InfoUserRepository extends EntityRepository {

    public function findStuffNotSelf($arrayRequest) {
        $objListResult = null;
        $objQuery = $this->_em->createQuery();
        $sqlUser = "select user "
            . " from securityWebBundle:InfoUser user "
            . " where user.id not in (:id) ";
        try {
            if (isset($arrayRequest['identification']) && !empty($arrayRequest['identification'])) {
                $sqlUser .= " and user.identification = :identification ";
                $objQuery->setParameter('identification', $arrayRequest['identification']);
            }
            if (isset($arrayRequest['email']) && !empty($arrayRequest['email'])) {
                $sqlUser .= " and user.email = :email ";
                $objQuery->setParameter('email', $arrayRequest['email']);
            }
            $objQuery->setDQL($sqlUser);
            $objQuery->setParameter('id', $arrayRequest['id']);
            $objListResult = $objQuery->getResult();
            if (!empty($objListResult)) {
                $objListResult = $objListResult[0];
            }
        } catch (\Exception $ex) {
            error_log('InfoUserRepository->findStuffNotSelf ' . $ex->getMessage());
            throw($ex);
        }
        return $objListResult;
    }

}


text:
package main

import (
	"context"
	"crypto/tls"
	"log"
	"net/http"

	"cloud.google.com/go/storage"
	"golang.org/x/build/autocertcache"
	"golang.org/x/crypto/acme/autocert"
)

func init() {
	runHTTPS = runHTTPSAutocert
	certInit = certInitAutocert
	wrapHTTPMux = wrapHTTPMuxAutocert
}

var autocertManager *autocert.Manager

func certInitAutocert() {
	var cache autocert.Cache
	if b := *autoCertCacheBucket; b != "" {
		sc, err := storage.NewClient(context.Background())
		if err != nil {
			log.Fatalf("storage.NewClient: %v", err)
		}
		cache = autocertcache.NewGoogleCloudStorageCache(sc, b)
	}
	autocertManager = &autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist(*autoCertDomain),
		Cache:      cache,
	}
}

func runHTTPSAutocert(h http.Handler) error {
	s := &http.Server{
		Addr:    ":https",
		Handler: h,
		TLSConfig: &tls.Config{
			GetCertificate: autocertManager.GetCertificate,
		},
	}
	return s.ListenAndServeTLS("", "")
}

func wrapHTTPMuxAutocert(h http.Handler) http.Handler {
	return autocertManager.HTTPHandler(h)
}


text:
layout: text/textblock
---
It's hard to audit content that's changing.

Putting in place a content freeze during your audit might help you manage the workload. A content freeze restricts what can be changed on the website and whether any new content can be published.

You will need to negotiate the scope of the freeze and any time frames with executives and content owners. Also, be aware of any upcoming publishing that will need to be factored in during your audit. (For example, ministerial announcements or legislative changes.)

An alternative approach is to place a content freeze on your high-profile pages only, and audit those pages as a priority. You can consider auditing the other pages on your site at another time.


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

namespace FataMirage.Core.Player
{
    class Legs
    {
        public const float speed = 0.2f;
        static float directionAngel = 0;
        public enum Directions
        {
            Top,
            Bottom,
            Left,
            Right
        }
        public static Directions direction
        {
            get
            {
                if (directionAngel > Math.PI / -4 && directionAngel <= Math.PI / 4)
                    return Directions.Right;
                if (directionAngel <= Math.PI /-4 * 3 || directionAngel > Math.PI / 4 * 3)
                    return Directions.Left;
                if (directionAngel > Math.PI / 4 && directionAngel <= Math.PI / 4 * 3)
                    return Directions.Bottom;
                return Directions.Top;
            }
        }
        public static Vector2 currentPosition
        {
            get
            {
                if (isWalking)
                    return Scene.SceneManager.currentScene.waypoints.interpolatePosition(currentPositionName, currentGoal, progress);
                else
                    return Scene.SceneManager.currentScene.waypoints.getPosition(currentPositionName);
            }
        }
        public static string currentPositionName;
        public static string currentGoal;
        public static float timeWalking;
        public static float progress
        {
            get
            {
                return (speed * timeWalking) /Scene.SceneManager.currentScene.waypoints.getDisctance(currentPositionName, currentGoal);
            }
        }
        //public static float walkingLength;
        public static bool isWalking
        {
            get { return _isWalking; }
            set{_isWalking = value; if (!value) timeWalking = 0;}
        }
        static bool _isWalking = false;

        public static void Init()
        {
        }
        public static void LoadContent()
        {
        }
        public static void Update(float elapsedTime)
        {
            if (isWalking)
            {
                timeWalking += elapsedTime;
                directionAngel = Scene.SceneManager.currentScene.waypoints.getAngel(currentPositionName, currentGoal);
                if (progress >= 1)
                {
                    isWalking = false;
                    currentPositionName = currentGoal;
                    timeWalking = 0;
                }
            }
        }
        public static void Draw(float elapsedTime)
        {
        }
    }
}


text:
from django.conf.urls import url
from . import views

app_name = 'web'

urlpatterns = [
    url(r'^$', views.home, name='home')
]


text:
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-01">
          Toggle navigation
        </button>

{{ title }}

            Save

            Export (CSV)

            Log In

            Sign Up

            Log Out


text:
RSpec.describe SoapyCake::ResponseValue do
  let(:time_converter) { instance_double(SoapyCake::TimeConverter) }

  def parse(key, value)
    described_class.new(key, value, time_converter).parse
  end

  describe '#parse' do
    context 'booleans' do
      it 'converts the string "true" to the true value' do
        expect(parse(:foo, 'true')).to eq(true)
      end

      it 'converts the string "false" to the false value' do
        expect(parse(:foo, 'false')).to eq(false)
      end
    end

    context 'dates' do
      it 'delegates date-conversion to a TimeConverter instance' do
        expect(time_converter).to receive(:from_cake)
          .with('2014-06-30T01:00:00').and_return(:nice_date)

        expect(parse(:foo, '2014-06-30T01:00:00')).to eq(:nice_date)
      end
    end

    context 'strings' do
      it 'parses a string' do
        expect(parse(:foo, 'abc')).to eq('abc')
      end
    end

    context 'IDs' do
      it 'converts keys ending in "_id" to integers' do
        expect(parse(:conversion_id, '42')).to eq(42)
      end

      it "doesn't convert ids in the blacklist to integers" do
        expect(parse(:tax_id, '123abc')).to eq('123abc')
        expect(parse(:other_tax_id, '123abc')).to eq('123abc')
        expect(parse(:transaction_id, '123abc')).to eq('123abc')
      end

      it 'raises an error if not in the blacklist and non-digit characters are detected' do
        expect { parse(:foo_id, '123abc') }.to raise_error(SoapyCake::Error)
      end

      it 'does not raise an error if the value is absent' do
        expect(parse(:foo_id, '-1')).to eq(-1)
        expect(parse(:foo_id, '')).to eq(0)
        expect(parse(:foo_id, nil)).to eq(0)
      end
    end
  end
end


text:
package me.zhongmingmao.primary.repository;

import me.zhongmingmao.primary.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}


text:
package net.rgielen.actionframeworks.domain;

import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.FormParam;
import java.util.Date;

/**
 * Actor domain object.
 *
 * @author Rene Gielen
 */
public class Actor {

    @FormParam("id")
    private String id;

    @NotNull @Size(min = 2)
    @FormParam("firstname")
    private String firstname;

    @NotNull @Size(min = 2)
    @FormParam("lastname")
    private String lastname;

    @FormParam("cool")
    private boolean cool;

    @FormParam("rank")
    @Digits(integer = 10, fraction = 0)
    private Integer rank;
    private Date birthday;
    private Float salary = 0f;

    public Actor() {
    }

    public Actor(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public Actor(String id, String firstname, String lastname) {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Integer getRank() {
        return rank;
    }

    public void setRank(Integer rank) {
        this.rank = rank;
    }

    public boolean isCool() {
        return cool;
    }

    public void setCool(boolean cool) {
        this.cool = cool;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Float getSalary() {
        return salary;
    }

    public void setSalary(Float salary) {
        this.salary = salary;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Actor)) return false;

        Actor actor = (Actor) o;

        return !(id != null ? !id.equals(actor.id) : actor.id != null);

    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}


text:
export const LOAD_USER = 'user/LOAD_USER'
export const UPDATE_ACCESS = 'user/UPDATE_ACCESS'
export const ADD_CONNECTION = 'user/ADD_CONNECTION'
export const SET_FROM_ID = 'user/SET_FROM_ID'

import {
  SIGN_OUT_SUCCESS,
} from '../auth'

// Reducer
export const initialState = null

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case LOAD_USER:
      return { ...action.payload }
    case UPDATE_ACCESS:
      return { ...state, hasAccess: action.payload }
    case ADD_CONNECTION: {
      const { id, timestamp } = action.payload
      return {
        ...state,
        connections: {
          ...state.connections,
          [id]: timestamp,
        }
      }
    }
    case SIGN_OUT_SUCCESS:
      return null
    case SET_FROM_ID:
      return {
        ...state,
        from: action.payload,
      }
    default:
      return state
  }
}

export function loadUser(user) {
  return { type: LOAD_USER, payload: user }
}

export function updateAccess(access) {
  return { type: UPDATE_ACCESS, payload: access }
}

export function addConnection(id, timestamp) {
  return { type: ADD_CONNECTION, payload: { id, timestamp } }
}

export function setFromId(id) {
  return { type: SET_FROM_ID, payload: id }
}

export * from './async'


text:
// TODO: Add test for React Redux connect function

import {
  createSelector,
  createSelectorCreator,
  defaultMemoize,
  createStructuredSelector
} from '../src/index'
import lodashMemoize from 'lodash/memoize'

// Construct 1E6 states for perf test outside of the perf test so as to not change the execute time of the test function
const numOfStates = 1000000
interface StateA {
  a: number
}

interface StateAB {
  a: number
  b: number
}

interface StateSub {
  sub: {
    a: number
  }
}

const states: StateAB[] = []

for (let i = 0; i < numOfStates; i++) {
  states.push({ a: 1, b: 2 })
}

describe('Basic selector behavior', () => {
  test('basic selector', () => {
    const selector = createSelector(
      (state: StateA) => state.a,
      a => a
    )
    const firstState = { a: 1 }
    const firstStateNewPointer = { a: 1 }
    const secondState = { a: 2 }

    expect(selector(firstState)).toBe(1)
    expect(selector(firstState)).toBe(1)
    expect(selector.recomputations()).toBe(1)
    expect(selector(firstStateNewPointer)).toBe(1)
    expect(selector.recomputations()).toBe(1)
    expect(selector(secondState)).toBe(2)
    expect(selector.recomputations()).toBe(2)
  })

  test("don't pass extra parameters to inputSelector when only called with the state", () => {
    const selector = createSelector(
      (...params: any[]) => params.length,
      a => a
    )
    expect(selector({})).toBe(1)
  })

  test('basic selector multiple keys', () => {
    const selector = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )
    const state1 = { a: 1, b: 2 }
    expect(selector(state1)).toBe(3)
    expect(selector(state1)).toBe(3)
    expect(selector.recomputations()).toBe(1)
    const state2 = { a: 3, b: 2 }
    expect(selector(state2)).toBe(5)
    expect(selector(state2)).toBe(5)
    expect(selector.recomputations()).toBe(2)
  })

  test('basic selector invalid input selector', () => {
    expect(() =>
      createSelector(
        // @ts-ignore
        (state: StateAB) => state.a,
        function input2(state: StateAB) {
          return state.b
        },
        'not a function',
        (a: any, b: any) => a + b
      )
    ).toThrow(
      'createSelector expects all input-selectors to be functions, but received the following types: [function unnamed(), function input2(), string]'
    )

    expect(() =>
      // @ts-ignore
      createSelector((state: StateAB) => state.a, 'not a function')
    ).toThrow(
      'createSelector expects an output function after the inputs, but received: [string]'
    )
  })

  test('basic selector cache hit performance', () => {
    if (process.env.COVERAGE) {
      return // don't run performance tests for coverage
    }

    const selector = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )
    const state1 = { a: 1, b: 2 }

    const start = new Date()
    for (let i = 0; i < 1000000; i++) {
      selector(state1)
    }
    const totalTime = new Date().getTime() - start.getTime()

    expect(selector(state1)).toBe(3)
    expect(selector.recomputations()).toBe(1)
    // Expected a million calls to a selector with the same arguments to take less than 1 second
    expect(totalTime).toBeLessThan(1000)
  })

  test('basic selector cache hit performance for state changes but shallowly equal selector args', () => {
    if (process.env.COVERAGE) {
      return // don't run performance tests for coverage
    }

    const selector = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )

    const start = new Date()
    for (let i = 0; i < numOfStates; i++) {
      selector(states[i])
    }
    const totalTime = new Date().getTime() - start.getTime()

    expect(selector(states[0])).toBe(3)
    expect(selector.recomputations()).toBe(1)

    // Expected a million calls to a selector with the same arguments to take less than 1 second
    expect(totalTime).toBeLessThan(1000)
  })

  test('memoized composite arguments', () => {
    const selector = createSelector(
      (state: StateSub) => state.sub,
      sub => sub
    )
    const state1 = { sub: { a: 1 } }
    expect(selector(state1)).toEqual({ a: 1 })
    expect(selector(state1)).toEqual({ a: 1 })
    expect(selector.recomputations()).toBe(1)
    const state2 = { sub: { a: 2 } }
    expect(selector(state2)).toEqual({ a: 2 })
    expect(selector.recomputations()).toBe(2)
  })

  test('first argument can be an array', () => {
    const selector = createSelector(
      [state => state.a, state => state.b],
      (a, b) => {
        return a + b
      }
    )
    expect(selector({ a: 1, b: 2 })).toBe(3)
    expect(selector({ a: 1, b: 2 })).toBe(3)
    expect(selector.recomputations()).toBe(1)
    expect(selector({ a: 3, b: 2 })).toBe(5)
    expect(selector.recomputations()).toBe(2)
  })

  test('can accept props', () => {
    let called = 0
    const selector = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (state: StateAB, props: { c: number }) => props.c,
      (a, b, c) => {
        called++
        return a + b + c
      }
    )
    expect(selector({ a: 1, b: 2 }, { c: 100 })).toBe(103)
  })

  test('recomputes result after exception', () => {
    let called = 0
    const selector = createSelector(
      (state: StateA) => state.a,
      () => {
        called++
        throw Error('test error')
      }
    )
    expect(() => selector({ a: 1 })).toThrow('test error')
    expect(() => selector({ a: 1 })).toThrow('test error')
    expect(called).toBe(2)
  })

  test('memoizes previous result before exception', () => {
    let called = 0
    const selector = createSelector(
      (state: StateA) => state.a,
      a => {
        called++
        if (a > 1) throw Error('test error')
        return a
      }
    )
    const state1 = { a: 1 }
    const state2 = { a: 2 }
    expect(selector(state1)).toBe(1)
    expect(() => selector(state2)).toThrow('test error')
    expect(selector(state1)).toBe(1)
    expect(called).toBe(2)
  })
})

describe('Combining selectors', () => {
  test('chained selector', () => {
    const selector1 = createSelector(
      (state: StateSub) => state.sub,
      sub => sub
    )
    const selector2 = createSelector(selector1, sub => sub.a)
    const state1 = { sub: { a: 1 } }
    expect(selector2(state1)).toBe(1)
    expect(selector2(state1)).toBe(1)
    expect(selector2.recomputations()).toBe(1)
    const state2 = { sub: { a: 2 } }
    expect(selector2(state2)).toBe(2)
    expect(selector2.recomputations()).toBe(2)
  })

  test('chained selector with props', () => {
    const selector1 = createSelector(
      (state: StateSub) => state.sub,
      (state: StateSub, props: { x: number; y: number }) => props.x,
      (sub, x) => ({ sub, x })
    )
    const selector2 = createSelector(
      selector1,
      (state: StateSub, props: { x: number; y: number }) => props.y,
      (param, y) => param.sub.a + param.x + y
    )
    const state1 = { sub: { a: 1 } }
    expect(selector2(state1, { x: 100, y: 200 })).toBe(301)
    expect(selector2(state1, { x: 100, y: 200 })).toBe(301)
    expect(selector2.recomputations()).toBe(1)
    const state2 = { sub: { a: 2 } }
    expect(selector2(state2, { x: 100, y: 201 })).toBe(303)
    expect(selector2.recomputations()).toBe(2)
  })

  test('chained selector with variadic args', () => {
    const selector1 = createSelector(
      (state: StateSub) => state.sub,
      (state: StateSub, props: { x: number; y: number }, another: number) =>
        props.x + another,
      (sub, x) => ({ sub, x })
    )
    const selector2 = createSelector(
      selector1,
      (state: StateSub, props: { x: number; y: number }) => props.y,
      (param, y) => param.sub.a + param.x + y
    )
    const state1 = { sub: { a: 1 } }
    expect(selector2(state1, { x: 100, y: 200 }, 100)).toBe(401)
    expect(selector2(state1, { x: 100, y: 200 }, 100)).toBe(401)
    expect(selector2.recomputations()).toBe(1)
    const state2 = { sub: { a: 2 } }
    expect(selector2(state2, { x: 100, y: 201 }, 200)).toBe(503)
    expect(selector2.recomputations()).toBe(2)
  })

  test('override valueEquals', () => {
    // a rather absurd equals operation we can verify in tests
    const createOverridenSelector = createSelectorCreator(
      defaultMemoize,
      (a, b) => typeof a === typeof b
    )
    const selector = createOverridenSelector(
      (state: StateA) => state.a,
      a => a
    )
    expect(selector({ a: 1 })).toBe(1)
    expect(selector({ a: 2 })).toBe(1) // yes, really true
    expect(selector.recomputations()).toBe(1)
    // @ts-expect-error
    expect(selector({ a: 'A' })).toBe('A')
    expect(selector.recomputations()).toBe(2)
  })
})

describe('Customizing selectors', () => {
  test('custom memoize', () => {
    const hashFn = (...args: any[]) =>
      args.reduce((acc, val) => acc + '-' + JSON.stringify(val))
    const customSelectorCreator = createSelectorCreator(lodashMemoize, hashFn)
    const selector = customSelectorCreator(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )
    expect(selector({ a: 1, b: 2 })).toBe(3)
    expect(selector({ a: 1, b: 2 })).toBe(3)
    expect(selector.recomputations()).toBe(1)
    expect(selector({ a: 1, b: 3 })).toBe(4)
    expect(selector.recomputations()).toBe(2)
    expect(selector({ a: 1, b: 3 })).toBe(4)
    expect(selector.recomputations()).toBe(2)
    expect(selector({ a: 2, b: 3 })).toBe(5)
    expect(selector.recomputations()).toBe(3)
    // TODO: Check correct memoize function was called
  })

  test('createSelector accepts direct memoizer arguments', () => {
    let memoizer1Calls = 0
    let memoizer2Calls = 0
    let memoizer3Calls = 0

    const defaultMemoizeAcceptsFirstArgDirectly = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b,
      {
        memoizeOptions: (a, b) => {
          memoizer1Calls++
          return a === b
        }
      }
    )

    defaultMemoizeAcceptsFirstArgDirectly({ a: 1, b: 2 })
    defaultMemoizeAcceptsFirstArgDirectly({ a: 1, b: 3 })

    expect(memoizer1Calls).toBeGreaterThan(0)

    const defaultMemoizeAcceptsArgsAsArray = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b,
      {
        memoizeOptions: [
          (a, b) => {
            memoizer2Calls++
            return a === b
          }
        ]
      }
    )

    defaultMemoizeAcceptsArgsAsArray({ a: 1, b: 2 })
    defaultMemoizeAcceptsArgsAsArray({ a: 1, b: 3 })

    expect(memoizer2Calls).toBeGreaterThan(0)

    const createSelectorWithSeparateArg = createSelectorCreator(
      defaultMemoize,
      (a, b) => {
        memoizer3Calls++
        return a === b
      }
    )

    const defaultMemoizeAcceptsArgFromCSC = createSelectorWithSeparateArg(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )

    defaultMemoizeAcceptsArgFromCSC({ a: 1, b: 2 })
    defaultMemoizeAcceptsArgFromCSC({ a: 1, b: 3 })

    expect(memoizer3Calls).toBeGreaterThan(0)
  })
})

describe('defaultMemoize', () => {
  test('Basic memoization', () => {
    let called = 0
    const memoized = defaultMemoize(state => {
      called++
      return state.a
    })

    const o1 = { a: 1 }
    const o2 = { a: 2 }
    expect(memoized(o1)).toBe(1)
    expect(memoized(o1)).toBe(1)
    expect(called).toBe(1)
    expect(memoized(o2)).toBe(2)
    expect(called).toBe(2)
  })

  test('Memoizes with multiple arguments', () => {
    const memoized = defaultMemoize((...args) =>
      args.reduce((sum, value) => sum + value, 0)
    )
    expect(memoized(1, 2)).toBe(3)
    expect(memoized(1)).toBe(1)
  })

  test('Memoizes with equalityCheck override', () => {
    // a rather absurd equals operation we can verify in tests
    let called = 0
    const valueEquals = (a: any, b: any) => typeof a === typeof b
    const memoized = defaultMemoize(a => {
      called++
      return a
    }, valueEquals)
    expect(memoized(1)).toBe(1)
    expect(memoized(2)).toBe(1) // yes, really true
    expect(called).toBe(1)
    expect(memoized('A')).toBe('A')
    expect(called).toBe(2)
  })

  test('Passes correct objects to equalityCheck', () => {
    let fallthroughs = 0
    function shallowEqual(newVal: any, oldVal: any) {
      if (newVal === oldVal) return true

      fallthroughs += 1 // code below is expensive and should be bypassed when possible

      let countA = 0
      let countB = 0
      for (const key in newVal) {
        if (
          Object.hasOwnProperty.call(newVal, key) &&
          newVal[key] !== oldVal[key]
        )
          return false
        countA++
      }
      for (const key in oldVal) {
        if (Object.hasOwnProperty.call(oldVal, key)) countB++
      }
      return countA === countB
    }

    const someObject = { foo: 'bar' }
    const anotherObject = { foo: 'bar' }
    const memoized = defaultMemoize(a => a, shallowEqual)

    // the first call to `memoized` doesn't hit because `defaultMemoize.lastArgs` is uninitialized
    // and so `equalityCheck` is never called
    memoized(someObject)
    // first call does not shallow compare
    expect(fallthroughs).toBe(0)

    // the next call, with a different object reference, does fall through
    memoized(anotherObject)

    // call with different object does shallow compare
    expect(fallthroughs).toBe(1)

    /*
    This test was useful when we had a cache size of 1 previously, and always saved `lastArgs`.
    But, with the new implementation, this doesn't make sense any more.

    // the third call does not fall through because `defaultMemoize` passes `anotherObject` as
    // both the `newVal` and `oldVal` params. This allows `shallowEqual` to be much more performant
    // than if it had passed `someObject` as `oldVal`, even though `someObject` and `anotherObject`
    // are shallowly equal
    memoized(anotherObject)
    // call with same object as previous call does not shallow compare
    expect(fallthroughs).toBe(1)

    */
  })

  test('Accepts a max size greater than 1 with LRU cache behavior', () => {
    let funcCalls = 0

    const memoizer = defaultMemoize(
      (state: any) => {
        funcCalls++
        return state
      },
      {
        maxSize: 3
      }
    )

    // Initial call
    memoizer('a') // ['a']
    expect(funcCalls).toBe(1)

    // In cache - memoized
    memoizer('a') // ['a']
    expect(funcCalls).toBe(1)

    // Added
    memoizer('b') // ['b', 'a']
    expect(funcCalls).toBe(2)

    // Added
    memoizer('c') // ['c', 'b', 'a']
    expect(funcCalls).toBe(3)

    // Added, removes 'a'
    memoizer('d') // ['d', 'c', 'b']
    expect(funcCalls).toBe(4)

    // No longer in cache, re-added, removes 'b'
    memoizer('a') // ['a', 'd', 'c']
    expect(funcCalls).toBe(5)

    // In cache, moved to front
    memoizer('c') // ['c', 'a', 'd']
    expect(funcCalls).toBe(5)

    // Added, removes 'd'
    memoizer('e') // ['e', 'c', 'a']
    expect(funcCalls).toBe(6)

    // No longer in cache, re-added, removes 'a'
    memoizer('d') // ['d', 'e', 'c']
    expect(funcCalls).toBe(7)
  })

  test('Allows reusing an existing result if they are equivalent', () => {
    interface Todo {
      id: number
      name: string
    }

    const todos1: Todo[] = [
      { id: 1, name: 'a' },
      { id: 2, name: 'b' },
      { id: 3, name: 'c' }
    ]
    const todos2 = todos1.slice()
    todos2[2] = { id: 3, name: 'd' }

    function is(x: unknown, y: unknown) {
      if (x === y) {
        return x !== 0 || y !== 0 || 1 / x === 1 / y
      } else {
        return x !== x && y !== y
      }
    }

    function shallowEqual(objA: any, objB: any) {
      if (is(objA, objB)) return true

      if (
        typeof objA !== 'object' ||
        objA === null ||
        typeof objB !== 'object' ||
        objB === null
      ) {
        return false
      }

      const keysA = Object.keys(objA)
      const keysB = Object.keys(objB)

      if (keysA.length !== keysB.length) return false

      for (let i = 0; i < keysA.length; i++) {
        if (
          !Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
          !is(objA[keysA[i]], objB[keysA[i]])
        ) {
          return false
        }
      }

      return true
    }

    for (const maxSize of [1, 3]) {
      let funcCalls = 0

      const memoizer = defaultMemoize(
        (state: Todo[]) => {
          funcCalls++
          return state.map(todo => todo.id)
        },
        {
          maxSize,
          resultEqualityCheck: shallowEqual
        }
      )

      const ids1 = memoizer(todos1)
      expect(funcCalls).toBe(1)

      const ids2 = memoizer(todos1)
      expect(funcCalls).toBe(1)
      expect(ids2).toBe(ids1)

      const ids3 = memoizer(todos2)
      expect(funcCalls).toBe(2)
      expect(ids3).toBe(ids1)
    }
  })

  test('updates the cache key even if resultEqualityCheck is a hit', () => {
    const selector = jest.fn(x => x)
    const equalityCheck = jest.fn((a, b) => a === b)
    const resultEqualityCheck = jest.fn((a, b) => typeof a === typeof b)

    const memoizedFn = defaultMemoize(selector, {
      maxSize: 1,
      resultEqualityCheck,
      equalityCheck
    })

    // initialize the cache
    memoizedFn('cache this result')
    expect(selector).toBeCalledTimes(1)

    // resultEqualityCheck hit (with a different cache key)
    const result = memoizedFn('arg1')
    expect(equalityCheck).toHaveLastReturnedWith(false)
    expect(resultEqualityCheck).toHaveLastReturnedWith(true)
    expect(result).toBe('cache this result')
    expect(selector).toBeCalledTimes(2)

    // cache key should now be updated
    const result2 = memoizedFn('arg1')
    expect(result2).toBe('cache this result')
    expect(equalityCheck).toHaveLastReturnedWith(true)
    expect(selector).toBeCalledTimes(2)
  })

  // Issue #527
  test('Allows caching a value of `undefined`', () => {
    const state = {
      foo: { baz: 'baz' },
      bar: 'qux'
    }

    const fooChangeSpy = jest.fn()

    const fooChangeHandler = createSelector(
      (state: any) => state.foo,
      fooChangeSpy
    )

    fooChangeHandler(state)
    expect(fooChangeSpy.mock.calls.length).toEqual(1)

    // no change
    fooChangeHandler(state)
    // this would fail
    expect(fooChangeSpy.mock.calls.length).toEqual(1)

    const state2 = { a: 1 }
    let count = 0

    const selector = createSelector([(state: any) => state.a], () => {
      count++
      return undefined
    })

    selector(state)
    expect(count).toBe(1)
    selector(state)
    expect(count).toBe(1)
  })

  test('Accepts an options object as an arg', () => {
    let memoizer1Calls = 0

    const acceptsEqualityCheckAsOption = defaultMemoize((a: any) => a, {
      equalityCheck: (a, b) => {
        memoizer1Calls++
        return a === b
      }
    })

    acceptsEqualityCheckAsOption(42)
    acceptsEqualityCheckAsOption(43)

    expect(memoizer1Calls).toBeGreaterThan(0)

    let called = 0
    const fallsBackToDefaultEqualityIfNoArgGiven = defaultMemoize(
      state => {
        called++
        return state.a
      },
      {
        // no args
      }
    )

    const o1 = { a: 1 }
    const o2 = { a: 2 }
    expect(fallsBackToDefaultEqualityIfNoArgGiven(o1)).toBe(1)
    expect(fallsBackToDefaultEqualityIfNoArgGiven(o1)).toBe(1)
    expect(called).toBe(1)
    expect(fallsBackToDefaultEqualityIfNoArgGiven(o2)).toBe(2)
    expect(called).toBe(2)
  })

  test('Exposes a clearCache method on the memoized function', () => {
    let funcCalls = 0

    // Cache size of 1
    const memoizer = defaultMemoize(
      (state: any) => {
        funcCalls++
        return state
      },
      {
        maxSize: 1
      }
    )

    // Initial call
    memoizer('a') // ['a']
    expect(funcCalls).toBe(1)

    // In cache - memoized
    memoizer('a') // ['a']
    expect(funcCalls).toBe(1)

    memoizer.clearCache()

    // Cache was cleared
    memoizer('a')
    expect(funcCalls).toBe(2)

    funcCalls = 0

    // Test out maxSize of 3 + exposure via createSelector
    const selector = createSelector(
      (state: string) => state,
      state => {
        funcCalls++
        return state
      },
      {
        memoizeOptions: { maxSize: 3 }
      }
    )

    // Initial call
    selector('a') // ['a']
    expect(funcCalls).toBe(1)

    // In cache - memoized
    selector('a') // ['a']
    expect(funcCalls).toBe(1)

    // Added
    selector('b') // ['b', 'a']
    expect(funcCalls).toBe(2)

    // Added
    selector('c') // ['c', 'b', 'a']
    expect(funcCalls).toBe(3)

    // Already in cache
    selector('c') // ['c', 'b', 'a']
    expect(funcCalls).toBe(3)

    selector.memoizedResultFunc.clearCache()

    // Added
    selector('a') // ['a']
    expect(funcCalls).toBe(4)

    // Already in cache
    selector('a') // ['a']
    expect(funcCalls).toBe(4)

    // make sure clearCache is passed to the selector correctly
    selector.clearCache()

    // Cache was cleared
    // Note: the outer arguments wrapper function still has 'a' in its own size-1 cache, so passing
    // 'a' here would _not_ recalculate
    selector('b') // ['b']
    expect(funcCalls).toBe(5)
  })
})

describe('createStructureSelector', () => {
  test('structured selector', () => {
    const selector = createStructuredSelector({
      x: (state: StateAB) => state.a,
      y: (state: StateAB) => state.b
    })
    const firstResult = selector({ a: 1, b: 2 })
    expect(firstResult).toEqual({ x: 1, y: 2 })
    expect(selector({ a: 1, b: 2 })).toBe(firstResult)
    const secondResult = selector({ a: 2, b: 2 })
    expect(secondResult).toEqual({ x: 2, y: 2 })
    expect(selector({ a: 2, b: 2 })).toBe(secondResult)
  })

  test('structured selector with invalid arguments', () => {
    expect(() =>
      // @ts-expect-error
      createStructuredSelector(
        (state: StateAB) => state.a,
        (state: StateAB) => state.b
      )
    ).toThrow(/expects first argument to be an object.*function/)
    expect(() =>
      createStructuredSelector({
        a: state => state.b,
        // @ts-expect-error
        c: 'd'
      })
    ).toThrow(
      'createSelector expects all input-selectors to be functions, but received the following types: [function a(), string]'
    )
  })

  test('structured selector with custom selector creator', () => {
    const customSelectorCreator = createSelectorCreator(
      defaultMemoize,
      (a, b) => a === b
    )
    const selector = createStructuredSelector(
      {
        x: (state: StateAB) => state.a,
        y: (state: StateAB) => state.b
      },
      customSelectorCreator
    )
    const firstResult = selector({ a: 1, b: 2 })
    expect(firstResult).toEqual({ x: 1, y: 2 })
    expect(selector({ a: 1, b: 2 })).toBe(firstResult)
    expect(selector({ a: 2, b: 2 })).toEqual({ x: 2, y: 2 })
  })
})

describe('createSelector exposed utils', () => {
  test('resetRecomputations', () => {
    const selector = createSelector(
      (state: StateA) => state.a,
      a => a
    )
    expect(selector({ a: 1 })).toBe(1)
    expect(selector({ a: 1 })).toBe(1)
    expect(selector.recomputations()).toBe(1)
    expect(selector({ a: 2 })).toBe(2)
    expect(selector.recomputations()).toBe(2)

    selector.resetRecomputations()
    expect(selector.recomputations()).toBe(0)

    expect(selector({ a: 1 })).toBe(1)
    expect(selector({ a: 1 })).toBe(1)
    expect(selector.recomputations()).toBe(1)
    expect(selector({ a: 2 })).toBe(2)
    expect(selector.recomputations()).toBe(2)
  })

  test('export last function as resultFunc', () => {
    const lastFunction = () => {}
    const selector = createSelector((state: StateA) => state.a, lastFunction)
    expect(selector.resultFunc).toBe(lastFunction)
  })

  test('export dependencies as dependencies', () => {
    const dependency1 = (state: StateA) => {
      state.a
    }
    const dependency2 = (state: StateA) => {
      state.a
    }

    const selector = createSelector(dependency1, dependency2, () => {})
    expect(selector.dependencies).toEqual([dependency1, dependency2])
  })

  test('export lastResult function', () => {
    const selector = createSelector(
      (state: StateAB) => state.a,
      (state: StateAB) => state.b,
      (a, b) => a + b
    )

    const result = selector({ a: 1, b: 2 })
    expect(result).toBe(3)
    expect(selector.lastResult()).toBe(3)
  })
})


text:
package org.jenkinsci.plugins.dockerbuildstep.cmd;

import hudson.Extension;
import hudson.FilePath;
import hudson.model.Result;
import hudson.model.AbstractBuild;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.stream.JsonParsingException;

import org.apache.commons.io.IOUtils;
import org.jenkinsci.plugins.dockerbuildstep.log.ConsoleLogger;
import org.jenkinsci.plugins.dockerbuildstep.util.Resolver;
import org.kohsuke.stapler.DataBoundConstructor;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.DockerException;

/**
 * This command creates a new image from specified Dockerfile.
 *
 * @see http://docs.docker.com/reference/api/docker_remote_api_v1.13/#build-an-image-from-dockerfile-via-stdin
 *
 * @author marcus
 *
 */
public class CreateImageCommand extends DockerCommand {

	private final String dockerFolder;
	private final String imageTag;
	private final boolean noCache;
	private final boolean rm;

	@DataBoundConstructor
	public CreateImageCommand(String dockerFolder, String imageTag, boolean noCache, boolean rm) {
		this.dockerFolder = dockerFolder;
		this.imageTag = imageTag;
		this.noCache = noCache;
		this.rm = rm;
	}

	public String getDockerFolder() {
		return dockerFolder;
	}

	public String getImageTag() {
		return imageTag;
	}

	public boolean isNoCache() {
		return noCache;
	}

	public boolean isRm() {
	    return rm;
	}

	@Override
	public void execute(@SuppressWarnings("rawtypes") AbstractBuild build,
			final ConsoleLogger console) throws DockerException {

		if (dockerFolder == null) {
			throw new IllegalArgumentException("dockerFolder is not configured");
		}

		if (imageTag == null) {
			throw new IllegalArgumentException("imageTag is not configured");
		}

		String dockerFolderRes = Resolver.buildVar(build, dockerFolder);
		String imageTagRes = Resolver.buildVar(build, imageTag);

		String expandedDockerFolder = expandEnvironmentVariables(dockerFolderRes,
				build, console);

		String expandedImageTag = expandEnvironmentVariables(imageTagRes, build,
				console);

		FilePath folder = new FilePath(new File(expandedDockerFolder));

		if (!exist(folder))
			throw new IllegalArgumentException("configured dockerFolder '"
					+ expandedDockerFolder + "' does not exist.");

		FilePath dockerFile = folder.child("Dockerfile");

		if (!exist(dockerFile))
			throw new IllegalArgumentException("configured dockerFolder '"
					+ folder + "' does not contain a Dockerfile.");

		DockerClient client = getClient(build, null);

		try {

			File docker = new File(expandedDockerFolder);

			console.logInfo("Creating docker image from " + docker.getAbsolutePath());

			InputStream istream = client.buildImageCmd(docker).withTag(expandedImageTag).withNoCache(noCache).withRemove(rm).exec();

			final List<JsonObject> errors = new ArrayList<JsonObject>();

			try {
				readJsonStream(istream, new JsonObjectCallback() {
					public void callback(JsonObject json) {
						if (json.containsKey("stream")) {
							console.log(json.getString("stream"));
						} else if (json.containsKey("status")) {
							console.log(json.getString("status"));
						} else if(json.containsKey("errorDetail")){
							errors.add(json);
							console.logError(json.containsKey("message") ? json.getString("message") : json.getString("errorDetail"));
						}
					}
				});

				if (!errors.isEmpty()) {
					build.setResult(Result.FAILURE);
				} else {
					console.logInfo("Sucessfully created image " + expandedImageTag);
				}

			} finally {
				IOUtils.closeQuietly(istream);
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	private interface JsonObjectCallback {
		void callback(JsonObject jsonObject);
	}

	private void readJsonStream(InputStream istream, JsonObjectCallback callback)
			throws IOException, UnsupportedEncodingException {

		final BufferedReader streamReader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));
		String inputStr;
		while ((inputStr = streamReader.readLine()) != null) {
			JsonObject json = null;
			try {
				json = Json.createReader(new StringReader(inputStr)).readObject();
			} catch (JsonParsingException e) {
				// just ignore and continue
				continue;
			}
			callback.callback(json);
		}

	}

	private String expandEnvironmentVariables(String string,
			@SuppressWarnings("rawtypes") AbstractBuild build, ConsoleLogger console) {
		try {
			return build.getEnvironment(console.getListener()).expand(string);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Extension
	public static class CreateImageCommandDescriptor extends
			DockerCommandDescriptor {
		@Override
		public String getDisplayName() {
			return "Create/build image";
		}
	}

	private boolean exist(FilePath filePath) throws DockerException {
		try {
			return filePath.exists();
		} catch (Exception e) {
			throw new DockerException("Could not check file", 0, e);
		}
	}

}


text:
////var v = 10e0;
////var x = {
////    p1: `hello world`,
////    p2: `goodbye ${0} cruel ${0} world`,
////};

var c = classification;
verify.syntacticClassificationsAre(
    c.keyword("var"), c.identifier("v"), c.operator("="), c.numericLiteral("10e0"), c.punctuation(";"),
    c.keyword("var"), c.identifier("x"), c.operator("="), c.punctuation("{"),
    c.identifier("p1"), c.punctuation(":"), c.stringLiteral("`hello world`"), c.punctuation(","),
    c.identifier("p2"), c.punctuation(":"), c.stringLiteral("`goodbye ${"), c.numericLiteral("0"), c.stringLiteral("} cruel ${"), c.numericLiteral("0"), c.stringLiteral("} world`"), c.punctuation(","),
    c.punctuation("}"), c.punctuation(";"));


text:
A personal boilerplate for creating jQuery plugins.

## Usage

## Contributing

Feel free to send suggestions, bug reports, etc. via the built in Github Issue Tracker. If you're feeling generous go ahead and send me a pull request for bug fixes, other ipsums, and other stuff.

## License

Licensed under MIT.


text:
<?php

/**
 * Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
 */
if ( !function_exists( 'unitedthemes_page_menu_args' ) ) {

	function unitedthemes_page_menu_args( $args ) {
		$args['show_home'] = true;
		return $args;
	}
	add_filter( 'wp_page_menu_args', 'unitedthemes_page_menu_args' );

}

/**
 * Adds custom classes to the array of body classes.
 */
if ( !function_exists( 'unitedthemes_body_classes' ) ) {

	function unitedthemes_body_classes( $classes ) {
		// Adds a class of group-blog to blogs with more than 1 published author
		if ( is_multi_author() ) {
			$classes[] = 'group-blog';
		}

		return $classes;
	}
	add_filter( 'body_class', 'unitedthemes_body_classes' );

}

/**
 * Filter in a link to a content ID attribute for the next/previous image links on image attachment pages
 */
if ( !function_exists( 'unitedthemes_enhanced_image_navigation' ) ) {

	function unitedthemes_enhanced_image_navigation( $url, $id ) {
		if ( ! is_attachment() && ! wp_attachment_is_image( $id ) )
			return $url;

		$image = get_post( $id );
		if ( ! empty( $image->post_parent ) && $image->post_parent != $id )
			$url .= '#main';

		return $url;
	}
	add_filter( 'attachment_link', 'unitedthemes_enhanced_image_navigation', 10, 2 );

}

/**
 * Filters wp_title to print a neat <title> tag based on what is being viewed.
 */
if ( !function_exists( 'unitedthemes_wp_title' ) ) {

	function unitedthemes_wp_title( $title, $sep ) {
		global $page, $paged;

		if ( is_feed() )
			return $title;

		// Add the blog name
		$title .= get_bloginfo( 'name' );

		// Add the blog description for the home/front page.
		$site_description = get_bloginfo( 'description', 'display' );
		if ( $site_description && ( is_home() || is_front_page() ) )
			$title .= " $sep $site_description";

		// Add a page number if necessary:
		if ( $paged >= 2 || $page >= 2 )
			$title .= " $sep " . sprintf( __( 'Page %s', 'unitedthemes' ), max( $paged, $page ) );

		return $title;
	}
	add_filter( 'wp_title', 'unitedthemes_wp_title', 10, 2 );

}

/**
 * let read more jump to article top
 */
if ( !function_exists( 'ut_remove_more_link_scroll' ) ) {

	function ut_remove_more_link_scroll( $link ) {
		$link = preg_replace( '|#more-[0-9]+|', '', $link );
		return $link;
	}

	add_filter( 'the_content_more_link', 'ut_remove_more_link_scroll' );

}


text:
module Cronloggable

  def open_log

    @start_time = DateTime.now

  end

  def write_log

    Cronlog.record( self, @start_time )

  end

end


text:
A module for approximating, solving, and simulating dynamic stochastic general equilibrium (DSGE) models.

Free use of this software is welcome and subject to the terms of the [license](https://github.com/letsgoexploring/linearsolve/blob/gh-pages/LICENSE). Please send me comments, feedback, suggestions, etc. at bcjenkin@uci.edu.

## Installation
Install the module from PyPI with the shell command:

```pip install linearsolve```

Or download the source here: https://github.com/letsgoexploring/linearsolve/blob/gh-pages/dist/linearsolve-3.4.10.tar.gz

## Documentation
Documentation for linearsolve: https://www.briancjenkins.com/linearsolve/docs/build/html/index.html

## Examples
Example Jupyter Notebooks available in the ``examples`` directory or follow the links below for the examples rendered in nbviewer:
1. [Quickly Simulate an RBC Model](https://nbviewer.jupyter.org/github/letsgoexploring/linearsolve/blob/gh-pages/examples/quick_rbc_model.ipynb)
2. [A Detailed RBC Model Example](https://nbviewer.jupyter.org/github/letsgoexploring/linearsolve/blob/gh-pages/examples/detailed_rbc_model.ipynb)
3. [A New-Keynesian Model](https://nbviewer.jupyter.org/github/letsgoexploring/linearsolve/blob/gh-pages/examples/nk_model.ipynb)
4. [A Cash-in-Advance Model](https://nbviewer.jupyter.org/github/letsgoexploring/linearsolve/blob/gh-pages/examples/cia_model.ipynb)

_Updated: December 22, 2021_


text:
// @conditional=ENABLE(WEB_RTC)

function initializeRTCPeerConnection(configuration)
{
    "use strict";

    if (arguments.length < 1)
        throw new @TypeError("Not enough arguments");

    if (!@isObject(configuration))
        throw new @TypeError("RTCPeerConnection argument must be a valid Dictionary");

    // FIXME: Handle errors in a better way than catching and re-throwing (http://webkit.org/b/158936)
    try {
        this.@initializeWith(configuration);
    } catch (e) {
        const message = e.name === "TypeMismatchError" ? "Invalid RTCPeerConnection constructor arguments"
            : "Error creating RTCPeerConnection";
        throw new @TypeError(message);
    }

    this.@operations = [];
    this.@localStreams = [];

    return this;
}

function getLocalStreams()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        throw new @TypeError("Function should be called on an RTCPeerConnection");

    return this.@localStreams.slice();
}

function getStreamById(streamIdArg)
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        throw new @TypeError("Function should be called on an RTCPeerConnection");

    if (arguments.length < 1)
        throw new @TypeError("Not enough arguments");

    const streamId = @String(streamIdArg);

    return this.@localStreams.find(stream => stream.id === streamId)
        || this.@getRemoteStreams().find(stream => stream.id === streamId)
        || null;
}

function addStream(stream)
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        throw new @TypeError("Function should be called on an RTCPeerConnection");

    if (arguments.length < 1)
        throw new @TypeError("Not enough arguments");

    if (!(stream instanceof @MediaStream))
        throw new @TypeError("Argument 1 ('stream') to RTCPeerConnection.addStream must be an instance of MediaStream");

    if (this.@localStreams.find(localStream => localStream.id === stream.id))
        return;

    this.@localStreams.@push(stream);
    stream.@getTracks().forEach(track => this.@addTrack(track, stream));
}

function removeStream(stream)
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        throw new @TypeError("Function should be called on an RTCPeerConnection");

    if (arguments.length < 1)
        throw new @TypeError("Not enough arguments");

    if (!(stream instanceof @MediaStream))
        throw new @TypeError("Argument 1 ('stream') to RTCPeerConnection.removeStream must be an instance of MediaStream");

    const indexOfStreamToRemove = this.@localStreams.findIndex(localStream => localStream.id === stream.id);
    if (indexOfStreamToRemove === -1)
        return;

    const senders = this.@getSenders();
    this.@localStreams[indexOfStreamToRemove].@getTracks().forEach(track => {
        const senderForTrack = senders.find(sender => sender.track && sender.track.id === track.id);
        if (senderForTrack)
            this.@removeTrack(senderForTrack);
    });

    this.@localStreams.splice(indexOfStreamToRemove, 1);
}

function createOffer()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    return @callbacksAndDictionaryOverload(arguments, "createOffer", function (options) {
        // Promise mode
        return @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedCreateOffer(options);
        });
    }, function (successCallback, errorCallback, options) {
        // Legacy callbacks mode
        @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedCreateOffer(options).@then(successCallback, errorCallback);
        });

        return @Promise.@resolve(@undefined);
    });
}

function createAnswer()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    return @callbacksAndDictionaryOverload(arguments, "createAnswer", function (options) {
        // Promise mode
        return @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedCreateAnswer(options);
        });
    }, function (successCallback, errorCallback, options) {
        // Legacy callbacks mode
        @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedCreateAnswer(options).@then(successCallback, errorCallback);
        });

        return @Promise.@resolve(@undefined);
    });
}

function setLocalDescription()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    const objectInfo = {
        "constructor": @RTCSessionDescription,
        "argName": "description",
        "argType": "RTCSessionDescription"
    };
    return @objectAndCallbacksOverload(arguments, "setLocalDescription", objectInfo, function (description) {
        // Promise mode
        return @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedSetLocalDescription(description);
        });
    }, function (description, successCallback, errorCallback) {
        // Legacy callbacks mode
        @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedSetLocalDescription(description).@then(successCallback, errorCallback);
        });

        return @Promise.@resolve(@undefined);
    });
}

function setRemoteDescription()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    const objectInfo = {
        "constructor": @RTCSessionDescription,
        "argName": "description",
        "argType": "RTCSessionDescription"
    };
    return @objectAndCallbacksOverload(arguments, "setRemoteDescription", objectInfo, function (description) {
        // Promise mode
        return @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedSetRemoteDescription(description);
        });
    }, function (description, successCallback, errorCallback) {
        // Legacy callbacks mode
        @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedSetRemoteDescription(description).@then(successCallback, errorCallback);
        });

        return @Promise.@resolve(@undefined);
    });
}

function addIceCandidate()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    const objectInfo = {
        "constructor": @RTCIceCandidate,
        "argName": "candidate",
        "argType": "RTCIceCandidate"
    };
    return @objectAndCallbacksOverload(arguments, "addIceCandidate", objectInfo, function (candidate) {
        // Promise mode
        return @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedAddIceCandidate(candidate);
        });
    }, function (candidate, successCallback, errorCallback) {
        // Legacy callbacks mode
        @enqueueOperation(peerConnection, function () {
            return peerConnection.@queuedAddIceCandidate(candidate).@then(successCallback, errorCallback);
        });

        return @Promise.@resolve(@undefined);
    });
}

function getStats()
{
    "use strict";

    if (!@isRTCPeerConnection(this))
        return @Promise.@reject(new @TypeError("Function should be called on an RTCPeerConnection"));

    const peerConnection = this;

    const objectInfo = {
        "constructor": @MediaStreamTrack,
        "argName": "selector",
        "argType": "MediaStreamTrack",
        "defaultsToNull": true
    };
    return @objectAndCallbacksOverload(arguments, "getStats", objectInfo, function (selector) {
        // Promise mode
        return peerConnection.@privateGetStats(selector);
    }, function (selector, successCallback, errorCallback) {
        // Legacy callbacks mode
        peerConnection.@privateGetStats(selector).@then(successCallback, errorCallback);

        return @Promise.@resolve(@undefined);
    });
}


text:
extern "C" {
#endif

void ion_hash(const char* input, int len, char* output);

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

namespace Elastica\Query;

/**
 * Match Phrase query.
 *
 * @author Jacques Moati <jacques@moati.net>
 * @author Tobias Schultze <http://tobion.de>
 *
 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html
 */
class MatchPhrase extends AbstractQuery
{
    /**
     * @param string $field
     * @param mixed  $values
     */
    public function __construct(?string $field = null, $values = null)
    {
        if (null !== $field && null !== $values) {
            $this->setParam($field, $values);
        }
    }

    /**
     * Sets a param for the message array.
     *
     * @param mixed $values
     *
     * @return $this
     */
    public function setField(string $field, $values): self
    {
        return $this->setParam($field, $values);
    }

    /**
     * Sets a param for the given field.
     *
     * @return $this
     */
    public function setFieldParam(string $field, string $key, string $value): self
    {
        if (!isset($this->_params[$field])) {
            $this->_params[$field] = [];
        }

        $this->_params[$field][$key] = $value;

        return $this;
    }

    /**
     * Sets the query string.
     *
     * @return $this
     */
    public function setFieldQuery(string $field, string $query): self
    {
        return $this->setFieldParam($field, 'query', $query);
    }

    /**
     * Set field analyzer.
     *
     * @return $this
     */
    public function setFieldAnalyzer(string $field, string $analyzer): self
    {
        return $this->setFieldParam($field, 'analyzer', $analyzer);
    }

    /**
     * Set field boost value.
     *
     * If not set, defaults to 1.0.
     *
     * @return $this
     */
    public function setFieldBoost(string $field, float $boost = 1.0): self
    {
        return $this->setFieldParam($field, 'boost', $boost);
    }
}


text:
namespace webcrypto {

namespace {

// Creates an AES algorithm name for the given key size (in bytes). For
// instance "A128CBC" is the result of suffix="CBC", keylen_bytes=16.
std::string MakeJwkAesAlgorithmName(const std::string& suffix,
                                    size_t keylen_bytes) {
  if (keylen_bytes == 16)
    return std::string("A128") + suffix;
  if (keylen_bytes == 24)
    return std::string("A192") + suffix;
  if (keylen_bytes == 32)
    return std::string("A256") + suffix;
  return std::string();
}

}  // namespace

AesAlgorithm::AesAlgorithm(blink::WebCryptoKeyUsageMask all_key_usages,
                           const std::string& jwk_suffix)
    : all_key_usages_(all_key_usages), jwk_suffix_(jwk_suffix) {
}

AesAlgorithm::AesAlgorithm(const std::string& jwk_suffix)
    : all_key_usages_(blink::WebCryptoKeyUsageEncrypt |
                      blink::WebCryptoKeyUsageDecrypt |
                      blink::WebCryptoKeyUsageWrapKey |
                      blink::WebCryptoKeyUsageUnwrapKey),
      jwk_suffix_(jwk_suffix) {
}

Status AesAlgorithm::GenerateKey(const blink::WebCryptoAlgorithm& algorithm,
                                 bool extractable,
                                 blink::WebCryptoKeyUsageMask usages,
                                 GenerateKeyResult* result) const {
  Status status = CheckKeyCreationUsages(all_key_usages_, usages, false);
  if (status.IsError())
    return status;

  unsigned int keylen_bits;
  status = GetAesKeyGenLengthInBits(algorithm.aesKeyGenParams(), &keylen_bits);
  if (status.IsError())
    return status;

  return GenerateWebCryptoSecretKey(
      blink::WebCryptoKeyAlgorithm::createAes(algorithm.id(), keylen_bits),
      extractable, usages, keylen_bits, result);
}

Status AesAlgorithm::VerifyKeyUsagesBeforeImportKey(
    blink::WebCryptoKeyFormat format,
    blink::WebCryptoKeyUsageMask usages) const {
  switch (format) {
    case blink::WebCryptoKeyFormatRaw:
    case blink::WebCryptoKeyFormatJwk:
      return CheckKeyCreationUsages(all_key_usages_, usages, false);
    default:
      return Status::ErrorUnsupportedImportKeyFormat();
  }
}

Status AesAlgorithm::ImportKeyRaw(const CryptoData& key_data,
                                  const blink::WebCryptoAlgorithm& algorithm,
                                  bool extractable,
                                  blink::WebCryptoKeyUsageMask usages,
                                  blink::WebCryptoKey* key) const {
  const unsigned int keylen_bytes = key_data.byte_length();
  Status status = VerifyAesKeyLengthForImport(keylen_bytes);
  if (status.IsError())
    return status;

  // No possibility of overflow.
  unsigned int keylen_bits = keylen_bytes * 8;

  return CreateWebCryptoSecretKey(
      key_data,
      blink::WebCryptoKeyAlgorithm::createAes(algorithm.id(), keylen_bits),
      extractable, usages, key);
}

Status AesAlgorithm::ImportKeyJwk(const CryptoData& key_data,
                                  const blink::WebCryptoAlgorithm& algorithm,
                                  bool extractable,
                                  blink::WebCryptoKeyUsageMask usages,
                                  blink::WebCryptoKey* key) const {
  std::vector<uint8_t> raw_data;
  JwkReader jwk;
  Status status = ReadSecretKeyNoExpectedAlg(key_data, extractable, usages,
                                             &raw_data, &jwk);
  if (status.IsError())
    return status;

  bool has_jwk_alg;
  std::string jwk_alg;
  status = jwk.GetAlg(&jwk_alg, &has_jwk_alg);
  if (status.IsError())
    return status;

  if (has_jwk_alg) {
    std::string expected_algorithm_name =
        MakeJwkAesAlgorithmName(jwk_suffix_, raw_data.size());

    if (jwk_alg != expected_algorithm_name) {
      // Give a different error message if the key length was wrong.
      if (jwk_alg == MakeJwkAesAlgorithmName(jwk_suffix_, 16) ||
          jwk_alg == MakeJwkAesAlgorithmName(jwk_suffix_, 24) ||
          jwk_alg == MakeJwkAesAlgorithmName(jwk_suffix_, 32)) {
        return Status::ErrorJwkIncorrectKeyLength();
      }
      return Status::ErrorJwkAlgorithmInconsistent();
    }
  }

  return ImportKeyRaw(CryptoData(raw_data), algorithm, extractable, usages,
                      key);
}

Status AesAlgorithm::ExportKeyRaw(const blink::WebCryptoKey& key,
                                  std::vector<uint8_t>* buffer) const {
  *buffer = SymKeyOpenSsl::Cast(key)->raw_key_data();
  return Status::Success();
}

Status AesAlgorithm::ExportKeyJwk(const blink::WebCryptoKey& key,
                                  std::vector<uint8_t>* buffer) const {
  const std::vector<uint8_t>& raw_data =
      SymKeyOpenSsl::Cast(key)->raw_key_data();

  WriteSecretKeyJwk(CryptoData(raw_data),
                    MakeJwkAesAlgorithmName(jwk_suffix_, raw_data.size()),
                    key.extractable(), key.usages(), buffer);

  return Status::Success();
}

Status AesAlgorithm::SerializeKeyForClone(
    const blink::WebCryptoKey& key,
    blink::WebVector<uint8_t>* key_data) const {
  key_data->assign(SymKeyOpenSsl::Cast(key)->serialized_key_data());
  return Status::Success();
}

Status AesAlgorithm::DeserializeKeyForClone(
    const blink::WebCryptoKeyAlgorithm& algorithm,
    blink::WebCryptoKeyType type,
    bool extractable,
    blink::WebCryptoKeyUsageMask usages,
    const CryptoData& key_data,
    blink::WebCryptoKey* key) const {
  return ImportKeyRaw(key_data, CreateAlgorithm(algorithm.id()), extractable,
                      usages, key);
}

Status AesAlgorithm::GetKeyLength(
    const blink::WebCryptoAlgorithm& key_length_algorithm,
    bool* has_length_bits,
    unsigned int* length_bits) const {
  return GetAesKeyLength(key_length_algorithm, has_length_bits, length_bits);
}

}  // namespace webcrypto