text:
namespace autofill {

AutofillExternalDelegate::AutofillExternalDelegate(
    AutofillManager* manager,
    AutofillDriver* driver)
    : manager_(manager),
      driver_(driver),
      password_manager_(driver),
      query_id_(0),
      display_warning_if_disabled_(false),
      has_suggestion_(false),
      has_shown_popup_for_current_edit_(false),
      weak_ptr_factory_(this) {
  DCHECK(manager);
}

AutofillExternalDelegate::~AutofillExternalDelegate() {}

void AutofillExternalDelegate::OnQuery(int query_id,
                                       const FormData& form,
                                       const FormFieldData& field,
                                       const gfx::RectF& element_bounds,
                                       bool display_warning_if_disabled) {
  query_form_ = form;
  query_field_ = field;
  display_warning_if_disabled_ = display_warning_if_disabled;
  query_id_ = query_id;
  element_bounds_ = element_bounds;
}

void AutofillExternalDelegate::OnSuggestionsReturned(
    int query_id,
    const std::vector<base::string16>& suggested_values,
    const std::vector<base::string16>& suggested_labels,
    const std::vector<base::string16>& suggested_icons,
    const std::vector<int>& suggested_unique_ids) {
  if (query_id != query_id_)
    return;

  std::vector<base::string16> values(suggested_values);
  std::vector<base::string16> labels(suggested_labels);
  std::vector<base::string16> icons(suggested_icons);
  std::vector<int> ids(suggested_unique_ids);

  // Add or hide warnings as appropriate.
  ApplyAutofillWarnings(&values, &labels, &icons, &ids);

  // Add a separator to go between the values and menu items.
  values.push_back(base::string16());
  labels.push_back(base::string16());
  icons.push_back(base::string16());
  ids.push_back(POPUP_ITEM_ID_SEPARATOR);

  // Only include "Autofill Options" special menu item if we have Autofill
  // suggestions.
  has_suggestion_ = false;
  for (size_t i = 0; i < ids.size(); ++i) {
    if (ids[i] > 0) {
      has_suggestion_ = true;
      break;
    }
  }

  if (has_suggestion_)
    ApplyAutofillOptions(&values, &labels, &icons, &ids);

  // Remove the separator if it is the last element.
  DCHECK_GT(ids.size(), 0U);
  if (ids.back() == POPUP_ITEM_ID_SEPARATOR) {
    values.pop_back();
    labels.pop_back();
    icons.pop_back();
    ids.pop_back();
  }

  // If anything else is added to modify the values after inserting the data
  // list, AutofillPopupControllerImpl::UpdateDataListValues will need to be
  // updated to match.
  InsertDataListValues(&values, &labels, &icons, &ids);

  if (values.empty()) {
    // No suggestions, any popup currently showing is obsolete.
    manager_->delegate()->HideAutofillPopup();
    return;
  }

  // Send to display.
  if (query_field_.is_focusable) {
    manager_->delegate()->ShowAutofillPopup(
        element_bounds_,
        query_field_.text_direction,
        values,
        labels,
        icons,
        ids,
        GetWeakPtr());
  }
}

void AutofillExternalDelegate::OnShowPasswordSuggestions(
    const std::vector<base::string16>& suggestions,
    const std::vector<base::string16>& realms,
    const FormFieldData& field,
    const gfx::RectF& element_bounds) {
  query_field_ = field;
  element_bounds_ = element_bounds;

  if (suggestions.empty()) {
    manager_->delegate()->HideAutofillPopup();
    return;
  }

  std::vector<base::string16> empty(suggestions.size());
  std::vector<int> password_ids(suggestions.size(),
                                POPUP_ITEM_ID_PASSWORD_ENTRY);
  manager_->delegate()->ShowAutofillPopup(
      element_bounds_,
      query_field_.text_direction,
      suggestions,
      realms,
      empty,
      password_ids,
      GetWeakPtr());
}

void AutofillExternalDelegate::SetCurrentDataListValues(
    const std::vector<base::string16>& data_list_values,
    const std::vector<base::string16>& data_list_labels) {
  data_list_values_ = data_list_values;
  data_list_labels_ = data_list_labels;

  manager_->delegate()->UpdateAutofillPopupDataListValues(
      data_list_values,
      data_list_labels);
}

void AutofillExternalDelegate::OnPopupShown() {
  manager_->DidShowSuggestions(
      has_suggestion_ && !has_shown_popup_for_current_edit_);
  has_shown_popup_for_current_edit_ |= has_suggestion_;
}

void AutofillExternalDelegate::OnPopupHidden() {
}

bool AutofillExternalDelegate::ShouldRepostEvent(const ui::MouseEvent& event) {
  NOTREACHED();
  return true;
}

void AutofillExternalDelegate::DidSelectSuggestion(int identifier) {
  ClearPreviewedForm();

  // Only preview the data if it is a profile.
  if (identifier > 0)
    FillAutofillFormData(identifier, true);
}

void AutofillExternalDelegate::DidAcceptSuggestion(const base::string16& value,
                                                   int identifier) {
  if (identifier == POPUP_ITEM_ID_AUTOFILL_OPTIONS) {
    // User selected 'Autofill Options'.
    manager_->ShowAutofillSettings();
  } else if (identifier == POPUP_ITEM_ID_CLEAR_FORM) {
    // User selected 'Clear form'.
    driver_->RendererShouldClearFilledForm();
  } else if (identifier == POPUP_ITEM_ID_PASSWORD_ENTRY) {
    bool success = password_manager_.DidAcceptAutofillSuggestion(
        query_field_, value);
    DCHECK(success);
  } else if (identifier == POPUP_ITEM_ID_DATALIST_ENTRY) {
    driver_->RendererShouldAcceptDataListSuggestion(value);
  } else if (identifier == POPUP_ITEM_ID_AUTOCOMPLETE_ENTRY) {
    // User selected an Autocomplete, so we fill directly.
    driver_->RendererShouldSetNodeText(value);
  } else {
    FillAutofillFormData(identifier, false);
  }

  manager_->delegate()->HideAutofillPopup();
}

void AutofillExternalDelegate::RemoveSuggestion(const base::string16& value,
                                                int identifier) {
  if (identifier > 0)
    manager_->RemoveAutofillProfileOrCreditCard(identifier);
  else
    manager_->RemoveAutocompleteEntry(query_field_.name, value);
}

void AutofillExternalDelegate::DidEndTextFieldEditing() {
  manager_->delegate()->HideAutofillPopup();

  has_shown_popup_for_current_edit_ = false;
}

void AutofillExternalDelegate::ClearPreviewedForm() {
  driver_->RendererShouldClearPreviewedForm();
}

void AutofillExternalDelegate::Reset() {
  manager_->delegate()->HideAutofillPopup();

  password_manager_.Reset();
}

void AutofillExternalDelegate::AddPasswordFormMapping(
      const FormFieldData& username_field,
      const PasswordFormFillData& fill_data) {
  password_manager_.AddPasswordFormMapping(username_field, fill_data);
}

base::WeakPtr<AutofillExternalDelegate> AutofillExternalDelegate::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void AutofillExternalDelegate::FillAutofillFormData(int unique_id,
                                                    bool is_preview) {
  // If the selected element is a warning we don't want to do anything.
  if (unique_id == POPUP_ITEM_ID_WARNING_MESSAGE)
    return;

  AutofillDriver::RendererFormDataAction renderer_action = is_preview ?
      AutofillDriver::FORM_DATA_ACTION_PREVIEW :
      AutofillDriver::FORM_DATA_ACTION_FILL;

  DCHECK(driver_->RendererIsAvailable());
  // Fill the values for the whole form.
  manager_->FillOrPreviewForm(renderer_action,
                              query_id_,
                              query_form_,
                              query_field_,
                              unique_id);
}

void AutofillExternalDelegate::ApplyAutofillWarnings(
    std::vector<base::string16>* values,
    std::vector<base::string16>* labels,
    std::vector<base::string16>* icons,
    std::vector<int>* unique_ids) {
  if (!query_field_.should_autocomplete) {
    // Autofill is disabled.  If there were some profile or credit card
    // suggestions to show, show a warning instead.  Otherwise, clear out the
    // list of suggestions.
    if (!unique_ids->empty() && (*unique_ids)[0] > 0) {
      // If autofill is disabled and we had suggestions, show a warning instead.
      values->assign(
          1, l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_FORM_DISABLED));
      labels->assign(1, base::string16());
      icons->assign(1, base::string16());
      unique_ids->assign(1, POPUP_ITEM_ID_WARNING_MESSAGE);
    } else {
      values->clear();
      labels->clear();
      icons->clear();
      unique_ids->clear();
    }
  } else if (unique_ids->size() > 1 &&
             (*unique_ids)[0] == POPUP_ITEM_ID_WARNING_MESSAGE) {
    // If we received a warning instead of suggestions from autofill but regular
    // suggestions from autocomplete, don't show the autofill warning.
    values->erase(values->begin());
    labels->erase(labels->begin());
    icons->erase(icons->begin());
    unique_ids->erase(unique_ids->begin());
  }

  // If we were about to show a warning and we shouldn't, don't.
  if (!unique_ids->empty() &&
      (*unique_ids)[0] == POPUP_ITEM_ID_WARNING_MESSAGE &&
      !display_warning_if_disabled_) {
    values->clear();
    labels->clear();
    icons->clear();
    unique_ids->clear();
  }
}

void AutofillExternalDelegate::ApplyAutofillOptions(
    std::vector<base::string16>* values,
    std::vector<base::string16>* labels,
    std::vector<base::string16>* icons,
    std::vector<int>* unique_ids) {
  // The form has been auto-filled, so give the user the chance to clear the
  // form.  Append the 'Clear form' menu item.
  if (query_field_.is_autofilled) {
    values->push_back(
        l10n_util::GetStringUTF16(IDS_AUTOFILL_CLEAR_FORM_MENU_ITEM));
    labels->push_back(base::string16());
    icons->push_back(base::string16());
    unique_ids->push_back(POPUP_ITEM_ID_CLEAR_FORM);
  }

  // Append the 'Chrome Autofill options' menu item;
  values->push_back(l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_POPUP));
  labels->push_back(base::string16());
  icons->push_back(base::string16());
  unique_ids->push_back(POPUP_ITEM_ID_AUTOFILL_OPTIONS);
}

void AutofillExternalDelegate::InsertDataListValues(
    std::vector<base::string16>* values,
    std::vector<base::string16>* labels,
    std::vector<base::string16>* icons,
    std::vector<int>* unique_ids) {
  if (data_list_values_.empty())
    return;

  // Insert the separator between the datalist and Autofill values (if there
  // are any).
  if (!values->empty()) {
    values->insert(values->begin(), base::string16());
    labels->insert(labels->begin(), base::string16());
    icons->insert(icons->begin(), base::string16());
    unique_ids->insert(unique_ids->begin(), POPUP_ITEM_ID_SEPARATOR);
  }

  // Insert the datalist elements.
  values->insert(values->begin(),
                 data_list_values_.begin(),
                 data_list_values_.end());
  labels->insert(labels->begin(),
                 data_list_labels_.begin(),
                 data_list_labels_.end());

  // Set the values that all datalist elements share.
  icons->insert(icons->begin(),
                data_list_values_.size(),
                base::string16());
  unique_ids->insert(unique_ids->begin(),
                     data_list_values_.size(),
                     POPUP_ITEM_ID_DATALIST_ENTRY);
}

}  // namespace autofill


text:
require 'spec_helper'

