text:
require 'spec_helper'
load File.join(File.dirname(__FILE__), "..",  "auto_refresh_examples.rb")

describe 'stages/stage.html.erb' do

  include StageModelMother, GoUtil, JobMother, PipelineModelMother, ApplicationHelper

  before(:each) do
    view.stub(:is_user_an_admin?).and_return(true)
    view.stub(:config_change_path)

    in_params :pipeline_name => "pipeline_name", :stage_name => "stage_name", :pipeline_counter => 10, :stage_counter => 3
    @stage_history_page = stage_history_page(10)
    assign :stage_history_page, stage_history_page(10)
    empty_material_revision_arr = [].to_java(MaterialRevision)
    @revisions = MaterialRevisions.new( empty_material_revision_arr)
    @revisions.addAll(ModificationsMother.multipleModifications())
    @revisions.addAll(ModificationsMother.multipleModifications(MaterialsMother.hgMaterial()))
    view.stub(:render_comment).and_return("link to traker")
    assign :pipeline, @pipeline =  pipeline_model("pipeline_name", "blah_label", false, false, "working with agent", false, @revisions).getLatestPipelineInstance()
    assign :current_tab,  "overview"
    assign :fbh_pipeline_instances, []
  end

  def mat_revisions()
    modification = Modification.new(@date=java.util.Date.new, "1234", "label-1")
    modification.setUserName("username")
    modification.setComment("I changed something")
    modification.setModifiedFiles([ModifiedFile.new("nimmappa/foo.txt", "", ModifiedAction::added)])
    svn_revisions = ModificationsMother.createSvnMaterialRevisions(modification)
    svn_revisions.getMaterialRevision(0).markAsChanged()
    svn_revisions.materials().get(0).setName("SvnName")
    return svn_revisions
  end

  def pipeline(svn_revisions, counter)
    stage_models = StageInstanceModels.new
    stage_models.add(stage_model("cruise", "10"))
    pipeline = PipelineInstanceModel.createPipeline("pipeline_name", -1, "label", BuildCause.createManualForced(), stage_models)
    pipeline.setCounter(counter);
    pipeline.setMaterialRevisionsOnBuildCause(svn_revisions)
    pipeline
  end

  describe "overview_tab" do
    before(:each) do
      params[:action] = "overview"
      view.stub(:can_view_admin_page?).and_return(false)
      assign :user, Username.new(CaseInsensitiveString.new("bob"))
    end

    describe "stage html" do
      before(:each) do
        assign :stage, stage_with_three_runs()
        params[:pipeline_name] = "cruise"
        params[:pipeline_counter] = "1"
        params[:stage_name] = "dev"
        view.stub(:stage_detail_tab_path)
        assign :failing_tests, StageTestRuns.new(12, 0, 0)
      end

      it "should render stage history" do
        render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"
        expect(response).to have_selector "#stage-history-page[type='hidden'][value='" + @stage_history_page.currentPage().to_s() +"']"
        expect(response).to have_selector "#stage_history"
      end

      it "should render latest materials revisions" do
        render
        @revisions.each do |revision|
          latest = revision.getLatestModification()

          revision.getModifications().each do |mod|
            if mod==latest
              expect(response).to have_selector ".change .revision dd", :text => mod.getRevision()
            else
              expect(response).to_not have_selector ".change .revision dd", :text => mod.getRevision()
            end
          end
        end
        expect(response).to_not have_selector ".modified_files"
      end

      describe :auto_refresh do
        before(:each) do
          @partial = 'stages/stage.html.erb'
          @ajax_refresher = /StageDetailAjaxRefresher/
        end

        it_should_behave_like :auto_refresh
      end

      it "should set title" do
        render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"
        page = Capybara::Node::Simple.new(response.body)
        expect(page.title).to include("Stage Detail")
      end

      describe :title_bar do

        it "should show stage result" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"

          Capybara.string(response.body).find(".result").tap do |result|
            expect(result).to have_selector(".Passed")
            expect(result).to have_selector(".message", :text => "Passed")
          end
        end

        it "should show build cause message" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"

          Capybara.string(response.body).find(".run_details .schedule_info").tap do |f|
            expect(f).to have_selector("span.label", :text => "Automatically triggered")
            expect(f).to have_selector("span.time", :text => /\s+at\s+/)
          end
        end

        it "should show duration" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"
          Capybara.string(response.body).find(".run_details .duration").tap do |f|
            expect(f).to have_selector("span.label", :text => "Duration:")
            expect(f).to have_selector("span.time", :text => /\d{2}:\d{2}:\d{2}/)
          end
        end

        it "should show compare link" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"

          Capybara.string(response.body).find(".run_details").tap do |f|
            expect(f).to have_selector("span.compare_pipeline a[href='/compare/cruise/0/with/1']", :text => "Compare")
          end
        end

        it "should show the schedule info" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"
          Capybara.string(response.body).find(".schedule_info").tap do |f|
            expect(f).to have_selector(".label", :text => "Automatically triggered")
            expect(f).to have_selector(".time", :text => /\s+at\s+/)
          end
        end

        it "should show this stage run among others in its pipeline instance" do
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"
          Capybara.string(response.body).find(".run_results .run").tap do |f|
            expect(f).to have_selector("span.label", :text => "Run:")
            expect(f).to have_selector("#show_other_stage_runs", :text => "2 of 3")
          end
        end

        it "should show links to other stage runs" do
          in_params :action => 'foo'
          view.stub(:stage_detail_tab_path).with(instance_of(Hash)).and_return do |params|
            "url_for_#{params[:pipeline_counter]}_run_#{params[:stage_counter]}"
          end
          view.should_receive(:stage_detail_tab_path).with(:stage_counter => 1, :action => "foo").and_return("url_to_1")
          view.should_receive(:stage_detail_tab_path).with(:stage_counter => 3, :action => "foo").and_return("url_to_3")
          render :template => "stages/stage.html.erb", :layout => "layouts/pipelines.html.erb"

          Capybara.string(response.body).find(".other_runs").tap do |other_runs|
            other_runs.find("li a[href='url_to_1']").tap do |f|
              expect(f).to have_selector "span", :text => "Run: 1 of 3"
              expect(f).to have_selector ".color_code.Passed"
              expect(f).to have_selector ".message", :text => "Passed"
            end
            other_runs.find("li a[href='url_to_3']").tap do |f|
              expect(f).to have_selector "span", :text => "Run: 3 of 3"
              expect(f).to have_selector ".color_code.Failed"
              expect(f).to have_selector ".message", :text => "Failed"
            end
          end
        end
      end
    end

    describe "jobs section with all jobs passed" do
      before(:each) do
        params[:pipeline_name] = "cruise"
        params[:pipeline_counter] = "1"
        params[:stage_name] = "dev"
        view.stub(:stage_detail_tab_path)
        assign :failing_tests, StageTestRuns.new(12, 0, 0)
        assign(:stage, stage_with_all_jobs_passed())
      end

      it "should expand passed section if all jobs passed" do
        render

        Capybara.string(response.body).find(".jobs").tap do |jobs|
          expect(jobs).to have_selector(".jobs_failed.hidereveal_collapsed")
          expect(jobs).to have_selector(".jobs_passed")
          expect(jobs).to_not have_selector(".jobs_passed.hidereveal_collapsed")
          expect(jobs).to have_selector(".jobs_in_progress.hidereveal_collapsed")
        end
      end
    end

    describe "jobs section with passed jobs" do
      before(:each) do
        assign :stage, stage_with_three_runs()

        params[:pipeline_name] = "cruise"
        params[:pipeline_counter] = "1"
        params[:stage_name] = "dev"
        view.stub(:stage_detail_tab_path)

        assign :failing_tests, StageTestRuns.new(12, 0, 0)
      end

      it "should hide in progress section if no jobs are in progress" do
        render

        expect(response.body).to have_selector ".jobs .jobs_in_progress.hidereveal_collapsed"
      end

      it "should hide failed section if no jobs failed" do
        render
        expect(response.body).to have_selector ".jobs .jobs_failed.hidereveal_collapsed"
      end

      it "should render urls" do
        view.stub(:stage_detail_tab_path).with(instance_of(Hash)).and_return do |params|
          "url_for_#{params[:pipeline_counter]}_run_#{params[:stage_counter]}"
        end

        view.stub(:stage_detail_tab_path).with({:action=>"overview"}).and_return("overview_link")
        view.stub(:stage_detail_tab_path).with({:action=>"pipeline"}).and_return("pipeline_link")
        view.stub(:stage_detail_tab_path).with({:action=>"jobs"}).and_return("jobs_link")
        view.stub(:stage_detail_tab_path).with({:action=>"materials"}).and_return("materials_link")
        view.stub(:stage_detail_tab_path).with({:action=>"tests"}).and_return("fbh_link")
        view.stub(:stage_detail_tab_path).with({:action=>"stage_config"}).and_return("config_link")
        view.should_receive(:stage_detail_tab_path).with(:format => 'json', :action=>'jobs').and_return("link_to_json")
        in_params :action => 'jobs'
        assign :jobs, []
        render

        Capybara.string(response.body).find(".sub_tabs_container").tap do |f|
          expect(f).to have_selector "a[href='pipeline_link']", :text => "Pipeline Dependencies"
          expect(f).to have_selector "a[href='materials_link']", :text => "Materials"
          expect(f).to have_selector ".current a[href='jobs_link']", :text => "Jobs"
          expect(f).to have_selector "a[href='fbh_link']", :text => "Tests"
          expect(f).to have_selector "a[href='overview_link']", :text => "Overview"
          expect(f).to have_selector "a[href='config_link']", :text => "Config"
        end

        Capybara.string(response.body).find("script[type='text/javascript']", :visible => false).tap do |script_tag|
          expect(script_tag.text).to include "link_to_json"
        end
      end
    end

    describe "jobs section" do
      before(:each) do
        assign :stage, stage_with_5_jobs()
        params[:pipeline_name] = "cruise"

        params[:pipeline_counter] = "1"
        params[:stage_name] = "dev"
        view.stub(:stage_detail_tab_path)

        assign :failing_tests, StageTestRuns.new(12, 0, 0)
      end

      it "should expand in progress section if any jobs are in progress" do
        render
        expect(response.body).to have_selector ".jobs .jobs_in_progress"
        expect(response.body).to_not have_selector ".jobs .jobs_in_progress.hidereveal_collapsed"
      end

      it "should expand failed section if any jobs failed" do
        render
        expect(response.body).to have_selector ".jobs .jobs_failed"
        expect(response.body).to_not have_selector ".jobs .jobs_failed.hidereveal_collapsed"
      end

      it "should display jobs sections" do
        render
        Capybara.string(response.body).find(".jobs").tap do |jobs|
          jobs.find(".jobs_failed").tap do |job|
            expect(job).to have_selector "span", :text => "Failed: 2"
            job.all(".job").tap do |f|
              expect(f[0]).to have_selector("a", :text => /^[\s\S]*fifth[\s\S]*$/)
              expect(f[0]).to have_selector("a .color_code_small.Cancelled")
              expect(f[1]).to have_selector("a", :text => /^[\s\S]*first[\s\S]*$/)
              expect(f[1]).to have_selector("a .color_code_small.Failed")
            end
          end
          jobs.find(".jobs_passed").tap do |job|
            expect(job).to have_selector "span", :text => "Passed: 2"
            job.all(".job").tap do |f|
              expect(f[0]).to have_selector("a", :text => /^[\s\S]*second[\s\S]*$/)
              expect(f[0]).to have_selector("a .color_code_small.Passed")
              expect(f[1]).to have_selector("a", :text => /^[\s\S]*third[\s\S]*$/)
              expect(f[1]).to have_selector("a .color_code_small.Passed")
            end
          end

          jobs.find(".jobs_in_progress").tap do |job|
            expect(job).to have_selector "span", :text => "In Progress: 1"
            job.all(".job").tap do |f|
              expect(f[0]).to have_selector("a", :text => /^[\s\S]*fourth[\s\S]*$/)
              expect(f[0]).to have_selector("a .color_code_small.Active")
            end
          end

          jobs.find(".hidereveal_collapsed").tap do |job_group|
            expect(job_group).to have_selector ".hidereveal_expander"
            expect(job_group).to have_selector ".hidereveal_content"
            expect(job_group.text).to include "make_collapsable"
          end
        end
      end

    end
  end
  describe "non overview tabs" do

    before(:each) do
      assign :stage, stage_with_three_runs()
    end

    describe "jobs tab" do
      before(:each) do
        params[:action] = "jobs"
        assign :jobs, jobs_model
      end

      it "should render jobs tab" do
        render
        expect(response).to have_selector ".jobs_summary .job .job_name a", :text => "first"
      end

    end

    describe "materials tab" do
      before(:each) do
        params[:action] = "materials"
      end

      it "should render jobs tab" do
        render
        cnt_modifications = 0
        @revisions.each do |revision|
          revision.getModifications().each do |mod|
            expect(response).to have_selector ".change .revision dd", mod.getRevision()
            cnt_modifications += 1
          end
        end
        Capybara.string(response.body).all(".modified_files").tap do |modified_files|
          expect(modified_files.count()).to eq cnt_modifications
        end
      end
    end

    describe "pipeline tab" do
      before(:each) do
        down1 = PipelineHistoryMother.pipelineHistoryItemWithOneStage("down1", "stage", java.util.Date.new())
        down2 = PipelineHistoryMother.pipelineHistoryItemWithOneStage("down2", "stage", java.util.Date.new())
        pim = PipelineHistoryMother.singlePipeline("pipline-name", StageInstanceModels.new)
        assign :graph, PipelineDependencyGraphOld.new(pim, PipelineInstanceModels.createPipelineInstanceModels([down1, down2]))
        params[:action] = 'pipeline'
      end

      it "should render PDG" do
        render
        Capybara.string(response.body).find("#pipeline_visualization").tap do |f|
          expect(f).to have_selector ".upstream"
          expect(f).to have_selector ".current"
          expect(f).to have_selector ".downstream"
        end
      end

      it "should render unsupported message if IE8" do
        view.stub(:is_ie8?).and_return(true)
        render

        Capybara.string(response.body).find("div.vsm_not_supported.notification").tap do |f|
          expect(f).to have_selector "p.information", :text => /^[\s\S]*Your browser is not supported. Please either upgrade your browser or use a different browser to view <a href='http:\/\/www.go.cd\/documentation\/user\/current\/navigation\/value_stream_map\.html' target='_blank'>Value Stream Map<\/a>.[\s\S]*$/
        end
      end

      it "should not render unsupported message if IE9 or Firefox or Chrome or Safari or Opera" do
        view.stub(:is_ie8?).and_return(false)
        render

        expect(response).to_not have_selector "div.vsm_not_supported.notification"
      end

    end

    describe "fbh tab" do
      before(:each) do
        params[:action] = 'tests'
        view.stub(:failure_details_path).and_return("/path/to/failures")
      end
      describe :failingTestsWithMultiplePipelines do
        before(:each) do
          job_identifier = JobIdentifier.new(nil, 1, nil, nil, nil, "job-1")
          @failing_tests = StageTestRuns.new(2,1,1)
          @failing_tests.add(10, "1.0", "suite1", "test1-2", TestStatus::Failure, job_identifier)
          @failing_tests.add(10, "1.0", "suite1", "test1-1", TestStatus::Error, job_identifier)
          @failing_tests.add(11, "1.1", "suite1", "test1-1", TestStatus::Error, job_identifier)
          @failing_tests.add(9, "0.9", "suite1", "test1-2", TestStatus::Failure, job_identifier)
          @failing_tests.addUser(10, "1.0", "user1")

          @failing_tests.addUser(10, "1.0", "user2")
          @failing_tests.addUser(11, "1.1", "user3")
          @failing_tests.removeDuplicateTestEntries()

          assign :failing_tests, @failing_tests
          assign :stage, failing_stage("dev")
        end

        describe "fbh partial caching" do
          before(:each) do
            assign :response_format, "html"
          end

          it "should cache fbh partial" do
            @failing_stage = StageMother.custom("dev")
            @failing_stage.getJobInstances().get(0).fail()
            @failing_stage.calculateResult()

            @passed_stage = StageMother.custom("dev")
            @passed_stage.passed()
            @passed_stage.setIdentifier(@failing_stage.getIdentifier())
            check_fragment_caching(@failing_stage, @passed_stage, proc {|stage| [ViewCacheKey.new.forFbhOfStagesUnderPipeline(stage.getIdentifier().pipelineIdentifier()), {:subkey => ViewCacheKey.new.forFailedBuildHistoryStage( stage, "html" )}]}) do |stage|
              assign :stage, stage_model_for(stage)
              render
            end
          end

          it "should use html to scope the key to format" do
            failing_stage = StageMother.custom("dev")
            failing_stage.getJobInstances().get(0).fail()
            failing_stage.calculateResult()

            assign :stage, stage_model_for(failing_stage)
            view.stub(:view_cache_key).and_return(key = double('view_cache_key'))
            key.should_receive(:forFbhOfStagesUnderPipeline).with(failing_stage.getIdentifier().pipelineIdentifier()).and_return("pipeline_id_based_key")
            key.should_receive(:forFailedBuildHistoryStage).with(failing_stage, "html").and_return("stage_fbh_html_key")
            view.should_receive(:cache).with("pipeline_id_based_key", :subkey => "stage_fbh_html_key", :skip_digest=>true)
            render
          end
        end

        it "should contain header text" do
          render
          Capybara.string(response.body).find(".non_passing_tests").tap do |f|
            expect(f).to have_selector ".message", :text => "New Tests Broken Since: (ordered by check-in/material time)"
            expect(f).to have_selector ".counts .total", :text => "Tests Run: 2"
            expect(f).to have_selector ".counts .failures", :text => "Total Failures: 1"
            expect(f).to have_selector ".counts .errors", :text => "Total Errors: 1"
          end
        end

        it "should display message for empty stages" do
          render
          expect(response).to have_selector(".non_passing_tests #failing_pipeline2 .block_to_hide_or_reveal_by_above_pipeline_bar", :text => "These changes did not break any of the currently failing tests.")
        end

        it "should display user that trigger the pipeline" do
          render
          expect(response).to have_selector(".non_passing_tests #failing_pipeline0 .users", :text => "By user1, user2")
          expect(response).to have_selector(".non_passing_tests #failing_pipeline1 .users", :text => "By user3")
          expect(response).to_not have_selector(".non_passing_tests #failing_pipeline2 .users")
        end

        it "should be grouped by pipeline" do
          render

          Capybara.string(response.body).find(".non_passing_tests").tap do |f|
            expect(f).to have_selector ".counts .failures", :text => "Total Failures: 1"
            expect(f).to have_selector ".counts .errors", :text => "Total Errors: 1"
          end
          Capybara.string(response.body).find(".non_passing_tests #failing_pipeline0").tap do |f|
            expect(f).to have_selector ".pipeline_bar .pipeline_label", :text => "Pipeline Label: 1.0"
            expect(f).to have_selector ".pipeline_bar .counts .failures", :text => "Unique Failures: 1"
            expect(f).to have_selector ".pipeline_bar .counts .errors", :text => "Unique Errors: 0"
            expect(f).to have_selector ".suite .suite_name", :text => "suite1"
            f.find(".test_suite").tap do |test_suite|
              expect(test_suite).to have_selector ".test_case .test_name .name", :text => "test1-2"
              expect(test_suite).to_not have_selector ".test_case .test_name .name", :text => "test1-1"

            end
          end
          Capybara.string(response.body).find(".non_passing_tests #failing_pipeline1").tap do |f|
            expect(f).to have_selector ".pipeline_bar .pipeline_label", :text => "Pipeline Label: 1.1"
            expect(f).to have_selector ".pipeline_bar .counts .failures", :text => "Unique Failures: 0"
            expect(f).to have_selector ".pipeline_bar .counts .errors", :text => "Unique Errors: 1"
            expect(f).to have_selector ".suite .suite_name", :text => "suite1"
            f.find(".test_suite").tap do |test_suite|
              expect(test_suite).to_not have_selector ".test_case .test_name .name", :text => "test1-2"
              expect(test_suite).to have_selector ".test_case .test_name .name", :text => "test1-1"
            end
          end

          Capybara.string(response.body).find(".non_passing_tests #failing_pipeline2").tap do |f|
            expect(f).to have_selector ".pipeline_bar .pipeline_label", :text => "Pipeline Label: 0.9"
            expect(f).to have_selector ".pipeline_bar .counts .failures", :text => "Unique Failures: 0"
            expect(f).to have_selector ".pipeline_bar .counts .errors", :text => "Unique Errors: 0"
            expect(f).to_not have_selector ".test_suite"
          end
        end
      end

      describe :testsCounts do
        before(:each) do
          @failing_tests = StageTestRuns.new(2, 0, 0)
          assign :failing_tests, @failing_tests
        end

        it "should show the number of test runs if the stage passed" do
          assign :failing_tests, @failing_tests
          assign :stage, stage_with_all_jobs_passed()

          render
          Capybara.string(response.body).find(".non_passing_tests").tap do |f|
            expect(f).to have_selector "h3 .counts .total", :text => "Tests Run: 2"
            expect(f).to have_selector "h3 .counts .failures", :text => "Total Failures: 0"
            expect(f).to have_selector "h3 .counts .errors", :text => "Total Errors: 0"
            expect(f).to have_selector "h3 .message", :text => "The stage passed"
          end
          expect(response).to_not have_selector(".non_passing_tests .failing_pipeline")
        end

        it "should show a message and the failure/error count if the stage passed" do
          assign :failing_tests, StageTestRuns.new(4, 1, 1)
          assign :stage, stage_with_all_jobs_passed()

          render

          Capybara.string(response.body).find(".non_passing_tests").tap do |f|
            expect(f).to have_selector "h3 .counts .total", :text => "Tests Run: 4"
            expect(f).to have_selector "h3 .counts .failures", :text => "Total Failures: 1"
            expect(f).to have_selector "h3 .counts .errors", :text => "Total Errors: 1"
          end
          Capybara.string(response.body).find(".non_passing_tests").tap do |f|
            expect(f).to have_selector "h3 .message", :text => "Although all the jobs in this stage have passed, there are some tests that have failed."
            expect(f).to have_selector "h3 .message", :text => "This is may be due to the test task configuration in the build script. You might want to fail the build on test failures."
          end
        end
      end

      it "should return no tests configured message" do
        assign :failing_tests, StageTestRuns.new(0, 0, 0)
        render

        Capybara.string(response.body).find(".non_passing_tests").tap do |f|
          expect(f).to have_selector "h3 .message", :text => "There are tests configured in this stage but could not compute results."
        end

        expect(response).to_not have_selector(".non_passing_tests .failing_pipeline")
        expect(response).to_not have_selector(".non_passing_tests .counts")
      end

      describe :failingTests do
        before(:each) do
          @failing_tests = StageTestRuns.new(4, 0, 0)
          job1 = JobIdentifier.new('pipeline', 1, "label", "stage", "1", "job1")
          job2 = JobIdentifier.new('pipeline', 1, "label", "stage", "1", "job2")
          @failing_tests.add(12, "1.2", "suite1", "test1-1", TestStatus::Error, job1)
          @failing_tests.add(12, "1.2", "suite1", "test1-2", TestStatus::Failure, job1)
          @failing_tests.add(12, "1.2", "suite1", "test1-2", TestStatus::Failure, job2)
          @failing_tests.add(12, "1.2", "suite2", "test2-1", TestStatus::Error, job2)
          @failing_tests.add(12, "1.2", "suite2", "test2-2", TestStatus::Failure, job2)
          @failing_tests.add(12, "1.2", "suite2", "test2-2", TestStatus::Error, job1)
          assign :failing_tests, @failing_tests
          stage = failing_stage("dev")
          assign :stage, stage
        end

        it "should render failure message if set" do
          assign :failing_tests_error_message, "Unable to connect to shine"
          render
          expect(response).to have_selector(".non_passing_tests .error", :text => "Unable to connect to shine")
        end

        it "should be grouped by test suite" do
          render
          Capybara.string(response.body).all(".non_passing_tests .suite .suite_name").tap do |f|
            expect(f[0].text).to eq "suite1"
            expect(f[1].text).to eq "suite2"
          end
        end

        it "should show test cases under suite" do
          render
          Capybara.string(response.body).all(".non_passing_tests .test_suite").tap do |test_suites|

            first = test_suites[0]
            second = test_suites[1]

            first.all(".test_case").tap do |test_cases|
              expect(test_cases[0]).to have_selector ".test_name .name", :text => "test1-1"
              expect(test_cases[0]).to have_selector(".jobs a[href='/tab/build/detail/pipeline/1/stage/1/job1']", :text => "job1")
              expect(test_cases[0]).to have_selector(".test_status .Error", :text => /^[\s\S]*$/)

              expect(test_cases[1]).to have_selector ".test_name .name", :text => "test1-2"
              expect(test_cases[1]).to have_selector(".jobs a[href='/tab/build/detail/pipeline/1/stage/1/job1']", :text => "job1")
              expect(test_cases[1]).to have_selector(".jobs a[href='/tab/build/detail/pipeline/1/stage/1/job2']", :text => "job2")
              expect(test_cases[1]).to have_selector(".test_status .Failure", :text => /^[\s\S]*$/)

            end
            second.all(".test_case").tap do |test_cases|
              expect(test_cases[0]).to have_selector ".test_name .name", :text => "test2-1"
              expect(test_cases[0]).to have_selector(".jobs a[href='/tab/build/detail/pipeline/1/stage/1/job2']", :text => "job2")
              expect(test_cases[0]).to have_selector(".test_status .Error", :text => /^[\s\S]*$/)

              expect(test_cases[1]).to have_selector ".test_name .name", :text => "test2-2"
              expect(test_cases[1]).to have_selector(".jobs a[href='/tab/build/detail/pipeline/1/stage/1/job2']", :text => "job2")
              expect(test_cases[1]).to have_selector(".test_status .Failure", :text => /^[\s\S]*$/)

            end
          end
        end
      end
    end

    describe "stats tab" do
      before(:each) do
        params[:action] = "stats"
        assign :chart_stage_duration, [{"link"=> "/pipelines/pipeline-name/1/stage/1", "x" => 1, "y"=>10.0}, {"link" => "/pipelines/pipeline-name/2/stage/1", "x" => 2, "y"=> 20.0}].to_json
        assign :chart_tooltip_data, {"1_60" => ["00:10:00", "22 Feb, 2008 at 10:21:23 [+0530]", "LABEL-1"], "2_120" => ["00:20:00", "22 Feb, 2008 at 10:21:23 [+0530]", "LABEL-2"]}.to_json
        assign :pagination, Pagination.pageStartingAt(12, 200, 10)
        assign :start_end_dates, ["start date", "end date"]
        assign :chart_scale, "some scale"
      end

      it "should render stats tab with chart for given stage" do
        render
        Capybara.string(response.body).find("#stage_stats .stats").tap do |f|
          expect(f).to have_selector("#chart_details_container #highcharts")
          expect(f.find("#chart_details_container script[type='text/javascript']", :visible => false).text).to include "tooltipData:"
          expect(f.find("#chart_details_container script[type='text/javascript']", :visible => false).text).to include "data:"
        end
      end

      it "should show prev and next links if page_number is 2" do
        params[:page_number] = "2"

        render

        Capybara.string(response.body).find("#stage_stats .stats").tap do |f|
          expect(f).to have_selector("a[href='#{stage_detail_tab_path(:action => "stats", :page_number => "1")}']", :text => "Newer")
          expect(f).to have_selector("a[href='#{stage_detail_tab_path(:action => "stats", :page_number => "3")}']", :text => "Older")
        end
      end
    end

    describe "config tab" do
      before(:each) do
        params[:action] = "stage_config"
        assign :ran_with_config_revision,  GoConfigRevision.new("config-xml", "my-md5", "loser", "2.3.0", TimeProvider.new);
        view.stub(:is_user_an_admin?).and_return(true)
      end

      it "should render Config tab" do
        render
        expect(response).to have_selector("#ran_with_config .config")
      end

      it "should render Config tab with message if user is not admin" do
        view.stub(:is_user_an_admin?).and_return(false)
        render

        Capybara.string(response.body).find("#ran_with_config .config").tap do |f|
          expect(f).to have_selector("div.notification p.information", :text => "Historical configuration is available only for Go Administrators.")
        end
      end

      it "should render the config file contents in config tab" do
        render
        Capybara.string(response.body).find("#ran_with_config .config").tap do |f|
          expect(f).to have_selector("pre#content_container.wrap_pre", :text => "config-xml")
        end
      end

      it "should render information message if no revision is found" do
        assign :ran_with_config_revision, nil
        render
        Capybara.string(response.body).find("#ran_with_config div.config").tap do |f|
          expect(f).to have_selector("div.notification p.information", :text => "Historical configuration is not available for this stage run.")
        end
      end
    end
  end
