text:
require 'abstract_unit'

begin
  require 'openssl'
  OpenSSL::PKCS5
rescue LoadError, NameError
  $stderr.puts "Skipping KeyGenerator test: broken OpenSSL install"
else

require 'active_support/key_generator'
require 'active_support/message_verifier'

class CookiesTest < ActionController::TestCase
  class CustomSerializer
    def self.load(value)
      value.to_s + " and loaded"
    end

    def self.dump(value)
      value.to_s + " was dumped"
    end
  end

  class JSONWrapper
    def initialize(obj)
      @obj = obj
    end

    def as_json(options = nil)
      "wrapped: #{@obj.as_json(options)}"
    end
  end

  class TestController < ActionController::Base
    def authenticate
      cookies["user_name"] = "david"
      head :ok
    end

    def set_with_with_escapable_characters
      cookies["that & guy"] = "foo & bar => baz"
      head :ok
    end

    def authenticate_for_fourteen_days
      cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
      head :ok
    end

    def authenticate_for_fourteen_days_with_symbols
      cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
      head :ok
    end

    def set_multiple_cookies
      cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
      cookies["login"]     = "XJ-122"
      head :ok
    end

    def access_frozen_cookies
      cookies["will"] = "work"
      head :ok
    end

    def logout
      cookies.delete("user_name")
      head :ok
    end

    alias delete_cookie logout

    def delete_cookie_with_path
      cookies.delete("user_name", :path => '/beaten')
      head :ok
    end

    def authenticate_with_http_only
      cookies["user_name"] = { :value => "david", :httponly => true }
      head :ok
    end

    def authenticate_with_secure
      cookies["user_name"] = { :value => "david", :secure => true }
      head :ok
    end

    def set_permanent_cookie
      cookies.permanent[:user_name] = "Jamie"
      head :ok
    end

    def set_signed_cookie
      cookies.signed[:user_id] = 45
      head :ok
    end

    def set_wrapped_signed_cookie
      cookies.signed[:user_id] = JSONWrapper.new(45)
      head :ok
    end

    def get_signed_cookie
      cookies.signed[:user_id]
      head :ok
    end

    def set_encrypted_cookie
      cookies.encrypted[:foo] = 'bar'
      head :ok
    end

    def set_wrapped_encrypted_cookie
      cookies.encrypted[:foo] = JSONWrapper.new('bar')
      head :ok
    end

    def get_encrypted_cookie
      cookies.encrypted[:foo]
      head :ok
    end

    def set_invalid_encrypted_cookie
      cookies[:invalid_cookie] = 'invalid--9170e00a57cfc27083363b5c75b835e477bd90cf'
      head :ok
    end

    def raise_data_overflow
      cookies.signed[:foo] = 'bye!' * 1024
      head :ok
    end

    def tampered_cookies
      cookies[:tampered] = "BAh7BjoIZm9vIghiYXI%3D--123456780"
      cookies.signed[:tampered]
      head :ok
    end

    def set_permanent_signed_cookie
      cookies.permanent.signed[:remember_me] = 100
      head :ok
    end

    def delete_and_set_cookie
      cookies.delete :user_name
      cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
      head :ok
    end

    def set_cookie_with_domain
      cookies[:user_name] = {:value => "rizwanreza", :domain => :all}
      head :ok
    end

    def delete_cookie_with_domain
      cookies.delete(:user_name, :domain => :all)
      head :ok
    end

    def set_cookie_with_domain_and_tld
      cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2}
      head :ok
    end

    def delete_cookie_with_domain_and_tld
      cookies.delete(:user_name, :domain => :all, :tld_length => 2)
      head :ok
    end

    def set_cookie_with_domains
      cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)}
      head :ok
    end

    def delete_cookie_with_domains
      cookies.delete(:user_name, :domain => %w(example1.com example2.com .example3.com))
      head :ok
    end

    def symbol_key
      cookies[:user_name] = "david"
      head :ok
    end

    def string_key
      cookies['user_name'] = "dhh"
      head :ok
    end

    def symbol_key_mock
      cookies[:user_name] = "david" if cookies[:user_name] == "andrew"
      head :ok
    end

    def string_key_mock
      cookies['user_name'] = "david" if cookies['user_name'] == "andrew"
      head :ok
    end

    def noop
      head :ok
    end
  end

  tests TestController

  def setup
    super
    @request.env["action_dispatch.key_generator"] = ActiveSupport::KeyGenerator.new("b3c631c314c0bbca50c1b2843150fe33", iterations: 2)
    @request.env["action_dispatch.signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.encrypted_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.host = "www.nextangle.com"
  end

  def test_fetch
    x = Object.new
    assert_not request.cookie_jar.key?('zzzzzz')
    assert_equal x, request.cookie_jar.fetch('zzzzzz', x)
    assert_not request.cookie_jar.key?('zzzzzz')
  end

  def test_fetch_exists
    x = Object.new
    request.cookie_jar['foo'] = 'bar'
    assert_equal 'bar', request.cookie_jar.fetch('foo', x)
  end

  def test_fetch_block
    x = Object.new
    assert_not request.cookie_jar.key?('zzzzzz')
    assert_equal x, request.cookie_jar.fetch('zzzzzz') { x }
  end

  def test_key_is_to_s
    request.cookie_jar['foo'] = 'bar'
    assert_equal 'bar', request.cookie_jar.fetch(:foo)
  end

  def test_fetch_type_error
    assert_raises(KeyError) do
      request.cookie_jar.fetch(:omglolwut)
    end
  end

  def test_each
    request.cookie_jar['foo'] = :bar
    list = []
    request.cookie_jar.each do |k,v|
      list << [k, v]
    end

    assert_equal [['foo', :bar]], list
  end

  def test_enumerable
    request.cookie_jar['foo'] = :bar
    actual = request.cookie_jar.map { |k,v| [k.to_s, v.to_s] }
    assert_equal [['foo', 'bar']], actual
  end

  def test_key_methods
    assert !request.cookie_jar.key?(:foo)
    assert !request.cookie_jar.has_key?("foo")

    request.cookie_jar[:foo] = :bar
    assert request.cookie_jar.key?(:foo)
    assert request.cookie_jar.has_key?("foo")
  end

  def test_setting_cookie
    get :authenticate
    assert_cookie_header "user_name=david; path=/"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_setting_the_same_value_to_cookie
    request.cookies[:user_name] = 'david'
    get :authenticate
    assert response.cookies.empty?
  end

  def test_setting_the_same_value_to_permanent_cookie
    request.cookies[:user_name] = 'Jamie'
    get :set_permanent_cookie
    assert_equal({'user_name' => 'Jamie'}, response.cookies)
  end

  def test_setting_with_escapable_characters
    get :set_with_with_escapable_characters
    assert_cookie_header "that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"
    assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies)
  end

  def test_setting_cookie_for_fourteen_days
    get :authenticate_for_fourteen_days
    assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_setting_cookie_for_fourteen_days_with_symbols
    get :authenticate_for_fourteen_days_with_symbols
    assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_setting_cookie_with_http_only
    get :authenticate_with_http_only
    assert_cookie_header "user_name=david; path=/; HttpOnly"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_setting_cookie_with_secure
    @request.env["HTTPS"] = "on"
    get :authenticate_with_secure
    assert_cookie_header "user_name=david; path=/; secure"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_setting_cookie_with_secure_when_always_write_cookie_is_true
    ActionDispatch::Cookies::CookieJar.any_instance.stubs(:always_write_cookie).returns(true)
    get :authenticate_with_secure
    assert_cookie_header "user_name=david; path=/; secure"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_not_setting_cookie_with_secure
    get :authenticate_with_secure
    assert_not_cookie_header "user_name=david; path=/; secure"
    assert_not_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_multiple_cookies
    get :set_multiple_cookies
    assert_equal 2, @response.cookies.size
    assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000\nlogin=XJ-122; path=/"
    assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies)
  end

  def test_setting_test_cookie
    assert_nothing_raised { get :access_frozen_cookies }
  end

  def test_expiring_cookie
    request.cookies[:user_name] = 'Joe'
    get :logout
    assert_cookie_header "user_name=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
    assert_equal({"user_name" => nil}, @response.cookies)
  end

  def test_delete_cookie_with_path
    request.cookies[:user_name] = 'Joe'
    get :delete_cookie_with_path
    assert_cookie_header "user_name=; path=/beaten; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
  end

  def test_delete_unexisting_cookie
    request.cookies.clear
    get :delete_cookie
    assert @response.cookies.empty?
  end

  def test_deleted_cookie_predicate
    cookies[:user_name] = 'Joe'
    cookies.delete("user_name")
    assert cookies.deleted?("user_name")
    assert_equal false, cookies.deleted?("another")
  end

  def test_deleted_cookie_predicate_with_mismatching_options
    cookies[:user_name] = 'Joe'
    cookies.delete("user_name", :path => "/path")
    assert_equal false, cookies.deleted?("user_name", :path => "/different")
  end

  def test_cookies_persist_throughout_request
    response = get :authenticate
    assert response.headers["Set-Cookie"] =~ /user_name=david/
  end

  def test_set_permanent_cookie
    get :set_permanent_cookie
    assert_match(/Jamie/, @response.headers["Set-Cookie"])
    assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
  end

  def test_read_permanent_cookie
    get :set_permanent_cookie
    assert_equal 'Jamie', @controller.send(:cookies).permanent[:user_name]
  end

  def test_signed_cookie_using_default_digest
    get :set_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"]
    secret = key_generator.generate_key(signed_cookie_salt)

    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: Marshal, digest: 'SHA1')
    assert_equal verifier.generate(45), cookies[:user_id]
  end

  def test_signed_cookie_using_custom_digest
    @request.env["action_dispatch.cookies_digest"] = 'SHA256'
    get :set_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"]
    secret = key_generator.generate_key(signed_cookie_salt)

    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: Marshal, digest: 'SHA256')
    assert_equal verifier.generate(45), cookies[:user_id]
  end

  def test_signed_cookie_using_default_serializer
    get :set_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]
  end

  def test_signed_cookie_using_marshal_serializer
    @request.env["action_dispatch.cookies_serializer"] = :marshal
    get :set_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]
  end

  def test_signed_cookie_using_json_serializer
    @request.env["action_dispatch.cookies_serializer"] = :json
    get :set_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]
  end

  def test_wrapped_signed_cookie_using_json_serializer
    @request.env["action_dispatch.cookies_serializer"] = :json
    get :set_wrapped_signed_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'wrapped: 45', cookies[:user_id]
    assert_equal 'wrapped: 45', cookies.signed[:user_id]
  end

  def test_signed_cookie_using_custom_serializer
    @request.env["action_dispatch.cookies_serializer"] = CustomSerializer
    get :set_signed_cookie
    assert_not_equal 45, cookies[:user_id]
    assert_equal '45 was dumped and loaded', cookies.signed[:user_id]
  end

  def test_signed_cookie_using_hybrid_serializer_can_migrate_marshal_dumped_value_to_json
    @request.env["action_dispatch.cookies_serializer"] = :hybrid

    key_generator = @request.env["action_dispatch.key_generator"]
    signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"]
    secret = key_generator.generate_key(signed_cookie_salt)

    marshal_value = ActiveSupport::MessageVerifier.new(secret, serializer: Marshal).generate(45)
    @request.headers["Cookie"] = "user_id=#{marshal_value}"

    get :get_signed_cookie

    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]

    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: JSON)
    assert_equal 45, verifier.verify(@response.cookies['user_id'])
  end

  def test_signed_cookie_using_hybrid_serializer_can_read_from_json_dumped_value
    @request.env["action_dispatch.cookies_serializer"] = :hybrid

    key_generator = @request.env["action_dispatch.key_generator"]
    signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"]
    secret = key_generator.generate_key(signed_cookie_salt)
    json_value = ActiveSupport::MessageVerifier.new(secret, serializer: JSON).generate(45)
    @request.headers["Cookie"] = "user_id=#{json_value}"

    get :get_signed_cookie

    cookies = @controller.send :cookies
    assert_not_equal 45, cookies[:user_id]
    assert_equal 45, cookies.signed[:user_id]

    assert_nil @response.cookies["user_id"]
  end

  def test_accessing_nonexistant_signed_cookie_should_not_raise_an_invalid_signature
    get :set_signed_cookie
    assert_nil @controller.send(:cookies).signed[:non_existant_attribute]
  end

  def test_encrypted_cookie_using_default_serializer
    get :set_encrypted_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'bar', cookies[:foo]
    assert_raise TypeError do
      cookies.signed[:foo]
    end
    assert_equal 'bar', cookies.encrypted[:foo]
  end

  def test_encrypted_cookie_using_marshal_serializer
    @request.env["action_dispatch.cookies_serializer"] = :marshal
    get :set_encrypted_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'bar', cookies[:foo]
    assert_raises TypeError do
      cookies.signed[:foo]
    end
    assert_equal 'bar', cookies.encrypted[:foo]
  end

  def test_encrypted_cookie_using_json_serializer
    @request.env["action_dispatch.cookies_serializer"] = :json
    get :set_encrypted_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'bar', cookies[:foo]
    assert_raises ::JSON::ParserError do
      cookies.signed[:foo]
    end
    assert_equal 'bar', cookies.encrypted[:foo]
  end

  def test_wrapped_encrypted_cookie_using_json_serializer
    @request.env["action_dispatch.cookies_serializer"] = :json
    get :set_wrapped_encrypted_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'wrapped: bar', cookies[:foo]
    assert_raises ::JSON::ParserError do
      cookies.signed[:foo]
    end
    assert_equal 'wrapped: bar', cookies.encrypted[:foo]
  end

  def test_encrypted_cookie_using_custom_serializer
    @request.env["action_dispatch.cookies_serializer"] = CustomSerializer
    get :set_encrypted_cookie
    assert_not_equal 'bar', cookies.encrypted[:foo]
    assert_equal 'bar was dumped and loaded', cookies.encrypted[:foo]
  end

  def test_encrypted_cookie_using_custom_digest
    @request.env["action_dispatch.cookies_digest"] = 'SHA256'
    get :set_encrypted_cookie
    cookies = @controller.send :cookies
    assert_not_equal 'bar', cookies[:foo]
    assert_equal 'bar', cookies.encrypted[:foo]

    sign_secret = @request.env["action_dispatch.key_generator"].generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])

    sha1_verifier   = ActiveSupport::MessageVerifier.new(sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer, digest: 'SHA1')
    sha256_verifier = ActiveSupport::MessageVerifier.new(sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer, digest: 'SHA256')

    assert_raises(ActiveSupport::MessageVerifier::InvalidSignature) do
      sha1_verifier.verify(cookies[:foo])
    end

    assert_nothing_raised do
      sha256_verifier.verify(cookies[:foo])
    end
  end

  def test_encrypted_cookie_using_hybrid_serializer_can_migrate_marshal_dumped_value_to_json
    @request.env["action_dispatch.cookies_serializer"] = :hybrid

    key_generator = @request.env["action_dispatch.key_generator"]
    encrypted_cookie_salt = @request.env["action_dispatch.encrypted_cookie_salt"]
    encrypted_signed_cookie_salt = @request.env["action_dispatch.encrypted_signed_cookie_salt"]
    secret = key_generator.generate_key(encrypted_cookie_salt)
    sign_secret = key_generator.generate_key(encrypted_signed_cookie_salt)

    marshal_value = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: Marshal).encrypt_and_sign("bar")
    @request.headers["Cookie"] = "foo=#{marshal_value}"

    get :get_encrypted_cookie

    cookies = @controller.send :cookies
    assert_not_equal "bar", cookies[:foo]
    assert_equal "bar", cookies.encrypted[:foo]

    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)
    assert_equal "bar", encryptor.decrypt_and_verify(@response.cookies["foo"])
  end

  def test_encrypted_cookie_using_hybrid_serializer_can_read_from_json_dumped_value
    @request.env["action_dispatch.cookies_serializer"] = :hybrid

    key_generator = @request.env["action_dispatch.key_generator"]
    encrypted_cookie_salt = @request.env["action_dispatch.encrypted_cookie_salt"]
    encrypted_signed_cookie_salt = @request.env["action_dispatch.encrypted_signed_cookie_salt"]
    secret = key_generator.generate_key(encrypted_cookie_salt)
    sign_secret = key_generator.generate_key(encrypted_signed_cookie_salt)
    json_value = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON).encrypt_and_sign("bar")
    @request.headers["Cookie"] = "foo=#{json_value}"

    get :get_encrypted_cookie

    cookies = @controller.send :cookies
    assert_not_equal "bar", cookies[:foo]
    assert_equal "bar", cookies.encrypted[:foo]

    assert_nil @response.cookies["foo"]
  end

  def test_accessing_nonexistant_encrypted_cookie_should_not_raise_invalid_message
    get :set_encrypted_cookie
    assert_nil @controller.send(:cookies).encrypted[:non_existant_attribute]
  end

  def test_setting_invalid_encrypted_cookie_should_return_nil_when_accessing_it
    get :set_invalid_encrypted_cookie
    assert_nil @controller.send(:cookies).encrypted[:invalid_cookie]
  end

  def test_permanent_signed_cookie
    get :set_permanent_signed_cookie
    assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
    assert_equal 100, @controller.send(:cookies).signed[:remember_me]
  end

  def test_delete_and_set_cookie
    request.cookies[:user_name] = 'Joe'
    get :delete_and_set_cookie
    assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
    assert_equal({"user_name" => "david"}, @response.cookies)
  end

  def test_raise_data_overflow
    assert_raise(ActionDispatch::Cookies::CookieOverflow) do
      get :raise_data_overflow
    end
  end

  def test_tampered_cookies
    assert_nothing_raised do
      get :tampered_cookies
      assert_response :success
    end
  end

  def test_raises_argument_error_if_missing_secret
    assert_raise(ArgumentError, nil.inspect) {
      @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new(nil)
      get :set_signed_cookie
    }

    assert_raise(ArgumentError, ''.inspect) {
      @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("")
      get :set_signed_cookie
    }
  end

  def test_raises_argument_error_if_secret_is_probably_insecure
    assert_raise(ArgumentError, "password".inspect) {
      @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("password")
      get :set_signed_cookie
    }

    assert_raise(ArgumentError, "secret".inspect) {
      @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("secret")
      get :set_signed_cookie
    }

    assert_raise(ArgumentError, "12345678901234567890123456789".inspect) {
      @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("12345678901234567890123456789")
      get :set_signed_cookie
    }
  end

  def test_signed_uses_signed_cookie_jar_if_only_secret_token_is_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = nil
    get :set_signed_cookie
    assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed
  end

  def test_signed_uses_signed_cookie_jar_if_only_secret_key_base_is_set
    @request.env["action_dispatch.secret_token"] = nil
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :set_signed_cookie
    assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed
  end

  def test_signed_uses_upgrade_legacy_signed_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :set_signed_cookie
    assert_kind_of ActionDispatch::Cookies::UpgradeLegacySignedCookieJar, cookies.signed
  end

  def test_signed_or_encrypted_uses_signed_cookie_jar_if_only_secret_token_is_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = nil
    get :get_encrypted_cookie
    assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed_or_encrypted
  end

  def test_signed_or_encrypted_uses_encrypted_cookie_jar_if_only_secret_key_base_is_set
    @request.env["action_dispatch.secret_token"] = nil
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :get_encrypted_cookie
    assert_kind_of ActionDispatch::Cookies::EncryptedCookieJar, cookies.signed_or_encrypted
  end

  def test_signed_or_encrypted_uses_upgrade_legacy_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :get_encrypted_cookie
    assert_kind_of ActionDispatch::Cookies::UpgradeLegacyEncryptedCookieJar, cookies.signed_or_encrypted
  end

  def test_encrypted_uses_encrypted_cookie_jar_if_only_secret_key_base_is_set
    @request.env["action_dispatch.secret_token"] = nil
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :get_encrypted_cookie
    assert_kind_of ActionDispatch::Cookies::EncryptedCookieJar, cookies.encrypted
  end

  def test_encrypted_uses_upgrade_legacy_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    get :get_encrypted_cookie
    assert_kind_of ActionDispatch::Cookies::UpgradeLegacyEncryptedCookieJar, cookies.encrypted
  end

  def test_legacy_signed_cookie_is_read_and_transparently_upgraded_by_signed_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate(45)

    @request.headers["Cookie"] = "user_id=#{legacy_value}"
    get :get_signed_cookie

    assert_equal 45, @controller.send(:cookies).signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
    verifier = ActiveSupport::MessageVerifier.new(secret)
    assert_equal 45, verifier.verify(@response.cookies["user_id"])
  end

  def test_legacy_signed_cookie_is_read_and_transparently_encrypted_by_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    @request.env["action_dispatch.encrypted_cookie_salt"] = "4433796b79d99a7735553e316522acee"
    @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "00646eb40062e1b1deff205a27cd30f9"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate('bar')

    @request.headers["Cookie"] = "foo=#{legacy_value}"
    get :get_encrypted_cookie

    assert_equal 'bar', @controller.send(:cookies).encrypted[:foo]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_cookie_salt"])
    sign_secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])
    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
    assert_equal 'bar', encryptor.decrypt_and_verify(@response.cookies["foo"])
  end

  def test_legacy_json_signed_cookie_is_read_and_transparently_upgraded_by_signed_json_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :json
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33", serializer: JSON).generate(45)

    @request.headers["Cookie"] = "user_id=#{legacy_value}"
    get :get_signed_cookie

    assert_equal 45, @controller.send(:cookies).signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: JSON)
    assert_equal 45, verifier.verify(@response.cookies["user_id"])
  end

  def test_legacy_json_signed_cookie_is_read_and_transparently_encrypted_by_encrypted_json_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :json
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    @request.env["action_dispatch.encrypted_cookie_salt"] = "4433796b79d99a7735553e316522acee"
    @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "00646eb40062e1b1deff205a27cd30f9"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33", serializer: JSON).generate('bar')

    @request.headers["Cookie"] = "foo=#{legacy_value}"
    get :get_encrypted_cookie

    assert_equal 'bar', @controller.send(:cookies).encrypted[:foo]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_cookie_salt"])
    sign_secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])
    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)
    assert_equal 'bar', encryptor.decrypt_and_verify(@response.cookies["foo"])
  end

  def test_legacy_json_signed_cookie_is_read_and_transparently_upgraded_by_signed_json_hybrid_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :hybrid
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33", serializer: JSON).generate(45)

    @request.headers["Cookie"] = "user_id=#{legacy_value}"
    get :get_signed_cookie

    assert_equal 45, @controller.send(:cookies).signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: JSON)
    assert_equal 45, verifier.verify(@response.cookies["user_id"])
  end

  def test_legacy_json_signed_cookie_is_read_and_transparently_encrypted_by_encrypted_hybrid_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :hybrid
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    @request.env["action_dispatch.encrypted_cookie_salt"] = "4433796b79d99a7735553e316522acee"
    @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "00646eb40062e1b1deff205a27cd30f9"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33", serializer: JSON).generate('bar')

    @request.headers["Cookie"] = "foo=#{legacy_value}"
    get :get_encrypted_cookie

    assert_equal 'bar', @controller.send(:cookies).encrypted[:foo]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_cookie_salt"])
    sign_secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])
    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)
    assert_equal 'bar', encryptor.decrypt_and_verify(@response.cookies["foo"])
  end

  def test_legacy_marshal_signed_cookie_is_read_and_transparently_upgraded_by_signed_json_hybrid_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :hybrid
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate(45)

    @request.headers["Cookie"] = "user_id=#{legacy_value}"
    get :get_signed_cookie

    assert_equal 45, @controller.send(:cookies).signed[:user_id]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
    verifier = ActiveSupport::MessageVerifier.new(secret, serializer: JSON)
    assert_equal 45, verifier.verify(@response.cookies["user_id"])
  end

  def test_legacy_marshal_signed_cookie_is_read_and_transparently_encrypted_by_encrypted_hybrid_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
    @request.env["action_dispatch.cookies_serializer"] = :hybrid
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
    @request.env["action_dispatch.encrypted_cookie_salt"] = "4433796b79d99a7735553e316522acee"
    @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "00646eb40062e1b1deff205a27cd30f9"

    legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate('bar')

    @request.headers["Cookie"] = "foo=#{legacy_value}"
    get :get_encrypted_cookie

    assert_equal 'bar', @controller.send(:cookies).encrypted[:foo]

    key_generator = @request.env["action_dispatch.key_generator"]
    secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_cookie_salt"])
    sign_secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])
    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)
    assert_equal 'bar', encryptor.decrypt_and_verify(@response.cookies["foo"])
  end

  def test_legacy_signed_cookie_is_treated_as_nil_by_signed_cookie_jar_if_tampered
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    @request.headers["Cookie"] = "user_id=45"
    get :get_signed_cookie

    assert_equal nil, @controller.send(:cookies).signed[:user_id]
    assert_equal nil, @response.cookies["user_id"]
  end

  def test_legacy_signed_cookie_is_treated_as_nil_by_encrypted_cookie_jar_if_tampered
    @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
    @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"

    @request.headers["Cookie"] = "foo=baz"
    get :get_encrypted_cookie

    assert_equal nil, @controller.send(:cookies).encrypted[:foo]
    assert_equal nil, @response.cookies["foo"]
  end

  def test_cookie_with_all_domain_option
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
  end

  def test_cookie_with_all_domain_option_using_a_non_standard_tld
    @request.host = "two.subdomains.nextangle.local"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
  end

  def test_cookie_with_all_domain_option_using_australian_style_tld
    @request.host = "nextangle.com.au"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com.au; path=/"
  end

  def test_cookie_with_all_domain_option_using_uk_style_tld
    @request.host = "nextangle.co.uk"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.co.uk; path=/"
  end

  def test_cookie_with_all_domain_option_using_host_with_port
    @request.host = "nextangle.local:3000"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
  end

  def test_cookie_with_all_domain_option_using_localhost
    @request.host = "localhost"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; path=/"
  end

  def test_cookie_with_all_domain_option_using_ipv4_address
    @request.host = "192.168.1.1"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; path=/"
  end

  def test_cookie_with_all_domain_option_using_ipv6_address
    @request.host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
    get :set_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; path=/"
  end

  def test_deleting_cookie_with_all_domain_option
    request.cookies[:user_name] = 'Joe'
    get :delete_cookie_with_domain
    assert_response :success
    assert_cookie_header "user_name=; domain=.nextangle.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
  end

  def test_cookie_with_all_domain_option_and_tld_length
    get :set_cookie_with_domain_and_tld
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
  end

  def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length
    @request.host = "two.subdomains.nextangle.local"
    get :set_cookie_with_domain_and_tld
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
  end

  def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length
    @request.host = "nextangle.local:3000"
    get :set_cookie_with_domain_and_tld
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
  end

  def test_deleting_cookie_with_all_domain_option_and_tld_length
    request.cookies[:user_name] = 'Joe'
    get :delete_cookie_with_domain_and_tld
    assert_response :success
    assert_cookie_header "user_name=; domain=.nextangle.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
  end

  def test_cookie_with_several_preset_domains_using_one_of_these_domains
    @request.host = "example1.com"
    get :set_cookie_with_domains
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/"
  end

  def test_cookie_with_several_preset_domains_using_other_domain
    @request.host = "other-domain.com"
    get :set_cookie_with_domains
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; path=/"
  end

  def test_cookie_with_several_preset_domains_using_shared_domain
    @request.host = "example3.com"
    get :set_cookie_with_domains
    assert_response :success
    assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/"
  end

  def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains
    @request.host = "example2.com"
    request.cookies[:user_name] = 'Joe'
    get :delete_cookie_with_domains
    assert_response :success
    assert_cookie_header "user_name=; domain=example2.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
  end

  def test_deletings_cookie_with_several_preset_domains_using_other_domain
    @request.host = "other-domain.com"
    request.cookies[:user_name] = 'Joe'
    get :delete_cookie_with_domains
    assert_response :success
    assert_cookie_header "user_name=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
  end

  def test_cookies_hash_is_indifferent_access
    get :symbol_key
    assert_equal "david", cookies[:user_name]
    assert_equal "david", cookies['user_name']
    get :string_key
    assert_equal "dhh", cookies[:user_name]
    assert_equal "dhh", cookies['user_name']
  end

  def test_setting_request_cookies_is_indifferent_access
    cookies.clear
    cookies[:user_name] = "andrew"
    get :string_key_mock
    assert_equal "david", cookies['user_name']

    cookies.clear
    cookies['user_name'] = "andrew"
    get :symbol_key_mock
    assert_equal "david", cookies[:user_name]
  end

  def test_cookies_retained_across_requests
    get :symbol_key
    assert_cookie_header "user_name=david; path=/"
    assert_equal "david", cookies[:user_name]

    get :noop
    assert_nil @response.headers["Set-Cookie"]
    assert_equal "david", cookies[:user_name]

    get :noop
    assert_nil @response.headers["Set-Cookie"]
    assert_equal "david", cookies[:user_name]
  end

  def test_cookies_can_be_cleared
    get :symbol_key
    assert_equal "david", cookies[:user_name]

    cookies.clear
    get :noop
    assert_nil cookies[:user_name]

    get :symbol_key
    assert_equal "david", cookies[:user_name]
  end

  def test_can_set_http_cookie_header
    @request.env['HTTP_COOKIE'] = 'user_name=david'
    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    @request.env['HTTP_COOKIE'] = 'user_name=andrew'
    get :noop
    assert_equal 'andrew', cookies['user_name']
    assert_equal 'andrew', cookies[:user_name]
  end

  def test_can_set_request_cookies
    @request.cookies['user_name'] = 'david'
    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    @request.cookies[:user_name] = 'andrew'
    get :noop
    assert_equal 'andrew', cookies['user_name']
    assert_equal 'andrew', cookies[:user_name]
  end

  def test_cookies_precedence_over_http_cookie
    @request.env['HTTP_COOKIE'] = 'user_name=andrew'
    get :authenticate
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]
  end

  def test_cookies_precedence_over_request_cookies
    @request.cookies['user_name'] = 'andrew'
    get :authenticate
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]

    get :noop
    assert_equal 'david', cookies['user_name']
    assert_equal 'david', cookies[:user_name]
  end

  private
    def assert_cookie_header(expected)
      header = @response.headers["Set-Cookie"]
      if header.respond_to?(:to_str)
        assert_equal expected.split("\n").sort, header.split("\n").sort
      else
        assert_equal expected.split("\n"), header
      end
    end

    def assert_not_cookie_header(expected)
      header = @response.headers["Set-Cookie"]
      if header.respond_to?(:to_str)
        assert_not_equal expected.split("\n").sort, header.split("\n").sort
      else
        assert_not_equal expected.split("\n"), header
      end
    end