describe Repository, models: true do
  include RepoHelpers
  TestBlob = Struct.new(:name)

  let(:repository) { create(:project).repository }
  let(:user) { create(:user) }
  let(:commit_options) do
    author = repository.user_to_committer(user)
    { message: 'Test message', committer: author, author: author }
  end
  let(:merge_commit) do
    source_sha = repository.find_branch('feature').target
    merge_commit_id = repository.merge(user, source_sha, 'master', commit_options)
    repository.commit(merge_commit_id)
  end

  describe :branch_names_contains do
    subject { repository.branch_names_contains(sample_commit.id) }

    it { is_expected.to include('master') }
    it { is_expected.not_to include('feature') }
    it { is_expected.not_to include('fix') }
  end

  describe :tag_names_contains do
    subject { repository.tag_names_contains(sample_commit.id) }

    it { is_expected.to include('v1.1.0') }
    it { is_expected.not_to include('v1.0.0') }
  end

  describe :last_commit_for_path do
    subject { repository.last_commit_for_path(sample_commit.id, '.gitignore').id }

    it { is_expected.to eq('c1acaa58bbcbc3eafe538cb8274ba387047b69f8') }
  end

  describe :find_commits_by_message do
    subject { repository.find_commits_by_message('submodule').map{ |k| k.id } }

    it { is_expected.to include('5937ac0a7beb003549fc5fd26fc247adbce4a52e') }
    it { is_expected.to include('6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9') }
    it { is_expected.to include('cfe32cf61b73a0d5e9f13e774abde7ff789b1660') }
    it { is_expected.not_to include('913c66a37b4a45b9769037c55c2d238bd0942d2e') }
  end

  describe :blob_at do
    context 'blank sha' do
      subject { repository.blob_at(Gitlab::Git::BLANK_SHA, '.gitignore') }

      it { is_expected.to be_nil }
    end
  end

  describe :merged_to_root_ref? do
    context 'merged branch' do
      subject { repository.merged_to_root_ref?('improve/awesome') }

      it { is_expected.to be_truthy }
    end
  end

  describe :can_be_merged? do
    context 'mergeable branches' do
      subject { repository.can_be_merged?('0b4bc9a49b562e85de7cc9e834518ea6828729b9', 'master') }

      it { is_expected.to be_truthy }
    end

    context 'non-mergeable branches' do
      subject { repository.can_be_merged?('bb5206fee213d983da88c47f9cf4cc6caf9c66dc', 'feature') }

      it { is_expected.to be_falsey }
    end

    context 'non merged branch' do
      subject { repository.merged_to_root_ref?('fix') }

      it { is_expected.to be_falsey }
    end

    context 'non existent branch' do
      subject { repository.merged_to_root_ref?('non_existent_branch') }

      it { is_expected.to be_nil }
    end
  end

  describe "search_files" do
    let(:results) { repository.search_files('feature', 'master') }
    subject { results }

    it { is_expected.to be_an Array }

    it 'regex-escapes the query string' do
      results = repository.search_files("test\\", 'master')

      expect(results.first).not_to start_with('fatal:')
    end

    describe 'result' do
      subject { results.first }

      it { is_expected.to be_an String }
      it { expect(subject.lines[2]).to eq("master:CHANGELOG:188:  - Feature: Replace teams with group membership\n") }
    end

    describe 'parsing result' do
      subject { repository.parse_search_result(search_result) }
      let(:search_result) { results.first }

      it { is_expected.to be_an OpenStruct }
      it { expect(subject.filename).to eq('CHANGELOG') }
      it { expect(subject.basename).to eq('CHANGELOG') }
      it { expect(subject.ref).to eq('master') }
      it { expect(subject.startline).to eq(186) }
      it { expect(subject.data.lines[2]).to eq("  - Feature: Replace teams with group membership\n") }

      context "when filename has extension" do
        let(:search_result) { "master:CONTRIBUTE.md:5:- [Contribute to GitLab](#contribute-to-gitlab)\n" }

        it { expect(subject.filename).to eq('CONTRIBUTE.md') }
        it { expect(subject.basename).to eq('CONTRIBUTE') }
      end

      context "when file under directory" do
        let(:search_result) { "master:a/b/c.md:5:a b c\n" }

        it { expect(subject.filename).to eq('a/b/c.md') }
        it { expect(subject.basename).to eq('a/b/c') }
      end
    end
  end

  describe "#changelog" do
    before do
      repository.send(:cache).expire(:changelog)
    end

    it 'accepts changelog' do
      expect(repository.tree).to receive(:blobs).and_return([TestBlob.new('changelog')])

      expect(repository.changelog.name).to eq('changelog')
    end

    it 'accepts news instead of changelog' do
      expect(repository.tree).to receive(:blobs).and_return([TestBlob.new('news')])

      expect(repository.changelog.name).to eq('news')
    end

    it 'accepts history instead of changelog' do
      expect(repository.tree).to receive(:blobs).and_return([TestBlob.new('history')])

      expect(repository.changelog.name).to eq('history')
    end

    it 'accepts changes instead of changelog' do
      expect(repository.tree).to receive(:blobs).and_return([TestBlob.new('changes')])

      expect(repository.changelog.name).to eq('changes')
    end

    it 'is case-insensitive' do
      expect(repository.tree).to receive(:blobs).and_return([TestBlob.new('CHANGELOG')])

      expect(repository.changelog.name).to eq('CHANGELOG')
    end
  end

  describe "#license_blob" do
    before do
      repository.send(:cache).expire(:license_blob)
      repository.remove_file(user, 'LICENSE', 'Remove LICENSE', 'master')
    end

    it 'handles when HEAD points to non-existent ref' do
      repository.commit_file(user, 'LICENSE', 'Copyright!', 'Add LICENSE', 'master', false)
      rugged = double('rugged')
      expect(rugged).to receive(:head_unborn?).and_return(true)
      expect(repository).to receive(:rugged).and_return(rugged)

      expect(repository.license_blob).to be_nil
    end

    it 'looks in the root_ref only' do
      repository.remove_file(user, 'LICENSE', 'Remove LICENSE', 'markdown')
      repository.commit_file(user, 'LICENSE', Licensee::License.new('mit').content, 'Add LICENSE', 'markdown', false)

      expect(repository.license_blob).to be_nil
    end

    it 'detects license file with no recognizable open-source license content' do
      repository.commit_file(user, 'LICENSE', 'Copyright!', 'Add LICENSE', 'master', false)

      expect(repository.license_blob.name).to eq('LICENSE')
    end

    %w[LICENSE LICENCE LiCensE LICENSE.md LICENSE.foo COPYING COPYING.md].each do |filename|
      it "detects '#{filename}'" do
        repository.commit_file(user, filename, Licensee::License.new('mit').content, "Add #{filename}", 'master', false)

        expect(repository.license_blob.name).to eq(filename)
      end
    end
  end

  describe '#license_key' do
    before do
      repository.send(:cache).expire(:license_key)
      repository.remove_file(user, 'LICENSE', 'Remove LICENSE', 'master')
    end

    it 'handles when HEAD points to non-existent ref' do
      repository.commit_file(user, 'LICENSE', 'Copyright!', 'Add LICENSE', 'master', false)
      rugged = double('rugged')
      expect(rugged).to receive(:head_unborn?).and_return(true)
      expect(repository).to receive(:rugged).and_return(rugged)

      expect(repository.license_key).to be_nil
    end

    it 'returns nil when no license is detected' do
      expect(repository.license_key).to be_nil
    end

    it 'detects license file with no recognizable open-source license content' do
      repository.commit_file(user, 'LICENSE', 'Copyright!', 'Add LICENSE', 'master', false)

      expect(repository.license_key).to be_nil
    end

    it 'returns the license key' do
      repository.commit_file(user, 'LICENSE', Licensee::License.new('mit').content, 'Add LICENSE', 'master', false)

      expect(repository.license_key).to eq('mit')
    end
  end

  describe "#gitlab_ci_yml" do
    it 'returns valid file' do
      files = [TestBlob.new('file'), TestBlob.new('.gitlab-ci.yml'), TestBlob.new('copying')]
      expect(repository.tree).to receive(:blobs).and_return(files)

      expect(repository.gitlab_ci_yml.name).to eq('.gitlab-ci.yml')
    end

    it 'returns nil if not exists' do
      expect(repository.tree).to receive(:blobs).and_return([])
      expect(repository.gitlab_ci_yml).to be_nil
    end

    it 'returns nil for empty repository' do
      expect(repository).to receive(:empty?).and_return(true)
      expect(repository.gitlab_ci_yml).to be_nil
    end
  end

  describe :add_branch do
    context 'when pre hooks were successful' do
      it 'should run without errors' do
        hook = double(trigger: true)
        expect(Gitlab::Git::Hook).to receive(:new).exactly(3).times.and_return(hook)

        expect { repository.add_branch(user, 'new_feature', 'master') }.not_to raise_error
      end

      it 'should create the branch' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(true)

        branch = repository.add_branch(user, 'new_feature', 'master')

        expect(branch.name).to eq('new_feature')
      end

      it 'calls the after_create_branch hook' do
        expect(repository).to receive(:after_create_branch)

        repository.add_branch(user, 'new_feature', 'master')
      end
    end

    context 'when pre hooks failed' do
      it 'should get an error' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(false)

        expect do
          repository.add_branch(user, 'new_feature', 'master')
        end.to raise_error(GitHooksService::PreReceiveError)
      end

      it 'should not create the branch' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(false)

        expect do
          repository.add_branch(user, 'new_feature', 'master')
        end.to raise_error(GitHooksService::PreReceiveError)
        expect(repository.find_branch('new_feature')).to be_nil
      end
    end
  end

  describe :rm_branch do
    context 'when pre hooks were successful' do
      it 'should run without errors' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(true)

        expect { repository.rm_branch(user, 'feature') }.not_to raise_error
      end

      it 'should delete the branch' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(true)

        expect { repository.rm_branch(user, 'feature') }.not_to raise_error

        expect(repository.find_branch('feature')).to be_nil
      end
    end

    context 'when pre hooks failed' do
      it 'should get an error' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(false)

        expect do
          repository.rm_branch(user, 'new_feature')
        end.to raise_error(GitHooksService::PreReceiveError)
      end

      it 'should not delete the branch' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(false)

        expect do
          repository.rm_branch(user, 'feature')
        end.to raise_error(GitHooksService::PreReceiveError)
        expect(repository.find_branch('feature')).not_to be_nil
      end
    end
  end

  describe :commit_with_hooks do
    context 'when pre hooks were successful' do
      before do
        expect_any_instance_of(GitHooksService).to receive(:execute).
          and_return(true)
      end

      it 'should run without errors' do
        expect do
          repository.commit_with_hooks(user, 'feature') { sample_commit.id }
        end.not_to raise_error
      end

      it 'should ensure the autocrlf Git option is set to :input' do
        expect(repository).to receive(:update_autocrlf_option)

        repository.commit_with_hooks(user, 'feature') { sample_commit.id }
      end
    end

    context 'when pre hooks failed' do
      it 'should get an error' do
        allow_any_instance_of(Gitlab::Git::Hook).to receive(:trigger).and_return(false)

        expect do
          repository.commit_with_hooks(user, 'feature') { sample_commit.id }
        end.to raise_error(GitHooksService::PreReceiveError)
      end
    end
  end

  describe '#exists?' do
    it 'returns true when a repository exists' do
      expect(repository.exists?).to eq(true)
    end

    it 'returns false when a repository does not exist' do
      expect(repository.raw_repository).to receive(:rugged).
        and_raise(Gitlab::Git::Repository::NoRepository)

      expect(repository.exists?).to eq(false)
    end

    it 'returns false when there is no namespace' do
      allow(repository).to receive(:path_with_namespace).and_return(nil)

      expect(repository.exists?).to eq(false)
    end
  end

  describe '#has_visible_content?' do
    subject { repository.has_visible_content? }

    describe 'when there are no branches' do
      before do
        allow(repository).to receive(:branch_count).and_return(0)
      end

      it { is_expected.to eq(false) }
    end

    describe 'when there are branches' do
      it 'returns true' do
        expect(repository).to receive(:branch_count).and_return(3)

        expect(subject).to eq(true)
      end

      it 'caches the output' do
        expect(repository).to receive(:branch_count).
          once.
          and_return(3)

        repository.has_visible_content?
        repository.has_visible_content?
      end
    end
  end

  describe '#update_autocrlf_option' do
    describe 'when autocrlf is not already set to :input' do
      before do
        repository.raw_repository.autocrlf = true
      end

      it 'sets autocrlf to :input' do
        repository.update_autocrlf_option

        expect(repository.raw_repository.autocrlf).to eq(:input)
      end
    end

    describe 'when autocrlf is already set to :input' do
      before do
        repository.raw_repository.autocrlf = :input
      end

      it 'does nothing' do
        expect(repository.raw_repository).to_not receive(:autocrlf=).
          with(:input)

        repository.update_autocrlf_option
      end
    end
  end

  describe '#empty?' do
    let(:empty_repository) { create(:project_empty_repo).repository }

    it 'returns true for an empty repository' do
      expect(empty_repository.empty?).to eq(true)
    end

    it 'returns false for a non-empty repository' do
      expect(repository.empty?).to eq(false)
    end

    it 'caches the output' do
      expect(repository.raw_repository).to receive(:empty?).
        once.
        and_return(false)

      repository.empty?
      repository.empty?
    end
  end

  describe '#root_ref' do
    it 'returns a branch name' do
      expect(repository.root_ref).to be_an_instance_of(String)
    end

    it 'caches the output' do
      expect(repository.raw_repository).to receive(:root_ref).
        once.
        and_return('master')

      repository.root_ref
      repository.root_ref
    end
  end

  describe '#expire_cache' do
    it 'expires all caches' do
      expect(repository).to receive(:expire_branch_cache)
      expect(repository).to receive(:expire_branch_count_cache)
      expect(repository).to receive(:expire_tag_count_cache)

      repository.expire_cache
    end

    it 'expires the caches for a specific branch' do
      expect(repository).to receive(:expire_branch_cache).with('master')

      repository.expire_cache('master')
    end

    it 'expires the emptiness caches for an empty repository' do
      expect(repository).to receive(:empty?).and_return(true)
      expect(repository).to receive(:expire_emptiness_caches)

      repository.expire_cache
    end

    it 'does not expire the emptiness caches for a non-empty repository' do
      expect(repository).to receive(:empty?).and_return(false)
      expect(repository).to_not receive(:expire_emptiness_caches)

      repository.expire_cache
    end
  end

  describe '#expire_root_ref_cache' do
    it 'expires the root reference cache' do
      repository.root_ref

      expect(repository.raw_repository).to receive(:root_ref).
        once.
        and_return('foo')

      repository.expire_root_ref_cache

      expect(repository.root_ref).to eq('foo')
    end
  end

  describe '#expire_has_visible_content_cache' do
    it 'expires the visible content cache' do
      repository.has_visible_content?

      expect(repository).to receive(:branch_count).
        once.
        and_return(0)

      repository.expire_has_visible_content_cache

      expect(repository.has_visible_content?).to eq(false)
    end
  end

  describe '#expire_branch_cache' do
    # This method is private but we need it for testing purposes. Sadly there's
    # no other proper way of testing caching operations.
    let(:cache) { repository.send(:cache) }

    it 'expires the cache for all branches' do
      expect(cache).to receive(:expire).
        at_least(repository.branches.length).
        times

      repository.expire_branch_cache
    end

    it 'expires the cache for all branches when the root branch is given' do
      expect(cache).to receive(:expire).
        at_least(repository.branches.length).
        times

      repository.expire_branch_cache(repository.root_ref)
    end

    it 'expires the cache for a specific branch' do
      expect(cache).to receive(:expire).once

      repository.expire_branch_cache('foo')
    end
  end

  describe '#expire_emptiness_caches' do
    let(:cache) { repository.send(:cache) }

    it 'expires the caches' do
      expect(cache).to receive(:expire).with(:empty?)
      expect(repository).to receive(:expire_has_visible_content_cache)

      repository.expire_emptiness_caches
    end
  end

  describe :skip_merged_commit do
    subject { repository.commits(Gitlab::Git::BRANCH_REF_PREFIX + "'test'", limit: 100, skip_merges: true).map{ |k| k.id } }

    it { is_expected.not_to include('e56497bb5f03a90a51293fc6d516788730953899') }
  end

  describe '#merge' do
    it 'should merge the code and return the commit id' do
      expect(merge_commit).to be_present
      expect(repository.blob_at(merge_commit.id, 'files/ruby/feature.rb')).to be_present
    end
  end

  describe '#revert' do
    let(:new_image_commit) { repository.commit('33f3729a45c02fc67d00adb1b8bca394b0e761d9') }
    let(:update_image_commit) { repository.commit('2f63565e7aac07bcdadb654e253078b727143ec4') }

    context 'when there is a conflict' do
      it 'should abort the operation' do
        expect(repository.revert(user, new_image_commit, 'master')).to eq(false)
      end
    end

    context 'when commit was already reverted' do
      it 'should abort the operation' do
        repository.revert(user, update_image_commit, 'master')

        expect(repository.revert(user, update_image_commit, 'master')).to eq(false)
      end
    end

    context 'when commit can be reverted' do
      it 'should revert the changes' do
        expect(repository.revert(user, update_image_commit, 'master')).to be_truthy
      end
    end

    context 'reverting a merge commit' do
      it 'should revert the changes' do
        merge_commit
        expect(repository.blob_at_branch('master', 'files/ruby/feature.rb')).to be_present

        repository.revert(user, merge_commit, 'master')
        expect(repository.blob_at_branch('master', 'files/ruby/feature.rb')).not_to be_present
      end
    end
  end

  describe '#cherry_pick' do
    let(:conflict_commit) { repository.commit('c642fe9b8b9f28f9225d7ea953fe14e74748d53b') }
    let(:pickable_commit) { repository.commit('7d3b0f7cff5f37573aea97cebfd5692ea1689924') }
    let(:pickable_merge) { repository.commit('e56497bb5f03a90a51293fc6d516788730953899') }

    context 'when there is a conflict' do
      it 'should abort the operation' do
        expect(repository.cherry_pick(user, conflict_commit, 'master')).to eq(false)
      end
    end

    context 'when commit was already cherry-picked' do
      it 'should abort the operation' do
        repository.cherry_pick(user, pickable_commit, 'master')

        expect(repository.cherry_pick(user, pickable_commit, 'master')).to eq(false)
      end
    end

    context 'when commit can be cherry-picked' do
      it 'should cherry-pick the changes' do
        expect(repository.cherry_pick(user, pickable_commit, 'master')).to be_truthy
      end
    end

    context 'cherry-picking a merge commit' do
      it 'should cherry-pick the changes' do
        expect(repository.blob_at_branch('master', 'foo/bar/.gitkeep')).to be_nil

        repository.cherry_pick(user, pickable_merge, 'master')
        expect(repository.blob_at_branch('master', 'foo/bar/.gitkeep')).not_to be_nil
      end
    end
  end

  describe '#before_delete' do
    describe 'when a repository does not exist' do
      before do
        allow(repository).to receive(:exists?).and_return(false)
      end

      it 'does not flush caches that depend on repository data' do
        expect(repository).to_not receive(:expire_cache)

        repository.before_delete
      end

      it 'flushes the root ref cache' do
        expect(repository).to receive(:expire_root_ref_cache)

        repository.before_delete
      end

      it 'flushes the emptiness caches' do
        expect(repository).to receive(:expire_emptiness_caches)

        repository.before_delete
      end

      it 'flushes the exists cache' do
        expect(repository).to receive(:expire_exists_cache).twice

        repository.before_delete
      end
    end

    describe 'when a repository exists' do
      before do
        allow(repository).to receive(:exists?).and_return(true)
      end

      it 'flushes the caches that depend on repository data' do
        expect(repository).to receive(:expire_cache)

        repository.before_delete
      end

      it 'flushes the root ref cache' do
        expect(repository).to receive(:expire_root_ref_cache)

        repository.before_delete
      end

      it 'flushes the emptiness caches' do
        expect(repository).to receive(:expire_emptiness_caches)

        repository.before_delete
      end
    end
  end

  describe '#before_change_head' do
    it 'flushes the branch cache' do
      expect(repository).to receive(:expire_branch_cache)

      repository.before_change_head
    end

    it 'flushes the root ref cache' do
      expect(repository).to receive(:expire_root_ref_cache)

      repository.before_change_head
    end
  end

  describe '#before_push_tag' do
    it 'flushes the cache' do
      expect(repository).to receive(:expire_cache)
      expect(repository).to receive(:expire_tag_count_cache)

      repository.before_push_tag
    end
  end

  describe '#before_import' do
    it 'flushes the emptiness cachess' do
      expect(repository).to receive(:expire_emptiness_caches)

      repository.before_import
    end

    it 'flushes the exists cache' do
      expect(repository).to receive(:expire_exists_cache)

      repository.before_import
    end
  end

  describe '#after_import' do
    it 'flushes the emptiness cachess' do
      expect(repository).to receive(:expire_emptiness_caches)

      repository.after_import
    end

    it 'flushes the exists cache' do
      expect(repository).to receive(:expire_exists_cache)

      repository.after_import
    end
  end

  describe '#after_push_commit' do
    it 'flushes the cache' do
      expect(repository).to receive(:expire_cache).with('master', '123')

      repository.after_push_commit('master', '123')
    end
  end

  describe '#after_create_branch' do
    it 'flushes the visible content cache' do
      expect(repository).to receive(:expire_has_visible_content_cache)

      repository.after_create_branch
    end
  end

  describe '#after_remove_branch' do
    it 'flushes the visible content cache' do
      expect(repository).to receive(:expire_has_visible_content_cache)

      repository.after_remove_branch
    end
  end

  describe '#after_create' do
    it 'flushes the exists cache' do
      expect(repository).to receive(:expire_exists_cache)

      repository.after_create
    end

    it 'flushes the root ref cache' do
      expect(repository).to receive(:expire_root_ref_cache)

      repository.after_create
    end

    it 'flushes the emptiness caches' do
      expect(repository).to receive(:expire_emptiness_caches)

      repository.after_create
    end

  end

  describe "#copy_gitattributes" do
    it 'returns true with a valid ref' do
      expect(repository.copy_gitattributes('master')).to be_truthy
    end

    it 'returns false with an invalid ref' do
      expect(repository.copy_gitattributes('invalid')).to be_falsey
    end
  end

  describe "#main_language" do
    it 'shows the main language of the project' do
      expect(repository.main_language).to eq("Ruby")
    end

    it 'returns nil when the repository is empty' do
      allow(repository).to receive(:empty?).and_return(true)

      expect(repository.main_language).to be_nil
    end
  end

  describe '#before_remove_tag' do
    it 'flushes the tag cache' do
      expect(repository).to receive(:expire_tag_count_cache)

      repository.before_remove_tag
    end
  end

  describe '#branch_count' do
    it 'returns the number of branches' do
      expect(repository.branch_count).to be_an_instance_of(Fixnum)
    end
  end

  describe '#tag_count' do
    it 'returns the number of tags' do
      expect(repository.tag_count).to be_an_instance_of(Fixnum)
    end
  end

  describe '#expire_branch_count_cache' do
    let(:cache) { repository.send(:cache) }

    it 'expires the cache' do
      expect(cache).to receive(:expire).with(:branch_count)

      repository.expire_branch_count_cache
    end
  end

  describe '#expire_tag_count_cache' do
    let(:cache) { repository.send(:cache) }

    it 'expires the cache' do
      expect(cache).to receive(:expire).with(:tag_count)

      repository.expire_tag_count_cache
    end
  end

  describe '#add_tag' do
    context 'with a valid target' do
      let(:user) { build_stubbed(:user) }

      it 'creates the tag using rugged' do
        expect(repository.rugged.tags).to receive(:create).
          with('8.5', repository.commit('master').id,
            hash_including(message: 'foo',
                           tagger: hash_including(name: user.name, email: user.email))).
          and_call_original

        repository.add_tag(user, '8.5', 'master', 'foo')
      end

      it 'returns a Gitlab::Git::Tag object' do
        tag = repository.add_tag(user, '8.5', 'master', 'foo')

        expect(tag).to be_a(Gitlab::Git::Tag)
      end
    end

    context 'with an invalid target' do
      it 'returns false' do
        expect(repository.add_tag(user, '8.5', 'bar', 'foo')).to be false
      end
    end
  end

  describe '#rm_branch' do
    let(:user) { create(:user) }

    it 'removes a branch' do
      expect(repository).to receive(:before_remove_branch)
      expect(repository).to receive(:after_remove_branch)

      repository.rm_branch(user, 'feature')
    end
  end

  describe '#rm_tag' do
    it 'removes a tag' do
      expect(repository).to receive(:before_remove_tag)
      expect(repository.rugged.tags).to receive(:delete).with('v1.1.0')

      repository.rm_tag('v1.1.0')
    end
  end

  describe '#avatar' do
    it 'returns nil if repo does not exist' do
      expect(repository).to receive(:exists?).and_return(false)

      expect(repository.avatar).to eq(nil)
    end

    it 'returns the first avatar file found in the repository' do
      expect(repository).to receive(:blob_at_branch).
        with('master', 'logo.png').
        and_return(true)

      expect(repository.avatar).to eq('logo.png')
    end

    it 'caches the output' do
      allow(repository).to receive(:blob_at_branch).
        with('master', 'logo.png').
        and_return(true)

      expect(repository.avatar).to eq('logo.png')

      expect(repository).to_not receive(:blob_at_branch)
      expect(repository.avatar).to eq('logo.png')
    end
  end

  describe '#expire_avatar_cache' do
    let(:cache) { repository.send(:cache) }

    before do
      allow(repository).to receive(:cache).and_return(cache)
    end

    context 'without a branch or revision' do
      it 'flushes the cache' do
        expect(cache).to receive(:expire).with(:avatar)

        repository.expire_avatar_cache
      end
    end

    context 'with a branch' do
      it 'does not flush the cache if the branch is not the default branch' do
        expect(cache).not_to receive(:expire)

        repository.expire_avatar_cache('cats')
      end

      it 'flushes the cache if the branch equals the default branch' do
        expect(cache).to receive(:expire).with(:avatar)

        repository.expire_avatar_cache(repository.root_ref)
      end
    end

    context 'with a branch and revision' do
      let(:commit) { double(:commit) }

      before do
        allow(repository).to receive(:commit).and_return(commit)
      end

      it 'does not flush the cache if the commit does not change any logos' do
        diff = double(:diff, new_path: 'test.txt')

        expect(commit).to receive(:diffs).and_return([diff])
        expect(cache).not_to receive(:expire)

        repository.expire_avatar_cache(repository.root_ref, '123')
      end

      it 'flushes the cache if the commit changes any of the logos' do
        diff = double(:diff, new_path: Repository::AVATAR_FILES[0])

        expect(commit).to receive(:diffs).and_return([diff])
        expect(cache).to receive(:expire).with(:avatar)

        repository.expire_avatar_cache(repository.root_ref, '123')
      end
    end
  end

  describe '#expire_exists_cache' do
    let(:cache) { repository.send(:cache) }

    it 'expires the cache' do
      expect(cache).to receive(:expire).with(:exists?)

      repository.expire_exists_cache
    end
  end

  describe '#build_cache' do
    let(:cache) { repository.send(:cache) }

    it 'builds the caches if they do not already exist' do
      expect(cache).to receive(:exist?).
        exactly(repository.cache_keys.length).
        times.
        and_return(false)

      repository.cache_keys.each do |key|
        expect(repository).to receive(key)
      end

      repository.build_cache
    end

    it 'does not build any caches that already exist' do
      expect(cache).to receive(:exist?).
        exactly(repository.cache_keys.length).
        times.
        and_return(true)

      repository.cache_keys.each do |key|
        expect(repository).to_not receive(key)
      end

      repository.build_cache
    end
  end

  describe '#local_branches' do
    it 'returns the local branches' do
      masterrev = repository.find_branch('master').target
      create_remote_branch('joe', 'remote_branch', masterrev)
      repository.add_branch(user, 'local_branch', masterrev)

      expect(repository.local_branches.any? { |branch| branch.name == 'remote_branch' }).to eq(false)
      expect(repository.local_branches.any? { |branch| branch.name == 'local_branch' }).to eq(true)
    end
  end

  describe '.clean_old_archives' do
    let(:path) { Gitlab.config.gitlab.repository_downloads_path }

    context 'when the downloads directory does not exist' do
      it 'does not remove any archives' do
        expect(File).to receive(:directory?).with(path).and_return(false)

        expect(Gitlab::Popen).not_to receive(:popen)

        described_class.clean_old_archives
      end
    end

    context 'when the downloads directory exists' do
      it 'removes old archives' do
        expect(File).to receive(:directory?).with(path).and_return(true)

        expect(Gitlab::Popen).to receive(:popen)

        described_class.clean_old_archives
      end
    end
  end

  def create_remote_branch(remote_name, branch_name, target)
    rugged = repository.rugged
    rugged.references.create("refs/remotes/#{remote_name}/#{branch_name}", target)
  end
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const wraptile = require('wraptile');
const {promisify} = require('es6-promisify');
const zipio = promisify(require('zipio'));