end


text:
#include <iostream>
#include <memory>
#include <llvm/ADT/STLExtras.h>
#include "../include/parser.hpp"
#include "../include/debug.hpp"

namespace llscm {
	using namespace std;
	using namespace llvm;

	bool Parser::match(const Token * tok, const Token && expected) {
		if (!tok || *tok != expected) {
			stringstream ss;
			ss << "Expected token \"" << expected.name << "\".";
			error(ss.str());
			return false;
		}
		return true;
	}

	void Parser::error(const string & msg) {
		cout << "Error: " << msg << endl;
		err_flag = true;
	}

	/*
	 * prog = form { form }
	 */
	ScmProg Parser::NT_Prog() {
		const Token * tok;
		ScmProg prog;
		bool first = true;

		D(cerr << "NT_Prog: " << endl);

		while (true) {
			tok = reader->nextToken();

			if (!tok) {
				if (first) {
					error("Program is empty.");
					return prog;
				}
				else break;
			}
			//D(cerr << tok->name << endl);
			P_ScmObj form = NT_Form();
			if (fail()) break;
			prog.push_back(move(form));
			first = false;
		}

		return prog;
	}

	/*
	 * form = "(" def ")" | expr | "(" "require" str ")"
	 * def = "define" sym expr ...
	 * expr = atom | "(" callsyn ")" | "'" data
	 */
	P_ScmObj Parser::NT_Form() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		D(cerr << "NT_Form: " << endl);
		D(cerr << tok->name << endl);

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();
			if (!tok) {
				error("Reached EOF while parsing a list.");
				return nullptr;
			}
			//D(cerr << tok->name << endl);
			if (tok->t == KWRD && tok->kw == KW_DEFINE) {
				// Current token is "define"
				reader->nextToken();
				obj = NT_Def();
				if (fail()) return nullptr;
			}
			else if (tok->t == KWRD && tok->kw == KW_REQUIRE) {
				tok = reader->nextToken();
				if (!tok) {
					error("Expected name of the required module.");
				}
				if (tok->t == STR) {
					obj = make_unique<ScmRequire>(make_unique<ScmStr>(tok->name));
					reader->nextToken();
				}
				else {
					error("Expected string with the required module name.");
				}
			}
			else {
				obj = NT_CallOrSyntax();
				if (fail()) return nullptr;
			}