end

end


text:
package org.dependencytrack.tasks;

import alpine.event.framework.Event;
import alpine.logging.Logger;
import org.dependencytrack.event.KennaSecurityUploadEventAbstract;
import org.dependencytrack.integrations.kenna.KennaSecurityUploader;

public class KennaSecurityUploadTask extends VulnerabilityManagementUploadTask {

    private static final Logger LOGGER = Logger.getLogger(KennaSecurityUploadTask.class);

    /**
     * {@inheritDoc}
     */
    public void inform(final Event e) {
        if (e instanceof KennaSecurityUploadEventAbstract) {
            final KennaSecurityUploadEventAbstract event = (KennaSecurityUploadEventAbstract) e;
            LOGGER.debug("Starting Kenna Security upload task");
            super.inform(event, new KennaSecurityUploader());
            LOGGER.debug("Kenna Security upload complete");
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace DbAndRepository.IRepositories
{
    using DbAndRepository.GenericsEFRepository;

    public interface INewTechWorksRepository : IGenericsRepository<NewTechWorks>
    {
        void AddNewTechWork(string address, string customerName, DateTime orderTime, int technicianID);

        List<NewTechWorks> GetMyNewTechWorks(string username);
    }
}


text:
<?php

/**
 * Unit test core class.
 * This test class is inspired by lime of Symfony of a PHP framework.
 *
 * @package    ApplestFramework
 * @author     Yusei Yamanaka<info@applest.net>
 * @version    $id$
 */
class Test {
	const EPSILON = 0.0000000001;
	private static $count = 0;
	private static $pass_count = 0;
	private static $fail_count = 0;

	public static function ok() {}
	/**
	 *
	 *
	 * @param $exp1 needle
	 * @param $exp2 expected value
	 */
	public static function is($exp1, $exp2, $title) {
		if(is_object($exp1) || is_object($exp2)) {
			$result = $exp1 === $exp2;
		}else if(is_float($exp1) && is_float($exp2)) {
			$result = abs($exp1 - $exp2) < self::EPSILON;
		}else{
			$result = $exp1 == $exp2;
		}
		static::show_result($result, $title);
		if(!$result) {
			static::show_error(sprintf('got: %s, expected: %s', var_export($exp1, true), var_export($exp2, true)));
		}
		return $result;
	}

	public static function exp_ok($exp, $title) {
		$result = (bool)$exp;
		static::show_result($result, $title);
		return $result;
	}

	public static function is_fail() {
		return static::$fail_count > 0;
	}
	private static function show_result($result, $title) {
		if($result) {
			static::$pass_count++;
			Console::println('#' . ++static::$count . ' Pass - ' . $title, Console::GREEN);
		}else{
			static::$fail_count++;
			Console::println('#' . ++static::$count . ' Fail - ' . $title, Console::RED, Console::BOLD);
		}
	}
	private static function show_error($message) {
		Console::println(str_repeat(' ', strlen(static::$count) + 2) . $message);
	}
}


text:
package com.breadwallet.corenative.crypto;

public enum BRCryptoStatus {

    CRYPTO_SUCCESS {
        @Override
        public int toCore() {
            return CRYPTO_SUCCESS_VALUE;
        }
    },
    CRYPTO_ERROR_FAILED {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_FAILED_VALUE;
        }
    },

    // Reference access
    CRYPTO_ERROR_UNKNOWN_NODE {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_NODE_VALUE;
        }
    },
    CRYPTO_ERROR_UNKNOWN_TRANSFER {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_TRANSFER_VALUE;
        }
    },
    CRYPTO_ERROR_UNKNOWN_ACCOUNT {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_ACCOUNT_VALUE;
        }
    },
    CRYPTO_ERROR_UNKNOWN_WALLET {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_WALLET_VALUE;
        }
    },
    CRYPTO_ERROR_UNKNOWN_BLOCK {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_BLOCK_VALUE;
        }
    },
    CRYPTO_ERROR_UNKNOWN_LISTENER {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_UNKNOWN_LISTENER_VALUE;
        }
    },

    // Node
    CRYPTO_ERROR_NODE_NOT_CONNECTED {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_NODE_NOT_CONNECTED_VALUE;
        }
    },

    // Transfer
    CRYPTO_ERROR_TRANSFER_HASH_MISMATCH {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_TRANSFER_HASH_MISMATCH_VALUE;
        }
    },
    CRYPTO_ERROR_TRANSFER_SUBMISSION {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_TRANSFER_SUBMISSION_VALUE;
        }
    },

    // Numeric
    CRYPTO_ERROR_NUMERIC_PARSE {
        @Override
        public int toCore() {
            return CRYPTO_ERROR_NUMERIC_PARSE_VALUE;
        }
    };

    private static final int CRYPTO_SUCCESS_VALUE                       = 0;
    private static final int CRYPTO_ERROR_FAILED_VALUE                  = 1;

    private static final int CRYPTO_ERROR_UNKNOWN_NODE_VALUE            = 10000;
    private static final int CRYPTO_ERROR_UNKNOWN_TRANSFER_VALUE        = 10001;
    private static final int CRYPTO_ERROR_UNKNOWN_ACCOUNT_VALUE         = 10002;
    private static final int CRYPTO_ERROR_UNKNOWN_WALLET_VALUE          = 10003;
    private static final int CRYPTO_ERROR_UNKNOWN_BLOCK_VALUE           = 10004;
    private static final int CRYPTO_ERROR_UNKNOWN_LISTENER_VALUE        = 10005;

    private static final int CRYPTO_ERROR_NODE_NOT_CONNECTED_VALUE      = 20000;

    private static final int CRYPTO_ERROR_TRANSFER_HASH_MISMATCH_VALUE  = 30000;
    private static final int CRYPTO_ERROR_TRANSFER_SUBMISSION_VALUE     = 30001;

    private static final int CRYPTO_ERROR_NUMERIC_PARSE_VALUE           = 40000;

    public static BRCryptoStatus fromCore(int nativeValue) {
        switch (nativeValue) {
            case CRYPTO_SUCCESS_VALUE:                      return CRYPTO_SUCCESS;
            case CRYPTO_ERROR_FAILED_VALUE:                 return CRYPTO_ERROR_FAILED;

            case CRYPTO_ERROR_UNKNOWN_NODE_VALUE:           return CRYPTO_ERROR_UNKNOWN_NODE;
            case CRYPTO_ERROR_UNKNOWN_TRANSFER_VALUE:       return CRYPTO_ERROR_UNKNOWN_TRANSFER;
            case CRYPTO_ERROR_UNKNOWN_ACCOUNT_VALUE:        return CRYPTO_ERROR_UNKNOWN_ACCOUNT;
            case CRYPTO_ERROR_UNKNOWN_WALLET_VALUE:         return CRYPTO_ERROR_UNKNOWN_WALLET;
            case CRYPTO_ERROR_UNKNOWN_BLOCK_VALUE:          return CRYPTO_ERROR_UNKNOWN_BLOCK;
            case CRYPTO_ERROR_UNKNOWN_LISTENER_VALUE:       return CRYPTO_ERROR_UNKNOWN_LISTENER;

            case CRYPTO_ERROR_NODE_NOT_CONNECTED_VALUE:     return CRYPTO_ERROR_NODE_NOT_CONNECTED;

            case CRYPTO_ERROR_TRANSFER_HASH_MISMATCH_VALUE: return CRYPTO_ERROR_TRANSFER_HASH_MISMATCH;
            case CRYPTO_ERROR_TRANSFER_SUBMISSION_VALUE:    return CRYPTO_ERROR_TRANSFER_SUBMISSION;

            case CRYPTO_ERROR_NUMERIC_PARSE_VALUE:          return CRYPTO_ERROR_NUMERIC_PARSE;
            default: throw new IllegalArgumentException("Invalid core value");
        }
    }

    public abstract int toCore();
}