const setValue = wraptile(_setValue);

module.exports = function() {
    save.call(this)
        .then(setValue(this))
        .catch(this._onSave.bind(this));

    return this;
};

async function save() {
    const value = this.getValue();
    const {length} = value;
    const {
        _filename,
        _maxSize,
    } = this;

    const {diff, zip} = await this._loadOptions();

    if (diff) {
        const patch = await this._doDiff(_filename);
        const isPatch = checkPatch(length, _maxSize, patch);

        if (isPatch)
            return this._patch(_filename, patch);
    }

    if (!zip)
        return this._write(_filename, value);

    const zipedValue = await zipio(value);
    return this._write(`${_filename}?unzip`, zipedValue);
}

function _setValue(ctx) {
    ctx._value = ctx.getValue();
}

function checkPatch(length, maxSize, patch) {
    const patchLength = patch?.length || 0;
    const isLessMaxLength = length < maxSize;
    const isLessLength = isLessMaxLength && patchLength < length;
    const isStr = typeof patch === 'string';

    return patch && isStr && isLessLength;
}


text:
module Utilities where

import Graphics.Rendering.OpenGL.Raw
import Foreign

when predicate action = do
  shouldRun <- predicate
  case shouldRun of
    True  -> action
    False -> return ()

glCheckErrors code | code == gl_INVALID_ENUM                  = error "[Error] Invalid enum"
                   | code == gl_INVALID_VALUE                 = error "[Error] Invalid value"
                   | code == gl_INVALID_OPERATION             = error "[Error] Invalid operation"
                   | code == gl_STACK_OVERFLOW                = error "[Error] Stack overflow"
                   | code == gl_STACK_UNDERFLOW               = error "[Error] Stack underflow"
                   | code == gl_OUT_OF_MEMORY                 = error "[Error] Out of memory"
                   | code == gl_INVALID_FRAMEBUFFER_OPERATION = error "[Error] Invalid framebuffer operation"
                   | code == gl_TABLE_TOO_LARGE               = error "[Error] Table too large"
                   | code == gl_NO_ERROR                      = return ()
                   | otherwise                                = error "[Error] Unknown error code"