			if (!match(reader->currToken(), Token(KW_RPAR))) {
				return nullptr;
			}
			return obj;
		}

		if (tok->t == KWRD && tok->kw == KW_QUCHAR) {
			// Quote, short form
			reader->nextToken();
			obj = NT_Data();
			if (fail()) return nullptr;
			return make_unique<ScmQuoteSyntax>(move(obj));
		}

		// Anything other than "(" must be an atom
		return NT_Atom(false);
	}

	/*
	 * callsyn = "lambda" "(" symlist ")" body
	 *		   | "quote" data
	 *		   | "if" expr expr expr
	 *		   | "let" "(" bindlist ")" body
	 *		   | "and" { expr }
	 *		   | "or" { expr }
	 *		   | expr { expr }
	 */
	P_ScmObj Parser::NT_CallOrSyntax() {
		const Token * tok = reader->currToken();
		P_ScmObj expr, ce, te, ee;
		vector<P_ScmObj> lst;

		D(cerr << "NT_CallOrSyntax: " << endl);
		if (!tok) {
			error("Reached EOF while parsing a list.");
			return nullptr;
		}

		if (tok->t == KWRD) {
			switch (tok->kw) {
				case KW_LAMBDA:
					tok = reader->nextToken();

					/*if (!match(tok, Token(KW_LPAR))) {
						return nullptr;
					}*/
					if (tok->t == KWRD && tok->kw == KW_LPAR) {
						reader->nextToken();
						expr = NT_SymList();
						if (fail()) return nullptr;

						if (!match(reader->currToken(), Token(KW_RPAR))) {
							return nullptr;
						}
					}
					else if (tok->t == KWRD && tok->kw == KW_NULL) {
						// We also accept leteral "null" as empty list
						// so that quoted code is evaluated right
						expr = make_unique<ScmNull>(true);
					}
					else {
						error("Expected lambda argument list.");
						return nullptr;
					}

					reader->nextToken();
					return make_unique<ScmLambdaSyntax>(move(expr), NT_Body());
				case KW_QUOTE:
					tok = reader->nextToken();
					if (!tok || (tok->t == KWRD && tok->kw == KW_RPAR)) {
						error("Expected atom or list to quote.");
						return nullptr;
					}
					expr = NT_Data();
					if (fail()) return nullptr;
					reader->nextToken();
					return make_unique<ScmQuoteSyntax>(move(expr));
				case KW_IF:
					tok = reader->nextToken();
					if (!tok || (tok->t == KWRD && tok->kw == KW_RPAR)) {
						error("Missing condition expression.");
						return nullptr;
					}
					ce = NT_Expr();
					if (fail()) return nullptr;
					tok = reader->nextToken();
					if (!tok || (tok->t == KWRD && tok->kw == KW_RPAR)) {
						error("Missing then expression.");
						return nullptr;
					}
					te = NT_Expr();
					if (fail()) return nullptr;
					tok = reader->nextToken();
					if (!tok || (tok->t == KWRD && tok->kw == KW_RPAR)) {
						error("Missing else expression.");
						return nullptr;
					}
					ee = NT_Expr();
					if (fail()) return nullptr;
					reader->nextToken();
					return make_unique<ScmIfSyntax>(move(ce), move(te), move(ee));
				case KW_LET:
					D(cerr << "NT_Let: " << endl);
					tok = reader->nextToken();

					/*if (!match(tok, Token(KW_LPAR))) {
						return nullptr;
					}*/
					if (tok->t == KWRD && tok->kw == KW_LPAR) {
						reader->nextToken();
						//D(cerr << tok->name << endl);

						expr = NT_BindList();
						if (fail()) return nullptr;
						if (!match(reader->currToken(), Token(KW_RPAR))) {
							return nullptr;
						}
					}
					else if (tok->t == KWRD && tok->kw == KW_NULL) {
						// We also accept leteral "null" as empty list
						// so that quoted code is evaluated right
						expr = make_unique<ScmNull>(true);
					}
					else {
						error("Expected let binding list.");
						return nullptr;
					}

					reader->nextToken();
					//D(cerr << tok->name << endl);

					return make_unique<ScmLetSyntax>(move(expr), NT_Body());
				case KW_AND:
					tok = reader->nextToken();
					do {
						if (!tok) {
							error("Reached EOF while parsing and expression.");
							return nullptr;
						}
						if (tok->t == KWRD && tok->kw == KW_RPAR) {
							return make_unique<ScmAndSyntax>(makeScmList(move(lst)));
						}
						lst.push_back(NT_Expr());
						if (fail()) return nullptr;
						tok = reader->nextToken();
					} while (true);
				case KW_OR:
					tok = reader->nextToken();
					do {
						if (!tok) {
							error("Reached EOF while parsing or expression.");
							return nullptr;
						}
						if (tok->t == KWRD && tok->kw == KW_RPAR) {
							return make_unique<ScmOrSyntax>(makeScmList(move(lst)));
						}
						lst.push_back(NT_Expr());
						if (fail()) return nullptr;
						tok = reader->nextToken();
					} while (true);
				case KW_LPAR:
					break; // Fall through to function call
				case KW_RPAR:
					error("Missing function expression or syntax keyword.");
					return nullptr;
				default:
					error("Unexpected keyword at first list position.");
					return nullptr;
			}
		}
		// else: function call

		expr = NT_Expr(); // function
		if (fail()) return nullptr;
		tok = reader->nextToken();
		do {
			if (!tok) {
				error("Reached EOF while parsing function call.");
				return nullptr;
			}
			if (tok->t == KWRD && tok->kw == KW_RPAR) {
				return make_unique<ScmCall>(move(expr), makeScmList(move(lst)));
			}
			lst.push_back(NT_Expr());
			if (fail()) return nullptr;
			tok = reader->nextToken();
		} while (true);
	}

	/*
	 * def = "define" sym expr
	 *		 | "define" "(" sym symlist ")" body
	 */
	P_ScmObj Parser::NT_Def() {
		const Token * tok = reader->currToken();
		P_ScmObj name, lst, expr;

		D(cerr << "NT_Def: " << endl);

		if (!tok) {
			error("Reached EOF while parsing a definition.");
			return nullptr;
		}
		D(cerr << tok->name << endl);

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			// Function definition
			tok = reader->nextToken();
			if (!tok || tok->t != SYM) {
				error("Missing function name in definition.");
				return nullptr;
			}
			name = make_unique<ScmSym>(tok->name);
			reader->nextToken();
			lst = NT_SymList();
			if (fail()) return nullptr;

			if (!match(reader->currToken(), Token(KW_RPAR))) {
				return nullptr;
			}
			reader->nextToken();

			return make_unique<ScmDefineFuncSyntax>(move(name), move(lst), NT_Body());
		}
		if (tok->t != SYM) {
			error("Expected symbol as first argument of define.");
			return nullptr;
		}
		name = make_unique<ScmSym>(tok->name);
		tok = reader->nextToken();
		//D(cerr << tok->name << endl);
		if (tok && tok->t == KWRD && tok->kw == KW_RPAR) {
			error("Missing expression in variable definition.");
			return nullptr;
		}

		expr = NT_Expr();
		if (fail()) return nullptr;
		reader->nextToken();
		//D(cerr << tok->name << endl);

		return make_unique<ScmDefineVarSyntax>(move(name), move(expr));
	}

	/*
	 * expr = atom | ( "(" callsyn ")" ) | "'" data
	 */
	P_ScmObj Parser::NT_Expr() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		D(cerr << "NT_Expr: " << endl);

		if (!tok) {
			error("Expected expression.");
			return nullptr;
		}

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			reader->nextToken();
			obj = NT_CallOrSyntax();
			if (fail()) return nullptr;

			if (!match(reader->currToken(), Token(KW_RPAR))) {
				return nullptr;
			}
			return obj;
		}
		D(cerr << tok->name << endl);

		if (tok->t == KWRD && tok->kw == KW_QUCHAR) {
			// Quote, short form
			reader->nextToken();
			obj = NT_Data();
			if (fail()) return nullptr;
			return make_unique<ScmQuoteSyntax>(move(obj));
		}

		return NT_Atom(false);
	}

	/*
	 * data = atom | ( "(" list ")" ) | "'" data
	 */
	P_ScmObj Parser::NT_Data() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		D(cerr << "NT_Data: " << endl);

		if (!tok) {
			error("Expected atom or list.");
			return nullptr;
		}

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();

			if (!tok) {
				error("Reached EOF while parsing a list.");
				return nullptr;
			}

			D(cerr << tok->name << endl);

			if (tok->t == KWRD && tok->kw == KW_RPAR) {
				// Empty list
				D(cerr << "EMPTY LIST" << endl);
				obj = make_unique<ScmNull>(true);
			}
			else {
				obj = NT_List();
			}
			if (fail()) return nullptr;

			if (!match(reader->currToken(), Token(KW_RPAR))) {
				return nullptr;
			}
			return obj;
		}

		// Short form quote inside quote (eval as symbol "quote")
		if (tok->t == KWRD && tok->kw == KW_QUCHAR) {
			// Quote, short form
			reader->nextToken();
			if (fail()) return nullptr;
			return makeScmList({make_unique<ScmSym>("quote"), NT_Data()});
		}

		D(cerr << tok->name << endl);
		return NT_Atom(true);
	}

	/*
	 * atom = str | sym | int | float | true | false | null
	 */
	P_ScmObj Parser::NT_Atom(bool quoted) {
		const Token * tok = reader->currToken();

		D(cerr << "NT_Atom: " << endl);

		switch (tok->t) {
			case STR:
				return make_unique<ScmStr>(tok->name);
			case SYM:
				return make_unique<ScmSym>(tok->name);
			case INT:
				return make_unique<ScmInt>(tok->int_val);
			case FLOAT:
				return make_unique<ScmFloat>(tok->float_val);
			case ERR:
				err_flag = true;
				return nullptr;
			default:;
		}

		if (tok->t != KWRD) {
			error("Invalid token for an atom.");
			return nullptr;
		}
		switch (tok->kw) {
			case KW_TRUE:
				return make_unique<ScmTrue>();
			case KW_FALSE:
				return make_unique<ScmFalse>();
			case KW_NULL:
				return make_unique<ScmNull>();
			default:
				if (!quoted) error("Invalid token for an atom.");
		}
		return make_unique<ScmSym>(tok->name);
	}

	/*
	 * list = { data }
	 */
	P_ScmObj Parser::NT_List() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		D(cerr << "NT_List: " << endl);
		if (!tok) {
			error("Reached EOF while parsing a list.");
			return nullptr;
		}

		D(cerr << tok->name << endl);

		if (tok->t == KWRD && tok->kw == KW_RPAR) {
			// End of list
			return make_unique<ScmNull>();
		}
		obj = NT_Data();
		if (fail()) return nullptr;
		reader->nextToken();
		return make_unique<ScmCons>(move(obj), NT_List());
	}

	/*
	 * symlist = { sym }
	 */
	P_ScmObj Parser::NT_SymList() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		if (!tok) {
			error("Reached EOF while parsing a list.");
			return nullptr;
		}

		if (tok->t == KWRD && tok->kw == KW_RPAR) {
			// Empty list
			return make_unique<ScmNull>();
		}
		if (tok->t != SYM) {
			error("Invalid expression in argument list. Only symbols are allowed.");
			return nullptr;
		}
		obj = make_unique<ScmSym>(tok->name);
		reader->nextToken();
		return make_unique<ScmCons>(move(obj), NT_SymList());
	}

	/*
	 * bindlist = { "(" sym expr ")" }
	 */
	P_ScmObj Parser::NT_BindList() {
		const Token * tok = reader->currToken();
		vector<P_ScmObj> vec;

		D(cerr << "NT_BindList" << endl);
		if (!tok) {
			error("Reached EOF while parsing a list.");
			return nullptr;
		}

		D(cerr << tok->name << endl);

		if (tok->t == KWRD && tok->kw == KW_RPAR) {
			// Empty list
			return make_unique<ScmNull>();
		}
		if (!match(reader->currToken(), Token(KW_LPAR))) {
			return nullptr;
		}
		tok = reader->nextToken();
		//D(cerr << tok->name << endl);

		if (!tok || tok->t != SYM) {
			error("First element of binding list must be a symbol.");
			return nullptr;
		}

		vec.push_back(make_unique<ScmSym>(tok->name));
		tok = reader->nextToken();

		if (!tok) {
			error("Reached EOF while parsing a list.");
			return nullptr;
		}

		if (tok->t == KWRD && tok->kw == KW_RPAR) {
			error("Binding list must have exactly two elements: id, expression.");
			return nullptr;
		}
		//D(cerr << tok->name << endl);

		vec.push_back(NT_Expr());
		if (!match(reader->nextToken(), Token(KW_RPAR))) {
			return nullptr;
		}
		reader->nextToken();
		//D(cerr << tok->name << endl);

		return make_unique<ScmCons>(makeScmList(move(vec)), NT_BindList());
	}

	/*
	 * body = { form } ; with at least one expr
	 */
	P_ScmObj Parser::NT_Body() {
		vector<P_ScmObj> lst;
		const Token * tok = reader->currToken();
		P_ScmObj obj;
		bool expr = false;

		D(cerr << "NT_Body" << endl);

		do {
			if (!tok) {
				error("Reached EOF while parsing a body.");
				return nullptr;
			}
			if (tok->t == KWRD && tok->kw == KW_RPAR) {
				if (!expr) {
					error("Missing expression at the end of a body.");
					return nullptr;
				}
				return makeScmList(move(lst));
			}
			obj = NT_Form();
			if (obj->t == T_DEF) {
				expr = false;
			}
			else {
				expr = true;
			}
			lst.push_back(move(obj));
			if (fail()) return nullptr;
			tok = reader->nextToken();
		} while (true);
	}
}