text:
package models

import (
	"strings"

	"github.com/jinzhu/gorm"
	"github.com/qor/l10n"
	"github.com/qor/publish"
	"github.com/qor/validations"
	"github.com/qor/sorting"
)

type Size struct {
	gorm.Model
	l10n.Locale
	publish.Status
	sorting.Sorting
	Name string
	Code string `l10n:"sync"`
}

func (size Size) Validate(db *gorm.DB) {
	if strings.TrimSpace(size.Name) == "" {
		db.AddError(validations.NewError(size, "Name", "Name can not be empty"))
	}

	if strings.TrimSpace(size.Code) == "" {
		db.AddError(validations.NewError(size, "Code", "Code can not be empty"))
	}
}


text:
<?php
declare(strict_types=1);

namespace SwagImportExport\Components\Utils;

class DataHelper
{
    /**
     * This function strips sql commands from the
     * string like "as" to get a "cleaned" value for the column
     * and the in the query used alias.
     *
     * example: 'customer.number as customerNumber' results in ['customerNumber', 'number']
     */
    public static function generateMappingFromColumns(string $column): array
    {
        if (!\preg_match('/(?<=as ).*/', $column, $alias)) {
            return [];
        }
        $alias = \trim($alias[0]);

        \preg_match("/(?<=\.).*?(?= as|\W)/", $column, $name);
        $name = \trim($name[0]);

        return [$alias, $name];
    }