listSize list = fromIntegral $ length list * sizeOf (head list)

createBuffer target bufferData size = do
  bufferPtr <- (malloc :: IO (Ptr GLuint))
  glGenBuffers 1 bufferPtr
  buffer <- peek bufferPtr
  glBindBuffer target buffer
  glBufferData target size bufferData gl_STATIC_DRAW
  return buffer

cross (a, b, c, _) (x, y, z, _) = (b*z - c*y, c*x - a*z, a*y - b*x, 1.0)

minus     (a, b, c, _) (x, y, z, _) = (a - x, b - y, c - z, 1.0)
plus      (a, b, c, _) (x, y, z, _) = (a + x, b + y, c + z, 1.0)
midpoint  (a, b, c, _) (x, y, z, _) = ((a+x)/2.0, (b+y)/2.0, (c+z)/2.0, 1.0)
normalize (x, y, z, w)              = (x/l, y/l, z/l, w) where l = sqrt $ (x^2) + (y^2) + (z^2)

detuple (a, b, c, d) = [a, b, c, d]

flattenVerticies = concat . map detuple

glTypeSize glType | glType == gl_FLOAT = sizeOf (0 :: GLfloat)
                  | glType == gl_INT   = sizeOf (0 :: GLint)

glSizeOf count glType = fromIntegral $ (fromIntegral count) * glTypeSize glType


text:
package ga

import (
	"log"
	"math/rand"
	"time"
)

type Param struct {
	Name         string
	Normal       int32
	MinimumValue int32
	MaximumValue int32
}

type Config struct {
	Params             []Param
	NumberOfIndividual int
	Duration           time.Duration
}

func validateConfig(config Config) {
	if config.NumberOfIndividual == 0 {
		log.Fatal("NumberOfIndividual must not be zero")
	}

	if config.NumberOfIndividual%2 != 0 {
		log.Fatal("NumberOfIndividual must be even number")
	}
}

func generateNormalValues(config Config) []int32 {
	values := make([]int32, len(config.Params))
	for i := range config.Params {
		values[i] = config.Params[i].Normal
	}
	return values
}

func generateRandomValues(config Config) []int32 {
	values := make([]int32, len(config.Params))
	for i := range config.Params {
		min := config.Params[i].MinimumValue
		max := config.Params[i].MaximumValue
		values[i] = min + rand.Int31n(max-min+1)
	}
	return values
}


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_PIPE_HPP
#define BOOST_PROCESS_PIPE_HPP

#include <boost/config.hpp>
#include <boost/process/detail/config.hpp>
#include <streambuf>
#include <istream>
#include <ostream>
#include <vector>

#if defined(BOOST_POSIX_API)
#include <boost/process/detail/posix/basic_pipe.hpp>
#elif defined(BOOST_WINDOWS_API)
#include <boost/process/detail/windows/basic_pipe.hpp>
#endif

namespace boost { namespace process {

using ::boost::process::detail::api::basic_pipe;

#if defined(BOOST_PROCESS_DOXYGEN)
/** Class implementation of a pipe.
 *
 */
template<class CharT, class Traits = std::char_traits<CharT>>
class basic_pipe
{
public:
    typedef CharT                      char_type  ;
    typedef          Traits            traits_type;
    typedef typename Traits::int_type  int_type   ;
    typedef typename Traits::pos_type  pos_type   ;
    typedef typename Traits::off_type  off_type   ;
    typedef ::boost::detail::winapi::HANDLE_ native_handle;

    /// Default construct the pipe. Will be opened.
    basic_pipe();