redpajama_set_name: RedPajamaGithub


text:
## Common build issues:

### Cannot find g_shaders.h

```
Rift-Volume\src\Util\GL\ShaderFunctions.cpp(21): fatal error C1083: Cannot open include file: 'g_shaders.h': No such file or directory
```

#### Solution
`python` needs to be installed and in your path. When CMakeLists.txt configures the build, `tools/hardcode_shaders.py` runs and generates the file g_shaders.h

### Cannot find DCMTK

```
Rift-Volume\src\Dicom\DicomLoader.h(12): fatal error C1083: Cannot open include file: 'dcmtk/config/osconfig.h': No such file or directory
```

#### Solution

See [BuildingDCMTK.md](BuildingDCMTK.md): obtain and build [OFFIS's DCMTK DICOM Toolkit](http://git.dcmtk.org/web/), and configure **DCMTK\_DEBUG** or **DCMTK\_RELEASE** in CMakeLists.txt(or `cmake-gui`) to point to the root of its path. Also, make sure **USE\_DCMTK** is turned on (as it is by default).


text:
Trace-VstsEnteringInvocation $MyInvocation
Import-VstsLocStrings "$PSScriptRoot\Task.json"

function Write-Exception
{
    param (
        $exception
    )

    if($exception.Message)
    {
        Write-Error ($exception.Message)
    }
    else
    {
        Write-Error ($exception)
    }
    throw
}

function Get-SingleFile
{
    param (
        [string]$pattern
    )

    Write-Verbose "Finding files with pattern $pattern"
    $files = Find-VstsFiles -LegacyPattern "$pattern"
    Write-Verbose "Matched files = $files"

    if ($files -is [system.array])
    {
        throw (Get-VstsLocString -Key "Foundmorethanonefiletodeploywithsearchpattern0Therecanbeonlyone" -ArgumentList $pattern)
    }
    else
    {
        if (!$files)
        {
            throw (Get-VstsLocString -Key "Nofileswerefoundtodeploywithsearchpattern0" -ArgumentList $pattern)
        }
        return $files
    }
}

function New-SqlBatchFilesDestDirectory
{
    param (
        [string]$directoryName
    )

    if ((Test-Path -Path $directoryName) -eq $true)
    {

        Get-ChildItem -Path $directoryName -Force -Recurse |
            Sort-Object -Property FullName -Descending |
            Remove-Item -Recurse -Force | Out-Null

        Remove-Item -Path $directoryName -Force | Out-Null
    }

    New-Item -Path $directoryName -ItemType Directory | Out-Null
}

$taskType = Get-VstsInput -Name "TaskType" -Require
$dacpacFile = Get-VstsInput -Name "dacpacFile"
$sqlFiles = Get-VstsInput -Name "sqlFile"
$executeInTransaction = Get-VstsInput -Name "ExecuteInTransaction" -AsBool
$exclusiveLock = Get-VstsInput -Name "ExclusiveLock" -AsBool
$appLockName = Get-VstsInput -Name "AppLockName"
$inlineSql = Get-VstsInput -Name "inlineSql"
$targetMethod = Get-VstsInput -Name "targetMethod"
$serverName = Get-VstsInput -Name "serverName" -Require
$databaseName = Get-VstsInput -Name "databaseName" -Require
$authscheme = Get-VstsInput -Name "authscheme" -Require
$sqlUsername = Get-VstsInput -Name "sqlUsername"
$sqlPassword = Get-VstsInput -Name "sqlPassword"
$connectionString = Get-VstsInput -Name "connectionString"
$publishProfile = Get-VstsInput -Name "publishProfile"
$additionalArguments = Get-VstsInput -Name "additionalArguments"
$additionalArgumentsSql = Get-VstsInput -Name "additionalArgumentsSql"

Import-Module $PSScriptRoot\ps_modules\TaskModuleSqlUtility
. "$PSScriptRoot\Utility.ps1"
. "$PSScriptRoot\GenerateSqlBatchFiles.ps1"

Try
{

    if ($taskType -ne "dacpac")
    {
        $additionalArguments = $additionalArgumentsSql
        $targetMethod = "server"
    }

    if($sqlUsername -and $sqlPassword)
    {
        $secureAdminPassword = "$sqlPassword" | ConvertTo-SecureString  -AsPlainText -Force
        $sqlServerCredentials = New-Object System.Management.Automation.PSCredential ("$sqlUserName", $secureAdminPassword)
    }

    if ($taskType -eq "dacpac")
    {
        $dacpacFile = Get-SingleFile -pattern $dacpacFile
        Invoke-DacpacDeployment -dacpacFile $dacpacFile -targetMethod $targetMethod -serverName $serverName -databaseName $databaseName -authscheme $authscheme -sqlServerCredentials $sqlServerCredentials -connectionString $connectionString -publishProfile $publishProfile -additionalArguments $additionalArguments
    }
    else
    {
        if ($taskType -eq "sqlQuery")
        {
            if ($executeInTransaction)
            {
                if ($exclusiveLock -and ($appLockName.Length -eq 0))
                {
                    Write-Error "Invalid Applock name. exclusiveLock: $exclusiveLock, appLockName: $appLockName"
                }

                $batch = 1
                $destPath = [System.IO.Path]::Combine($env:SYSTEM_DEFAULTWORKINGDIRECTORY, "batchdir")
                New-SqlBatchFilesDestDirectory -directoryName $destPath

                $sqlScriptsWithExpandedPath = ""
                $sqlScriptFiles = $sqlFiles -split ";"
                foreach ($sqlScript in $sqlScriptFiles)
                {
                    $sqlScript = $sqlScript.Trim()
                    if (-not [string]::IsNullOrEmpty($sqlScript))
                    {
                        $sqlScript = Get-SingleFile -pattern $sqlScript
                        $batchFiles = Create-BatchFilesForSqlFile -sqlFilePath $sqlScript -destPath $destPath -batch $batch
                        $sqlScriptsWithExpandedPath = $sqlScriptsWithExpandedPath + $batchFiles + "; "
                        $batch = [int]$batch + 1
                    }
                }
                Write-Verbose "Executing sql scripts $sqlScriptsWithExpandedPath under transaction using app lock $appLockName"
                Invoke-SqlScriptsInTransaction -serverName $serverName -databaseName $databaseName -appLockName $appLockName -sqlscriptFiles $sqlScriptsWithExpandedPath -authscheme $authscheme -sqlServerCredentials $sqlServerCredentials -additionalArguments $additionalArguments

                if ($env:system_debug -eq $false)
                {
                    #Leave the batch files if in debug mode. Remove otherwise.
                    Get-ChildItem -Path $destPath -Force -Recurse |
                        Sort-Object -Property FullName -Descending |
                        Remove-Item -Recurse -Force | Out-Null
                    Remove-Item -Path $destPath -Force
                }

            }
            else
            {
                $sqlScriptFiles = $sqlFiles -split ";"
                foreach ($sqlScript in $sqlScriptFiles)
                {
                    $sqlScript = $sqlScript.Trim()
                    if (-not [string]::IsNullOrEmpty($sqlScript))
                    {
                        $sqlScript = Get-SingleFile -pattern $sqlScript
                        Invoke-SqlQueryDeployment -taskType $taskType -sqlFile $sqlScript -serverName $serverName -databaseName $databaseName -authscheme $authscheme -sqlServerCredentials $sqlServerCredentials -additionalArguments $additionalArguments
                    }
                }
            }
        }
        else
        {
            Invoke-SqlQueryDeployment -taskType $taskType -inlineSql $inlineSql -serverName $serverName -databaseName $databaseName -authscheme $authscheme -sqlServerCredentials $sqlServerCredentials -additionalArguments $additionalArguments
        }
    }
}
Catch [System.Management.Automation.CommandNotFoundException]
{
    if ($_.Exception.CommandName -ieq "Invoke-Sqlcmd")
    {
        Write-Error (Get-VstsLocString -Key "SQLPowershellModuleisnotinstalledonyouragentmachine")
        Write-Error (Get-VstsLocString -Key "InstallPowershellToolsharedManagementObjectsdependency")
        Write-Error (Get-VstsLocString -Key "RestartagentmachineafterinstallingtoolstoregisterModulepathupdates")
        Write-Error (Get-VstsLocString -Key "RunImportModuleSQLPSonyouragentPowershellprompt")
    }

    Write-Exception($_.Exception)
}
Catch [Exception]
{
    Write-Exception($_.Exception)
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useWrapEvent = useWrapEvent;

var _react = require("react");

function useWrapEvent(ourHandler, theirHandler) {
  return (0, _react.useCallback)(function (event) {
    theirHandler && theirHandler(event);

    if (!event.defaultPrevented) {
      return ourHandler(event);
    }
  }, [ourHandler, theirHandler]);
}
//# sourceMappingURL=useWrapEvent.js.map


text:
/* global spyOn, jest, describe, beforeEach, it, expect */

jest.dontMock('reflux');
jest.dontMock('../../actions/actions.js');
jest.dontMock('../../components/search.js');
jest.dontMock('../../stores/auth.js');

var React = require('react/addons');
var TestUtils = React.addons.TestUtils;

describe('Test for Footer', function () {

  var Actions, AuthStore, Search;

  window.localStorage = {
    item: false,
    setItem: function (item) {
      this.item = item;
    },
    getItem: function () {
      return this.item;
    },
    clear: function () {
      this.item = false;
    }
  };

  beforeEach(function () {
    // Mock Electron's window.require
    // and remote.require('shell')
    window.require = function () {
      return {
        require: function () {
          return {
            openExternal: function () {
              return {};
            }
          };
        }
      };
    };

    Actions = require('../../actions/actions.js');
    AuthStore = require('../../stores/auth.js');
    Search = require('../../components/search.js');
  });

  it('Should make a search', function () {

    spyOn(Actions, 'updateSearchTerm');
    spyOn(Actions, 'clearSearchTerm');

    var instance = TestUtils.renderIntoDocument(<Search showSearch={true} />);

    var wrapper = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'search-wrapper');
    expect(wrapper.length).toBe(1);

    instance.clearSearch();

    instance.updateSearchTerm({
      target: {
        value: 'hello'
      }
    });

    expect(Actions.updateSearchTerm).toHaveBeenCalledWith('hello');

    instance.componentWillReceiveProps({showSearch: false});
    expect(Actions.updateSearchTerm).toHaveBeenCalledWith('');
  });

  it('Should only render clear button if search term is not empty', function () {
    var instance = TestUtils.renderIntoDocument(<Search showSearch={true} />);

    var clearButton = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'octicon-x');
    expect(clearButton.length).toBe(0);

    instance.state.searchTerm = 'hello';
    instance.forceUpdate();

    clearButton = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'octicon-x');
    expect(clearButton.length).toBe(1);
  });

  it('Should hide the search bar', function () {
    var instance = TestUtils.renderIntoDocument(<Search showSearch={false} />);
    var searchBar = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'search-bar');
    expect(searchBar.length).toBe(0);
  });
});