    public static function formatFileSize(int $bytes): string
    {
        if ($bytes > 0) {
            $unit = (int) \log($bytes, 1024);

            $units = ['B', 'KB', 'MB', 'GB'];

            if (\array_key_exists($unit, $units) === true) {
                return \sprintf('%s %s', \number_format($bytes / \pow(1024, $unit), 2), $units[$unit]);
            }
        }

        return (string) $bytes;
    }
}


text:
package com.huawei.streaming.cql;

import com.huawei.streaming.cql.exception.CQLException;
import com.huawei.streaming.exception.ErrorCode;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;

import org.junit.Test;

import com.huawei.streaming.cql.parser.ApplicationParseTest;

import static org.junit.Assert.fail;

/**
 * 命令行客户端测试用例
 *
 */
public class CQLClientTest
{
    /**
     * 最基本的文件路径
     */
    private static final String BASICPATH = File.separator + "cqlclient" + File.separator;

    /**
     * 原始SQL文件路径
     */
    private static String inPutDir = null;

    /**
     * 测试用例
     *
     */
    @Test
    public void testLoadFile()
        throws Exception
    {
        setDir();
        String f = inPutDir + "simple" + CQLTestCommons.INPUT_POSTFIX;
        String[] arg = {"-f", f};

        int result = CQLSessionState.STATE_OK;
        CQLClient client = new CQLClient();

        result = client.initSessionState();
        if (result != CQLSessionState.STATE_OK)
        {
            System.exit(result);
        }

        if (!client.parseArgs(arg))
        {
            System.exit(CQLSessionState.STATE_NORMAL_EXIT);
        }

        result = client.executeDriver();
        assertTrue(result == 0);
    }