    ///Construct a named pipe.
    inline explicit basic_pipe(const std::string & name);
    /** Copy construct the pipe.
     *  \note Duplicated the handles.
     */
    inline basic_pipe(const basic_pipe& p);
    /** Move construct the pipe. */
    basic_pipe(basic_pipe&& lhs);
    /** Copy assign the pipe.
     *  \note Duplicated the handles.
     */
    inline basic_pipe& operator=(const basic_pipe& p);
    /** Move assign the pipe. */
    basic_pipe& operator=(basic_pipe&& lhs);
    /** Destructor closes the handles. */
    ~basic_pipe();
    /** Get the native handle of the source. */
    native_handle native_source() const;
    /** Get the native handle of the sink. */
    native_handle native_sink  () const;

    /** Assign a new value to the source */
    void assign_source(native_handle h);
    /** Assign a new value to the sink */
    void assign_sink  (native_handle h);

    ///Write data to the pipe.
    int_type write(const char_type * data, int_type count);
    ///Read data from the pipe.
    int_type read(char_type * data, int_type count);
    ///Check if the pipe is open.
    bool is_open();
    ///Close the pipe
    void close();
};

#endif

typedef basic_pipe<char>     pipe;
typedef basic_pipe<wchar_t> wpipe;

/** Implementation of the stream buffer for a pipe.
 */
template<
    class CharT,
    class Traits = std::char_traits<CharT>
>
struct basic_pipebuf : std::basic_streambuf<CharT, Traits>
{
    typedef basic_pipe<CharT, Traits> pipe_type;

    typedef           CharT            char_type  ;
    typedef           Traits           traits_type;
    typedef  typename Traits::int_type int_type   ;
    typedef  typename Traits::pos_type pos_type   ;
    typedef  typename Traits::off_type off_type   ;

    constexpr static int default_buffer_size = BOOST_PROCESS_PIPE_SIZE;

    ///Default constructor, will also construct the pipe.
    basic_pipebuf() : _write(default_buffer_size), _read(default_buffer_size)
    {
        this->setg(_read.data(),  _read.data()+ 128,  _read.data() + 128);
        this->setp(_write.data(), _write.data() + _write.size());
    }
    ///Copy Constructor.
    basic_pipebuf(const basic_pipebuf & ) = default;
    ///Move Constructor
    basic_pipebuf(basic_pipebuf && ) = default;

    ///Destructor -> writes the frest of the data
    ~basic_pipebuf()
    {
        if (basic_pipebuf::is_open())
            basic_pipebuf::overflow(Traits::eof());
    }

    ///Move construct from a pipe.
    basic_pipebuf(pipe_type && p) : _pipe(std::move(p)),
                                    _write(default_buffer_size),
                                    _read(default_buffer_size)
    {
        this->setg(_read.data(),  _read.data()+ 128,  _read.data() + 128);
        this->setp(_write.data(), _write.data() + _write.size());
    }
    ///Construct from a pipe.
    basic_pipebuf(const pipe_type & p) : _pipe(p),
                                        _write(default_buffer_size),
                                        _read(default_buffer_size)
    {
        this->setg(_read.data(),  _read.data()+ 128,  _read.data() + 128);
        this->setp(_write.data(), _write.data() + _write.size());
    }
    ///Copy assign.
    basic_pipebuf& operator=(const basic_pipebuf & ) = delete;
    ///Move assign.
    basic_pipebuf& operator=(basic_pipebuf && ) = default;
    ///Move assign a pipe.
    basic_pipebuf& operator=(pipe_type && p)
    {
        _pipe = std::move(p);
        return *this;
    }
    ///Copy assign a pipe.
    basic_pipebuf& operator=(const pipe_type & p)
    {
        _pipe = p;
        return *this;
    }
    ///Writes characters to the associated output sequence from the put area
    int_type overflow(int_type ch = traits_type::eof()) override
    {
        if (_pipe.is_open() && (ch != traits_type::eof()))
        {
            if (this->pptr() == this->epptr())
            {
                bool wr = this->_write_impl();
                if (wr)
                {
                    *this->pptr() = ch;
                    this->pbump(1);
                    return ch;
                }
            }
            else
            {
                *this->pptr() = ch;
                this->pbump(1);
                if (this->_write_impl())
                    return ch;
            }
        }
        else if (ch == traits_type::eof())
           this->sync();

        return traits_type::eof();
    }
    ///Synchronizes the buffers with the associated character sequence
    int sync() override { return this->_write_impl() ? 0 : -1; }

    ///Reads characters from the associated input sequence to the get area
    int_type underflow() override
    {
        if (!_pipe.is_open())
            return traits_type::eof();

        if (this->egptr() == &_read.back()) //ok, so we're at the end of the buffer
            this->setg(_read.data(),  _read.data()+ 10,  _read.data() + 10);

        auto len = &_read.back() - this->egptr() ;
        auto res = _pipe.read(
                        this->egptr(),
                        static_cast<typename pipe_type::int_type>(len));
        if (res == 0)
            return traits_type::eof();

        this->setg(this->eback(), this->gptr(), this->egptr() + res);
        auto val = *this->gptr();

        return traits_type::to_int_type(val);
    }

    ///Set the pipe of the streambuf.
    void pipe(pipe_type&& p)      {_pipe = std::move(p); }
    ///Set the pipe of the streambuf.
    void pipe(const pipe_type& p) {_pipe = p; }
    ///Get a reference to the pipe.
    pipe_type &      pipe() &       {return _pipe;}
    ///Get a const reference to the pipe.
    const pipe_type &pipe() const & {return _pipe;}
    ///Get a rvalue reference to the pipe. Qualified as rvalue.
    pipe_type &&     pipe()  &&     {return std::move(_pipe);}

    ///Check if the pipe is open
    bool is_open() const {return _pipe.is_open(); }

    ///Open a new pipe
    basic_pipebuf<CharT, Traits>* open()
    {
        if (is_open())
            return nullptr;
        _pipe = pipe();
        return this;
    }

    ///Open a new named pipe
    basic_pipebuf<CharT, Traits>* open(const std::string & name)
    {
        if (is_open())
            return nullptr;
        _pipe = pipe(name);
        return this;
    }

    ///Flush the buffer & close the pipe
    basic_pipebuf<CharT, Traits>* close()
    {
        if (!is_open())
            return nullptr;
        overflow(Traits::eof());
        return this;
    }
private:
    pipe_type _pipe;
    std::vector<char_type> _write;
    std::vector<char_type> _read;

    bool _write_impl()
    {
        if (!_pipe.is_open())
            return false;

        auto base = this->pbase();

        if (base == this->pptr())
            return true;

        std::ptrdiff_t wrt = _pipe.write(base,
                static_cast<typename pipe_type::int_type>(this->pptr() - base));

        std::ptrdiff_t diff = this->pptr() - base;

        if (wrt < diff)
            std::move(base + wrt, base + diff, base);
        else if (wrt == 0) //broken pipe
            return false;

        this->pbump(-wrt);

        return true;
    }
};

typedef basic_pipebuf<char>     pipebuf;
typedef basic_pipebuf<wchar_t> wpipebuf;

/** Implementation of a reading pipe stream.
 *
 */
template<
    class CharT,
    class Traits = std::char_traits<CharT>
>
class basic_ipstream : public std::basic_istream<CharT, Traits>
{
    mutable basic_pipebuf<CharT, Traits> _buf;
public:

    typedef basic_pipe<CharT, Traits> pipe_type;

    typedef           CharT            char_type  ;
    typedef           Traits           traits_type;
    typedef  typename Traits::int_type int_type   ;
    typedef  typename Traits::pos_type pos_type   ;
    typedef  typename Traits::off_type off_type   ;

    ///Get access to the underlying stream_buf
    basic_pipebuf<CharT, Traits>* rdbuf() const {return &_buf;};

    ///Default constructor.
    basic_ipstream() : std::basic_istream<CharT, Traits>(nullptr)
    {
        std::basic_istream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy constructor.
    basic_ipstream(const basic_ipstream & ) = delete;
    ///Move constructor.
    basic_ipstream(basic_ipstream && lhs) : std::basic_istream<CharT, Traits>(nullptr), _buf(std::move(lhs._buf))
    {
        std::basic_istream<CharT, Traits>::rdbuf(&_buf);
    }

    ///Move construct from a pipe.
    basic_ipstream(pipe_type && p)      : std::basic_istream<CharT, Traits>(nullptr), _buf(std::move(p))
    {
        std::basic_istream<CharT, Traits>::rdbuf(&_buf);
    }

    ///Copy construct from a pipe.
    basic_ipstream(const pipe_type & p) : std::basic_istream<CharT, Traits>(nullptr), _buf(p)
    {
        std::basic_istream<CharT, Traits>::rdbuf(&_buf);
    }

    ///Copy assignment.
    basic_ipstream& operator=(const basic_ipstream & ) = delete;
    ///Move assignment
    basic_ipstream& operator=(basic_ipstream && lhs)
    {
        std::basic_istream<CharT, Traits>::operator=(std::move(lhs));
        _buf = std::move(lhs._buf);
        std::basic_istream<CharT, Traits>::rdbuf(&_buf);
        return *this;
    };
    ///Move assignment of a pipe.
    basic_ipstream& operator=(pipe_type && p)
    {
        _buf = std::move(p);
        return *this;
    }
    ///Copy assignment of a pipe.
    basic_ipstream& operator=(const pipe_type & p)
    {
        _buf = p;
        return *this;
    }
    ///Set the pipe of the streambuf.
    void pipe(pipe_type&& p)      {_buf.pipe(std::move(p)); }
    ///Set the pipe of the streambuf.
    void pipe(const pipe_type& p) {_buf.pipe(p); }
    ///Get a reference to the pipe.
    pipe_type &      pipe() &       {return _buf.pipe();}
    ///Get a const reference to the pipe.
    const pipe_type &pipe() const & {return _buf.pipe();}
    ///Get a rvalue reference to the pipe. Qualified as rvalue.
    pipe_type &&     pipe()  &&     {return std::move(_buf).pipe();}
    ///Check if the pipe is open
    bool is_open() const {return _buf.is_open();}

    ///Open a new pipe
    void open()
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Open a new named pipe
    void open(const std::string & name)
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Flush the buffer & close the pipe
    void close()
    {
        if (_buf.close() == nullptr)
            this->setstate(std::ios_base::failbit);
    }
};

typedef basic_ipstream<char>     ipstream;
typedef basic_ipstream<wchar_t> wipstream;

/** Implementation of a write pipe stream.
 *
 */
template<
    class CharT,
    class Traits = std::char_traits<CharT>
>
class basic_opstream : public std::basic_ostream<CharT, Traits>
{
    mutable basic_pipebuf<CharT, Traits> _buf;
public:
    typedef basic_pipe<CharT, Traits> pipe_type;

    typedef           CharT            char_type  ;
    typedef           Traits           traits_type;
    typedef  typename Traits::int_type int_type   ;
    typedef  typename Traits::pos_type pos_type   ;
    typedef  typename Traits::off_type off_type   ;

    ///Get access to the underlying stream_buf
    basic_pipebuf<CharT, Traits>* rdbuf() const {return &_buf;};