text:
var jsc = FBjqRY.now(),
	rscript = /<script(.|\s)*?\/script>/gi,
	rselectTextarea = /select|textarea/i,
	rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
	//jsre = /\=\?(&|$)/,
	rquery = /\?/,
	rts = /(\?|&)_=.*?(&|$)/,
	//rurl = /^(\w+:)?\/\/([^\/?#]+)/,
	r20 = /%20/g,

	// Keep a copy of the old load method
	_load = FBjqRY.fn.load;

FBjqRY.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" && _load ) {
			return _load.apply( this, arguments );
		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( FBjqRY.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;
			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = FBjqRY.param( params, FBjqRY.ajaxSettings.traditional );
				type = "POST";
			}
		}

		var self = this;

		// Request the remote document
		FBjqRY.ajax({
			url: url,
			type: type,
			dataType: "html", // @todo ???
			data: params,
			complete: function( res, status ) { // @todo non sense !!!
				// If successful, inject the HTML into all the matched elements
				if ( status === "success" || status === "notmodified" ) {
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div />")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(rscript, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );
				}

				if ( callback ) {
					self.each( callback, [res.responseText, status, res] );
				}
			}
		});

		return this;
	},

	serialize: function() {
		return FBjqRY.param( this.serializeArray() );
	},
	serializeArray: function() {
		//return this.map( function() {
		//	return this.elements ? jQuery.makeArray(this.elements) : this;
		//})
        return this
		.filter(function() {
			return this.getName() && ! this.getDisabled() &&
				( this.getChecked() || rselectTextarea.test(this.getTagName()) ||
					rinput.test(this.getType()) );
		})
		.map(function() {
			var val = FBjqRY(this).val();
            if (val == null) return null;
            var name = this.getName();

            if ( FBjqRY.isArray(val) ) {
                var ret = [];
                for ( var i = 0; i < val.length; i++ ) {
                    ret.push( { name: name, value: val[i] } );
                }
                return ret;
            }
            else {
                return { name: name, value: val };
            }
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
FBjqRY.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
	FBjqRY.fn[o] = function( f ) {
		return this.bind(o, f);
	};
});

FBjqRY.extend({
	get: function( url, data, callback, type ) {
		// shift arguments if data argument was ommited
		if ( FBjqRY.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = null;
		}
		return FBjqRY.ajax({
			type: "GET", // it will be a POST anyway !
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	getScript: function( url, callback ) {
		//return jQuery.get(url, null, callback, "script");
        return FBjqRY.error("getScript() not supported");
	},

	getJSON: function( url, data, callback ) {
        //return jQuery.get(url, data, callback, "json");
		return FBjqRY.get(url, data, callback, Ajax.JSON);
	},

	post: function( url, data, callback, type ) {
		if ( FBjqRY.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}
		return FBjqRY.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	ajaxSetup: function( settings ) {
		FBjqRY.extend( FBjqRY.ajaxSettings, settings );
	},

	ajaxSettings: {
		url: null, //location.href,
		global: true,
		type: "POST", // we can only do a POST !
		//contentType: "application/x-www-form-urlencoded",
		//processData: true,
		//async: true,
		//accepts: { // @todo only a placeholder
		//	xml: "application/xml, text/xml",
		//	html: "text/html",
		//	script: "text/javascript, application/javascript",
		//	json: "application/json, text/javascript",
		//	text: "text/plain",
		//	_default: "*/*"
		//}
        dataType: Ajax.RAW, // FB "extension"
        retryCount: 1, // FB "extension"
        requireLogin: null // FB "extension"
	},

//	ajaxSettings: {
//		url: location.href,
//		global: true,
//		type: "GET",
//		contentType: "application/x-www-form-urlencoded",
//		processData: true,
//		async: true,
//		/*
//		timeout: 0,
//		data: null,
//		username: null,
//		password: null,
//		traditional: false,
//		*/
//		// Create the request object; Microsoft failed to properly
//		// implement the XMLHttpRequest in IE7 (can't request local files),
//		// so we use the ActiveXObject when it is available
//		// This function can be overriden by calling jQuery.ajaxSetup
//		xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
//			function() {
//				return new window.XMLHttpRequest();
//			} :
//			function() {
//				try {
//					return new window.ActiveXObject("Microsoft.XMLHTTP");
//				} catch(e) {}
//			},
//		accepts: {
//			xml: "application/xml, text/xml",
//			html: "text/html",
//			script: "text/javascript, application/javascript",
//			json: "application/json, text/javascript",
//			text: "text/plain",
//			_default: "*/*"
//		}
//	},

	ajax: function( origSettings ) {
		var options = FBjqRY.extend(true, {}, FBjqRY.ajaxSettings, origSettings),
			type = options.type.toUpperCase();

		options.context = origSettings && origSettings.context || options;

		// convert data if not already a string
		if ( options.data && options.processData && typeof options.data !== "string" ) {
			options.data = FBjqRY.param( options.data, options.traditional );
		}

		if ( options.cache === false && type === "GET" ) {
			var ts = FBjqRY.now();
			// try replacing _= if it is there
			var ret = options.url.replace(rts, "$1_=" + ts + "$2");
			// if nothing was replaced, add timestamp to the end
			options.url = ret + ((ret === options.url) ? (rquery.test(options.url) ? "&" : "?") + "_=" + ts : "");
		}

		// If data is available, append data to url for get requests
		if ( options.data && type === "GET" ) {
			options.url += (rquery.test(options.url) ? "&" : "?") + options.data;
		}

		// Watch for a new set of requests
		if ( options.global && FBjqRY.ajax.active++ === 0 ) {
			FBjqRY.event.trigger( "ajaxStart" ); // @todo
		}

		// Matches an absolute URL, and saves the domain
		//var parts = rurl.exec( s.url ),
		//	remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

        var ajax = new Ajax();
        ajax.responseType = options.dataType;
        ajax.ondone = function( data ) {
            //options.success();
            FBjqRY.ajax.handleSuccess( options, ajax, data );
            // Fire the complete handlers
            FBjqRY.ajax.handleComplete( options, ajax, data );
        };
        ajax.onerror = function() {
            var retryCount = options.retryCount || 0;
            FBjqRY.log("ajax() error occurred, retrying ...");
            if ( retryCount-- > 0 ) {
                options.retryCount = retryCount;
                FBjqRY.ajax(options);
            }
            else {
                FBjqRY.ajax.handleError(options, ajax, null);
                // Fire the complete handlers
                FBjqRY.ajax.handleComplete( options, ajax, undefined);
            }
        };
		try {
			ajax.post(options.url, options.data);
		}
        catch(e) {
			FBjqRY.ajax.handleError(options, ajax, e);
            // Fire the complete handlers
            FBjqRY.ajax.handleComplete( options, ajax, undefined);
		}

		// Allow custom headers/mimetypes and early abort
        // @todo ?!
//		if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
//			// Handle the global AJAX counter
//			if ( s.global && FBjqRY.ajax.active-- === 1 ) {
//				FBjqRY.event.trigger( "ajaxStop" ); // @todo
//			}
//			// close opended socket
//			xhr.abort();
//			return false;
//		}

		if ( options.global ) {
			FBjqRY.ajax.triggerGlobal( options, "ajaxSend", [ajax, options] );
		}

		// return XMLHttpRequest to allow aborting the request etc.
		return ajax;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( array, traditional ) {
		var s = [], add = function( key, value ) {
			// If value is a function, invoke it and return its value
			value = FBjqRY.isFunction(value) ? value() : value;
			s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
		};

		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = FBjqRY.ajaxSettings.traditional;
		}

		// If an array was passed in, assume that it is an array of form elements.
		if ( FBjqRY.isArray(array) || array.jquery ) {
            if ( array.jquery ) array = array.nodes;
			// Serialize the form elements
			FBjqRY.each( array, function() {
				add( this.name, this.value );
			});
		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in array ) {
				buildParams( prefix, array[prefix], traditional, add );
			}
		}

		// Return the resulting serialization
		return s.join("&").replace(r20, "+");
	}
});

var req = /=/g, rand = /&/g;
function encodeURIComponent(str) {
    if ( typeof(str) === "string" ) {
        return str.replace(req,'%3D').replace(rand,'%26');
    }
    // checkboxes and radio buttons return objects instead of a string
    else if( typeof(str) === "object" ){
        for (var i in str) {
            return str[i].replace(req,'%3D').replace(rand,'%26');
        }
    }
}

function buildParams( prefix, obj, traditional, add ) {
	if ( FBjqRY.isArray(obj) ) {
		// Serialize array item.
		FBjqRY.each( obj, function( i, v ) {
			if ( traditional || /\[\]$/.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );
			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || FBjqRY.isArray(v) ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		// Serialize object item.
		FBjqRY.each( obj, function( k, v ) {
			buildParams( prefix + "[" + k + "]", v, traditional, add );
		});

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}

var ajaxExtend;
FBjqRY.extend( FBjqRY.ajax, ajaxExtend = {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	//lastModified: {},
	//etag: {},

	handleError: function( s, xhr, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) {
			s.error.call( s.context, xhr, status, e );
		}

		// Fire the global callback
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
		}
	},

	handleSuccess: function( s, xhr, status, data ) {
		// If a local callback was specified, fire it and pass it the data
		if ( s.success ) {
			s.success.call( s.context, data, status, xhr );
		}

		// Fire the global callback
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
		}
	},

	handleComplete: function( s, xhr, status ) {
		// Process result
		if ( s.complete ) {
			s.complete.call( s.context, xhr, status );
		}

		// The request was completed
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
		}

		// Handle the global AJAX counter
		if ( s.global && jQuery.ajax.active-- === 1 ) {
			jQuery.event.trigger( "ajaxStop" );
		}
	},

	triggerGlobal: function( s, type, args ) {
		(s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
	}
});

// For backwards compatibility
//FBjqRY.extend( FBjqRY.ajax );
FBjqRY.extend( ajaxExtend );


text:
Fabricator(:gene, class_name: 'DataModel::Gene') do
  name { sequence(:name) { |i| "Gene ##{i}" } }
  long_name { sequence(:long_name) { |i| "Gene ##{i} long name" } }
end

Fabricator(:gene_alias, class_name: 'DataModel::GeneAlias') do |f|
  f.alias { sequence(:alias) { |i| "Gene Alias ##{i}" } }
end

Fabricator(:gene_claim, class_name: 'DataModel::GeneClaim') do
  name { sequence(:name) { |i| "Gene Claim ##{i}" } }
  nomenclature { |attrs| "#{attrs[:source].source_db_name} gene claim name" }
  nomenclature { sequence(:nomenclature) { |i| "Gene claim ##{i} nomenclature" } }
end

Fabricator(:gene_claim_alias, class_name: 'DataModel::GeneClaimAlias') do |f|
  f.alias { sequence(:alias) { |i| "Gene Claim Alias ##{i}" } }
  f.nomenclature { sequence(:nomenclature) { |i| "Gene Claim Alias nomenclature ##{i}" } }
end

Fabricator(:gene_claim_attribute, class_name: 'DataModel::GeneClaimAttribute') do
  name { sequence(:name) { |i| "Gene Claim Attribute Name ##{i}" } }
  value { sequence(:value) { |i| "Gene Claim Attribute Value ##{i}" } }
end

Fabricator(:gene_claim_category, class_name: 'DataModel::GeneClaimCategory') do
  name { sequence(:gene_claim_category) { |i| "Gene Claim Category ##{i}" } }
end

Fabricator(:gene_gene_interaction_claim, class_name: 'DataModel::GeneGeneInteractionClaim')

Fabricator(:gene_gene_interaction_claim_attribute, class_name: 'DataModel::GeneGeneInteractionClaimAttribute') do
  name { sequence(:gene_gene_interaction_claim_attribute_name) { |i| "Inter gene interaction ##{i} name" } }
  value { sequence(:gene_gene_interaction_claim_attribute_value) { |i| "Inter gene interaction ##{i} value" } }
end


text:
module Doorkeeper
  module OpenidConnect
    module Models
      class UserInfo
        include ActiveModel::Validations

        def initialize(resource_owner)
          @resource_owner = resource_owner
        end

        def claims
          {
            sub: subject,
            email: email,
            assignments: assignments
          }
        end

        def as_json(options = {})
          claims
        end

        private

        def subject
          @resource_owner.instance_eval(&Doorkeeper::OpenidConnect.configuration.subject).to_s
        end

        def email
          @resource_owner.instance_eval(&Doorkeeper::OpenidConnect.configuration.email).to_s
        end

        def assignments
          @resource_owner.instance_eval(&Doorkeeper::OpenidConnect.configuration.assignments)
        end
      end
    end
  end
end


text:
package com.uphyca.idobata.android.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.uphyca.idobata.Idobata;
import com.uphyca.idobata.IdobataError;
import com.uphyca.idobata.android.InjectionUtils;

import javax.inject.Inject;

public class PostTouchService extends IntentService {

    public static void postTouch(Context context, Uri roomUri) {
        Intent intent = new Intent(context, PostTouchService.class).setData(roomUri);
        context.startService(intent);
    }

    @Inject
    Idobata mIdobata;

    public PostTouchService() {
        super("PostTouchService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        InjectionUtils.getObjectGraph(this)
                      .inject(this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Uri roomUri = intent.getData();
        try {
            String[] tuple = roomUri.getFragment()
                                    .split("/");
            String organizationSlug = tuple[2];
            String roomName = tuple[4];
            long roomId = mIdobata.getRoom(organizationSlug, roomName)
                                  .getId();
            mIdobata.postTouch(roomId);
        } catch (IdobataError idobataError) {
            idobataError.printStackTrace();
        }
    }
}


text:
////////////////////////////////////////////////////////////////////////////////
// Implements the Server class. See server.h for details on the API
////////////////////////////////////////////////////////////////////////////////

#include "network/server.h"
#include <string>
#include <utility>
#include "basics/basics.h"

Server::Server(EventLoop* eventLoop, const NetworkOptions& _options)
    : BaseServer(eventLoop, _options) {
  request_rid_gen_ = new REQID_Generator();
}

Server::~Server() {
  delete request_rid_gen_;
}

sp_int32 Server::Start() { return Start_Base(); }

sp_int32 Server::Stop() { return Stop_Base(); }

void Server::SendResponse(REQID _id, Connection* _connection,
                          const google::protobuf::Message& _response) {
  sp_int32 byte_size = _response.ByteSize();
  sp_uint32 data_size = OutgoingPacket::SizeRequiredToPackString(_response.GetTypeName()) +
                        REQID_size + OutgoingPacket::SizeRequiredToPackProtocolBuffer(byte_size);
  auto opkt = new OutgoingPacket(data_size);
  CHECK_EQ(opkt->PackString(_response.GetTypeName()), 0);
  CHECK_EQ(opkt->PackREQID(_id), 0);
  CHECK_EQ(opkt->PackProtocolBuffer(_response, byte_size), 0);
  InternalSendResponse(_connection, opkt);
  return;
}

void Server::SendMessage(Connection* _connection,
                         sp_int32 _byte_size,
                         const sp_string _type_name,
                         const char* _message) {
  // Generate a zero reqid
  REQID rid = REQID_Generator::generate_zero_reqid();

  sp_uint32 data_size = OutgoingPacket::SizeRequiredToPackString(_type_name) +
                          REQID_size + OutgoingPacket::SizeRequiredToPackProtocolBuffer(_byte_size);

  OutgoingPacket* opkt = new OutgoingPacket(data_size);

  CHECK_EQ(opkt->PackString(_type_name), 0);
  CHECK_EQ(opkt->PackREQID(rid), 0);
  CHECK_EQ(opkt->PackProtocolBuffer(_message, _byte_size), 0);
  InternalSendResponse(_connection, opkt);
  return;
}

void Server::SendMessage(Connection* _connection, const google::protobuf::Message& _message) {
  // Generate a zero reqid
  REQID rid = REQID_Generator::generate_zero_reqid();
  // Currently its no different than response
  return SendResponse(rid, _connection, _message);
}

void Server::CloseConnection(Connection* _connection) { CloseConnection_Base(_connection); }

void Server::AddTimer(VCallback<> cb, sp_int64 _msecs) { AddTimer_Base(std::move(cb), _msecs); }

void Server::SendRequest(Connection* _conn, google::protobuf::Message* _request, void* _ctx,
                         google::protobuf::Message* _response_placeholder) {
  SendRequest(_conn, _request, _ctx, -1, _response_placeholder);
}

void Server::SendRequest(Connection* _conn, google::protobuf::Message* _request, void* _ctx,
                         sp_int64 _msecs, google::protobuf::Message* _response_placeholder) {
  InternalSendRequest(_conn, _request, _msecs, _response_placeholder, _ctx);
}

// The interfaces of BaseServer being implemented
BaseConnection* Server::CreateConnection(ConnectionEndPoint* _endpoint, ConnectionOptions* _options,
                                         EventLoop* eventLoop) {
  // Create the connection object and register our callbacks on various events.
  auto conn = new Connection(_endpoint, _options, eventLoop);
  auto npcb = [conn, this](IncomingPacket* packet) { this->OnNewPacket(conn, packet); };
  conn->registerForNewPacket(npcb);

  // Backpressure reliever - will point to the inheritor of this class in case the virtual function
  // is implemented in the inheritor
  auto backpressure_reliever_ = [this](Connection* conn) {
    this->StopBackPressureConnectionCb(conn);
  };

  auto backpressure_starter_ = [this](Connection* conn) {
    this->StartBackPressureConnectionCb(conn);
  };

  conn->registerForBackPressure(std::move(backpressure_starter_),
                                std::move(backpressure_reliever_));

  return conn;
}

void Server::HandleNewConnection_Base(BaseConnection* _connection) {
  HandleNewConnection(static_cast<Connection*>(_connection));
}

void Server::HandleConnectionClose_Base(BaseConnection* _connection, NetworkErrorCode _status) {
  HandleConnectionClose(static_cast<Connection*>(_connection), _status);
}

void Server::OnNewPacket(Connection* _connection, IncomingPacket* _packet) {
  // Maybe we can could the number of packets received by each connection?
  if (active_connections_.find(_connection) == active_connections_.end()) {
    LOG(ERROR) << "Packet Received on on unknown connection " << _connection << " from hostport "
               << _connection->getIPAddress() << ":" << _connection->getPort();
    delete _packet;
    _connection->closeConnection();
    return;
  }

  std::string typname;
  if (_packet->UnPackString(&typname) != 0) {
    LOG(ERROR) << "UnPackString failed from connection " << _connection << " from hostport "
               << _connection->getIPAddress() << ":" << _connection->getPort();
    delete _packet;
    _connection->closeConnection();
    return;
  }
  if (requestHandlers.count(typname) > 0) {
    // This is a request
    requestHandlers[typname](_connection, _packet);
  } else if (messageHandlers.count(typname) > 0) {
    // This is a message
    messageHandlers[typname](_connection, _packet);
  } else {
    // This might be a response for a send request
    REQID rid;
    CHECK_EQ(_packet->UnPackREQID(&rid), 0);
    if (context_map_.find(rid) != context_map_.end()) {
      // Yes this is indeed a good packet
      std::pair<google::protobuf::Message*, void*> pr = context_map_[rid];
      context_map_.erase(rid);
      NetworkErrorCode status = OK;
      if (_packet->UnPackProtocolBuffer(pr.first) != 0) {
        status = INVALID_PACKET;
      }
      auto cb = [pr, status, this]() { this->HandleResponse(pr.first, pr.second, status); };

      AddTimer(std::move(cb), 0);
    } else {
      // This is some unknown message
      LOG(ERROR) << "Unknown type protobuf received " << typname << " deleting...";
    }
  }
  delete _packet;
}

// Backpressure here - works for sending to both worker and stmgr
void Server::InternalSendResponse(Connection* _connection, OutgoingPacket* _packet) {
  if (active_connections_.find(_connection) == active_connections_.end()) {
    LOG(ERROR) << "Trying to send on unknown connection! Dropping.. " << std::endl;
    delete _packet;
    return;
  }
  if (_connection->sendPacket(_packet) != 0) {
    LOG(ERROR) << "Error sending packet to! Dropping... " << std::endl;
    delete _packet;
    return;
  }
  return;
}

void Server::InternalSendRequest(Connection* _conn, google::protobuf::Message* _request,
                                 sp_int64 _msecs, google::protobuf::Message* _response_placeholder,
                                 void* _ctx) {
  if (active_connections_.find(_conn) == active_connections_.end()) {
    delete _request;
    auto cb = [_response_placeholder, _ctx, this]() {
      this->HandleResponse(_response_placeholder, _ctx, WRITE_ERROR);
    };
    AddTimer(std::move(cb), 0);
    return;
  }

  // Generate the rid.
  REQID rid = request_rid_gen_->generate();

  // Insert into context map
  // TODO(kramasamy): If connection closes and there is no timeout associated with
  // a request, then the context_map_ will forever be left dangling.
  // One way to solve this would be to always have a timeout associated
  context_map_[rid] = std::make_pair(_response_placeholder, _ctx);

  // Make the outgoing packet
  sp_int32 byte_size = _request->ByteSize();
  sp_uint32 sop = OutgoingPacket::SizeRequiredToPackString(_request->GetTypeName()) + REQID_size +
                  OutgoingPacket::SizeRequiredToPackProtocolBuffer(byte_size);
  auto opkt = new OutgoingPacket(sop);
  CHECK_EQ(opkt->PackString(_request->GetTypeName()), 0);
  CHECK_EQ(opkt->PackREQID(rid), 0);
  CHECK_EQ(opkt->PackProtocolBuffer(*_request, byte_size), 0);

  // delete the request
  delete _request;

  if (_conn->sendPacket(opkt) != 0) {
    context_map_.erase(rid);
    delete opkt;
    auto cb = [_response_placeholder, _ctx, this]() {
      this->HandleResponse(_response_placeholder, _ctx, WRITE_ERROR);
    };
    AddTimer(std::move(cb), 0);
    return;
  }
  if (_msecs > 0) {
    auto cb = [rid, this](EventLoop::Status status) { this->OnPacketTimer(rid, status); };
    CHECK_GT(eventLoop_->registerTimer(std::move(cb), false, _msecs), 0);
  }
  return;
}

void Server::OnPacketTimer(REQID _id, EventLoop::Status) {
  if (context_map_.find(_id) == context_map_.end()) {
    // most likely this was due to the requests being retired before the timer.
    return;
  }

  std::pair<google::protobuf::Message*, void*> pr = context_map_[_id];
  context_map_.erase(_id);

  HandleResponse(pr.first, pr.second, TIMEOUT);
}

// default implementation
void Server::HandleResponse(google::protobuf::Message* _response, void*, NetworkErrorCode) {
  delete _response;
}

void Server::StartBackPressureConnectionCb(Connection* conn) {
  // Nothing to be done here. Should be handled by inheritors if they care about backpressure
}

void Server::StopBackPressureConnectionCb(Connection* conn) {
  // Nothing to be done here. Should be handled by inheritors if they care about backpressure
}


text:
<?php

namespace Tenshibe\MovappBundle\Command\Search;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Search initialize command
 *
 * @package Tenshibe\MovappBundle\Command\Search
 */
class SearchinitializeCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('movapp:search:initialize')
            ->setDescription('(Re)Initialize the search database - Destructive !');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $searchclient = $this->getContainer()->get('movapp_search');
        $searchclient->initialize();

    }
}


text:
.now-playing {
  text-align: center;
  padding: 5px 20px;
  line-height: 1.5em;
}

.now-playing .show-name {
  font-weight: bold;
}

.now-playing .show-broadcasters {
  font-style: italic;
}


text:
import App from "../app";
import {pubsub} from "../helpers/subscriptionManager";
import taskDefinitions from "../tasks";

let lastTime = Date.now();
function verifyTasks() {
  App.flights
    .filter(f => f.running === true)
    .forEach(f => {
      f.simulators
        .map(s => App.simulators.find(sim => sim.id === s))
        .forEach(sim => {
          let time = Date.now() - lastTime;
          let tasks = App.tasks.filter(s => s.simulatorId === sim.id);
          // Add on all of the report tasks.
          tasks = tasks.concat(
            App.taskReports
              .filter(s => s.simulatorId === sim.id && !s.cleared)
              .map(r => r.tasks.filter(t => !t.verified))
              .reduce((prev, next) => prev.concat(next), []),
          );
          // Go through each task and run the verify function.
          tasks.forEach(t => {
            // Increment the time elapsed
            if (t.verified) return;
            t.timeElapsedInMS += time;
            const taskDef = taskDefinitions.find(d => d.name === t.definition);
            if (
              taskDef.verify &&
              taskDef.verify({simulator: sim, requiredValues: t.values})
            ) {
              t.verify();
            }
          });
          pubsub.publish(
            "tasksUpdate",
            App.tasks.filter(s => s.simulatorId === sim.id),
          );
        });
    });
  pubsub.publish("taskReportUpdate", App.taskReports);
  lastTime = Date.now();
  setTimeout(verifyTasks, 1000);
}

verifyTasks();


text:
提供方:emichael

[link](https://chrome.google.com/webstore/detail/tex-all-the-things/cbimabofgmfdkicghcadidpemeenbffn)


text:
module Doorkeeper
  module Rails
    module Helpers
      extend ActiveSupport::Concern

      def doorkeeper_authorize!(*scopes)
        @_doorkeeper_scopes = scopes.presence || Doorkeeper.configuration.default_scopes

        if !valid_doorkeeper_token?
          doorkeeper_render_error
        end
      end

      def doorkeeper_unauthorized_render_options
        nil
      end

      def doorkeeper_forbidden_render_options
        nil
      end

      def valid_doorkeeper_token?
        doorkeeper_token && doorkeeper_token.acceptable?(@_doorkeeper_scopes)
      end

      private

      def doorkeeper_render_error
        error = doorkeeper_error
        headers.merge! error.headers.reject { |k| "Content-Type" == k }
        doorkeeper_render_error_with(error)
      end

      def doorkeeper_render_error_with(error)
        options = doorkeeper_render_options || {}
        if options.blank?
          head error.status
        else
          options[:status] = error.status
          options[:layout] = false if options[:layout].nil?
          render options
        end
      end

      def doorkeeper_error
        if doorkeeper_invalid_token_response?
          OAuth::InvalidTokenResponse.from_access_token(doorkeeper_token)
        else
          OAuth::ForbiddenTokenResponse.from_scopes(@_doorkeeper_scopes)
        end
      end

      def doorkeeper_render_options
        if doorkeeper_invalid_token_response?
          doorkeeper_unauthorized_render_options
        else
          doorkeeper_forbidden_render_options
        end
      end

      def doorkeeper_invalid_token_response?
        !doorkeeper_token || !doorkeeper_token.accessible?
      end

      def doorkeeper_token
        @_doorkeeper_token ||= OAuth::Token.authenticate(
          request,
          *Doorkeeper.configuration.access_token_methods
        )
      end
    end
  end
end


text:
/**
 *
 *  File:       dcpudis.h
 *
 *  Project:    DCPU-16 Toolchain
 *  Component:  LibDCPU-VM
 *
 *  Authors:    James Rhodes
 *
 *  Description:    Declares structures and functions that
 *          assist in disassembling and analysing
 *          instructions.
 *
 **/

#ifndef __DCPUDIS_H
#define __DCPUDIS_H

#include "vm.h"

///
/// Represents an instruction that was observed or
/// resolved without affecting the virtual machine.
/// Internally this structure is *not* used to process
/// instructions, it exists only to allow easy
/// inspection of instructions without affecting the
/// state of the virtual machine.
///
struct inst
{
    struct
    {
        uint16_t full;
        uint8_t op;
        uint8_t a;
        uint8_t b;
    } original;
    struct
    {
        bstring op;
        bstring a;
        bstring b;
    } pretty;
    uint8_t op;
    uint16_t a;
    uint16_t b;
    uint16_t size;
    uint16_t extra[2];
    uint16_t next[2];
    uint8_t used[2];
};

struct inst vm_disassemble(vm_t* vm, uint16_t pos, bool pretty);

#endif