    /**
     * 测试用例
     *
     */
    @Test
    public void testSubmit()
        throws IOException, ReflectiveOperationException
    {
        setDir();
        String f = inPutDir + "localSubmit2" + CQLTestCommons.INPUT_POSTFIX;
        String[] arg = {"-f", f};

        int result = CQLSessionState.STATE_OK;
        CQLClient client = new CQLClient();

        result = client.initSessionState();
        if (result != CQLSessionState.STATE_OK)
        {
            System.exit(result);
        }

        if (!client.parseArgs(arg))
        {
            System.exit(CQLSessionState.STATE_NORMAL_EXIT);
        }

        try
        {
            Method processFileMethod = client.getClass().getDeclaredMethod("processFile", String.class);
            processFileMethod.setAccessible(true);
            processFileMethod.invoke(client, f);
            client.executeDriver();
        }
        catch (IOException e)
        {
            throw e;
        }
        catch (InvocationTargetException e)
        {
            if (e.getTargetException() instanceof CQLException)
            {
                assertEquals(((CQLException)e.getTargetException()).getErrorCode(), ErrorCode.TOP_ONE_FILE_ONE_TOP);
                return;
            }
            throw e;
        }
        catch (SecurityException e)
        {
            throw e;
        }

        fail("submit test execute failed.");
    }

    private static void setDir()
        throws UnsupportedEncodingException
    {
        String classPath = ApplicationParseTest.class.getResource("/").getPath();
        classPath = URLDecoder.decode(classPath, "UTF-8");
        inPutDir = classPath + BASICPATH;
    }
}


text:
namespace boomhs
{
class Camera;

struct WorldOrientation
{
  glm::vec3 forward, up;

  glm::vec3 right() const { return glm::cross(forward, up); }
};

class WorldObject
{
  EntityID          eid_;
  EntityRegistry*   registry_;
  WorldOrientation const* world_orientation_;

public:
  WorldObject(EntityID, EntityRegistry&, WorldOrientation const&);
  NO_COPY(WorldObject);
  MOVE_DEFAULT(WorldObject);

  // The "local" vectors are the object's world vectors multiplied with the object's rotation.
  //
  // The direction the object face's, normalized.
  glm::vec3 eye_forward() const;
  glm::vec3 eye_up() const;
  glm::vec3 eye_backward() const { return -eye_forward(); }

  glm::vec3 eye_left() const { return -eye_right(); }
  glm::vec3 eye_right() const { return glm::normalize(glm::cross(eye_forward(), eye_up())); }
  glm::vec3 eye_down() const { return -eye_up(); }

  // The "world" vectors are the the 3 Axis unit vector (X_UNIT_VECTOR, Y_UNIT_VECTOR,
  // Z_UNIT_VECTOR) translated to the object's position.
  //glm::vec3 world_forward() const { return forward_; }
  //glm::vec3 world_up() const { return up_; }
  //glm::vec3 world_backward() const { return -world_forward(); }

  //glm::vec3 world_left() const { return -world_right(); }
  //glm::vec3 world_right() const { return glm::normalize(glm::cross(world_forward(), world_up())); }
  //glm::vec3 world_down() const { return -world_up(); }

  std::string display() const;

  Transform&       transform() { return registry_->get<Transform>(eid_); }
  Transform const& transform() const { return registry_->get<Transform>(eid_); }

  glm::quat        orientation() const { return transform().rotation; }
  glm::vec3 const& world_position() const;

  WorldObject& move(glm::vec3 const&);

  void rotate_degrees(float const, math::EulerAxis);
  void rotate_to_match_camera_rotation(Camera const&);

  void move_to(glm::vec3 const& pos) { transform().translation = pos; }
  void move_to(float const x, float const y, float const z) { move_to(glm::vec3{x, y, z}); }

  glm::mat4 model_matrix() const { return transform().model_matrix(); }
};

} // namespace boomhs


text:
<!DOCTYPE html>

    <title> About </title>
    <link rel="stylesheet" href="stylesheet.css">

         Eric L. Chen
        About
        Projects

 COMING SOON!


text:
(Arduino Motor Shield Library)
==============================
This library is a basic driver for Arduino Motor Shield R3 (http://arduino.cc/en/Main/ArduinoMotorShieldR3)

## Overview:
This library help you to use the Arduino Motor Shield R3 in your Arduino projects.
This motor shield library controls two DC motors with a L298 H-bridge that can drive up to 2 amps per channel.
see http://arduino.cc/en/Main/ArduinoMotorShieldR3 for details.

## Features:
  * Set the motor at a desired speed: range 0 up to 255
  * Brake the motor
  * Stop the motor
  * Release the motor
  * Throttle the motor (Up and Down)
  * Support you to programming easy, using a lot of "Keyworks"

## Library Usage:
  * Download the source
  * Place the "ArduMotorShield Library" folder in your Arduino1.1+ "libraries" folder ( details: http://arduino.cc/en/Guide/Libraries)
  * Open example sketch: "file-->Examples-->ArduMotorShield-->TestMotorA" ( or another you want )
  * Connect the Arduino Motor Shield R3 to your Arduino UNO ( remember connect Vcc and GND on the shield to an extra power supply )
  * Connect your Arduino UNO, compile & upload the code
  * The motor should be running as described in the examples

## Version History:
  * Version 0.1: The first functional Tested version


text:
using System;
using Nancy.ErrorHandling;

namespace Nancy.Testing
{
    public class PassThroughStatusCodeHandler : IStatusCodeHandler
    {
        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
        {
            if (!context.Items.ContainsKey(NancyEngine.ERROR_EXCEPTION))
            {
                return false;
            }

            var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;

            return statusCode == HttpStatusCode.InternalServerError && exception != null;
        }

        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            throw new Exception("ConfigurableBootstrapper Exception", context.Items[NancyEngine.ERROR_EXCEPTION] as Exception);
        }
    }
}


text:
#import "NSObject.h"

@class WKConnection;

@interface WKWebProcessPlugInController : NSObject
{
    struct RetainPtr<id<WKWebProcessPlugIn>> _principalClassInstance;
    struct WKRetainPtr<const OpaqueWKBundle *> _bundleRef;
    struct HashMap<const OpaqueWKBundlePage *, WTF::RetainPtr<WKWebProcessPlugInBrowserContextController *>, WTF::PtrHash<const OpaqueWKBundlePage *>, WTF::HashTraits<const OpaqueWKBundlePage *>, WTF::HashTraits<WTF::RetainPtr<WKWebProcessPlugInBrowserContextController *>>> _bundlePageWrapperCache;
    struct RetainPtr<WKConnection *> _connectionWrapper;
}

- (id).cxx_construct;
- (void).cxx_destruct;
@property(readonly) WKConnection *connection;

@end


text:
(function() {
    'use strict';

    angular.module('app', [
        'ngRoute',
        'app.config'
    ]);
})();
(function() {
    'use strict';

    angular.module('app.config', []).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'app/components/home/homeView.html',
                controller: 'homeController'
            }).
            when('/about', {
                templateUrl: 'app/components/about/aboutView.html',
                controller: 'aboutController'
            }).
            otherwise({
                redirectTo: '/'
            });
    }]);
})();
(function() {
'use strict';

angular.module('app').
controller('aboutController', [
'$scope',
function($scope) {
    $scope.title = 'About';
}]);

})();
(function() {
'use strict';

angular.module('app').
controller('homeController', [
'$scope',
function($scope) {
    $scope.title = 'Home';
}]);

})();
(function() {
'use strict';

angular.module('app').
directive('pageFooter', [

function() {

    return {
        templateUrl: 'app/shared/footer/footerView.html',
        restrict: 'A'
    }

}]);

})();
(function() {
'use strict';

angular.module('app').
directive('pageHeader', [

function() {

    return {
        templateUrl: 'app/shared/header/headerView.html',
        restrict: 'A'
    }

}]);

})();


text:
import collections
from pynhost import api, commands, constants, dynamic

class CommandHistory:
    def __init__(self):
        self.commands = collections.deque(maxlen=constants.MAX_HISTORY_LENGTH)

    def run_command(self, command):
        pos = len(self.commands)
        self.commands.append(command)
        if pos == len(self.commands):
            pos -= 1
        self.execute_command(pos, -1, -1)
        # remove all action lists with only repeat elements
        command.remove_repeats()
        if not command.action_lists:
            self.commands.pop()

    def execute_command(self, command_pos, action_list_end, action_end):
        if command_pos < 0:
            return
        for i, action_list in enumerate(self.commands[command_pos].action_lists):
            if i == action_list_end:
                self.execute_actions(command_pos, i, action_end)
            else:
                self.execute_actions(command_pos, i, -1)

    def execute_actions(self, command_pos, action_list_pos, stop):
        assert min(command_pos, action_list_pos) >= 0
        action_list = self.commands[command_pos].action_lists[action_list_pos]
        for i, action in enumerate(action_list.actions):
            if i == stop:
                return
            if not self.execute_string_or_func(action):
                if isinstance(action, int):
                    self.repeat_previous_action_list(action, command_pos, action_list_pos, i)
                elif isinstance(action, dynamic.RepeatCommand):
                    count = action.count.evaluate(action_list.rule_match) if \
                    isinstance(action.count, dynamic.Num) else count
                    for i in range(count):
                        self.execute_command(command_pos - 1, -1, -1)

    def execute_string_or_func(self, action):
        if isinstance(action, str):
            api.send_string(action)
            return True
        elif isinstance(action, tuple):
            action[0](*action[1], **action[2])
            return True
        return False

    def repeat_previous_action_list(self, num, command_pos, action_list_pos, action_pos):
        if max(command_pos, action_list_pos, action_pos) == 0:
            return
        for i in range(num):
            if action_pos > 0:
                self.execute_actions(command_pos, action_list_pos, action_pos)
            elif action_list_pos > 0:
                self.execute_actions(command_pos, action_list_pos - 1, -1)
            else:
                self.execute_actions(command_pos - 1, len(self.commands[command_pos - 1].action_lists) - 1, -1)


text:
/**
 * Persian-Datepicker
 * @author Reza Babakhani
 */
(function ($) {
    $.fn.persianDatepicker = $.fn.pDatepicker = function (options) {
        var args = Array.prototype.slice.call(arguments), output = this;
        if (!this) {
            $.error("Invalid selector");
        }
        $(this).each(function () {
            // encapsulation Args
            var emptyArr = new Array, tempArg = args.concat(emptyArr), dp = $(this).data("datepicker");
            if (dp && typeof tempArg[0] == "string") {
                var funcName = tempArg[0], funcArgs = tempArg.splice(0, 1);
                output = dp[funcName](tempArg[0]);
            } else {
                this.pDatePicker = new Datepicker(this, options);
            }
        });
        return output;
    };
})(jQuery);


