text:
require 'test_helper'
require 'lotus/cli'
require 'lotus/commands/new'

describe Lotus::Commands::New do
  let(:opts)    { Hash.new }
  let(:env)     { Lotus::Environment.new(opts) }
  let(:command) { Lotus::Commands::New.new(app_name, env, cli) }
  let(:cli)     { Lotus::Cli.new }
  let(:architecture) { 'container' }

  def create_temporary_dir
    tmp = Pathname.new(@pwd = Dir.pwd).join('tmp/generators/new')
    tmp.rmtree if tmp.exist?
    tmp.mkpath

    Dir.chdir(tmp)
    @root = tmp.join(app_name)
  end

  def chdir_to_root
    Dir.chdir(@pwd)
  end

  before do
    create_temporary_dir
  end

  after do
    chdir_to_root
  end

  describe 'container architecture' do
    def container_options
      Hash[architecture: architecture, application: 'web', application_base_url: '/', lotus_head: false, database: 'filesystem']
    end

    let(:opts)     { container_options }
    let(:app_name) { 'chirp' }

    before do
      capture_io { command.start }
    end

    describe 'Gemfile' do
      it 'generates it' do
        content = @root.join('Gemfile').read
        content.must_match %(gem 'bundler')
        content.must_match %(gem 'rake')
        content.must_match %(gem 'lotusrb',       '#{ Lotus::VERSION }')
        content.must_match %(gem 'lotus-model',   '~> 0.4')
        content.must_match %(gem 'capybara')
      end

      describe 'lotus-head option' do
        let(:opts) { container_options.merge(lotus_head: true) }

        it 'generates it' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'bundler')
          content.must_match %(gem 'rake')
          content.must_match %(gem 'lotus-utils',       require: false, github: 'lotus/utils')
          content.must_match %(gem 'lotus-router',      require: false, github: 'lotus/router')
          content.must_match %(gem 'lotus-validations', require: false, github: 'lotus/validations')
          content.must_match %(gem 'lotus-helpers',     require: false, github: 'lotus/helpers')
          content.must_match %(gem 'lotus-controller',  require: false, github: 'lotus/controller')
          content.must_match %(gem 'lotus-view',        require: false, github: 'lotus/view')
          content.must_match %(gem 'lotus-model',       require: false, github: 'lotus/model')
          content.must_match %(gem 'lotusrb',                           github: 'lotus/lotus')
        end
      end

      describe 'minitest (default)' do
        it 'includes minitest' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'minitest')
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'includes rspec' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'rspec')
        end
      end

      describe 'production group' do
        it 'includes a server example' do
          content = @root.join('Gemfile').read
          content.must_match %(group :production do)
          content.must_match %(# gem 'puma')
        end
      end

      describe 'database option' do
        describe 'mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'includes mysql' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'mysql')
          end
        end

        describe 'mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'includes mysql2' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'mysql2')
          end
        end

        describe 'postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'includes pg' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'pg')
          end
        end

        describe 'postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'includes pg' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'pg')
          end
        end

        describe 'sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'includes sqlite3 gem' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'sqlite3')
          end
        end

        describe 'sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }

          it 'includes sqlite3 gem' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'sqlite3')
          end
        end
      end
    end

    describe 'Rakefile' do
      describe 'minitest (default)' do
        it 'generates it' do
          content = @root.join('Rakefile').read
          content.must_match %(Rake::TestTask.new)
          content.must_match %(t.pattern = 'spec/**/*_spec.rb')
          content.must_match %(t.libs    << 'spec')
          content.must_match %(task default: :test)
          content.must_match %(task spec: :test)
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'generates it' do
          content = @root.join('Rakefile').read
          content.must_match %(RSpec::Core::RakeTask.new(:spec))
          content.must_match %(task default: :spec)
        end
      end
    end

    describe 'config.ru' do
      it 'generates it' do
        content = @root.join('config.ru').read
        content.must_match %(require './config/environment')
        content.must_match %(run Lotus::Container.new)
      end
    end

    describe '.lotusrc' do
      describe 'minitest (default)' do
        it 'generates it' do
          content = @root.join('.lotusrc').read
          content.must_match %(architecture=container)
          content.must_match %(test=minitest)
          content.must_match %(template=erb)
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'generates it' do
          content = @root.join('.lotusrc').read
          content.must_match %(test=rspec)
        end
      end
    end

    describe '.gitignore' do
      it 'generates it' do
        content = @root.join('.gitignore').read
        content.must_match %(/db/chirp_development)
        content.must_match %(/db/chirp_test)
      end
    end

    describe 'config/environment.rb' do
      it 'generates it' do
        content = @root.join('config/environment.rb').read
        content.must_match %(require 'rubygems')
        content.must_match %(require 'bundler/setup')
        content.must_match %(require 'lotus/setup')
        content.must_match %(require_relative '../lib/chirp')

        content.must_match %(Lotus::Container.configure)
      end
    end

    describe '.env' do
      it 'generates it' do
        content = @root.join('.env').read
        content.must_match %(# Define ENV variables)
      end
    end

    describe '.env.development' do
      it 'generates it' do
        content = @root.join('.env.development').read
        content.must_match %(# Define ENV variables for development environment)
        content.must_match %(CHIRP_DATABASE_URL="file:///db/chirp_development")
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('.env.development').read
          content.must_match %(CHIRP_TWO_DATABASE_URL="file:///db/chirp-two_development")
        end
      end

      describe 'database option' do
        describe 'with mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }

          it 'generates db config for mysql' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="mysql://localhost/chirp_development")
          end
        end

        describe 'with mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }

          it 'generates db config for mysql2' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="mysql2://localhost/chirp_development")
          end
        end

        describe 'with postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'generates db config for postgresql' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_development")
          end
        end

        describe 'with postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates db config for postgres' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_development")
          end
        end

        describe 'with sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates db config for sqlite' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_development.sqlite")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.development').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_development.sqlite")
            end
          end
        end

        describe 'with sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates db config for sqlite3' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_development.sqlite")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.development').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_development.sqlite")
            end
          end
        end

        describe 'with memory' do
          let(:opts) { container_options.merge(database: 'memory') }

          it 'generates db config for memory' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="memory://localhost/chirp_development")
          end
        end
      end
    end

    describe '.env.test' do
      it 'generates it' do
        content = @root.join('.env.test').read
        content.must_match %(# Define ENV variables for test environment)
        content.must_match %(CHIRP_DATABASE_URL="file:///db/chirp_test")
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('.env.test').read
          content.must_match %(CHIRP_TWO_DATABASE_URL="file:///db/chirp-two_test")
        end
      end

      describe 'database option' do
        describe 'with mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'generates db config for mysql' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="mysql://localhost/chirp_test")
          end
        end

        describe 'with mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'generates db config for mysql2' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="mysql2://localhost/chirp_test")
          end
        end

        describe 'with postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'generates db config for postgresql' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_test")
          end
        end

        describe 'with postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates db config for postgres' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_test")
          end
        end

        describe 'with sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates db config for sqlite' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_test.sqlite")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.test').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_test.sqlite")
            end
          end
        end

        describe 'with sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates db config for sqlite3' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_test.sqlite")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }
            it 'escapes the database url' do
              content = @root.join('.env.test').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_test.sqlite")
            end
          end
        end

        describe 'with memory' do
          let(:opts) { container_options.merge(database: 'memory') }
          it 'generates db config for memory' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="memory://localhost/chirp_test")
          end
        end
      end
    end

    describe 'lib/chirp.rb' do
      it 'generates it' do
        content = @root.join('lib/chirp.rb').read
        content.must_match 'Dir["#{ __dir__ }/chirp/**/*.rb"].each { |file| require_relative file }'
        content.must_match %(require 'lotus/model')
        content.must_match %(Lotus::Model.configure)
        content.must_match %(adapter type: :file_system, uri: ENV['CHIRP_DATABASE_URL'])
        content.must_match %(mapping do)
        content.must_match %(mapping "\#{__dir__}/config/mapping")
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('lib/chirp-two.rb').read
          content.must_match 'Dir["#{ __dir__ }/chirp-two/**/*.rb"].each { |file| require_relative file }'
          content.must_match %(adapter type: :file_system, uri: ENV['CHIRP_TWO_DATABASE_URL'])
        end
      end

      describe 'database option' do
        describe 'mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'generates adapter config for mysql' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'generates adapter config for mysql2' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }
          it 'generates adapter config for postgresql' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates adapter config for postgres' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates adapter config for sqlite' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates adapter config for sqlite3' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'memory' do
          let(:opts) { container_options.merge(database: 'memory') }
          it 'generates adapter config for memory' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :memory, uri: ENV['CHIRP_DATABASE_URL'])
            content.wont_match %(migrations 'db/migrations')
            content.wont_match %(schema     'db/schema.sql')
          end
        end
      end
    end

    describe 'lib/config/mapping.rb' do
      it 'generates it' do
        content = @root.join('lib/config/mapping.rb').read
        content.must_match %(# collection :users do)
        content.must_match %(#   entity     User)
        content.must_match %(#   repository UserRepository)
        content.must_match %(#   attribute :id,   Integer)
        content.must_match %(#   attribute :name, String)
        content.must_match %(# end)
      end
    end

    describe 'db' do
      it 'generates it' do
        @root.join('db').must_be            :directory?
        @root.join('db/migrations').wont_be :exist?
      end

      ['postgres', 'postgresql', 'mysql', 'mysql2', 'sqlite', 'sqlite3'].each do |database|
        describe "with #{ database }" do
          let(:opts) { container_options.merge(database: database) }

          it "generates 'db/migrations'" do
            @root.join('db/migrations').must_be          :directory?
            @root.join('db/migrations/.gitkeep').must_be :exist?

            @root.join('db/.gitkeep').wont_be :exist?
          end

          it "generates empty 'db/schema.sql'" do
            @root.join('db/schema.sql').must_be      :exist?
            @root.join('db/schema.sql').read.must_be :empty?
          end
        end
      end
    end

    describe 'lib/chirp/entities' do
      it 'generates it' do
        @root.join('lib/chirp/entities').must_be :directory?
      end
    end

    describe 'lib/chirp/repositories' do
      it 'generates it' do
        @root.join('lib/chirp/repositories').must_be :directory?
      end
    end

    describe 'empty spec/* directory' do
      it 'generates it' do
        @root.join('spec/chirp/entities').must_be :directory?
        @root.join('spec/chirp/repositories').must_be :directory?
        @root.join('spec/support').must_be :directory?
      end
    end

    describe 'testing' do
      describe 'when minitest (default)' do
        describe 'spec/chirp/entities' do
          it 'generates it' do
            @root.join('spec/chirp/entities').must_be :directory?
          end
        end

        describe 'spec/chirp/repositories' do
          it 'generates it' do
            @root.join('spec/chirp/repositories').must_be :directory?
          end
        end

        describe 'spec/spec_helper.rb' do
          describe 'minitest (default)' do
            it 'generates it' do
              content = @root.join('spec/spec_helper.rb').read
              content.must_match %(ENV['LOTUS_ENV'] ||= 'test')
              content.must_match %(require_relative '../config/environment')
              content.must_match %(require 'minitest/autorun')
              content.must_match %(Lotus::Application.preload!)
            end
          end

          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/spec_helper.rb').read
              content.must_match %(ENV['LOTUS_ENV'] ||= 'test')
              content.must_match %(require_relative '../config/environment')
              content.must_match %(Lotus::Application.preload!)
              content.must_match %(RSpec.configure do |config|)
              content.must_match %(config.filter_run :focus)
              content.must_match %(config.run_all_when_everything_filtered = true)

              content.must_match %(if config.files_to_run.one?)
              content.must_match %(config.default_formatter = 'doc')

              content.must_match %(config.order = :random)
              content.must_match %(Kernel.srand config.seed)

              content.must_match %(config.expect_with :rspec do |expectations|)

              content.must_match %(config.mock_with :rspec do |mocks|)
              content.must_match %(mocks.verify_partial_doubles = true)
            end
          end
        end

        describe '.rspec' do
          let(:opts) { container_options.merge(test: 'rspec') }

          it 'generates it' do
            content = @root.join('.rspec').read
            content.must_match %(--color)
            content.must_match %(--require spec_helper)
          end
        end

        describe 'spec/features_helper.rb' do
          describe 'minitest (default)' do
            it 'generates it' do
              content = @root.join('spec/features_helper.rb').read
              content.must_match %(require_relative './spec_helper')
              content.must_match %(require 'capybara')
              content.must_match %(require 'capybara/dsl')
              content.must_match %(Capybara.app = Lotus::Container.new)
              content.must_match %(class MiniTest::Spec)
              content.must_match %(include Capybara::DSL)
            end
          end

          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/features_helper.rb').read
              content.must_match %(require_relative './spec_helper')
              content.must_match %(require 'capybara')
              content.must_match %(require 'capybara/rspec')
              content.must_match %(RSpec.configure do |config|)
              content.must_match %(config.include RSpec::FeatureExampleGroup)
              content.must_match %(config.include Capybara::DSL)
              content.must_match %(config.include Capybara::RSpecMatchers)
            end
          end
        end

        describe 'spec/support/capybara.rb' do
          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/support/capybara.rb').read
              content.must_match %(module RSpec)
              content.must_match %(module FeatureExampleGroup)
              content.must_match %(def self.included(group))
              content.must_match %(group.metadata[:type] = :feature)
              content.must_match %(Capybara.app = Lotus::Container.new)
            end
          end
        end
      end
    end

    ################
    # SLICE
    ################

    describe 'config/environment.rb' do
      it 'patches the file to reference slice' do
        content = @root.join('config/environment.rb').read
        content.must_match %(require_relative '../apps/web/application')
        content.must_match %(mount Web::Application, at: '/')
      end
    end

    describe '.env.development' do
      it 'patches the file to reference slice env vars' do
        content = @root.join('.env.development').read
        content.wont_match %(WEB_DATABASE_URL="file:///db/web_development")
        content.must_match %r{WEB_SESSIONS_SECRET="[\w]{64}"}
      end
    end

    describe '.env.test' do
      it 'patches the file to reference slice env vars' do
        content = @root.join('.env.test').read
        content.wont_match %(WEB_DATABASE_URL="file:///db/web_test")
        content.must_match %r{WEB_SESSIONS_SECRET="[\w]{64}"}
      end
    end

    describe 'apps/web/application.rb' do
      it 'generates it' do
        content = @root.join('apps/web/application.rb').read
        content.must_match %(require 'lotus/helpers')
        content.must_match %(module Web)
        content.must_match %(class Application < Lotus::Application)

        # main configure block
        content.must_match %(configure do)
        content.must_match %(root __dir__)

        content.must_match %(routes 'config/routes')

        content.must_match %(layout :application)
        content.must_match %(templates 'templates')

        content.must_match %(# cookies true)

        content.must_match %(# sessions :cookie, secret: ENV['WEB_SESSIONS_SECRET'])

        content.must_match %(load_paths << [)
        content.must_match %('controllers')
        content.must_match %('views')

        content.must_match %(# middleware.use Rack::Protection)

        content.must_match %(# body_parsers :json)

        content.must_match %(# assets << [)
        content.must_match %(#   'vendor/javascripts')

        content.must_match %(# serve_assets false)

        # security
        content.must_match %(security.x_frame_options "DENY")
        content.must_match %(security.content_security_policy "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';")

        content.must_match %(controller.prepare)
        content.must_match %(view.prepare)
        content.must_match %(include Lotus::Helpers)

        # per environment configuration
        content.must_match %(configure :development do)
        content.must_match %(handle_exceptions false)
        content.must_match %(serve_assets      true)

        content.must_match %(configure :test do)
        content.must_match %(handle_exceptions false)
        content.must_match %(serve_assets      true)

        content.must_match %(configure :production do)
        content.must_match %(# scheme 'https')
        content.must_match %(# host   'example.org')
        content.must_match %(# port   443)
      end
    end

    describe 'apps/web/config/routes.rb' do
      it 'generates it' do
        content = @root.join('apps/web/config/routes.rb').read
        content.must_match %(# Configure your routes here)
      end
    end

    describe 'apps/web/controllers' do
      it 'generates it' do
        @root.join('apps/web/controllers').must_be :exist?
      end
    end

    describe 'apps/web/views' do
      it 'generates it' do
        @root.join('apps/web/views').must_be :exist?
      end
    end

    describe 'apps/web/views/application_layout.rb' do
      it 'generates it' do
        content = @root.join('apps/web/views/application_layout.rb').read
        content.must_match %(module Web)
        content.must_match %(module Views)
        content.must_match %(class ApplicationLayout)
        content.must_match %(include Web::Layout)
      end
    end

    describe 'apps/web/templates/application.html.rb' do
      it 'generates it' do
        content = @root.join('apps/web/templates/application.html.erb').read
        content.must_match %(<title>Web</title>)
        content.must_match %(<%= yield %>)
      end
    end

    describe 'apps/web/public/javascripts' do
      it 'generates it' do
        @root.join('apps/web/public/javascripts').must_be :exist?
      end
    end

    describe 'apps/web/public/stylesheets' do
      it 'generates it' do
        @root.join('apps/web/public/stylesheets').must_be :exist?
      end
    end

    describe 'testing' do
      describe 'when minitest (default)' do
        describe 'spec/web/features' do
          it 'generates it' do
            @root.join('spec/web/features').must_be :directory?
          end
        end

        describe 'spec/web/controllers' do
          it 'generates it' do
            @root.join('spec/web/controllers').must_be :directory?
          end
        end

        describe 'spec/web/views' do
          it 'generates it' do
            @root.join('spec/web/views').must_be :directory?
          end
        end
      end
    end
  end

  describe 'application architecture' do
    def container_options
      Hash[architecture: architecture, application: 'web', application_base_url: '/', lotus_head: false, database: 'filesystem']
    end

    let(:opts)     { container_options }
    let(:app_name) { 'chirp' }
    let(:architecture) { 'app' }

    before do
      capture_io { command.start }
    end

    describe 'Gemfile' do
      it 'generates it' do
        content = @root.join('Gemfile').read
        content.must_match %(gem 'bundler')
        content.must_match %(gem 'rake')
        content.must_match %(gem 'lotusrb',       '#{ Lotus::VERSION }')
        content.must_match %(gem 'lotus-model',   '~> 0.4')
        content.must_match %(gem 'capybara')
      end

      describe 'lotus-head option' do
        let(:opts) { container_options.merge(lotus_head: true) }

        it 'generates it' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'bundler')
          content.must_match %(gem 'rake')
          content.must_match %(gem 'lotus-utils',       require: false, github: 'lotus/utils')
          content.must_match %(gem 'lotus-router',      require: false, github: 'lotus/router')
          content.must_match %(gem 'lotus-validations', require: false, github: 'lotus/validations')
          content.must_match %(gem 'lotus-helpers',     require: false, github: 'lotus/helpers')
          content.must_match %(gem 'lotus-controller',  require: false, github: 'lotus/controller')
          content.must_match %(gem 'lotus-view',        require: false, github: 'lotus/view')
          content.must_match %(gem 'lotus-model',       require: false, github: 'lotus/model')
          content.must_match %(gem 'lotusrb',                           github: 'lotus/lotus')
        end
      end

      describe 'minitest (default)' do
        it 'includes minitest' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'minitest')
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'includes rspec' do
          content = @root.join('Gemfile').read
          content.must_match %(gem 'rspec')
        end
      end

      describe 'production group' do
        it 'includes a server example' do
          content = @root.join('Gemfile').read
          content.must_match %(group :production do)
          content.must_match %(# gem 'puma')
        end
      end

      describe 'database option' do
        describe 'mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'includes mysql' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'mysql')
          end
        end

        describe 'mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'includes mysql2' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'mysql2')
          end
        end

        describe 'postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'includes pg' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'pg')
          end
        end

        describe 'postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'includes pg' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'pg')
          end
        end

        describe 'sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'includes sqlite3 gem' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'sqlite3')
          end
        end

        describe 'sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }

          it 'includes sqlite3 gem' do
            content = @root.join('Gemfile').read
            content.must_match %(gem 'sqlite3')
          end
        end
      end
    end

    describe 'Rakefile' do
      describe 'minitest (default)' do
        it 'generates it' do
          content = @root.join('Rakefile').read
          content.must_match %(Rake::TestTask.new)
          content.must_match %(t.pattern = 'spec/**/*_spec.rb')
          content.must_match %(t.libs    << 'spec')
          content.must_match %(task default: :test)
          content.must_match %(task spec: :test)
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'generates it' do
          content = @root.join('Rakefile').read
          content.must_match %(RSpec::Core::RakeTask.new(:spec))
          content.must_match %(task default: :spec)
        end
      end
    end

    describe 'config.ru' do
      it 'generates it' do
        content = @root.join('config.ru').read
        content.must_match %(require './config/environment')
        content.must_match %(run Chirp::Application.new)
      end
    end

    describe '.lotusrc' do
      describe 'minitest (default)' do
        it 'generates it' do
          content = @root.join('.lotusrc').read
          content.must_match %(architecture=app)
          content.must_match %(test=minitest)
          content.must_match %(template=erb)
        end
      end

      describe 'rspec' do
        let(:opts) { container_options.merge(test: 'rspec') }

        it 'generates it' do
          content = @root.join('.lotusrc').read
          content.must_match %(test=rspec)
        end
      end
    end

    describe '.gitignore' do
      it 'generates it' do
        content = @root.join('.gitignore').read
        content.must_match %(/db/chirp_development)
        content.must_match %(/db/chirp_test)
      end
    end

    describe 'config/environment.rb' do
      it 'generates it' do
        content = @root.join('config/environment.rb').read
        content.must_match %(require 'rubygems')
        content.must_match %(require 'bundler/setup')
        content.must_match %(require 'lotus/setup')
        content.must_match %(require_relative '../lib/chirp')
        content.must_match %(require_relative '../config/application')
      end
    end

    describe '.env' do
      it 'generates it' do
        content = @root.join('.env').read
        content.must_match %(# Define ENV variables)
      end
    end

    describe '.env.development' do
      it 'generates it' do
        content = @root.join('.env.development').read
        content.must_match %(# Define ENV variables for development environment)
        content.must_match %(CHIRP_DATABASE_URL="file:///db/chirp_development")
        content.wont_match %(CHIRP_SESSIONS_SECRET="")
        content.must_match %(CHIRP_SESSIONS_SECRET=)
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('.env.development').read
          content.must_match %(CHIRP_TWO_DATABASE_URL="file:///db/chirp-two_development")
        end
      end

      describe 'database option' do
        describe 'with mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }

          it 'generates db config for mysql' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="mysql://localhost/chirp_development")
          end
        end

        describe 'with mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }

          it 'generates db config for mysql2' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="mysql2://localhost/chirp_development")
          end
        end

        describe 'with postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'generates db config for postgresql' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_development")
          end
        end

        describe 'with postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates db config for postgres' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_development")
          end
        end

        describe 'with sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates db config for sqlite' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_development")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.development').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_development")
            end
          end
        end

        describe 'with sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates db config for sqlite3' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_development")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.development').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_development")
            end
          end
        end

        describe 'with memory' do
          let(:opts) { container_options.merge(database: 'memory') }

          it 'generates db config for memory' do
            content = @root.join('.env.development').read
            content.must_match %(CHIRP_DATABASE_URL="memory://localhost/chirp_development")
          end
        end
      end
    end

    describe '.env.test' do
      it 'generates it' do
        content = @root.join('.env.test').read
        content.must_match %(# Define ENV variables for test environment)
        content.must_match %(CHIRP_DATABASE_URL="file:///db/chirp_test")
        content.wont_match %(CHIRP_SESSIONS_SECRET="")
        content.must_match %(CHIRP_SESSIONS_SECRET=)
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('.env.test').read
          content.must_match %(CHIRP_TWO_DATABASE_URL="file:///db/chirp-two_test")
        end
      end

      describe 'database option' do
        describe 'with mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'generates db config for mysql' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="mysql://localhost/chirp_test")
          end
        end

        describe 'with mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'generates db config for mysql2' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="mysql2://localhost/chirp_test")
          end
        end

        describe 'with postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }

          it 'generates db config for postgresql' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_test")
          end
        end

        describe 'with postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates db config for postgres' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="postgres://localhost/chirp_test")
          end
        end

        describe 'with sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates db config for sqlite' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_test")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }

            it 'escapes the database url' do
              content = @root.join('.env.test').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_test")
            end
          end
        end

        describe 'with sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates db config for sqlite3' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="sqlite://db/chirp_test")
          end

          describe 'with non-simple application name' do
            let(:app_name) { "chirp'two" }
            it 'escapes the database url' do
              content = @root.join('.env.test').read
              content.must_match %(CHIRP_TWO_DATABASE_URL="sqlite://db/chirp\\'two_test")
            end
          end
        end

        describe 'with memory' do
          let(:opts) { container_options.merge(database: 'memory') }
          it 'generates db config for memory' do
            content = @root.join('.env.test').read
            content.must_match %(CHIRP_DATABASE_URL="memory://localhost/chirp_test")
          end
        end
      end
    end

    describe 'lib/chirp.rb' do
      it 'generates it' do
        content = @root.join('lib/chirp.rb').read
        content.must_match 'Dir["#{ __dir__ }/chirp/**/*.rb"].each { |file| require_relative file }'
        content.must_match %(require 'lotus/model')
        content.must_match %(Lotus::Model.configure)
        content.must_match %(adapter type: :file_system, uri: ENV['CHIRP_DATABASE_URL'])
        content.must_match %(mapping do)
        content.must_match %(mapping "\#{__dir__}/config/mapping")
      end

      describe "with non-simple application name" do
        let(:app_name) { "chirp-two" }

        it "sanitizes application names for env variables" do
          content = @root.join('lib/chirp-two.rb').read
          content.must_match 'Dir["#{ __dir__ }/chirp-two/**/*.rb"].each { |file| require_relative file }'
          content.must_match %(adapter type: :file_system, uri: ENV['CHIRP_TWO_DATABASE_URL'])
        end
      end

      describe 'database option' do
        describe 'mysql' do
          let(:opts) { container_options.merge(database: 'mysql') }
          it 'generates adapter config for mysql' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'mysql2' do
          let(:opts) { container_options.merge(database: 'mysql2') }
          it 'generates adapter config for mysql2' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'postgresql' do
          let(:opts) { container_options.merge(database: 'postgresql') }
          it 'generates adapter config for postgresql' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'postgres' do
          let(:opts) { container_options.merge(database: 'postgres') }

          it 'generates adapter config for postgres' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'sqlite' do
          let(:opts) { container_options.merge(database: 'sqlite') }

          it 'generates adapter config for sqlite' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'sqlite3' do
          let(:opts) { container_options.merge(database: 'sqlite3') }
          it 'generates adapter config for sqlite3' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :sql, uri: ENV['CHIRP_DATABASE_URL'])
            content.must_match %(migrations 'db/migrations')
            content.must_match %(schema     'db/schema.sql')
          end
        end

        describe 'memory' do
          let(:opts) { container_options.merge(database: 'memory') }
          it 'generates adapter config for memory' do
            content = @root.join('lib/chirp.rb').read
            content.must_match %(adapter type: :memory, uri: ENV['CHIRP_DATABASE_URL'])
          end
        end
      end
    end

    describe 'lib/config/mapping.rb' do
      it 'generates it' do
        content = @root.join('lib/config/mapping.rb').read
        content.must_match %(# collection :users do)
        content.must_match %(#   entity     User)
        content.must_match %(#   repository UserRepository)
        content.must_match %(#   attribute :id,   Integer)
        content.must_match %(#   attribute :name, String)
        content.must_match %(# end)
      end
    end

    describe 'db' do
      it 'generates it' do
        @root.join('db').must_be            :directory?
        @root.join('db/migrations').wont_be :exist?
      end

      ['postgres', 'postgresql', 'mysql', 'mysql2', 'sqlite', 'sqlite3'].each do |database|
        describe "with #{ database }" do
          let(:opts) { container_options.merge(database: database) }

          it "generates 'db/migrations'" do
            @root.join('db/migrations').must_be          :directory?
            @root.join('db/migrations/.gitkeep').must_be :exist?

            @root.join('db/.gitkeep').wont_be :exist?
          end

          it "generates empty 'db/schema.sql'" do
            @root.join('db/schema.sql').must_be      :exist?
            @root.join('db/schema.sql').read.must_be :empty?
          end
        end
      end
    end

    describe 'lib/chirp/entities' do
      it 'generates it' do
        @root.join('lib/chirp/entities').must_be :directory?
      end
    end

    describe 'lib/chirp/repositories' do
      it 'generates it' do
        @root.join('lib/chirp/repositories').must_be :directory?
      end
    end

    describe 'empty spec/* directory' do
      it 'generates it' do
        @root.join('spec/chirp/entities').must_be :directory?
        @root.join('spec/chirp/repositories').must_be :directory?
        @root.join('spec/support').must_be :directory?
      end
    end

    describe 'testing' do
      describe 'when minitest (default)' do
        describe 'spec/chirp/entities' do
          it 'generates it' do
            @root.join('spec/chirp/entities').must_be :directory?
          end
        end

        describe 'spec/chirp/repositories' do
          it 'generates it' do
            @root.join('spec/chirp/repositories').must_be :directory?
          end
        end

        describe 'spec/spec_helper.rb' do
          describe 'minitest (default)' do
            it 'generates it' do
              content = @root.join('spec/spec_helper.rb').read
              content.must_match %(ENV['LOTUS_ENV'] ||= 'test')
              content.must_match %(require_relative '../config/environment')
              content.must_match %(require 'minitest/autorun')
              content.must_match %(Lotus::Application.preload!)
            end
          end

          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/spec_helper.rb').read
              content.must_match %(ENV['LOTUS_ENV'] ||= 'test')
              content.must_match %(require_relative '../config/environment')
              content.must_match %(Lotus::Application.preload!)
              content.must_match %(RSpec.configure do |config|)
              content.must_match %(config.filter_run :focus)
              content.must_match %(config.run_all_when_everything_filtered = true)

              content.must_match %(if config.files_to_run.one?)
              content.must_match %(config.default_formatter = 'doc')

              content.must_match %(config.order = :random)
              content.must_match %(Kernel.srand config.seed)

              content.must_match %(config.expect_with :rspec do |expectations|)

              content.must_match %(config.mock_with :rspec do |mocks|)
              content.must_match %(mocks.verify_partial_doubles = true)
            end
          end
        end

        describe '.rspec' do
          let(:opts) { container_options.merge(test: 'rspec') }

          it 'generates it' do
            content = @root.join('.rspec').read
            content.must_match %(--color)
            content.must_match %(--require spec_helper)
          end
        end

        describe 'spec/features_helper.rb' do
          describe 'minitest (default)' do
            it 'generates it' do
              content = @root.join('spec/features_helper.rb').read
              content.must_match %(require_relative './spec_helper')
              content.must_match %(require 'capybara')
              content.must_match %(require 'capybara/dsl')
              content.must_match %(Capybara.app = Chirp::Application.new)
              content.must_match %(class MiniTest::Spec)
              content.must_match %(include Capybara::DSL)
            end
          end

          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/features_helper.rb').read
              content.must_match %(require_relative './spec_helper')
              content.must_match %(require 'capybara')
              content.must_match %(require 'capybara/rspec')
              content.must_match %(RSpec.configure do |config|)
              content.must_match %(config.include RSpec::FeatureExampleGroup)
              content.must_match %(config.include Capybara::DSL)
              content.must_match %(config.include Capybara::RSpecMatchers)
            end
          end
        end

        describe 'spec/support/capybara.rb' do
          describe 'rspec' do
            let(:opts) { container_options.merge(test: 'rspec') }

            it 'generates it' do
              content = @root.join('spec/support/capybara.rb').read
              content.must_match %(module RSpec)
              content.must_match %(module FeatureExampleGroup)
              content.must_match %(def self.included(group))
              content.must_match %(group.metadata[:type] = :feature)
              content.must_match %(Capybara.app = Chirp::Application.new)
            end
          end
        end
      end
    end

    ################
    # SLICE
    ################

    describe 'config/application.rb' do
      it 'generates it' do
        content = @root.join('config/application.rb').read
        content.must_match %(require 'lotus/helpers')
        content.must_match %(module Chirp)
        content.must_match %(class Application < Lotus::Application)

        # main configure block
        content.must_match %(configure do)
        content.must_match 'root "#{ __dir__ }/.."'

        content.must_match %(routes 'config/routes')

        content.must_match %(layout :application)
        content.must_match %(templates 'app/templates')

        content.must_match %(# cookies true)

        content.must_match %(# sessions :cookie, secret: ENV['CHIRP_SESSIONS_SECRET'])

        content.must_match %(load_paths << [)
        content.must_match %('app/controllers')
        content.must_match %('app/views')

        content.must_match %(# middleware.use Rack::Protection)

        content.must_match %(# body_parsers :json)

        content.must_match %(# assets << [)
        content.must_match %(#   'vendor/javascripts')

        content.must_match %(# serve_assets false)

        # security
        content.must_match %(security.x_frame_options "DENY")
        content.must_match %(security.content_security_policy "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';")

        content.must_match %(controller.prepare)
        content.must_match %(view.prepare)
        content.must_match %(include Lotus::Helpers)

        # per environment configuration
        content.must_match %(configure :development do)
        content.must_match %(handle_exceptions false)
        content.must_match %(serve_assets      true)

        content.must_match %(configure :test do)
        content.must_match %(handle_exceptions false)
        content.must_match %(serve_assets      true)

        content.must_match %(configure :production do)
        content.must_match %(# scheme 'https')
        content.must_match %(# host   'example.org')
        content.must_match %(# port   443)
      end
    end

    describe 'config/routes.rb' do
      it 'generates it' do
        content = @root.join('config/routes.rb').read
        content.must_match %(# Configure your routes here)
      end
    end

    describe 'app/controllers' do
      it 'generates it' do
        @root.join('app/controllers').must_be :exist?
      end
    end

    describe 'app/views' do
      it 'generates it' do
        @root.join('app/views').must_be :exist?
      end
    end

    describe 'app/views/application_layout.rb' do
      it 'generates it' do
        content = @root.join('app/views/application_layout.rb').read
        content.must_match %(module Chirp)
        content.must_match %(module Views)
        content.must_match %(class ApplicationLayout)
        content.must_match %(include Chirp::Layout)
      end
    end

    describe 'app/templates/application.html.rb' do
      it 'generates it' do
        content = @root.join('app/templates/application.html.erb').read
        content.must_match %(<title>Chirp</title>)
        content.must_match %(<%= yield %>)
      end
    end

    describe 'public/javascripts' do
      it 'generates it' do
        @root.join('public/javascripts').must_be :exist?
      end
    end

    describe 'public/stylesheets' do
      it 'generates it' do
        @root.join('public/stylesheets').must_be :exist?
      end
    end

    describe 'testing' do
      describe 'when minitest (default)' do
        describe 'spec/features' do
          it 'generates it' do
            @root.join('spec/features').must_be :directory?
          end
        end

        describe 'spec/controllers' do
          it 'generates it' do
            @root.join('spec/controllers').must_be :directory?
          end
        end

        describe 'spec/views' do
          it 'generates it' do
            @root.join('spec/views').must_be :directory?
          end
        end
      end
    end
  end

  describe 'when app_name is .' do
    def container_options
      Hash[architecture: architecture, application: 'web', application_base_url: '/', lotus_head: false, database: 'filesystem']
    end

    def clear_root_folder
      FileUtils.rm_rf("#{@root}/.", secure: true)
    end

    let(:opts)      { container_options }
    let(:app_name)  { '.' }

    before do
      clear_root_folder
      capture_io { command.start }
    end

    describe 'when architecture is container' do
      let(:architecture) { 'container' }

      describe 'config/environment.rb' do
        it 'generates it' do
          content = @root.join('config/environment.rb').read
          content.must_match %(require_relative '../lib/new')
        end
      end

      describe 'lib/new' do
        it 'generates it' do
          @root.join('lib/new').must_be :directory?
        end
      end

      describe 'lib/new.rb' do
        it 'generates it' do
          @root.join('lib/new.rb').must_be :file?
          content = @root.join('lib/new.rb').read
          content.must_match %(adapter type: :file_system, uri: ENV['NEW_DATABASE_URL'])
        end
      end

      describe '.env.development' do
        it 'generates it' do
          content = @root.join('.env.development').read
          content.must_match %(NEW_DATABASE_URL="file:///db/new_development")
        end
      end

      describe '.env.test' do
        it 'generates it' do
          content = @root.join('.env.test').read
          content.must_match %(NEW_DATABASE_URL="file:///db/new_test")
        end
      end
    end

    describe 'when architecture is application' do
      let(:architecture) { 'app' }

      describe 'config/environment.rb' do
        it 'generates it' do
          content = @root.join('config/environment.rb').read
          content.must_match %(require_relative '../lib/new')
        end
      end

      describe 'lib/new' do
        it 'generates it' do
          @root.join('lib/new').must_be :directory?
        end
      end

      describe 'lib/new.rb' do
        it 'generates it' do
          @root.join('lib/new.rb').must_be :file?
          content = @root.join('lib/new.rb').read
          content.must_match %(adapter type: :file_system, uri: ENV['NEW_DATABASE_URL'])
        end
      end

      describe '.env.development' do
        it 'generates it' do
          content = @root.join('.env.development').read
          content.must_match %(NEW_DATABASE_URL="file:///db/new_development")
        end
      end

      describe '.env.test' do
        it 'generates it' do
          content = @root.join('.env.test').read
          content.must_match %(NEW_DATABASE_URL="file:///db/new_test")
        end
      end
    end
  end

  describe 'application path' do
    def container_options
      Hash[architecture: architecture, application: 'web', application_base_url: '/', lotus_head: false, database: 'filesystem']
    end

    let(:opts)      { container_options }
    let(:app_name)  { 'chirp' }

    before do
      capture_io { command.start }
    end

    describe 'when a path is provided' do
      let(:opts) { container_options.merge(path: 'my_lotus_app') }

      it 'generates the app at the specific path' do
        @root.dirname().join('my_lotus_app').must_be :directory?
      end
    end
  end

  describe 'when a path is provided as the app name' do
    let(:opts)      { Hash[architecture: architecture, application: 'web', application_base_url: '/', lotus_head: false] }
    let(:app_name)  { 'lib/chirp' }

    it 'raises an ArgumentError' do
      exception = -> { command.start }.must_raise ArgumentError
      exception.message.must_equal 'Invalid application name. If you want to set application path, please use --path option'
    end
  end
end


text:
param($packageRoot, $installArgs)

$executablePath = $installArgs.executablePath
$exeFile = Get-ChildItem $packageRoot -Recurse -Filter "$executablePath" | select -first 1
$sourcePath = Split-Path $exeFile.FullName -Parent
$packageInfo = Get-PackageInfo $packageRoot
$packageInfo.Add("sourcePath", $sourcePath)
@{
    'packageInfo' = $packageInfo
    'installAction' = {
        param($config, $packageInfo, $installArgs)
        $sourcePath = $packageInfo.sourcePath
        $executablePath = $installArgs.executablePath
        $name = $config.ServiceName
        $installPath = $config.ServicePath
        $username = $config.UserName
        $password = $config.Password

        Stop-ServiceForcibly($name)

        if (Test-Path $installPath) {
           ReDo-until {
                Remove-Item $installPath -Force -Recurse -ErrorVariable hasError -ErrorAction 'silentlycontinue'
                return $hasError
            } {
                !(Test-Path $installPath)
            } " Remove $installPath "
        }

        Write-Host "Start to copy $sourcePath to $installPath" -f green
        Copy-Item $sourcePath $installPath -Recurse

        $serviceBinPath = "$installPath\$executablePath"
        $service = Get-Service -Name $name -ErrorAction SilentlyContinue
        if(-not $service){
            Write-Host "Create Service[$name] for $serviceBinPath"
            if(($username) -and ($password)) {
                $secpasswd = ConvertTo-SecureString "$password" -AsPlainText -Force
                $credential = New-Object System.Management.Automation.PSCredential ("$username", $secpasswd)
                New-Service -Name $name -BinaryPathName "$serviceBinPath" -Description $name -DisplayName $name -StartupType Automatic -credential $credential
            } else {
                New-Service -Name $name -BinaryPathName "$serviceBinPath" -Description $name -DisplayName $name -StartupType Automatic
            }

        }else{
            $name = $service.Name
            Write-Host "Service[$name] already exists,change BinaryPathName to $serviceBinPath" -f green
            & SC.exe CONFIG $name binPath= "\`"$serviceBinPath\`""
            Set-Service $name -StartupType Automatic
        }

        Start-Service -Name $name

        if(-not ((Get-Service -Name $name).Status -eq "Running")){
            throw "Service[$name] is NOT running after installation."
        }
        Write-Host "Service started. " -f green
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace ppapi {
namespace thunk {

namespace {

typedef EnterResource<PPB_FileIO_API> EnterFileIO;

int32_t GetOSFileDescriptor(PP_Resource file_io) {
  EnterFileIO enter(file_io, true);
  if (enter.failed())
    return enter.retval();
  return enter.object()->GetOSFileDescriptor();
}

int32_t WillWrite(PP_Resource file_io,
                  int64_t offset,
                  int32_t bytes_to_write,
                  PP_CompletionCallback callback) {
  EnterFileIO enter(file_io, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->WillWrite(offset, bytes_to_write,
                                                   enter.callback()));
}

int32_t WillSetLength(PP_Resource file_io,
                      int64_t length,
                      PP_CompletionCallback callback) {
  EnterFileIO enter(file_io, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->WillSetLength(length,
                                                       enter.callback()));
}

const PPB_FileIOTrusted g_ppb_file_io_trusted_thunk = {
  &GetOSFileDescriptor,
  &WillWrite,
  &WillSetLength
};

}  // namespace

const PPB_FileIOTrusted_0_4* GetPPB_FileIOTrusted_0_4_Thunk() {
  return &g_ppb_file_io_trusted_thunk;
}

}  // namespace thunk
}  // namespace ppapi


text: Read in MNIST handwritten digit data for use in training neural networks


text:
<?php

namespace LoginExampleBundle\EventListener;

use LoginExampleBundle\APIBase\ApiProblem;
use LoginExampleBundle\APIBase\ApiProblemException;
use LoginExampleBundle\APIBase\ResponseFactory;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ApiExceptionSubscriber implements EventSubscriberInterface
{
    private $debug;

    private $responseFactory;

    private $logger;

    public function __construct($debug, ResponseFactory $responseFactory, LoggerInterface $logger)
    {
        $this->debug = $debug;
        $this->responseFactory = $responseFactory;
        $this->logger = $logger;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // only reply to /api URLs
        if (strpos($event->getRequest()->getPathInfo(), '/api') !== 0) {
            return;
        }

        $e = $event->getException();

        $statusCode = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;

        // allow 500 errors to be thrown
        if ($this->debug && $statusCode >= 500) {
            return;
        }

        $this->logException($e);

        if ($e instanceof ApiProblemException) {
            $apiProblem = $e->getApiProblem();
        } else {

            $apiProblem = new ApiProblem(
                $statusCode
            );

            /*
             * If it's an HttpException message (e.g. for 404, 403),
             * we'll say as a rule that the exception message is safe
             * for the client. Otherwise, it could be some sensitive
             * low-level exception, which should *not* be exposed
             */
            if ($e instanceof HttpExceptionInterface) {
                $apiProblem->set('detail', $e->getMessage());
            }
        }

        $response = $this->responseFactory->createResponse($apiProblem);

        $event->setResponse($response);
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::EXCEPTION => 'onKernelException'
        );
    }

    /**
     * Adapted from the core Symfony exception handling in ExceptionListener
     *
     * @param \Exception $exception
     */
    private function logException(\Exception $exception)
    {
        $message = sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine());
        $isCritical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
        $context = array('exception' => $exception);
        if ($isCritical) {
            $this->logger->critical($message, $context);
        } else {
            $this->logger->error($message, $context);
        }
    }
}


text:
package gopherdoc.buttercoin.trader;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ListItemHistory extends LinearLayout {
    private final TextView position;
    private final TextView date;
    private final TextView amount;
    private final TextView price;

    //Constructor
    public ListItemHistory(Context context) {
        super(context, null);
        setOrientation(LinearLayout.VERTICAL);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.lvitem_history, this);
        position = (TextView)findViewById(R.id.tradehistory_position);
        date = (TextView)findViewById(R.id.tradehistory_date);
        amount = (TextView)findViewById(R.id.tradehistory_amount);
        price = (TextView) findViewById(R.id.tradehistory_price);
    }

    public void setPosition(String pos){position.setText(pos);}
    public void setDate(String mydate){ date.setText(mydate);}
    public void setAmount(String amt){ amount.setText(amt);}
    public void setPrice(String cost){price.setText(cost);}
}


text:
ipython_pip_magics: %pip magics for IPython
===========================================

This project provides IPython "magics" for working with pip.

To load the IPython magics, do (in IPython):

   %load_ext ipython_pip

The primary magic is %pip. This works (almost) exactly
like pip from the operating system command line.

Do:
    %pip --help

to get an overview.

Note: when doing '%pip uninstall ...', use the -y option
to avoid being prompted (which does not work using %pip).

Other magics:

   %pip_upgrade_all

Attempt to upgrade all packages

   %pip_upgrade_all_user


text:
namespace content {

// This class mimics the behavior of WebKit's WebView class in a way that makes
// sense for Chrome.
//
// WebCore has the concept of "core commands", basically named actions such as
// "Select All" and "Move Cursor Left".  The commands are executed using their
// string value by WebCore.
//
// This class is responsible for 2 things:
// 1. Provide an abstraction to determine the enabled/disabled state of menu
// items that correspond to edit commands.
// 2. Hook up a bunch of objc selectors to the RenderWidgetHostViewCocoa object.
// (note that this is not a misspelling of RenderWidgetHostViewMac, it's in
//  fact a distinct object) When these selectors are called, the relevant
// edit command is executed in WebCore.
class CONTENT_EXPORT RenderWidgetHostViewMacEditCommandHelper {
   FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewMacEditCommandHelperTest,
                            TestAddEditingSelectorsToClass);
   FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewMacEditCommandHelperTest,
                            TestEditingCommandDelivery);

 public:
  RenderWidgetHostViewMacEditCommandHelper();
  ~RenderWidgetHostViewMacEditCommandHelper();

  // Adds editing selectors to the objc class using the objc runtime APIs.
  // Each selector is connected to a single c method which forwards the message
  // to WebCore's ExecuteEditCommand() function.
  // This method is idempotent.
  // The class passed in must conform to the RenderWidgetHostViewMacOwner
  // protocol.
  void AddEditingSelectorsToClass(Class klass);

  // Is a given menu item currently enabled?
  // SEL - the objc selector currently associated with an NSMenuItem.
  // owner - An object we can retrieve a RenderWidgetHostViewMac from to
  // determine the command states.
  bool IsMenuItemEnabled(SEL item_action,
                         id<RenderWidgetHostViewMacOwner> owner);

  // Converts an editing selector into a command name that can be sent to
  // webkit.
  static NSString* CommandNameForSelector(SEL selector);

 protected:
  // Gets a list of all the selectors that AddEditingSelectorsToClass adds to
  // the aforementioned class.
  // returns an array of NSStrings WITHOUT the trailing ':'s.
  NSArray* GetEditSelectorNames();

 private:
  base::hash_set<std::string> edit_command_set_;
  DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewMacEditCommandHelper);
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_MAC_EDITCOMMAND_HELPER_H_


text:
StatsD is common wrapper for graphite metrics. This project enables the use of statsd metrics collection via spark metrics.properties file

Scala version 2.10.4
Build version 0.13.6
Spark version 1.5.2

###Steps to create assembly jar

```
git clone git@github.com:vidhyaarvind/spark-statsd.git

cd spark-statsd

sbt assembly
```

creates target/scala-2.10/spark-statsd-1.0.0.jar assembly jar file

### Add settings to conf/metrics.properties

```
*.sink.statsd.class=org.apache.spark.metrics.sink.StatsDSink
*.sink.statsd.host=localhost
*.sink.statsd.port=8125
```

### Run spark job

eg.
```
./bin/run-example SparkPi 10 --driver-class-path target/scala-2.10/spark-statsd-1.0.0.jar
```


text:
package com.google.cloud.security.scanner.actions.extractors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.api.services.cloudresourcemanager.CloudResourceManager.Projects;
import com.google.api.services.cloudresourcemanager.CloudResourceManager.Projects.GetIamPolicy;
import com.google.api.services.cloudresourcemanager.model.Binding;
import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.model.Policy;
import com.google.cloud.dataflow.sdk.transforms.DoFnTester;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.security.scanner.primitives.GCPProject;
import com.google.cloud.security.scanner.primitives.GCPResource;
import com.google.cloud.security.scanner.primitives.GCPResourcePolicy;
import com.google.cloud.security.scanner.primitives.GCPResourcePolicy.PolicyBinding;
import com.google.cloud.security.scanner.primitives.GCPResourceState;
import com.google.cloud.security.scanner.primitives.PoliciedObject;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for FilePathToLiveState.
 */
@RunWith(JUnit4.class)
public class FilePathToLiveStateTest {

  private DoFnTester<List<String>, KV<GCPResource, GCPResourceState>> tester;
  private Projects projects = mock(Projects.class);

  @Before
  public void setUp() {
    tester = DoFnTester.of(new FilePathToLiveState());
    GCPProject.setProjectsApiStub(projects);
  }

  @Test
  public void testInvalidStateFile() {
    List<String> filePath = Arrays.asList("sampleOrg", "sampleProject", "invalidStateFileName");
    try {
      tester.processBatch(filePath);
      fail("No exception thrown on invalid statefile name");
    } catch (Exception ignored) {
      // test passed
    }
  }

  @Test
  public void testValidFile() throws IOException {
    String projectId = "sampleProject";
    List<String> filePath = Arrays.asList("sampleOrg", projectId, "POLICY");
    GCPProject project = new GCPProject(projectId);
    GCPResourcePolicy gcpResourcePolicy = getSampleGCPResourcePolicy(project);
    Policy policy = getSamplePolicy();
    GetIamPolicy correctRequest = mock(GetIamPolicy.class);
    GetIamPolicy wrongRequest = mock(GetIamPolicy.class);
    when(projects.getIamPolicy(anyString(), any(GetIamPolicyRequest.class)))
        .thenReturn(wrongRequest);
    when(projects.getIamPolicy(eq(projectId), any(GetIamPolicyRequest.class)))
        .thenReturn(correctRequest);
    when(correctRequest.execute()).thenReturn(policy);
    when(wrongRequest.execute()).thenThrow(new NoSuchElementException());
    try {
      assertEquals(tester.processBatch(filePath), Arrays.asList(KV.of(project, gcpResourcePolicy)));
    } catch (IllegalArgumentException ignored) {
      fail("Exception thrown on valid statefile name");
    } catch (NoSuchElementException nse) {
      fail("Tried accessing the wrong project ID");
    }
  }

  private Policy getSamplePolicy() {
    String ownerRole = "OWNER";
    String editorRole = "EDITOR";
    List<String> ownerMembers = Arrays.asList("owner@own.er", "own@erown.er");
    List<String> editorMembers = Arrays.asList("editor@edit.or", "edit@oredit.or");
    Binding ownerBinding = new Binding().setRole(ownerRole).setMembers(ownerMembers);
    Binding editorBinding = new Binding().setRole(editorRole).setMembers(editorMembers);
    List<Binding> bindings = Arrays.asList(ownerBinding, editorBinding);
    return new Policy().setBindings(bindings);
  }

  private GCPResourcePolicy getSampleGCPResourcePolicy(PoliciedObject resource) {
    String ownerRole = "OWNER";
    String editorRole = "EDITOR";
    List<String> ownerMembers = Arrays.asList("owner@own.er", "own@erown.er");
    List<String> editorMembers = Arrays.asList("editor@edit.or", "edit@oredit.or");
    PolicyBinding ownerBinding = new PolicyBinding(ownerRole, ownerMembers);
    PolicyBinding editorBinding = new PolicyBinding(editorRole, editorMembers);
    List<PolicyBinding> bindings = Arrays.asList(ownerBinding, editorBinding);
    return new GCPResourcePolicy(resource, bindings);
  }
}


text:
.. _learning.multiuser.intro:

Building Multi-User Applications With Zend Framework
====================================================

.. _learning.multiuser.intro.zf:

Zend Framework
--------------

When the original "web" was created, it was designed to be a publishing platform for predominantly static content.
As demand for content on the web grew, as did the number of consumers on the internet for web content, the demand
for using the web as an application platform also grew. Since the web is inherently good at delivering a
simultaneous experience to many consumers from a single location, it makes it an ideal environment for building
dynamically driven, multi-user, and more commonly today, social systems.

*HTTP* is the protocol of the web: a stateless, typically short lived, request and response protocol. This protocol
was designed this way because the original intent of the web was to serve or publish static content. It is this
very design that has made the web as immensely successful as it is. It is also exactly this design that brings new
concerns to developers who wish to use the web as an application platform.

These concerns and responsibilities can effectively be summed up by three questions:

- How do you distinguish one application consumer from another?

- How do you identify a consumer as authentic?

- How do you control what a consumer has access to?

.. note::

   **Consumer Vs. User**

   Notice we use the term "consumer" instead of person. Increasingly, web applications are becoming service driven.
   This means that not only are real people ("users") with real web browsers consuming and using your application,
   but also other web applications through machine service technologies such as *REST*, *SOAP*, and *XML-RPC*. In
   this respect, people, as well as other consuming applications, should all be treated in same with regard to the
   concerns outlined above.

In the following chapters, we'll take a look at these common problems relating to authentication and authorization
in detail. We will discover how 3 main components: ``Zend_Session``, ``Zend_Auth``, and ``Zend\Permissions\Acl``; provide an
out-of-the-box solution as well as the extension points each have that will cater to a more customized solution.


text:
package util

import (
	"os"
	"path/filepath"
	"strings"
)

func NameAndDescription() (string, string) {
	// Determine name to use in docstring. We want the docstring to change if
	// we're running as a kubectl plugin.
	name := "calicoctl"
	desc := "calicoctl command line tool"
	if strings.HasPrefix(filepath.Base(os.Args[0]), "kubectl-") {
		// We're a kubectl plugin
		name = "kubectl-calico"
		desc = "calico kubectl plugin"
	}
	return name, desc
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.rvesse.github.pr.stats.collectors;

import org.eclipse.egit.github.core.client.GitHubClient;

public interface Collector<T> {

    /**
     * Collects an item
     *
     * @param client
     *            GitHub Client
     * @param item
     *            Item
     */
    public abstract void collect(GitHubClient client, T item);

    /**
     * Starts collection
     */
    public abstract void start();

    /**
     * Ends collection
     */
    public abstract void end();
}


text:
% -------------------------------------------------------------------------
% Copyright C 2012 Amir Tahmasbi
% The University of Texas at Dallas
% a.tahmasbi@utdallas.edu
% http://www.utdallas.edu/~a.tahmasbi/research.html
%
% -------------------------------------------------------------------------
% Licence Agreement: You are free to use this code in your scientific
%                    research but you should cite the following paper:
%
% [1] - A. Tahmasbi, F. Saki, S. B. Shokouhi,
%      	Classification of Benign and Malignant Masses Based on Zernike Moments,
% 	J. Computers in Biology and Medicine, vol. 41, no. 8, pp. 726-735, 2011.
%
% [2] - A. Tahmasbi, F. Saki, H. Aghapanah, S. B. Shokouhi,
%	A Novel Breast Mass Diagnosis System based on Zernike Moments as Shape and Density Descriptors,
%	in Proc. IEEE, 18th Iranian Conf. on Biomedical Engineering (ICBME'2011),
%	Tehran, Iran, 2011, pp. 100-104.
%
% -------------------------------------------------------------------------
%%
% Function to find the Zernike moments for an N x N binary ROI
%
% [Z A Phi] = Zernikmoment(p,n,m)
% where
%   p = input image N x N (N should be an even number)
%   n = The order of Zernike moment
%   m = The iterration number of Zernike moment
% and
%   Z = Complex Zernike moment
%   A = Amplitude of the moment
%   Phi = phase (angle) of the mement (in degrees)
%
% Example:
%   1- calculate the Zernike moment (n,m) for an oval shape,
%   2- rotate the oval shape around its centeroid,
%   3- calculate the Zernike moment (n,m) again,
%   4- the amplitude of the moment (A) should be the same for both images
%   5- the phase (Phi) should be equal to the angle of rotation
% -------------------------------------------------------------------------

function [Z A Phi] = Zernikmoment(p,n,m)
N = size(p,1);
x = 1:N; y = x;
[X,Y] = meshgrid(x,y);
R = sqrt((2.*X-N-1).^2+(2.*Y-N-1).^2)/N;
Theta = atan2((N-1-2.*Y+2),(2.*X-N+1-2));
R = (R<=1).*R;
Rad = radialpoly(R,n,m);    % get the radial polynomial

Product = p(x,y).*Rad.*exp(-1i*m*Theta);
Z = sum(Product(:));        % calculate the moments

cnt = nnz(R)+1;             % count the number of pixels inside the unit circle
Z = (n+1)*Z/cnt;            % normalize the amplitude of moments
A = abs(Z);                 % calculate the amplitude of the moment
Phi = angle(Z)*180/pi;      % calculate the phase of the mement (in degrees)

% -------------------------------------------------------------------------


text:
gnunet-gns-import.sh

# list identities / gns zones
gnunet-identity -d

# create a new identity
gnunet-identity -C "new_zone"

# create an entry for google
gnunet-namestore -z master-zone -a -n google -t A -V 74.125.226.132 -e never -p

# test the setup
ping google.gnu
# if this fails, go back to the setup script and look up the section about nsswitch

# try adding Viktor to your zome with the nickanme v
gnunet-namestore -a -n v -i v --type PKEY -V A616CN3BM4LIT3RM83A8NJ78HI2VBJ7NFU8PVK04EID2UJ7PG2LG -e never -z master-zone
gnunet-namestore -a -n rui -i rui --type PKEY -V 6V4NA95P2LA2J67V2OLK6A95ESQKMVDHS3M3PLTIM3A76BFD5E3G -e never -z master-zone

# now see if you can resolve Google through him
ping google.v.gnu
# you should be able to also resolve Google without using the petname
ping google.A616CN3BM4LIT3RM83A8NJ78HI2VBJ7NFU8PVK04EID2UJ7PG2LG.zkey

# the zones:
# master-zone - you, publicly shared entries; thing.gnu
# private-zone - private entries; thing.private.gnu
# shorten-zone - others; after you access bob.alice.dave.gnu you acn use bob.short.gnu


text:
package com.gxl.test;

import org.apache.zookeeper.ZooKeeper;

/**
 * 注册节点接口
 *
 * @author JohnGao
 */
public interface RegisterNode {
	/**
	 * 注册Znode
	 *
	 * @author JohnGao
	 */
	public void register(ZooKeeper zk_client, String... paths) throws Exception;
}


text:
This image provides all tools required to automatically build and Android app out of your ionic (and possibly also cordova) project.

It is primarily meant to be run in a CI environment, such as Gitlab CI, but can certainly also be used to run the compilation process on any machine capable of running docker without having to go through the process of setting everything up.

## CI Configuration

Here is a sample .gitlab-ci.yml file for setting up the project and compiling it:

```yaml
image: tobitheo/ionic-build-android-ci-docker:latest

compile_android:
  stage: build
  script:
    - cp debug.keystore ~/.android/debug.keystore
    - npm install
    - bower install --allow-root
    - ionic config build
    - ionic state restore
    - ionic build android
```

It is important to manage your keystores correctly. For signing debug releases, the android build tools will automatically fall back to `~/.android/debug.keystore`, which should not be password protected.

## .gitignore

This example assumes, that your `.gitignore` looks approximately like this:

```
node_modules/
platforms/
plugins/
www/lib/
```

That will avoid checking in generated files or dependencies, that will be restored using the aforementioned commands during build.

## Getting the files out

Finally, you can get your compiled file out of your container. The image includes `sftp`, `scp`, `rsync`, `sendemail` with `ssmtp` and `s3cmd`, if you want to see more added, do not hesitate to send a pull request.

To send the apk in a mail, use sendemail to send the compiled APK as an attachment to yourself (using GMail):

```
    - sendemail -f $GMAIL_USER@gmail.com -t $MAIL_RCPT -s smtp.gmail.com:587 -xu $GMAIL_USER -xp $GMAIL_PASS -u "New CI build $CI_BUILD_ID" -m "Hi, \nthis is your Gitlab CI building $CI_BUILD_REPO, branch/tag $CI_BUILD_REF_NAME, commit $CI_BUILD_REF. \nThe generated APK file is attached. \nRegards, \n$CI_SERVER_NAME" -a platforms/android/build/outputs/apk/android-debug.apk
```

Note that `GMAIL_USER`, `GMAIL_PASS` and `MAIL_RCPT` are environment variables that have to be configured in the project settings -> Variables and the `CI_*` variables are set by the CI system and for Gitlab CI are documented [here](http://doc.gitlab.com/ce/ci/variables/README.html). The documentation for `sendemail` is [here](https://github.com/mogaal/sendemail).


text:
<!--[metadata]>
+++
title = "Installation on openSUSE and SUSE Linux Enterprise"
description = "Installation instructions for Docker on openSUSE and on SUSE Linux Enterprise."
keywords = ["openSUSE, SUSE Linux Enterprise, SUSE, SLE, docker, documentation,  installation"]
[menu.main]
parent = "smn_linux"
+++
<![end-metadata]-->

# openSUSE

Docker is available in **openSUSE 12.3 and later**. Please note that due
to its current limitations Docker is able to run only **64 bit** architecture.

Docker is not part of the official repositories of openSUSE 12.3 and
openSUSE 13.1. Hence  it is necessary to add the [Virtualization
repository](https://build.opensuse.org/project/show/Virtualization) from
[OBS](https://build.opensuse.org/) to install the `docker` package.

Execute one of the following commands to add the Virtualization repository:

    # openSUSE 12.3
    $ sudo zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_12.3/ Virtualization

    # openSUSE 13.1
    $ sudo zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_13.1/ Virtualization

No extra repository is required for openSUSE 13.2 and later.

# SUSE Linux Enterprise

Docker is available in **SUSE Linux Enterprise 12 and later**. Please note that
due to its current limitations Docker is able to run only on **64 bit**
architecture.

## Installation

Install the Docker package.

    $ sudo zypper in docker

Now that it's installed, let's start the Docker daemon.

    $ sudo systemctl start docker

If we want Docker to start at boot, we should also:

    $ sudo systemctl enable docker

The docker package creates a new group named docker. Users, other than
root user, need to be part of this group in order to interact with the
Docker daemon. You can add users with:

    $ sudo /usr/sbin/usermod -a -G docker <username>

To verify that everything has worked as expected:

    $ sudo docker run --rm -i -t opensuse /bin/bash

This should download and import the `opensuse` image, and then start `bash` in
a container. To exit the container type `exit`.

If you want your containers to be able to access the external network you must
enable the `net.ipv4.ip_forward` rule.
This can be done using YaST by browsing to the
`System -> Network Settings -> Routing` menu (for openSUSE Tumbleweed and later) or `Network Devices -> Network Settings -> Routing` menu (for SUSE Linux Enterprise 12 and previous openSUSE versions) and ensuring that the `Enable IPv4 Forwarding` box is checked.

This option cannot be changed when networking is handled by the Network Manager.
In such cases the `/etc/sysconfig/SuSEfirewall2` file needs to be edited by
hand to ensure the `FW_ROUTE` flag is set to `yes` like so:

    FW_ROUTE="yes"

**Done!**

## Custom daemon options

If you need to add an HTTP Proxy, set a different directory or partition for the
Docker runtime files, or make other customizations, read our systemd article to
learn how to [customize your systemd Docker daemon options](/articles/systemd/).

## Uninstallation

To uninstall the Docker package:

    $ sudo zypper rm docker

The above command will not remove images, containers, volumes, or user created
configuration files on your host. If you wish to delete all images, containers,
and volumes run the following command:

    $ rm -rf /var/lib/docker

You must delete the user created configuration files manually.

## What's next

Continue with the [User Guide](/userguide/).


text:
from direct.directnotify import DirectNotifyGlobal
from toontown.uberdog.DataStore import *

class ScavengerHuntDataStore(DataStore):
    QueryTypes = DataStore.addQueryTypes(['GetGoals', 'AddGoal'])
    notify = DirectNotifyGlobal.directNotify.newCategory('ScavengerHuntDataStore')

    def __init__(self, filepath):
        DataStore.__init__(self, filepath)

    def handleQuery(self, query):
        qId, qData = query
        if qId == self.QueryTypes['GetGoals']:
            avId, goal = qData
            goals = self.__getGoalsForAvatarId(avId)
            return (qId, (avId, goal, goals))
        elif qId == self.QueryTypes['AddGoal']:
            avId, goal = qData
            self.__addGoalToAvatarId(avId, goal)
            return (qId, (avId,))
        return None

    def __addGoalToAvatarId(self, avId, goal):
        if self.wantAnyDbm:
            pAvId = cPickle.dumps(avId)
            pGoal = cPickle.dumps(goal)
            pData = self.data.get(pAvId, None)
            if pData is not None:
                data = cPickle.loads(pData)
            else:
                data = set()
            data.add(goal)
            pData = cPickle.dumps(data)
            self.data[pAvId] = pData
        else:
            self.data.setdefault(avId, set())
            self.data[avId].add(goal)
        self.incrementWriteCount()
        return

    def __getGoalsForAvatarId(self, avId):
        if self.wantAnyDbm:
            pAvId = cPickle.dumps(avId)
            pData = self.data.get(pAvId, None)
            if pData is not None:
                data = list(cPickle.loads(pData))
            else:
                data = []
            return data
        else:
            return list(self.data.get(avId, []))
        return


text:
package com.ultrakline.domian;

public class StockDayEntity {

	String day ="";
	int openDays=1;
	double preOpen = 0.0;
	double opens = 0.0;
	double top = 0.0;
	double low = 0.0;
	double cls = 0.0;
	double amont = 0.0;
	double vol = 0.0;

	public String getDay() {
		return day;
	}
	public void setDay(String day) {
		this.day = day;
	}
	public int getOpenDays() {
		return openDays;
	}
	public void setOpenDays(int openDays) {
		this.openDays = openDays;
	}
	public double getPreOpen() {
		return preOpen;
	}
	public void setPreOpen(double preOpen) {
		this.preOpen = preOpen;
	}
	public double getOpens() {
		return opens;
	}
	public void setOpens(double opens) {
		this.opens = opens;
	}
	public double getTop() {
		return top;
	}
	public void setTop(double top) {
		this.top = top;
	}
	public double getLow() {
		return low;
	}
	public void setLow(double low) {
		this.low = low;
	}
	public double getCls() {
		return cls;
	}
	public void setCls(double cls) {
		this.cls = cls;
	}
	public double getAmont() {
		return amont;
	}
	public void setAmont(double amont) {
		this.amont = amont;
	}
	public double getVol() {
		return vol;
	}
	public void setVol(double vol) {
		this.vol = vol;
	}

}


text:
package e2e

import (
	"context"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/coreos/etcd-operator/pkg/spec"
	"github.com/coreos/etcd-operator/pkg/util/constants"
	"github.com/coreos/etcd-operator/test/e2e/framework"
)

func TestClusterRestore(t *testing.T) {
	t.Run("restore cluster from backup", func(t *testing.T) {
		t.Run("restore from the same name cluster", testClusterRestoreSameName)
		t.Run("restore from a different name cluster", testClusterRestoreDifferentName)
	})
}

func TestClusterRestoreS3(t *testing.T) {
	if os.Getenv("AWS_TEST_ENABLED") != "true" {
		t.Skip("skipping test since AWS_TEST_ENABLED is not set.")
	}

	t.Run("restore cluster from backup on S3", func(t *testing.T) {
		t.Run("restore from the same name cluster", testClusterRestoreS3SameName)
		t.Run("restore from a different name cluster", testClusterRestoreS3DifferentName)
	})
}

func testClusterRestoreSameName(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	testClusterRestore(t, false)
}

func testClusterRestoreDifferentName(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	testClusterRestore(t, true)
}

func testClusterRestore(t *testing.T, needDataClone bool) {
	testClusterRestoreWithStorageType(t, needDataClone, spec.BackupStorageTypePersistentVolume)
}

func testClusterRestoreWithStorageType(t *testing.T, needDataClone bool, bt spec.BackupStorageType) {
	f := framework.Global
	origEtcd := makeEtcdCluster("test-etcd-", 3)
	testEtcd, err := createEtcdCluster(t, f,
		etcdClusterWithBackup(origEtcd, backupPolicyWithStorageType(makeBackupPolicy(false), bt)))
	if err != nil {
		t.Fatal(err)
	}
	names, err := waitUntilSizeReached(t, f, testEtcd.Name, 3, 60*time.Second)
	if err != nil {
		t.Fatalf("failed to create 3 members etcd cluster: %v", err)
	}

	pod, err := f.KubeClient.Pods(f.Namespace).Get(names[0])
	if err != nil {
		t.Fatal(err)
	}
	err = putDataToEtcd(fmt.Sprintf("http://%s:2379", pod.Status.PodIP))
	if err != nil {
		t.Fatal(err)
	}

	if err := waitBackupPodUp(f, testEtcd.Name, 60*time.Second); err != nil {
		t.Fatalf("failed to create backup pod: %v", err)
	}
	if err := makeBackup(f, testEtcd.Name); err != nil {
		t.Fatalf("fail to make a backup: %v", err)
	}
	if err := deleteEtcdCluster(t, f, testEtcd); err != nil {
		t.Fatal(err)
	}
	// waits a bit to make sure resources are finally deleted on APIServer.
	time.Sleep(5 * time.Second)

	if !needDataClone {
		// Restore the etcd cluster of the same name:
		// - use the name already generated. We don't need to regenerate again.
		// - set BackupClusterName to the same name in RestorePolicy.
		// Then operator will use the existing backup in the same storage and
		// restore cluster with the same data.
		origEtcd.GenerateName = ""
		origEtcd.Name = testEtcd.Name
	}
	waitRestoreTimeout := calculateClusterRestoreWaitTime(bt, needDataClone)

	origEtcd = etcdClusterWithRestore(origEtcd, &spec.RestorePolicy{
		BackupClusterName: testEtcd.Name,
		StorageType:       bt,
	})
	testEtcd, err = createEtcdCluster(t, f,
		etcdClusterWithBackup(origEtcd, backupPolicyWithStorageType(makeBackupPolicy(true), bt)))
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := deleteEtcdCluster(t, f, testEtcd); err != nil {
			t.Fatal(err)
		}
	}()
	names, err = waitUntilSizeReached(t, f, testEtcd.Name, 3, waitRestoreTimeout)
	if err != nil {
		t.Fatalf("failed to create 3 members etcd cluster: %v", err)
	}

	pod, err = f.KubeClient.Pods(f.Namespace).Get(names[0])
	if err != nil {
		t.Fatal(err)
	}
	checkEtcdData(t, fmt.Sprintf("http://%s:2379", pod.Status.PodIP))
}

func putDataToEtcd(addr string) error {
	etcdcli, err := createEtcdClient(addr)
	if err != nil {
		return err
	}
	ctx, cancel := context.WithTimeout(context.Background(), constants.DefaultRequestTimeout)
	_, err = etcdcli.Put(ctx, etcdKeyFoo, etcdValBar)
	cancel()
	etcdcli.Close()
	return err
}

func checkEtcdData(t *testing.T, addr string) {
	etcdcli, err := createEtcdClient(addr)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), constants.DefaultRequestTimeout)
	resp, err := etcdcli.Get(ctx, etcdKeyFoo)
	cancel()
	etcdcli.Close()
	if err != nil {
		t.Fatal(err)
	}
	if len(resp.Kvs) != 1 {
		t.Errorf("want only 1 key result, get %d", len(resp.Kvs))
	} else {
		val := string(resp.Kvs[0].Value)
		if val != etcdValBar {
			t.Errorf("value want = '%s', get = '%s'", etcdValBar, val)
		}
	}
}

func calculateClusterRestoreWaitTime(bt spec.BackupStorageType, needDataClone bool) time.Duration {
	var waitTime time.Duration
	switch bt {
	case spec.BackupStorageTypePersistentVolume, spec.BackupStorageTypeDefault:
		// It could take very long due to delay of k8s controller detaching the volume
		waitTime = 180 * time.Second
	default:
		waitTime = 120 * time.Second
	}
	if needDataClone {
		// Take additional time to clone the data.
		waitTime += 60 * time.Second
	}
	return waitTime
}

func testClusterRestoreS3SameName(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	testClusterRestoreWithStorageType(t, false, spec.BackupStorageTypeS3)
}

func testClusterRestoreS3DifferentName(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	testClusterRestoreWithStorageType(t, true, spec.BackupStorageTypeS3)
}