    ///Default constructor.
    basic_opstream() : std::basic_ostream<CharT, Traits>(nullptr)
    {
        std::basic_ostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy constructor.
    basic_opstream(const basic_opstream & ) = delete;
    ///Move constructor.
    basic_opstream(basic_opstream && lhs) : std::basic_ostream<CharT, Traits>(nullptr), _buf(std::move(lhs._buf))
    {
        std::basic_ostream<CharT, Traits>::rdbuf(&_buf);
    }
    ///Move construct from a pipe.
    basic_opstream(pipe_type && p)      : std::basic_ostream<CharT, Traits>(nullptr), _buf(std::move(p))
    {
        std::basic_ostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy construct from a pipe.
    basic_opstream(const pipe_type & p) : std::basic_ostream<CharT, Traits>(nullptr), _buf(p)
    {
        std::basic_ostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy assignment.
    basic_opstream& operator=(const basic_opstream & ) = delete;
    ///Move assignment
    basic_opstream& operator=(basic_opstream && lhs)
    {
        std::basic_ostream<CharT, Traits>::operator=(std::move(lhs));
        _buf = std::move(lhs._buf);
        std::basic_ostream<CharT, Traits>::rdbuf(&_buf);
        return *this;
    };

    ///Move assignment of a pipe.
    basic_opstream& operator=(pipe_type && p)
    {
        _buf = std::move(p);
        return *this;
    }
    ///Copy assignment of a pipe.
    basic_opstream& operator=(const pipe_type & p)
    {
        _buf = p;
        return *this;
    }
    ///Set the pipe of the streambuf.
    void pipe(pipe_type&& p)      {_buf.pipe(std::move(p)); }
    ///Set the pipe of the streambuf.
    void pipe(const pipe_type& p) {_buf.pipe(p); }
    ///Get a reference to the pipe.
    pipe_type &      pipe() &       {return _buf.pipe();}
    ///Get a const reference to the pipe.
    const pipe_type &pipe() const & {return _buf.pipe();}
    ///Get a rvalue reference to the pipe. Qualified as rvalue.
    pipe_type &&     pipe()  &&     {return std::move(_buf).pipe();}

    ///Open a new pipe
    void open()
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Open a new named pipe
    void open(const std::string & name)
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Flush the buffer & close the pipe
    void close()
    {
        if (_buf.close() == nullptr)
            this->setstate(std::ios_base::failbit);
    }
};

typedef basic_opstream<char>     opstream;
typedef basic_opstream<wchar_t> wopstream;

/** Implementation of a read-write pipe stream.
 *
 */
template<
    class CharT,
    class Traits = std::char_traits<CharT>
>
class basic_pstream : public std::basic_iostream<CharT, Traits>
{
    mutable basic_pipebuf<CharT, Traits> _buf;
public:
    typedef basic_pipe<CharT, Traits> pipe_type;

    typedef           CharT            char_type  ;
    typedef           Traits           traits_type;
    typedef  typename Traits::int_type int_type   ;
    typedef  typename Traits::pos_type pos_type   ;
    typedef  typename Traits::off_type off_type   ;

    ///Get access to the underlying stream_buf
    basic_pipebuf<CharT, Traits>* rdbuf() const {return &_buf;};

    ///Default constructor.
    basic_pstream() : std::basic_iostream<CharT, Traits>(nullptr)
    {
        std::basic_iostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy constructor.
    basic_pstream(const basic_pstream & ) = delete;
    ///Move constructor.
    basic_pstream(basic_pstream && lhs) : std::basic_iostream<CharT, Traits>(nullptr), _buf(std::move(lhs._buf))
    {
        std::basic_iostream<CharT, Traits>::rdbuf(&_buf);
    }
    ///Move construct from a pipe.
    basic_pstream(pipe_type && p)      : std::basic_iostream<CharT, Traits>(nullptr), _buf(std::move(p))
    {
        std::basic_iostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy construct from a pipe.
    basic_pstream(const pipe_type & p) : std::basic_iostream<CharT, Traits>(nullptr), _buf(p)
    {
        std::basic_iostream<CharT, Traits>::rdbuf(&_buf);
    };
    ///Copy assignment.
    basic_pstream& operator=(const basic_pstream & ) = delete;
    ///Move assignment
    basic_pstream& operator=(basic_pstream && lhs)
    {
        std::basic_istream<CharT, Traits>::operator=(std::move(lhs));
        _buf = std::move(lhs._buf);
        std::basic_iostream<CharT, Traits>::rdbuf(&_buf);
        return *this;
    };
    ///Move assignment of a pipe.
    basic_pstream& operator=(pipe_type && p)
    {
        _buf = std::move(p);
        return *this;
    }
    ///Copy assignment of a pipe.
    basic_pstream& operator=(const pipe_type & p)
    {
        _buf = p;
        return *this;
    }
    ///Set the pipe of the streambuf.
    void pipe(pipe_type&& p)      {_buf.pipe(std::move(p)); }
    ///Set the pipe of the streambuf.
    void pipe(const pipe_type& p) {_buf.pipe(p); }
    ///Get a reference to the pipe.
    pipe_type &      pipe() &       {return _buf.pipe();}
    ///Get a const reference to the pipe.
    const pipe_type &pipe() const & {return _buf.pipe();}
    ///Get a rvalue reference to the pipe. Qualified as rvalue.
    pipe_type &&     pipe()  &&     {return std::move(_buf).pipe();}

    ///Open a new pipe
    void open()
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Open a new named pipe
    void open(const std::string & name)
    {
        if (_buf.open() == nullptr)
            this->setstate(std::ios_base::failbit);
        else
            this->clear();
    }

    ///Flush the buffer & close the pipe
    void close()
    {
        if (_buf.close() == nullptr)
            this->setstate(std::ios_base::failbit);
    }
};

typedef basic_pstream<char>     pstream;
typedef basic_pstream<wchar_t> wpstream;

}}

#endif


text:
define([
  'aeris/util',
  'aeris/errors/abstracterror'
], function(_, AbstractError) {
  var ErrorTypeFactory = function(config) {
    var ErrorType;

    _.defaults(config, {
      type: AbstractError
    });

    this.ParentType_ = config.type;

    ErrorType = this.initializeType_();

    ErrorType.prototype.setName = function() {
      return config.name;
    };

    ErrorType.prototype.setMessage = function() {
      var messageCb = config.message || function(msg) { return msg; };

      return messageCb.apply(this, arguments);
    };

    return ErrorType;
  };

  ErrorTypeFactory.prototype.initializeType_ = function() {
    var ParentType = this.ParentType_;
    var Type = function(var_args) {
      ParentType.apply(this, arguments);
    };
    _.inherits(Type, ParentType);

    return Type;
  };

  return ErrorTypeFactory;
});


text:
static const float s_fullScreenQuadData[] =
{
	-1.0f, 1.0f, 0.0f, 0.0f,
	1.0f, 1.0f, 1.0f, 0.0f,
	-1.0f, -1.0f, 0.0f, 1.0f,
	1.0f, -1.0f, 1.0f, 1.0f
};

NvQuadVK* NvQuadVK::Create(NvVkContext& vk) {
	VkResult result;

	NvQuadVK* quad = new NvQuadVK;

	// Create the vertex buffer
	result = vk.createAndFillBuffer(4 * 4 * sizeof(float),
		VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
		VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
		quad->mVBO, s_fullScreenQuadData);
	CHECK_VK_RESULT();

	// Create static state info for the mPipeline.
	quad->mVertexBindings.binding = 0;
	quad->mVertexBindings.stride = 4 * sizeof(float);
	quad->mVertexBindings.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;

	quad->mAttributes[0].location = 0;
	quad->mAttributes[0].binding = 0;
	quad->mAttributes[0].format = VK_FORMAT_R32G32_SFLOAT;
	quad->mAttributes[0].offset = 0;
	quad->mAttributes[1].location = 1;
	quad->mAttributes[1].binding = 0;
	quad->mAttributes[1].format = VK_FORMAT_R32G32_SFLOAT;
	quad->mAttributes[1].offset = 2 * sizeof(float);

	quad->mVIStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
	quad->mVIStateInfo.vertexBindingDescriptionCount = 1;
	quad->mVIStateInfo.pVertexBindingDescriptions = &quad->mVertexBindings;
	quad->mVIStateInfo.vertexAttributeDescriptionCount = 2;
	quad->mVIStateInfo.pVertexAttributeDescriptions = quad->mAttributes;

	quad->mIAStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
	quad->mIAStateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
	quad->mIAStateInfo.primitiveRestartEnable = VK_FALSE;

	return quad;
}

void NvQuadVK::Draw(VkCommandBuffer& cmd) {
	VkResult result = VK_SUCCESS;

	// Bind the vertex and index buffers
	VkDeviceSize offsets[] = { 0 };
	vkCmdBindVertexBuffers(cmd, 0, 1, &mVBO(), offsets);

	// Draw the triangle
	vkCmdDraw(cmd, 4, 1, 0, 0);
}

NvQuadVK::NvQuadVK() {

}


text:
import { PagerDutyReader, IPagerDutyService } from './pagerDuty.read.service';
import { module, IComponentController, IComponentOptions } from 'angular';

export class PagerDutyTagComponentController implements IComponentController {
  public apiKey: any;

  public servicesLoaded = false;
  public currentService: IPagerDutyService;

  private setCurrentService(): void {
    this.servicesLoaded = false;
    PagerDutyReader.listServices().subscribe((pagerDutyServices: IPagerDutyService[]) => {
      this.currentService = pagerDutyServices.find((service: IPagerDutyService) => {
        return service.integration_key === this.apiKey;
      });
      this.servicesLoaded = true;
    });
  }

  public $onInit(): void {
    this.setCurrentService();
  }

  public $onChanges(): void {
    this.setCurrentService();
  }
}

const pagerDutyTagComponent: IComponentOptions = {
  bindings: {
    apiKey: '<',
  },
  controller: PagerDutyTagComponentController,
  template: `

         Loading...

        {{ $ctrl.currentService.name }} ({{ $ctrl.currentService.integration_key }})

        Unable to locate PagerDuty key ({{ $ctrl.apiKey }})

  `,
};

export const PAGER_DUTY_TAG_COMPONENT = 'spinnaker.core.pagerDuty.pagerDutyTag.component';
module(PAGER_DUTY_TAG_COMPONENT, []).component('pagerDutyTag', pagerDutyTagComponent);


text:
/*
 * Receiver, knows how to perform operations.
 */
public class Player {
    public void jump() {
        System.out.println("Player jumping");
    }
    public void fire() {
        System.out.println("Player firing");
    }
    public void moveRight() {
        System.out.println("Player moving right");
    }
}


text:
#include "adesk.h"
#include "rxobject.h"
#include "rxboiler.h"
#include "brgbl.h"
#include "brmctl.h"

// forward class declarations
class AcBrMeshControl;

class AcBrMesh2dControl : public AcBrMeshControl
{
public:
    ACRX_DECLARE_MEMBERS(AcBrMesh2dControl);
    AcBrMesh2dControl();
    AcBrMesh2dControl(const AcBrMesh2dControl& src);
    ~AcBrMesh2dControl();

    // Assignment operator
    AcBrMesh2dControl&	operator =      (const AcBrMesh2dControl& src);

    // Queries & Initialisers
    AcBr::ErrorStatus   setMaxAspectRatio(const double& maxAspectRatio = *(double*)NULL);
    AcBr::ErrorStatus   getMaxAspectRatio(double& maxAspectRatio) const;
    AcBr::ErrorStatus   setElementShape	(const AcBr::Element2dShape& elementShape = *(AcBr::Element2dShape*)NULL);
    AcBr::ErrorStatus   getElementShape	(AcBr::Element2dShape& elementShape) const;
    AcBr::ErrorStatus   setMinSubdivisionsInU(const Adesk::UInt32& minSubsU = *(Adesk::UInt32*)NULL);
	AcBr::ErrorStatus   getMinSubdivisionsInU(Adesk::UInt32& minSubsU) const;
    AcBr::ErrorStatus   setMinSubdivisionsInV(const Adesk::UInt32& minSubsV = *(Adesk::UInt32*)NULL);
	AcBr::ErrorStatus   getMinSubdivisionsInV(Adesk::UInt32& minSubsV) const;
};

#endif


text:
title: WebGL, JS en el espacio
speakers: Facundo Ferrero
categories: talks
date: 2015-08-13 18:30
repository: webgl_js_en_el_espacio
video: https://www.youtube.com/watch?v=35lY0ikj-Yw
---


text:
package com.hivemq.plugin.discovery.k8s;

import com.hivemq.spi.PluginEntryPoint;
import com.hivemq.spi.callback.registry.CallbackRegistry;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**  This entry point call is called by the module main class. Currently there is not configuration happening.
 *
 *
 * @author Christian Rohmann, inovex GmbH
 */
public class K8SDiscoveryPluginEntryPoint extends PluginEntryPoint{
    Logger log = LoggerFactory.getLogger(K8SDiscoveryPluginEntryPoint.class);
    private final K8SDiscoveryCallback discoveryCallback;

    @Inject
    public K8SDiscoveryPluginEntryPoint(final K8SDiscoveryCallback discoveryCallback) {
        log.debug("K8SDiscoveryPluginEntryPoint constructor called");
        this.discoveryCallback = discoveryCallback;
    }

    /**
     * This method is executed after the instanciation of the whole class. It is used to initialize
     * the implemented callbacks and make them known to the HiveMQ core.
     */
    @PostConstruct
    public void postConstruct() {
        log.debug("Registering discoveryCallback with HiveMQ CallbackRegistry");
        CallbackRegistry callbackRegistry = getCallbackRegistry();
        callbackRegistry.addCallback(discoveryCallback);

    }

}


text:
**Owner: SIG-Node**

This document describes testing policy and process for runtimes implementing the
[Container Runtime Interface (CRI)](/contributors/devel/sig-node/container-runtime-interface.md)
to publish test results in a federated dashboard. The objective is to provide
the Kubernetes community an easy way to track the conformance, stability, and
supported features of a CRI runtime.

This document focuses on Kubernetes node/cluster end-to-end (E2E) testing
because many features require integration of runtime, OS, or even the cloud
provider. A higher-level integration tests provider better signals on vertical
stack compatibility to the Kubernetes community. On the other hand, runtime
developers are strongly encouraged to run low-level
[CRI validation test suite](https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/validation.md)
for validation as part of their development process.

## Required and optional tests

Runtime maintainers are **required** to submit the tests listed below.
 1. Node conformance test suite
 2. Node feature test suite

Node E2E tests qualify an OS image with a pre-installed CRI runtime. The
runtime maintainers are free to choose any OS distribution, packaging, and
deployment mechanism. Please see the
[tutorial](e2e-node-tests.md)
to know more about the Node E2E test framework and tests for validating a
compatible OS image.

The conformance suite is a set of platform-agnostic (e.g., OS, runtime, and
cloud provider) tests that validate the conformance of the OS image. The feature
suite allows the runtime to demonstrate what features are supported with the OS
distribution.

In addition to the required tests, the runtime maintainers are *strongly
recommended to run and submit results from the Kubernetes conformance test
suite*. This cluster-level E2E test suite provides extra test signal for areas
such as Networking, which cannot be covered by CRI, or Node-level
tests. Because networking requires deep integration between the runtime, the
cloud provider, and/or other cluster components, runtime maintainers are
recommended to reach out to other relevant SIGs (e.g., SIG-GCP or SIG-AWS) for
guidance and/or sponsorship.

## Process for publishing test results

To publish tests results, please submit a proposal in the
[Kubernetes community repository](https://github.com/kubernetes/community)
briefly explaining your runtime, providing at least two maintainers, and
assigning the proposal to the leads of SIG-Node.

These test results should be published under the `sig-node` tab, organized
as follows.

```
sig-node -> sig-node-cri-{Kubernetes-version} -> [page containing the required jobs]
```

Only the last three most recent Kubernetes versions and the master branch are
kept at any time. This is consistent with the Kubernetes release schedule and
policy.

## Test job maintenance

Tests are required to run at least nightly.

The runtime maintainers are responsible for keeping the tests healthy. If the
tests are deemed not actively maintained, SIG-Node may remove the tests from
the test grid at their discretion.

## Process for adding pre-submit testing

If the tests are in good standing (i.e., consistently passing for more than 2
weeks), the runtime maintainers may request that the tests to be included in the
pre-submit Pull Request (PR) tests. Please note that the pre-submit tests
require significantly higher testing capacity, and are held at a higher standard
since they directly affect the development velocity.

If the tests are flaky or failing, and the maintainers are unable to respond and
fix the issues in a timely manner, the SIG leads may remove the runtime from
the presubmit tests until the issues are resolved.

As of now, SIG-Node only accepts promotion of Node conformance tests to
pre-submit because Kubernetes conformance tests involve a wider scope and may
need co-sponsorships from other SIGs.

## FAQ

 *1. Can runtime maintainers publish results from other E2E tests?*

Yes, runtime maintainers can publish additional Node E2E tests results. These
test jobs will be displayed in the `sig-node-{runtime-name}` page. The same
policy for test maintenance applies.

As for additional Cluster E2E tests, SIG-Node may agree to host the
results. However, runtime maintainers are strongly encouraged to seek for a more
appropriate SIG to sponsor or host the results.

 *2. Can these runtime-specific test jobs be considered release blocking?*

This is beyond the authority of SIG-Node, and requires agreement and consensus
across multiple SIGs (e.g., Release, the relevant cloud provider SIG, etc).

 *3. How to run the aforementioned tests?*

It is hard to keep instructions are even links to them up-to-date in one
document. Please contact the relevant SIGs for assistance.

 *4. How can I change the test-grid to publish the test results?*

Please contact SIG-Node for the detailed instructions.

 *5. How does this policy apply to Windows containers?*

Windows containers are still in the early development phase and the features
they support change rapidly. Therefore, it is suggested to treat it as a
feature with select, whitelisted tests to run.


text:
<?php

namespace Admin\AdminBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase {

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;
    private $router;
    private $translator;
    private $client;
    private $clientLogged;
    private $PHP_AUTH_USER = 'Jerome';
    private $PHP_AUTH_PW = '1234';

    public function __construct() {
        static::$kernel = static::createKernel();
        static::$kernel->boot();
        $this->em = static::$kernel->getContainer()
                ->get('doctrine')
                ->getManager();

        $this->client = static::createClient();

        $this->router = $this->client->getContainer()->get('router');
        $this->translator = $this->client->getContainer()->get('translator');

        $this->clientLogged = static::createClient(array(), array(
                    'PHP_AUTH_USER' => $this->PHP_AUTH_USER,
                    'PHP_AUTH_PW' => $this->PHP_AUTH_PW
        ));
        $this->router = $this->clientLogged->getContainer()->get('router');
        $this->translator = $this->clientLogged->getContainer()->get('translator');
    }

    public function testIndexEn() {
        $crawler = $this->client->request('GET', $this->router->generate('admin_admin_homepage', array('_locale' => 'en')));
        $this->assertFalse($this->client->getResponse()->isSuccessful());
        $crawler = $this->clientLogged->request('GET', $this->router->generate('admin_admin_homepage', array('_locale' => 'en')));
        $this->assertTrue($this->clientLogged->getResponse()->isSuccessful());
    }

    public function testIndexFr() {
        $crawler = $this->client->request('GET', $this->router->generate('admin_admin_homepage', array('_locale' => 'fr')));
        $this->assertFalse($this->client->getResponse()->isSuccessful());
        $crawler = $this->clientLogged->request('GET', $this->router->generate('admin_admin_homepage', array('_locale' => 'fr')));
        $this->assertTrue($this->clientLogged->getResponse()->isSuccessful());
    }

    public function testSitemap() {
        $crawler = $this->client->request('GET', $this->router->generate('admin_admin_sitemap', array('_locale' => 'fr')));
        $this->assertFalse($this->client->getResponse()->isSuccessful());
        $crawler = $this->clientLogged->request('GET', $this->router->generate('admin_admin_sitemap', array('_locale' => 'fr')));
        $this->assertTrue($this->clientLogged->getResponse()->isSuccessful());
    }

}


text:
/**
 * Test for the util module.
 */
(function () {

    'use strict';

    var util = require('../../src/util.js');

    describe('isInteger', function () {

        it('Should return false for non-integers', function () {

            expect(util.isInteger(undefined)).toBeFalsy();
            expect(util.isInteger(null)).toBeFalsy();
            expect(util.isInteger(true)).toBeFalsy();
            expect(util.isInteger(false)).toBeFalsy();
            expect(util.isInteger(new Error())).toBeFalsy();
            expect(util.isInteger([])).toBeFalsy();
            expect(util.isInteger({})).toBeFalsy();
            expect(util.isInteger(0.01)).toBeFalsy();
            expect(util.isInteger(Math.PI)).toBeFalsy();
        });

        it('Should return true for integers', function () {

            expect(util.isInteger(0)).toBeTruthy();
            expect(util.isInteger(-1)).toBeTruthy();
            expect(util.isInteger(1)).toBeTruthy();
            expect(util.isInteger(1024)).toBeTruthy();
            expect(util.isInteger(-104)).toBeTruthy();
        });
    });

    describe('isPrime', function () {

        it('Should return false for non-integers', function () {

            expect(util.isPrime(undefined)).toBeFalsy();
            expect(util.isPrime(null)).toBeFalsy();
            expect(util.isPrime(true)).toBeFalsy();
            expect(util.isPrime(false)).toBeFalsy();
            expect(util.isPrime(new Error())).toBeFalsy();
            expect(util.isPrime([])).toBeFalsy();
            expect(util.isPrime({})).toBeFalsy();
            expect(util.isPrime(0.01)).toBeFalsy();
            expect(util.isPrime(Math.PI)).toBeFalsy();
        });

        it('Should return false for non-prime numbers', function () {

            expect(util.isPrime(4)).toBeFalsy();
            expect(util.isPrime(6)).toBeFalsy();
            expect(util.isPrime(8)).toBeFalsy();
            expect(util.isPrime(9)).toBeFalsy();
            expect(util.isPrime(10)).toBeFalsy();
            expect(util.isPrime(12)).toBeFalsy();
            expect(util.isPrime(14)).toBeFalsy();
            expect(util.isPrime(15)).toBeFalsy();
            expect(util.isPrime(16)).toBeFalsy();
            expect(util.isPrime(40)).toBeFalsy();
            expect(util.isPrime(42)).toBeFalsy();
            expect(util.isPrime(82)).toBeFalsy();
            expect(util.isPrime(84)).toBeFalsy();
            expect(util.isPrime(4788)).toBeFalsy();
            expect(util.isPrime(7874)).toBeFalsy();
            expect(util.isPrime(7875)).toBeFalsy();
            expect(util.isPrime(7876)).toBeFalsy();

        });

        it('Should return true for prime numbers', function () {

            expect(util.isPrime(2)).toBeTruthy();
            expect(util.isPrime(3)).toBeTruthy();
            expect(util.isPrime(5)).toBeTruthy();
            expect(util.isPrime(7)).toBeTruthy();
            expect(util.isPrime(11)).toBeTruthy();
            expect(util.isPrime(13)).toBeTruthy();
            expect(util.isPrime(17)).toBeTruthy();
            expect(util.isPrime(41)).toBeTruthy();
            expect(util.isPrime(83)).toBeTruthy();
            expect(util.isPrime(103)).toBeTruthy();
            expect(util.isPrime(4789)).toBeTruthy();
            expect(util.isPrime(7873)).toBeTruthy();
            expect(util.isPrime(7877)).toBeTruthy();

        });
    });

    describe('isPalindrome', function () {

        it('Should return false for non-integers', function () {

            expect(util.isPalindrome(undefined)).toBeFalsy();
            expect(util.isPalindrome(null)).toBeFalsy();
            expect(util.isPalindrome(true)).toBeFalsy();
            expect(util.isPalindrome(false)).toBeFalsy();
            expect(util.isPalindrome(new Error())).toBeFalsy();
            expect(util.isPalindrome([])).toBeFalsy();
            expect(util.isPalindrome({})).toBeFalsy();
            expect(util.isPalindrome(0.01)).toBeFalsy();
            expect(util.isPalindrome(Math.PI)).toBeFalsy();
        });

        it('Should return false for non-palindrome numbers', function () {

            expect(util.isPalindrome(10)).toBeFalsy();
            expect(util.isPalindrome(20)).toBeFalsy();
            expect(util.isPalindrome(50)).toBeFalsy();
            expect(util.isPalindrome(43)).toBeFalsy();
            expect(util.isPalindrome(25)).toBeFalsy();
            expect(util.isPalindrome(64)).toBeFalsy();
            expect(util.isPalindrome(2314)).toBeFalsy();
        });

        it('Should return true for palindrome numbers', function () {

            expect(util.isPalindrome(1)).toBeTruthy();
            expect(util.isPalindrome(2)).toBeTruthy();
            expect(util.isPalindrome(3)).toBeTruthy();
            expect(util.isPalindrome(4)).toBeTruthy();
            expect(util.isPalindrome(11)).toBeTruthy();
            expect(util.isPalindrome(22)).toBeTruthy();
            expect(util.isPalindrome(33)).toBeTruthy();
            expect(util.isPalindrome(44)).toBeTruthy();
            expect(util.isPalindrome(636)).toBeTruthy();
            expect(util.isPalindrome(6556)).toBeTruthy();
            expect(util.isPalindrome(9339)).toBeTruthy();
            expect(util.isPalindrome(12221)).toBeTruthy();

        });
    });

})();


text: PATH="/usr/local/phantomjs/bin:/usr/local/phantomjs:$PATH"


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 29: 241 (1987)

#### Original name
Parmelia irrugans Nyl.

### Remarks
null


text:
<mvc:View
		xmlns:mvc="sap.ui.core.mvc"
		xmlns:layout="sap.ui.layout"
		xmlns="sap.m">

	<layout:Grid defaultSpan="L4 M6 S12" hSpacing="0" width="100%">
		<layout:content>
			<layout:VerticalLayout>
				<layout:HorizontalLayout>
					<layout:Grid defaultSpan="L4 M4 S4" hSpacing="0" width="100%">
						<layout:content>
							<layout:VerticalLayout>
								<Label text="{emp1>name}"/>
								<Label text="{emp1>job}"/>
								<layout:layoutData>
									<layout:GridData span="L12 M12 S12"/>
								</layout:layoutData>
							</layout:VerticalLayout>
						</layout:content>
					</layout:Grid>
				</layout:HorizontalLayout>

				<layout:layoutData>
					<layout:GridData linebreak="true"/>
				</layout:layoutData>

				<layout:HorizontalLayout>
					<layout:Grid defaultSpan="L4 M4 S4" hSpacing="0" width="100%">
						<layout:VerticalLayout>
							<Label text="{emp2>name}"/>
							<Label text="{emp2>job}"/>
							<layout:layoutData>
								<layout:GridData span="L12 M12 S12"/>
							</layout:layoutData>
						</layout:VerticalLayout>
					</layout:Grid>
				</layout:HorizontalLayout>
			</layout:VerticalLayout>
		</layout:content>
	</layout:Grid>
</mvc:View>


text:
'use strict';

angular.module('redditBrowser.filters', [])
    .filter('imagesOnly', ['imageExtensionsRegex', 'imgurRegex', function(imageExtensionsRegex, imgurRegex) {
        return function(posts) {
            if (!posts || !posts) {
                return posts;
            }

            var imagePosts = [];
            posts.forEach(function(post) {
                if (imageExtensionsRegex.test(post.data.url) || imgurRegex.test(post.data.url)) {
                    imagePosts.push(post);
                }
            });
            return imagePosts;
        }
    }])
    .filter('imageify', ['imageExtensionsRegex', 'imgurRegex', 'imgurAlbumGalleryRegex', function(imageExtensionsRegex, imgurRegex, imgurAlbumGalleryRegex) {
        return function(post) {
            if (!post) {
                return post;
            }

            var url = post.data.url;
            if (!(imageExtensionsRegex.test(url))) {
                if (imgurRegex.test(url)) {
                    if (imgurAlbumGalleryRegex.test(url)) {
                        //TODO: Handle albums.
                        return url;
                    }
                    //TODO: Determine type.
                    return url + '.jpg';
                }
            } else {
                return post.data.url
            }
        }
    }])
    .filter('interpolate', ['version', function (version) {
        return function (text) {
            return String(text).replace(/\%VERSION\%/mg, version);
        };
    }]
);


text:
#include "structs.h"

/* Check an eigenpair of A by direct multiplication.  */
double checkeig(double *err, struct vtx_data **A, double *y, int n, double lambda, double *vwsqrt,
                double *work)
{
  double resid;
  double normy;
  double ch_norm();
  void   splarax(), scadd();

  splarax(err, A, n, y, vwsqrt, work);
  scadd(err, 1, n, -lambda, y);
  normy = ch_norm(y, 1, n);
  resid = ch_norm(err, 1, n) / normy;
  return (resid);
}


text:
import fs from 'fs';
import path from 'path';
import _ from 'lodash';
import Worker from '../../lib/workers/Worker';
import options from '../../lib/options';
import utils from './utils';

let assert = utils.assert;

// Ensure we have a clean slate before and after each test
beforeEach(() => {
  utils.cleanTestOutputDir();
});
afterEach(() => {
  utils.cleanTestOutputDir();
});

describe('Worker', () => {
  it('should be a function', () => {
    assert.isFunction(Worker);
  });
  describe('#onReady', () => {
    it('should accept and call functions when the process is ready', (done) => {
      let worker = new Worker();

      // Sanity checks
      assert.isObject(worker.worker);
      assert.isFunction(worker.worker.send);

      worker.onReady((err) => {
        assert.isNull(err);

        worker.kill();
        done();
      });
    });
    it('should produce errors if requests for a dead worker arrive', (done) => {
      let worker = new Worker();

      worker.onReady((err) => {
        assert.isNull(err);

        worker.kill();

        setTimeout(() => {
          worker.onReady((err) => {
            assert.instanceOf(err, Error);
            worker.onReady((_err) => {
              assert.strictEqual(_err, err);

              done();
            });
          });
        }, 50);
      });
    });
  });
  describe('#getStatus', () => {
    it('should accept and call functions when the process is ready', (done) => {
      let worker = new Worker();

      worker.getStatus((err, status) => {
        assert.isNull(err);

        assert.equal(status, 'ok');

        worker.kill();
        done();
      });
    });
  });
  describe('#build', () => {
    it('should accept an options argument and provide the output from the build', (done) => {
      let worker = new Worker();

      worker.build({
        config: path.join(__dirname, 'test_bundles', 'basic_bundle', 'webpack.config.js')
      }, (err, data) => {
        assert.isNull(err);
        assert.isObject(data);

        let existsAt = data.assets[0];
        assert.isString(existsAt);

        let contents = fs.readFileSync(existsAt).toString();
        assert.include(contents, '__BASIC_BUNDLE_ENTRY_TEST__');
        assert.include(contents, '__BASIC_BUNDLE_REQUIRE_TEST__');

        worker.kill();
        done();
      });
    });
    it('should handle errors', (done) => {
      let worker = new Worker();

      worker.build({
        config: path.join('/does/not/exist')
      }, (err, data) => {
        assert.isObject(err);
        assert.isString(err.type);
        assert.isString(err.message);
        assert.isString(err.stack);
        assert.isNull(data);

        worker.kill();
        done();
      });
    });
  });
});


text:
package org.apache.http.impl.client.cache;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.cache.HeaderConstants;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;

/**
 * Class used to represent an asynchronous revalidation event, such as with
 * "stale-while-revalidate"
 */
class AsynchronousValidationRequest implements Runnable {
    private final AsynchronousValidator parent;
    private final CachingExec cachingExec;
    private final HttpRoute route;
    private final HttpRequestWrapper request;
    private final HttpClientContext context;
    private final HttpExecutionAware execAware;
    private final HttpCacheEntry cacheEntry;
    private final String identifier;
    private final int consecutiveFailedAttempts;

    private final Log log = LogFactory.getLog(getClass());

    /**
     * Used internally by {@link AsynchronousValidator} to schedule a
     * revalidation.
     * @param request
     * @param context
     * @param cacheEntry
     * @param identifier
     * @param consecutiveFailedAttempts
     */
    AsynchronousValidationRequest(
            final AsynchronousValidator parent,
            final CachingExec cachingExec,
            final HttpRoute route,
            final HttpRequestWrapper request,
            final HttpClientContext context,
            final HttpExecutionAware execAware,
            final HttpCacheEntry cacheEntry,
            final String identifier,
            final int consecutiveFailedAttempts) {
        this.parent = parent;
        this.cachingExec = cachingExec;
        this.route = route;
        this.request = request;
        this.context = context;
        this.execAware = execAware;
        this.cacheEntry = cacheEntry;
        this.identifier = identifier;
        this.consecutiveFailedAttempts = consecutiveFailedAttempts;
    }

    public void run() {
        try {
            if (revalidateCacheEntry()) {
                parent.jobSuccessful(identifier);
            } else {
                parent.jobFailed(identifier);
            }
        } finally {
            parent.markComplete(identifier);
        }
    }

    /**
     * Revalidate the cache entry and return if the operation was successful.
     * Success means a connection to the server was established and replay did
     * not indicate a server error.
     * @return true if the cache entry was successfully validated;
     * otherwise false
     */
    protected boolean revalidateCacheEntry() {
        try {
            final CloseableHttpResponse httpResponse = cachingExec.revalidateCacheEntry(route, request, context, execAware, cacheEntry);
            try {
                final int statusCode = httpResponse.getStatusLine().getStatusCode();
                return isNotServerError(statusCode) && isNotStale(httpResponse);
            } finally {
                httpResponse.close();
            }
        } catch (final IOException ioe) {
            log.debug("Asynchronous revalidation failed due to I/O error", ioe);
            return false;
        } catch (final HttpException pe) {
            log.error("HTTP protocol exception during asynchronous revalidation", pe);
            return false;
        } catch (final RuntimeException re) {
            log.error("RuntimeException thrown during asynchronous revalidation: " + re);
            return false;
        }
    }

    /**
     * Return whether the status code indicates a server error or not.
     * @param statusCode the status code to be checked
     * @return if the status code indicates a server error or not
     */
    private boolean isNotServerError(final int statusCode) {
        return statusCode < 500;
    }

    /**
     * Try to detect if the returned response is generated from a stale cache entry.
     * @param httpResponse the response to be checked
     * @return whether the response is stale or not
     */
    private boolean isNotStale(final HttpResponse httpResponse) {
        final Header[] warnings = httpResponse.getHeaders(HeaderConstants.WARNING);
        if (warnings != null)
        {
            for (final Header warning : warnings)
            {
                /**
                 * warn-codes
                 * 110 = Response is stale
                 * 111 = Revalidation failed
                 */
                final String warningValue = warning.getValue();
                if (warningValue.startsWith("110") || warningValue.startsWith("111"))
                {
                    return false;
                }
            }
        }
        return true;
    }

    String getIdentifier() {
        return identifier;
    }

    /**
     * The number of consecutively failed revalidation attempts.
     * @return the number of consecutively failed revalidation attempts.
     */
    public int getConsecutiveFailedAttempts() {
        return consecutiveFailedAttempts;
    }

}