text:
package org.apache.hadoop.security;

import org.apache.hadoop.thirdparty.com.google.common.collect.Iterators;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.alias.CredentialProvider;
import org.apache.hadoop.security.alias.CredentialProviderFactory;
import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Test;

import javax.naming.AuthenticationException;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static org.apache.hadoop.security.LdapGroupsMapping.BIND_PASSWORD_ALIAS_SUFFIX;
import static org.apache.hadoop.security.LdapGroupsMapping.BIND_PASSWORD_FILE_SUFFIX;
import static org.apache.hadoop.security.LdapGroupsMapping.BIND_PASSWORD_SUFFIX;
import static org.apache.hadoop.security.LdapGroupsMapping.BIND_USERS_KEY;
import static org.apache.hadoop.security.LdapGroupsMapping.BIND_USER_SUFFIX;
import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_NUM_ATTEMPTS_KEY;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Test functionality for switching bind user information if
 * AuthenticationExceptions are encountered.
 */
public class TestLdapGroupsMappingWithBindUserSwitch
    extends TestLdapGroupsMappingBase {

  private static final String TEST_USER_NAME = "some_user";

  @Test
  public void testIncorrectConfiguration() {
    // No bind user configured for user2
    Configuration conf = getBaseConf();
    conf.set(BIND_USERS_KEY, "user1,user2");
    conf.set(BIND_USERS_KEY + ".user1" + BIND_USER_SUFFIX, "bindUsername1");

    LdapGroupsMapping groupsMapping = new LdapGroupsMapping();
    try {
      groupsMapping.setConf(conf);
      groupsMapping.getGroups(TEST_USER_NAME);
      fail("Should have failed with RuntimeException");
    } catch (RuntimeException e) {
      GenericTestUtils.assertExceptionContains(
          "Bind username or password not configured for user: user2", e);
    }
  }

  @Test
  public void testBindUserSwitchPasswordPlaintext() throws Exception {
    Configuration conf = getBaseConf();
    conf.set(BIND_USERS_KEY, "user1,user2");
    conf.set(BIND_USERS_KEY + ".user1" + BIND_USER_SUFFIX, "bindUsername1");
    conf.set(BIND_USERS_KEY + ".user2" + BIND_USER_SUFFIX, "bindUsername2");

    conf.set(BIND_USERS_KEY + ".user1" + BIND_PASSWORD_SUFFIX, "bindPassword1");
    conf.set(BIND_USERS_KEY + ".user2" + BIND_PASSWORD_SUFFIX, "bindPassword2");

    doTestBindUserSwitch(conf, 1,
        Arrays.asList("bindUsername1", "bindUsername2"),
        Arrays.asList("bindPassword1", "bindPassword2"));
  }

  @Test
  public void testBindUserSwitchPasswordFromAlias() throws Exception {
    Configuration conf = getBaseConf();
    conf.set(BIND_USERS_KEY, "joe,lukas");
    conf.set(BIND_USERS_KEY + ".joe" + BIND_USER_SUFFIX, "joeBindUsername");
    conf.set(BIND_USERS_KEY + ".lukas" + BIND_USER_SUFFIX, "lukasBindUsername");

    conf.set(BIND_USERS_KEY + ".joe" + BIND_PASSWORD_ALIAS_SUFFIX,
        "joeBindPasswordAlias");
    conf.set(BIND_USERS_KEY + ".lukas" + BIND_PASSWORD_ALIAS_SUFFIX,
        "lukasBindPasswordAlias");

    setupCredentialProvider(conf);
    createCredentialForAlias(conf, "joeBindPasswordAlias", "joeBindPassword");
    createCredentialForAlias(conf, "lukasBindPasswordAlias",
        "lukasBindPassword");

    // Simulate 2 failures to test cycling through the bind users
    List<String> expectedBindUsers = Arrays.asList("joeBindUsername",
        "lukasBindUsername", "joeBindUsername");
    List<String> expectedBindPasswords = Arrays.asList("joeBindPassword",
        "lukasBindPassword", "joeBindPassword");

    doTestBindUserSwitch(conf, 2, expectedBindUsers, expectedBindPasswords);
  }

  @Test
  public void testBindUserSwitchPasswordFromFile() throws Exception {
    Configuration conf = getBaseConf();
    conf.setInt(LDAP_NUM_ATTEMPTS_KEY, 10);

    conf.set(BIND_USERS_KEY, "bob,alice");
    conf.set(BIND_USERS_KEY + ".bob" + BIND_USER_SUFFIX, "bobUsername");
    conf.set(BIND_USERS_KEY + ".alice" + BIND_USER_SUFFIX, "aliceUsername");

    conf.set(BIND_USERS_KEY + ".bob" + BIND_PASSWORD_FILE_SUFFIX,
        createPasswordFile("bobPasswordFile1.txt", "bobBindPassword"));
    conf.set(BIND_USERS_KEY + ".alice" + BIND_PASSWORD_FILE_SUFFIX,
        createPasswordFile("alicePasswordFile2.txt", "aliceBindPassword"));

    // Simulate 4 failures to test cycling through the bind users
    List<String> expectedBindUsers = Arrays.asList("bobUsername",
        "aliceUsername", "bobUsername", "aliceUsername", "bobUsername");
    List<String> expectedBindPasswords = Arrays.asList("bobBindPassword",
        "aliceBindPassword", "bobBindPassword", "aliceBindPassword",
        "bobBindPassword");

    doTestBindUserSwitch(conf, 4, expectedBindUsers, expectedBindPasswords);
  }

  private void setupCredentialProvider(Configuration conf) {
    File testDir = GenericTestUtils.getTestDir();
    final Path jksPath = new Path(testDir.toString(), "test.jks");
    final String ourUrl =
        JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri();

    File file = new File(testDir, "test.jks");
    file.delete();
    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, ourUrl);
  }

  private void createCredentialForAlias(
      Configuration conf, String alias, String password) throws Exception {
    CredentialProvider provider =
        CredentialProviderFactory.getProviders(conf).get(0);
    char[] bindpass = password.toCharArray();

    // Ensure that we get null when the key isn't there
    assertNull(provider.getCredentialEntry(alias));

    // Create credential for the alias
    provider.createCredentialEntry(alias, bindpass);
    provider.flush();

    // Make sure we get back the right key
    assertArrayEquals(bindpass, provider.getCredentialEntry(
        alias).getCredential());
  }

  private String createPasswordFile(String filename, String password)
      throws Exception {
    File testDir = GenericTestUtils.getTestDir();
    testDir.mkdirs();
    File secretFile = new File(testDir, filename);
    Writer writer = new FileWriter(secretFile);
    writer.write(password);
    writer.close();
    return secretFile.getPath();
  }

  private void doTestBindUserSwitch(
      Configuration conf, Integer numFailures,
      List<String> expectedBindUsers,
      List<String> expectedBindPasswords) throws NamingException {
    doTestBindUserSwitch(conf, numFailures, Iterators.cycle(expectedBindUsers),
        Iterators.cycle(expectedBindPasswords));
  }

  /**
   *
   * @param conf Configuration to be used
   * @param numFailures number of AuthenticationException failures to simulate
   * @param expectedBindUsers expected sequence of distinguished user names
   *                          when binding to LDAP
   * @param expectedBindPasswords expected sequence of passwords to be used when
   *                              binding to LDAP
   * @throws NamingException from DirContext.search()
   */
  private void doTestBindUserSwitch(
      Configuration conf, Integer numFailures,
      Iterator<String> expectedBindUsers,
      Iterator<String> expectedBindPasswords) throws NamingException {

    DummyLdapCtxFactory.setExpectedBindUser(expectedBindUsers.next());
    DummyLdapCtxFactory.setExpectedBindPassword(expectedBindPasswords.next());

    final AtomicInteger failuresLeft = new AtomicInteger(numFailures);

    when(getContext().search(anyString(), anyString(), any(Object[].class),
        any(SearchControls.class))).thenAnswer(invocationOnMock -> {
          if (failuresLeft.get() > 0) {
            DummyLdapCtxFactory.setExpectedBindUser(expectedBindUsers.next());
            DummyLdapCtxFactory.setExpectedBindPassword(
                expectedBindPasswords.next());
            failuresLeft.decrementAndGet();
            throw new AuthenticationException();
          }
          // Return userNames for the first successful search()
          if (failuresLeft.getAndDecrement() == 0) {
            return getUserNames();
          }
          // Return groupNames for the second successful search()
          return getGroupNames();
        });

    LdapGroupsMapping groupsMapping = new LdapGroupsMapping();
    groupsMapping.setConf(conf);

    List<String> groups = groupsMapping.getGroups(TEST_USER_NAME);
    assertEquals(Arrays.asList("group1", "group2"), groups);

    // There will be one search() call for each failure and
    // 2 calls for the successful case; one for retrieving the
    // user and one for retrieving their groups.
    int numExpectedSearchCalls = numFailures + 2;
    verify(getContext(), times(numExpectedSearchCalls)).search(anyString(),
        anyString(), any(Object[].class), any(SearchControls.class));
  }
}


text:
A progress bar directive that is focused on providing feedback on the progress of a workflow or action.

It supports multiple (stacked) bars into the same `<progress>` element or a single `<progressbar>` elemtnt with optional `max` attribute and transition animations.

### Settings ###

#### `<progressbar>` ####

 * `value` <i class="glyphicon glyphicon-eye-open"></i>
 	:
 	The current value of progress completed.

 * `type`
 	_(Default: null)_ :
 	Style type. Possible values are 'success', 'warning' etc.

 * `max`
 	_(Default: 100)_ :
 	A number that specifies the total value of bars that is required.

 * `animate`
 	_(Default: true)_ :
 	Whether bars use transitions to achieve the width change.

### Stacked ###

Place multiple `<bars>` into the same `<progress>` element to stack them.
`<progress>` supports `max` and `animate` &  `<bar>` supports  `value` and `type` attributes.


text:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace HttpService.Controllers
{
    [Route("api/[controller]")]
    public class FailuresController : Controller
    {
        [Route("Exception")]
        [HttpGet, HttpPost]
        public string Exception()
        {
            throw new InvalidOperationException("this is an exception");
        }

        [Route("Delay")]
        [HttpGet, HttpPost]
        public async Task<string> Delay(int seconds)
        {
            await Task.Delay(TimeSpan.FromSeconds(seconds));
            return $"Response after {seconds} seconds";
        }

        [Route("NotFoundWithHeader")]
        [HttpGet]
        public IActionResult NotFoundWithHeader()
        {
            Response.Headers["X-ServiceFabric"] = "ResourceNotFound";

            return NotFound();
        }
    }
}


text:
package com.github.robozonky.internal.state;

import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.SoftAssertions.assertSoftly;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import com.github.robozonky.internal.Defaults;

class FileBackedStateStorageTest {

    private static final Logger LOGGER = LogManager.getLogger(FileBackedStateStorageTest.class);

    private final File f = new File(UUID.randomUUID()
        .toString() + ".state");
    private final FileBackedStateStorage s = new FileBackedStateStorage(f);

    @Test
    @DisplayName("Storing empty string means no value.")
    void valueEmpty() {
        s.setValue("section", "key", "     ");
        assertThat(s.getValue("section", "key")).isEmpty();
    }

    @Test
    @DisplayName("No sections are available.")
    void sectionsDoNotThrow() {
        assertThat(s.getSections()).isEmpty();
    }

    @Test
    @DisplayName("Random section has no keys.")
    void keysDoNotThrow() {
        assertThat(s.getKeys(UUID.randomUUID()
            .toString())).isEmpty();
    }

    @Test
    @DisplayName("Random section can be unset without throwing.")
    void sectionUnset() {
        s.unsetValues(UUID.randomUUID()
            .toString());
    }

    @Test
    @DisplayName("Random value can be unset without throwing.")
    void valueUnset() {
        s.unsetValue(UUID.randomUUID()
            .toString(),
                UUID.randomUUID()
                    .toString());
    }

    @Test
    @DisplayName("Random key has no value.")
    void valuesDoNotThrow() {
        assertThat(s.getValue(UUID.randomUUID()
            .toString(),
                UUID.randomUUID()
                    .toString())).isEmpty();
    }

    @AfterEach
    @BeforeEach
    void deleteState() {
        s.destroy();
    }

    @Nested
    @DisplayName("When the JSON file is corrupted")
    class CorruptionTesting {

        private final Path corrupted = Path.of(f.getAbsolutePath() + ".corrupted");

        @BeforeEach
        void corruptStateFile() throws IOException {
            Files.write(f.toPath(), "This is not a valid JSON.".getBytes(Defaults.CHARSET));
        }

        @Test
        @DisplayName("check that corruption is detected and the file moved out of the way.")
        void detectsAndFixesCorruption() {
            assertThat(s.getSections()).isEmpty(); // New empty state is read.
            assertThat(corrupted).exists(); // Old state file was moved to an old location.
        }

        @AfterEach
        void deleteCorruptStateFile() throws IOException {
            Files.deleteIfExists(corrupted);
        }

    }

    @Nested
    @DisplayName("When value is added to a section")
    class StorageTesting {

        @BeforeEach
        void setValue() {
            s.setValue("section", "key", "value");
        }

        @Test
        @DisplayName("is properly persisted without storing.")
        void persistence() { // strings are not reused to ensure that this typical use case works
            assertSoftly(softly -> {
                softly.assertThat(s.getValue("section", "key"))
                    .contains("value");
                softly.assertThat(s.getKeys("section"))
                    .containsOnly("key");
                softly.assertThat(s.getSections())
                    .containsOnly("section");
            });
        }

        @Test
        @DisplayName("can be removed as a single value.")
        void unsetValue() {
            s.unsetValue("section", "key");
            assertSoftly(softly -> {
                softly.assertThat(s.getValue("section", "key"))
                    .isEmpty();
                softly.assertThat(s.getKeys("section"))
                    .isEmpty();
                softly.assertThat(s.getSections())
                    .containsOnly("section");
            });
            assertThat(s.store()).isTrue();
        }

        @Test
        @DisplayName("can be removed with its section.")
        void unsetSection() {
            s.unsetValues("section");
            assertSoftly(softly -> {
                softly.assertThat(s.getValue("section", "key"))
                    .isEmpty();
                softly.assertThat(s.getKeys("section"))
                    .isEmpty();
                softly.assertThat(s.getSections())
                    .isEmpty();
            });
        }

        @Test
        @DisplayName("doesn't interfere with same in another section.")
        void nonInterference() { // strings are not reused to ensure that this typical use case works
            s.setValue("section2", "key", "value2");
            assertSoftly(softly -> {
                softly.assertThat(s.getValue("section", "key"))
                    .contains("value");
                softly.assertThat(s.getValue("section2", "key"))
                    .contains("value2");
                softly.assertThat(s.getKeys("section"))
                    .containsOnly("key");
                softly.assertThat(s.getKeys("section2"))
                    .containsOnly("key");
                softly.assertThat(s.getSections())
                    .containsOnly("section", "section2");
            });
        }

        @Nested
        @DisplayName("is stored and the file is re-read")
        class SurvivalTesting {

            @BeforeEach
            void storeValues() {
                s.store();
            }

            @Test
            @DisplayName("value survives into a new storage instance.")
            void survival() { // strings are not reused to ensure that this typical use case works
                final FileBackedStateStorage s2 = new FileBackedStateStorage(f);
                assertSoftly(softly -> {
                    softly.assertThat(s2.getValue("section", "key"))
                        .contains("value");
                    softly.assertThat(s2.getKeys("section"))
                        .containsOnly("key");
                    softly.assertThat(s2.getSections())
                        .containsOnly("section");
                });
            }

            @Test
            @DisplayName("unstored value can not be seen by the new instance.")
            void noWriteThrough() { // strings are not reused to ensure that this typical use case works
                s.setValue("section", "key2", "value2"); // store() not called
                final FileBackedStateStorage s2 = new FileBackedStateStorage(f);
                assertSoftly(softly -> { // only the stored values are available
                    softly.assertThat(s2.getValue("section", "key"))
                        .contains("value");
                    softly.assertThat(s2.getKeys("section"))
                        .containsOnly("key");
                    softly.assertThat(s2.getSections())
                        .containsOnly("section");
                });
            }
        }

        @Nested
        @DisplayName("when the file can not be written")
        class ExceptionTesting {

            @BeforeEach
            void makeFileNotWritable() throws IOException {
                Files.write(f.toPath(), "{}".getBytes(Defaults.CHARSET));
                f.setReadOnly();
            }

            @Test
            @DisplayName("storing catches and processes the exception.")
            void handlesException() { // strings are not reused to ensure that this typical use case works
                s.setValue("section", "key2", "value2");
                assertThat(s.store()).isFalse();
            }
        }

    }
}


text:
<?php
use Nayjest\Grids\Components\TotalsRow;
/** @var TotalsRow $component */
?>
<tr>
    <?php foreach($columns as $column): ?>
        <td
            class="column-<?= $column->getName() ?>"
            <?= $column->isHidden()?'style="display:none"':'' ?>
            >
            <?php
            if ($component->uses($column)):
                $label = '';
                switch($component->getFieldOperation($column->getName())) {
                    case \Nayjest\Grids\Components\TotalsRow::OPERATION_SUM:
                        $label = '∑';
                        break;
                    case \Nayjest\Grids\Components\TotalsRow::OPERATION_COUNT:
                        $label = 'Count';
                        break;
                    case \Nayjest\Grids\Components\TotalsRow::OPERATION_AVG:
                        $label = 'Avg.';
                        break;
                }
                echo $label, ' ', $column->getValue($component);
            endif;
            ?>
        </td>
    <?php endforeach ?>
</tr>


text:
@implementation MPResources

+ (UIStoryboard *)notificationStoryboard {
    NSString *storyboardName = @"MPNotification~ipad";

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
        if (isLandscape) {
            storyboardName = @"MPNotification~iphonelandscape";
        } else {
            storyboardName = @"MPNotification~iphoneportrait";
        }
    }

    return [MPResources storyboardWithName:storyboardName];
}

+ (UIStoryboard *)surveyStoryboard {
    return [MPResources storyboardWithName:@"MPSurvey"];
}

+ (UIStoryboard *)storyboardWithName:(NSString *)name {
    return [UIStoryboard storyboardWithName:name bundle:[MPResources frameworkBundle]];
}

+ (NSBundle *)frameworkBundle {
    return [NSBundle bundleForClass:self.class];
}

+ (UIImage *)imageNamed:(NSString *)name {
    NSString *imagePath = [[MPResources frameworkBundle] pathForResource:name ofType:@"png"];
    return [UIImage imageWithContentsOfFile:imagePath];
}

@end


text:
#ifndef LOGGER_H
#define LOGGER_H

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_LOG4CXX
/* log4cxx */
#include "log4cxx/logger.h"
#include "log4cxx/basicconfigurator.h"
#include "log4cxx/propertyconfigurator.h"
#include "log4cxx/helpers/exception.h"

class Logger
{
public:
  Logger(const std::string &name) :
    mLogger(log4cxx::Logger::getLogger(name)) {}

  Logger(const std::wstring &name) :
    mLogger(log4cxx::Logger::getLogger(name)) {}

  log4cxx::LoggerPtr operator = (const Logger &logger)
  {
    return mLogger;
  }

  log4cxx::LoggerPtr operator -> (void)
  {
    return mLogger;
  }

private:
  log4cxx::LoggerPtr mLogger;
};

#else // no LOG4CXX available...

#include <iostream>

#ifdef HAVE_LOGGING
// macros to log all and everything to stderr...
#define LOGSTR "[Logging] - "
#define LOG4CXX_TRACE(logger, expression) std::cerr << LOGSTR << "TRACE " << expression << std::endl;
#define LOG4CXX_DEBUG(logger, expression) std::cerr << LOGSTR << "DEBUG " << expression << std::endl;
#define LOG4CXX_INFO(logger, expression)  std::cerr << LOGSTR << "INFO "  << expression << std::endl;
#define LOG4CXX_WARN(logger, expression)  std::cerr << LOGSTR << "WARN "  << expression << std::endl;
#define LOG4CXX_ERROR(logger, expression) std::cerr << LOGSTR << "ERROR " << expression << std::endl;
#define LOG4CXX_FATAL(logger, expression) std::cerr << LOGSTR << "FATAL " << expression << std::endl;
#else
// macros to log nothing...
#define LOG4CXX_TRACE(logger, expression)
#define LOG4CXX_DEBUG(logger, expression)
#define LOG4CXX_INFO(logger, expression)
#define LOG4CXX_WARN(logger, expression)
#define LOG4CXX_ERROR(logger, expression)
#define LOG4CXX_FATAL(logger, expression)
#endif // LOG2NIX_ACTIVE

class Logger
{
public:
  Logger(const std::string &name) {}
  Logger(const std::wstring &name) {}
};

#endif // HAVE_LOG4CXX

#endif // LOGGER_H


text:
<?php

	Class extension_color_chooser_field extends Extension{

		public function about(){
			return array('name' => 'Field: Color Chooser',
						 'version' => '1.1',
						 'release-date' => '2009-05-25',
						 'author' => array('name' => 'Josh Nichols',
										   'website' => 'http://www.joshnichols.com',
										   'email' => 'mrblank@gmail.com'),
						 'description'	=> 'A custom field extension for choosing colors.'
				 		);
		}

		public function uninstall(){
			$this->_Parent->Database->query("DROP TABLE `tbl_fields_colorchooser`");
		}

		public function install(){

			return $this->_Parent->Database->query("CREATE TABLE `tbl_fields_colorchooser` (
			  `id` int(11) unsigned NOT NULL auto_increment,
			  `field_id` int(11) unsigned NOT NULL,
			  PRIMARY KEY  (`id`),
			  UNIQUE KEY `field_id` (`field_id`)
			) TYPE=MyISAM");

		}

		public function getSubscribedDelegates() {
			return array(
				array(
					'page'		=> '/backend/',
					'delegate'	=> 'InitaliseAdminPageHead',
					'callback'	=> 'initaliseAdminPageHead'
				)
			);
		}

		public function initaliseAdminPageHead($context) {
			$page = $context['parent']->Page;

            $page->addScriptToHead(URL . '/extensions/color_chooser_field/assets/farbtastic.js', 3001);
            $page->addScriptToHead(URL . '/extensions/color_chooser_field/assets/color-chooser.js', 3002);
            $page->addStylesheetToHead(URL . '/extensions/color_chooser_field/assets/farbtastic.css', 'screen', 3003);
		}

	}

?>


text:
package org.mule.tooling.lang.dw.parser.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface WeaveLiteralExpression extends WeaveExpression {

}


text:
package server

import (
	"fmt"

	"github.com/Sirupsen/logrus"
	"github.com/containers/storage/storage"
	"golang.org/x/net/context"
	pb "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
)

// ImageStatus returns the status of the image.
func (s *Server) ImageStatus(ctx context.Context, req *pb.ImageStatusRequest) (*pb.ImageStatusResponse, error) {
	logrus.Debugf("ImageStatusRequest: %+v", req)
	image := ""
	img := req.GetImage()
	if img != nil {
		image = img.Image
	}
	if image == "" {
		return nil, fmt.Errorf("no image specified")
	}
	status, err := s.images.ImageStatus(s.imageContext, image)
	if err != nil {
		if err == storage.ErrImageUnknown {
			return &pb.ImageStatusResponse{}, nil
		}
		return nil, err
	}
	resp := &pb.ImageStatusResponse{
		Image: &pb.Image{
			Id:       status.ID,
			RepoTags: status.Names,
			Size_:    *status.Size,
		},
	}
	logrus.Debugf("ImageStatusResponse: %+v", resp)
	return resp, nil
}


text:
#ifndef FORMATION_HPP
#define FORMATION_HPP
#include "Position6DOF.hpp"
#include "ros/ros.h"
#include <vector>

/**
 * Class used for handling formation-movement.
 *
 * @author Carina Kübler, Dominik Kiefer
 */
class Formation {
public:
	Formation(int distance, int amount, Position6DOF *position);
	Formation();
	void setDistance(int distance);
	void setAmount(int amount);
	void setFormationPosition(Position6DOF *position);
	int getDistance();
	int getAmount();
	Position6DOF* getFormationPosition();

private:
	int distance;
	int amount;
	Position6DOF position[10];
};

#endif // FORMATION_HPP


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  def after_sign_in_path_for(resource)
    complaints_path
  end

  # check_authorization :unless => :devise_controller?  # This will raise an exception if authorization is not performed in an action.

end


text:
/*
 * This module implements a data structure holding some data and
 * related to an index.
 */

#include "chunk.h"
#include "xmalloc.h"
#include "cast.h"

typedef struct chunk_implementation_s {
  int         size;
  char* data;
  index_t i;
} chunk_implementation_t;

chunk_t chunk_create (size_t s, index_t i) {chunk_implementation_t* chunk = xmalloc (chunk_implementation_t);
  chunk->size = s; chunk->data = (char*) malloc (s);
  chunk->i = i;
  return chunk;
}

uint8_t* chunk_data (chunk_t c) {declare_as (chunk_implementation_t*, chunk, c); return (chunk->data);}

size_t chunk_size (chunk_t c) {declare_as (chunk_implementation_t*, chunk, c);return (chunk->size);}

index_t chunk_index (chunk_t c) {
  declare_as (chunk_implementation_t*, chunk, c);
  return (chunk->i);}


text:
SROOK_NESTED_NAMESPACE(srook, tuple, utility) {
SROOK_INLINE_NAMESPACE(v1)

namespace detail {

template <class>
struct rewrap;

template <class... Ts>
struct rewrap<std::tuple<Ts...>>
    : type_constant<srook::tmpl::vt::packer<Ts...>> {};

template <class L, class R>
struct rewrap<std::pair<L, R>>
    : type_constant<srook::tmpl::vt::packer<L, R>> {};

template <class F, std::size_t I, class Tuple>
struct return_type
    : srook::tmpl::vt::transfer<
        std::tuple,
        SROOK_DEDUCED_TYPENAME srook::tmpl::vt::concat<
            SROOK_DEDUCED_TYPENAME srook::tmpl::vt::concat<
                SROOK_DEDUCED_TYPENAME srook::tmpl::vt::take<I, SROOK_DEDUCED_TYPENAME rewrap<SROOK_DEDUCED_TYPENAME decay<Tuple>::type>::type>::type,
                SROOK_DEDUCED_TYPENAME invoke_result<SROOK_DEDUCED_TYPENAME decay<F>::type, SROOK_DEDUCED_TYPENAME std::tuple_element<I, SROOK_DEDUCED_TYPENAME decay<Tuple>::type>::type>::type
            >::type,
            SROOK_DEDUCED_TYPENAME srook::tmpl::vt::drop<I + 1, SROOK_DEDUCED_TYPENAME detail::rewrap<decay_t<Tuple>>::type>::type
        >::type
      > {};

#if !SROOK_CPP_LAMBDAS && SROOK_CPLUSPLUS < SROOK_CPLUSPLUS14_CONSTANT
template <class F, std::size_t I>
class intrinsic_lambda_nth : srook::utility::lambda_wrapper<F> {
    typedef srook::utility::lambda_wrapper<F> base_type;
public:
    SROOK_FORCE_INLINE SROOK_CONSTEXPR
    intrinsic_lambda_nth(F f) SROOK_NOEXCEPT(is_nothrow_constructive<base_type, F>::value)
        : base_type(srook::forward<F>(f)) {}

    template <class T, SROOK_REQUIRES(is_tuple<SROOK_DEDUCED_TYPENAME decay<T>::type>::value)>
    SROOK_CONSTEXPR SROOK_FORCE_INLINE
    SROOK_DEDUCED_TYPENAME detail::return_type<F, I, SROOK_DEDUCED_TYPENAME decay<T>::type>::type
    operator()(T&& tpl) SROOK_MEMFN_NOEXCEPT(detail::is_noexcept_type<F>::value)
    {
        return std::tuple_cat(take<I>(tpl), std::make_tuple(base_type::operator()(std::get<I>(tpl))), drop<I + 1>(tpl));
    }
};
#endif

} // namespace detail

template <std::size_t I, class F, SROOK_REQUIRES(is_callable<SROOK_DEDUCED_TYPENAME decay<F>::type>::value)>
#if SROOK_CPP_LAMBDAS && SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS14_CONSTANT
auto
#else
detail::intrinsic_lambda_nth<SROOK_DEDUCED_TYPENAME decay<F>::type, I>
#endif
nth(F&& fn) SROOK_NOEXCEPT(detail::is_noexcept_type<F>::value)
{
#if SROOK_CPP_LAMBDAS && SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS14_CONSTANT
    return
        [f = srook::forward<F>(fn)](auto&& tpl) SROOK_CXX17_CONSTEXPR
        noexcept(detail::is_noexcept_type<F>::value)
        -> SROOK_DEDUCED_TYPENAME detail::return_type<F, I, SROOK_DECLTYPE(tpl)>::type
        {
            return std::tuple_cat(srook::tuple::utility::take<I>(tpl), std::make_tuple(f(std::get<I>(tpl))), srook::tuple::utility::drop<I + 1>(tpl));
        };
#else
    return detail::intrinsic_lambda_nth<SROOK_DEDUCED_TYPENAME decay<F>::type, I>(srook::forward<F>(fn));
#endif
}

SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(utility, tuple, srook)
#endif


text:
		<?php _e('Custom CSS','ultimate-member'); ?> <?php $this->tooltip( __('Enter custom css that will be applied to this form only','ultimate-member'), 'e'); ?>
		<textarea name="_um_register_custom_css" id="_um_register_custom_css" class="tall"><?php echo $ultimatemember->query->get_meta_value('_um_register_custom_css', null, 'na' ); ?></textarea>


text:
/**
 * sessionAuth
 *
 * @module      :: Policy
 * @description :: Simple policy to allow any authenticated user
 *                 Assumes that your login action in one of your controllers sets `req.session.authenticated = true;`
 * @docs        :: http://sailsjs.org/#!/documentation/concepts/Policies
 *
 */
module.exports = function(req, res, next) {

  // User is allowed, proceed to the next policy,
  // or if this is the last policy, the controller+
  if (req.session.authenticated) {
    return next();
  }
  var errDescription = 'Please Login before continuing';
  // write review route
  if (req.url.indexOf('/write-review') !== -1) {
      errDescription = 'Please Login before you write a review';
  }

  // User is not allowed
  // (default res.forbidden() behavior can be overridden in `config/403.js`)
  if (req.method === "POST" || req.method === "PUT") {
    return res.forbidden('You are not permitted to perform this action.');
  }

  // User is not allowed
  // return user to this url
  req.session.flash =  {err: {
    description: errDescription
  }};
  req.session.returnUrl = req.url;
  console.log(req.session);
  return res.redirect('/admin');

};