text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/ime/ash/input_method_ash.h"

#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <queue>
#include <string>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/i18n/char_iterator.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/ime/ash/ime_bridge.h"
#include "ui/base/ime/ash/mock_ime_candidate_window_handler.h"
#include "ui/base/ime/ash/mock_ime_engine_handler.h"
#include "ui/base/ime/ash/mock_input_method_manager.h"
#include "ui/base/ime/ash/text_input_method.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/dummy_text_input_client.h"
#include "ui/base/ime/fake_text_input_client.h"
#include "ui/base/ime/ime_key_event_dispatcher.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/events/test/keyboard_layout.h"
#include "ui/gfx/geometry/rect.h"

using base::UTF16ToUTF8;

namespace ui {
namespace {

const std::u16string kSampleText = u"あいうえお";

using KeyEventCallback = TextInputMethod::KeyEventDoneCallback;

uint32_t GetOffsetInUTF16(const std::u16string& utf16_string,
                          uint32_t utf8_offset) {
  DCHECK_LT(utf8_offset, utf16_string.size());
  base::i18n::UTF16CharIterator char_iterator(utf16_string);
  for (size_t i = 0; i < utf8_offset; ++i)
    char_iterator.Advance();
  return char_iterator.array_pos();
}

}  // namespace

class TestableInputMethodAsh : public InputMethodAsh {
 public:
  explicit TestableInputMethodAsh(
      ImeKeyEventDispatcher* ime_key_event_dispatcher)
      : InputMethodAsh(ime_key_event_dispatcher),
        process_key_event_post_ime_call_count_(0) {}

  struct ProcessKeyEventPostIMEArgs {
    ProcessKeyEventPostIMEArgs()
        : event(ET_UNKNOWN, VKEY_UNKNOWN, DomCode::NONE, EF_NONE),
          handled_state(ui::ime::KeyEventHandledState::kNotHandled) {}
    ui::KeyEvent event;
    ui::ime::KeyEventHandledState handled_state;
  };

  // Overridden from InputMethodAsh:
  ui::EventDispatchDetails ProcessKeyEventPostIME(
      ui::KeyEvent* key_event,
      ui::ime::KeyEventHandledState handled_state,
      bool stopped_propagation) override {
    ui::EventDispatchDetails details = InputMethodAsh::ProcessKeyEventPostIME(
        key_event, handled_state, stopped_propagation);
    process_key_event_post_ime_args_.event = *key_event;
    process_key_event_post_ime_args_.handled_state = handled_state;
    ++process_key_event_post_ime_call_count_;
    return details;
  }
  void CommitText(
      const std::u16string& text,
      TextInputClient::InsertTextCursorBehavior cursor_behavior) override {
    InputMethodAsh::CommitText(text, cursor_behavior);
    text_committed_ = text;
  }

  void SetEditableSelectionRange(gfx::Range range) {
    GetTextInputClient()->SetEditableSelectionRange(range);
  }

  void ResetCallCount() { process_key_event_post_ime_call_count_ = 0; }

  const ProcessKeyEventPostIMEArgs& process_key_event_post_ime_args() const {
    return process_key_event_post_ime_args_;
  }

  int process_key_event_post_ime_call_count() const {
    return process_key_event_post_ime_call_count_;
  }

  const std::u16string& text_committed() const { return text_committed_; }

  // Change access rights for testing.
  using InputMethodAsh::ExtractCompositionText;
  using InputMethodAsh::ResetContext;

 private:
  ProcessKeyEventPostIMEArgs process_key_event_post_ime_args_;
  int process_key_event_post_ime_call_count_;
  std::u16string text_committed_;
};

class SetSurroundingTextVerifier {
 public:
  SetSurroundingTextVerifier(const std::string& expected_surrounding_text,
                             uint32_t expected_cursor_position,
                             uint32_t expected_anchor_position)
      : expected_surrounding_text_(expected_surrounding_text),
        expected_cursor_position_(expected_cursor_position),
        expected_anchor_position_(expected_anchor_position) {}

  SetSurroundingTextVerifier(const SetSurroundingTextVerifier&) = delete;
  SetSurroundingTextVerifier& operator=(const SetSurroundingTextVerifier&) =
      delete;

  void Verify(const std::string& text,
              uint32_t cursor_pos,
              uint32_t anchor_pos) {
    EXPECT_EQ(expected_surrounding_text_, text);
    EXPECT_EQ(expected_cursor_position_, cursor_pos);
    EXPECT_EQ(expected_anchor_position_, anchor_pos);
  }

 private:
  const std::string expected_surrounding_text_;
  const uint32_t expected_cursor_position_;
  const uint32_t expected_anchor_position_;
};

class TestInputMethodManager
    : public ash::input_method::MockInputMethodManager {
  class TestState : public MockInputMethodManager::State {
   public:
    TestState() { Reset(); }

    TestState(const TestState&) = delete;
    TestState& operator=(const TestState&) = delete;

    // InputMethodManager::State:
    void ChangeInputMethodToJpKeyboard() override {
      is_jp_kbd_ = true;
      is_jp_ime_ = false;
    }
    void ChangeInputMethodToJpIme() override {
      is_jp_kbd_ = false;
      is_jp_ime_ = true;
    }
    void ToggleInputMethodForJpIme() override {
      if (!is_jp_ime_) {
        is_jp_kbd_ = false;
        is_jp_ime_ = true;
      } else {
        is_jp_kbd_ = true;
        is_jp_ime_ = false;
      }
    }
    void Reset() {
      is_jp_kbd_ = false;
      is_jp_ime_ = false;
    }
    bool is_jp_kbd() const { return is_jp_kbd_; }
    bool is_jp_ime() const { return is_jp_ime_; }

   protected:
    ~TestState() override = default;

   private:
    bool is_jp_kbd_ = false;
    bool is_jp_ime_ = false;
  };

 private:
  scoped_refptr<TestState> state_;

 public:
  TestInputMethodManager() {
    state_ = scoped_refptr<TestState>(new TestState());
  }

  TestInputMethodManager(const TestInputMethodManager&) = delete;
  TestInputMethodManager& operator=(const TestInputMethodManager&) = delete;

  TestState* state() { return state_.get(); }

  scoped_refptr<InputMethodManager::State> GetActiveIMEState() override {
    return scoped_refptr<InputMethodManager::State>(state_.get());
  }
};

class NiceMockIMEEngine : public ash::MockIMEEngineHandler {
 public:
  MOCK_METHOD1(Focus, void(const InputContext&));
  MOCK_METHOD0(Blur, void());
  MOCK_METHOD4(SetSurroundingText,
               void(const std::u16string&, uint32_t, uint32_t, uint32_t));
};

class InputMethodAshTest : public ImeKeyEventDispatcher,
                           public testing::Test,
                           public DummyTextInputClient {
 public:
  InputMethodAshTest()
      : dispatched_key_event_(ui::ET_UNKNOWN, ui::VKEY_UNKNOWN, ui::EF_NONE),
        stop_propagation_post_ime_(false) {
    ResetFlags();
  }

  InputMethodAshTest(const InputMethodAshTest&) = delete;
  InputMethodAshTest& operator=(const InputMethodAshTest&) = delete;

  ~InputMethodAshTest() override = default;

  void SetUp() override {
    mock_ime_engine_handler_ = std::make_unique<ash::MockIMEEngineHandler>();
    IMEBridge::Get()->SetCurrentEngineHandler(mock_ime_engine_handler_.get());

    mock_ime_candidate_window_handler_ =
        std::make_unique<ash::MockIMECandidateWindowHandler>();
    IMEBridge::Get()->SetCandidateWindowHandler(
        mock_ime_candidate_window_handler_.get());

    input_method_ash_ = std::make_unique<TestableInputMethodAsh>(this);
    input_method_ash_->SetFocusedTextInputClient(this);

    // InputMethodManager owns and delete it in InputMethodManager::Shutdown().
    input_method_manager_ = new TestInputMethodManager();
    ash::input_method::InputMethodManager::Initialize(input_method_manager_);
  }

  void TearDown() override {
    if (input_method_ash_.get())
      input_method_ash_->SetFocusedTextInputClient(nullptr);
    input_method_ash_.reset();
    IMEBridge::Get()->SetCurrentEngineHandler(nullptr);
    IMEBridge::Get()->SetCandidateWindowHandler(nullptr);
    mock_ime_engine_handler_.reset();
    mock_ime_candidate_window_handler_.reset();
    ash::input_method::InputMethodManager::Shutdown();

    ResetFlags();
  }

  // Overridden from ui::ImeKeyEventDispatcher:
  ui::EventDispatchDetails DispatchKeyEventPostIME(
      ui::KeyEvent* event) override {
    dispatched_key_event_ = *event;
    if (stop_propagation_post_ime_)
      event->StopPropagation();
    return ui::EventDispatchDetails();
  }

  // Overridden from ui::TextInputClient:
  void SetCompositionText(const CompositionText& composition) override {
    composition_text_ = composition;
  }
  size_t ConfirmCompositionText(bool keep_selection) override {
    // TODO(b/134473433) Modify this function so that the selection is not
    // changed when text committed
    NOTIMPLEMENTED_LOG_ONCE();
    confirmed_text_ = composition_text_;
    composition_text_ = CompositionText();
    return confirmed_text_.text.length();
  }
  void ClearCompositionText() override {
    composition_text_ = CompositionText();
  }
  void InsertText(
      const std::u16string& text,
      TextInputClient::InsertTextCursorBehavior cursor_behavior) override {
    inserted_text_ = text;
  }
  void InsertChar(const KeyEvent& event) override {
    inserted_char_ = event.GetCharacter();
    inserted_char_flags_ = event.flags();
  }
  TextInputType GetTextInputType() const override { return input_type_; }
  TextInputMode GetTextInputMode() const override { return input_mode_; }
  bool CanComposeInline() const override { return can_compose_inline_; }
  gfx::Rect GetCaretBounds() const override { return caret_bounds_; }
  bool HasCompositionText() const override {
    return composition_text_ != CompositionText();
  }
  bool GetTextRange(gfx::Range* range) const override {
    *range = text_range_;
    return true;
  }
  bool GetEditableSelectionRange(gfx::Range* range) const override {
    *range = selection_range_;
    return true;
  }
  bool GetTextFromRange(const gfx::Range& range,
                        std::u16string* text) const override {
    *text = surrounding_text_.substr(range.GetMin(), range.length());
    return true;
  }
  void OnInputMethodChanged() override {
    ++on_input_method_changed_call_count_;
  }
  bool SetCompositionFromExistingText(
      const gfx::Range& range,
      const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override {
    composition_text_ = CompositionText();
    GetTextFromRange(range, &composition_text_.text);
    return true;
  }
  bool SetAutocorrectRange(const gfx::Range& range) override {
    // TODO(crbug.com/1277388): This is a workaround to ensure that the range is
    // valid in the text. Change to use FakeTextInputClient instead of
    // DummyTextInputClient so that the text contents can be queried accurately.
    if (!inserted_text_.empty() || inserted_char_ != 0) {
      return DummyTextInputClient::SetAutocorrectRange(range);
    }
    return range.is_empty();
  }

  bool HasNativeEvent() const { return dispatched_key_event_.HasNativeEvent(); }

  void ResetFlags() {
    dispatched_key_event_ =
        ui::KeyEvent(ui::ET_UNKNOWN, ui::VKEY_UNKNOWN, ui::EF_NONE);

    composition_text_ = CompositionText();
    confirmed_text_ = CompositionText();
    inserted_text_.clear();
    inserted_char_ = 0;
    inserted_char_flags_ = 0;
    on_input_method_changed_call_count_ = 0;

    input_type_ = TEXT_INPUT_TYPE_NONE;
    input_mode_ = TEXT_INPUT_MODE_DEFAULT;
    can_compose_inline_ = true;
    caret_bounds_ = gfx::Rect();

    set_autocorrect_enabled(true);
  }

 protected:
  std::unique_ptr<TestableInputMethodAsh> input_method_ash_;

  // Copy of the dispatched key event.
  ui::KeyEvent dispatched_key_event_;

  // Variables for remembering the parameters that are passed to
  // ui::TextInputClient functions.
  CompositionText composition_text_;
  CompositionText confirmed_text_;
  std::u16string inserted_text_;
  char16_t inserted_char_;
  unsigned int on_input_method_changed_call_count_;
  int inserted_char_flags_;

  // Variables that will be returned from the ui::TextInputClient functions.
  TextInputType input_type_;
  TextInputMode input_mode_;
  bool can_compose_inline_;
  gfx::Rect caret_bounds_;
  gfx::Range text_range_;
  gfx::Range selection_range_;
  std::u16string surrounding_text_;

  std::unique_ptr<ash::MockIMEEngineHandler> mock_ime_engine_handler_;
  std::unique_ptr<ash::MockIMECandidateWindowHandler>
      mock_ime_candidate_window_handler_;

  bool stop_propagation_post_ime_;

  TestInputMethodManager* input_method_manager_;

  base::test::TaskEnvironment task_environment_;
};

// Tests public APIs in ui::InputMethod first.

TEST_F(InputMethodAshTest, GetInputTextType) {
  InputMethodAsh ime(this);
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  EXPECT_EQ(ime.GetTextInputType(), TEXT_INPUT_TYPE_TEXT);

  ime.SetFocusedTextInputClient(nullptr);
}

TEST_F(InputMethodAshTest, OnTextInputTypeChangedChangesInputType) {
  InputMethodAsh ime(this);
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  ime.SetFocusedTextInputClient(&fake_text_input_client);
  fake_text_input_client.set_text_input_type(TEXT_INPUT_TYPE_PASSWORD);

  ime.OnTextInputTypeChanged(&fake_text_input_client);

  EXPECT_EQ(ime.GetTextInputType(), TEXT_INPUT_TYPE_PASSWORD);

  ime.SetFocusedTextInputClient(nullptr);
}

TEST_F(InputMethodAshTest, GetTextInputClient) {
  EXPECT_EQ(this, input_method_ash_->GetTextInputClient());
  input_method_ash_->SetFocusedTextInputClient(nullptr);
  EXPECT_EQ(nullptr, input_method_ash_->GetTextInputClient());
}

TEST_F(InputMethodAshTest, GetInputTextType_WithoutFocusedClient) {
  EXPECT_EQ(TEXT_INPUT_TYPE_NONE, input_method_ash_->GetTextInputType());
  input_method_ash_->SetFocusedTextInputClient(nullptr);
  input_type_ = TEXT_INPUT_TYPE_PASSWORD;
  input_method_ash_->OnTextInputTypeChanged(this);
  // The OnTextInputTypeChanged() call above should be ignored since |this| is
  // not the current focused client.
  EXPECT_EQ(TEXT_INPUT_TYPE_NONE, input_method_ash_->GetTextInputType());

  input_method_ash_->SetFocusedTextInputClient(this);
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(TEXT_INPUT_TYPE_PASSWORD, input_method_ash_->GetTextInputType());
}

TEST_F(InputMethodAshTest, OnWillChangeFocusedClientClearAutocorrectRange) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->SetFocusedTextInputClient(this);
  input_method_ash_->CommitText(
      u"hello",
      TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  input_method_ash_->SetAutocorrectRange(gfx::Range(0, 5), base::DoNothing());
  EXPECT_EQ(gfx::Range(0, 5), this->GetAutocorrectRange());

  input_method_ash_->SetFocusedTextInputClient(nullptr);
  EXPECT_EQ(gfx::Range(), this->GetAutocorrectRange());
}

// Confirm that IBusClient::Focus is called on "connected" if input_type_ is
// TEXT.
TEST_F(InputMethodAshTest, Focus_Text) {
  // A context shouldn't be created since the daemon is not running.
  EXPECT_EQ(0U, on_input_method_changed_call_count_);
  // Click a text input form.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  // Since a form has focus, IBusClient::Focus() should be called.
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(1,
            mock_ime_candidate_window_handler_->set_cursor_bounds_call_count());
  // ui::TextInputClient::OnInputMethodChanged() should be called when
  // ui::InputMethodAsh connects/disconnects to/from ibus-daemon and the
  // current text input type is not NONE.
  EXPECT_EQ(1U, on_input_method_changed_call_count_);
}

// Confirm that InputMethodEngine::Focus is called on "connected" even if
// input_type_ is PASSWORD.
TEST_F(InputMethodAshTest, Focus_Password) {
  EXPECT_EQ(0U, on_input_method_changed_call_count_);
  input_type_ = TEXT_INPUT_TYPE_PASSWORD;
  input_method_ash_->OnTextInputTypeChanged(this);
  // InputMethodEngine::Focus() should be called even for password field.
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(1U, on_input_method_changed_call_count_);
}

// Confirm that IBusClient::Blur is called as expected.
TEST_F(InputMethodAshTest, Blur_None) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count());
  input_type_ = TEXT_INPUT_TYPE_NONE;
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count());
}

// Confirm that IBusClient::Blur is called as expected.
TEST_F(InputMethodAshTest, Blur_Password) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count());
  input_type_ = TEXT_INPUT_TYPE_PASSWORD;
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(2, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count());
}

// Focus/Blur scenario test
TEST_F(InputMethodAshTest, Focus_Scenario) {
  // Confirm that both Focus and Blur are NOT called.
  EXPECT_EQ(0, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count());
  EXPECT_EQ(TEXT_INPUT_TYPE_NONE,
            mock_ime_engine_handler_->last_text_input_context().type);
  EXPECT_EQ(TEXT_INPUT_MODE_DEFAULT,
            mock_ime_engine_handler_->last_text_input_context().mode);

  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_mode_ = TEXT_INPUT_MODE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  // Confirm that only Focus is called, the TextInputType is TEXT and the
  // TextInputMode is LATIN..
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count());
  EXPECT_EQ(TEXT_INPUT_TYPE_TEXT,
            mock_ime_engine_handler_->last_text_input_context().type);
  EXPECT_EQ(TEXT_INPUT_MODE_TEXT,
            mock_ime_engine_handler_->last_text_input_context().mode);

  input_mode_ = TEXT_INPUT_MODE_SEARCH;
  input_method_ash_->OnTextInputTypeChanged(this);
  // Confirm that both Focus and Blur are called for mode change.
  EXPECT_EQ(2, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count());
  EXPECT_EQ(TEXT_INPUT_TYPE_TEXT,
            mock_ime_engine_handler_->last_text_input_context().type);
  EXPECT_EQ(TEXT_INPUT_MODE_SEARCH,
            mock_ime_engine_handler_->last_text_input_context().mode);

  input_type_ = TEXT_INPUT_TYPE_URL;
  input_method_ash_->OnTextInputTypeChanged(this);
  // Confirm that both Focus and Blur are called and the TextInputType is
  // changed to URL.
  EXPECT_EQ(3, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(2, mock_ime_engine_handler_->focus_out_call_count());
  EXPECT_EQ(TEXT_INPUT_TYPE_URL,
            mock_ime_engine_handler_->last_text_input_context().type);
  EXPECT_EQ(TEXT_INPUT_MODE_SEARCH,
            mock_ime_engine_handler_->last_text_input_context().mode);

  // Confirm that Blur is called when set focus to NULL client.
  input_method_ash_->SetFocusedTextInputClient(nullptr);
  EXPECT_EQ(3, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(3, mock_ime_engine_handler_->focus_out_call_count());
  // Confirm that Focus is called when set focus to this client.
  input_method_ash_->SetFocusedTextInputClient(this);
  EXPECT_EQ(4, mock_ime_engine_handler_->focus_in_call_count());
  EXPECT_EQ(3, mock_ime_engine_handler_->focus_out_call_count());
}

// Test if the new |caret_bounds_| is correctly sent to ibus-daemon.
TEST_F(InputMethodAshTest, OnCaretBoundsChanged) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  EXPECT_EQ(1,
            mock_ime_candidate_window_handler_->set_cursor_bounds_call_count());
  caret_bounds_ = gfx::Rect(1, 2, 3, 4);
  input_method_ash_->OnCaretBoundsChanged(this);
  EXPECT_EQ(2,
            mock_ime_candidate_window_handler_->set_cursor_bounds_call_count());
  caret_bounds_ = gfx::Rect(0, 2, 3, 4);
  input_method_ash_->OnCaretBoundsChanged(this);
  EXPECT_EQ(3,
            mock_ime_candidate_window_handler_->set_cursor_bounds_call_count());
  caret_bounds_ = gfx::Rect(0, 2, 3, 4);  // unchanged
  input_method_ash_->OnCaretBoundsChanged(this);
  // Current InputMethodAsh implementation performs the IPC
  // regardless of the bounds are changed or not.
  EXPECT_EQ(4,
            mock_ime_candidate_window_handler_->set_cursor_bounds_call_count());
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_NoAttribute) {
  const std::u16string kSampleAsciiText = u"Sample Text";
  const uint32_t kCursorPos = 2UL;

  CompositionText ash_composition_text;
  ash_composition_text.text = kSampleAsciiText;

  CompositionText composition_text = input_method_ash_->ExtractCompositionText(
      ash_composition_text, kCursorPos);
  EXPECT_EQ(kSampleAsciiText, composition_text.text);
  // If there is no selection, |selection| represents cursor position.
  EXPECT_EQ(kCursorPos, composition_text.selection.start());
  EXPECT_EQ(kCursorPos, composition_text.selection.end());
  // If there is no underline, |ime_text_spans| contains one underline and it is
  // whole text underline.
  ASSERT_EQ(1UL, composition_text.ime_text_spans.size());
  EXPECT_EQ(0UL, composition_text.ime_text_spans[0].start_offset);
  EXPECT_EQ(kSampleAsciiText.size(),
            composition_text.ime_text_spans[0].end_offset);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThin,
            composition_text.ime_text_spans[0].thickness);
}

TEST_F(InputMethodAshTest, SetCompositionTextFails) {
  InputMethodAsh ime(this);
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  EXPECT_EQ(ime.GetTextInputType(), TEXT_INPUT_TYPE_TEXT);
  // Intentionally have a range start that does not exist.
  EXPECT_FALSE(ime.SetCompositionRange(10000, 5, {}));

  ime.SetFocusedTextInputClient(nullptr);
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_SingleUnderline) {
  const uint32_t kCursorPos = 2UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  ImeTextSpan underline(ImeTextSpan::Type::kComposition, 1UL, 4UL,
                        ui::ImeTextSpan::Thickness::kThin,
                        ui::ImeTextSpan::UnderlineStyle::kSolid,
                        SK_ColorTRANSPARENT);
  composition_text.ime_text_spans.push_back(underline);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  // If there is no selection, |selection| represents cursor position.
  EXPECT_EQ(kCursorPos, composition_text2.selection.start());
  EXPECT_EQ(kCursorPos, composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_offset),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_offset),
            composition_text2.ime_text_spans[0].end_offset);
  // Single underline represents as thin line with text color.
  EXPECT_EQ(SK_ColorTRANSPARENT,
            composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThin,
            composition_text2.ime_text_spans[0].thickness);
  EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT),
            composition_text2.ime_text_spans[0].background_color);
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_DoubleUnderline) {
  const uint32_t kCursorPos = 2UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  ImeTextSpan underline(ImeTextSpan::Type::kComposition, 1UL, 4UL,
                        ui::ImeTextSpan::Thickness::kThick,
                        ui::ImeTextSpan::UnderlineStyle::kSolid,
                        SK_ColorTRANSPARENT);
  composition_text.ime_text_spans.push_back(underline);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  // If there is no selection, |selection| represents cursor position.
  EXPECT_EQ(kCursorPos, composition_text2.selection.start());
  EXPECT_EQ(kCursorPos, composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_offset),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_offset),
            composition_text2.ime_text_spans[0].end_offset);
  // Double underline represents as thick line with text color.
  EXPECT_EQ(SK_ColorTRANSPARENT,
            composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThick,
            composition_text2.ime_text_spans[0].thickness);
  EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT),
            composition_text2.ime_text_spans[0].background_color);
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_ErrorUnderline) {
  const uint32_t kCursorPos = 2UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  ImeTextSpan underline(ImeTextSpan::Type::kComposition, 1UL, 4UL,
                        ui::ImeTextSpan::Thickness::kThin,
                        ui::ImeTextSpan::UnderlineStyle::kSolid,
                        SK_ColorTRANSPARENT);
  underline.underline_color = SK_ColorRED;
  composition_text.ime_text_spans.push_back(underline);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  EXPECT_EQ(kCursorPos, composition_text2.selection.start());
  EXPECT_EQ(kCursorPos, composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_offset),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_offset),
            composition_text2.ime_text_spans[0].end_offset);
  // Error underline represents as red thin line.
  EXPECT_EQ(SK_ColorRED, composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThin,
            composition_text2.ime_text_spans[0].thickness);
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_Selection) {
  const uint32_t kCursorPos = 2UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  composition_text.selection.set_start(1UL);
  composition_text.selection.set_end(4UL);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  EXPECT_EQ(kCursorPos, composition_text2.selection.start());
  EXPECT_EQ(kCursorPos, composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.start()),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.end()),
            composition_text2.ime_text_spans[0].end_offset);
  EXPECT_EQ(SK_ColorTRANSPARENT,
            composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThick,
            composition_text2.ime_text_spans[0].thickness);
  EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT),
            composition_text2.ime_text_spans[0].background_color);
}

TEST_F(InputMethodAshTest,
       ExtractCompositionTextTest_SelectionStartWithCursor) {
  const uint32_t kCursorPos = 1UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  composition_text.selection.set_start(kCursorPos);
  composition_text.selection.set_end(4UL);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  // If the cursor position is same as selection bounds, selection start
  // position become opposit side of selection from cursor.
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.end()),
            composition_text2.selection.start());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, kCursorPos),
            composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.start()),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.end()),
            composition_text2.ime_text_spans[0].end_offset);
  EXPECT_EQ(SK_ColorTRANSPARENT,
            composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThick,
            composition_text2.ime_text_spans[0].thickness);
  EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT),
            composition_text2.ime_text_spans[0].background_color);
}

TEST_F(InputMethodAshTest, ExtractCompositionTextTest_SelectionEndWithCursor) {
  const uint32_t kCursorPos = 4UL;

  // Set up Ash composition text with one underline attribute.
  CompositionText composition_text;
  composition_text.text = kSampleText;
  composition_text.selection.set_start(1UL);
  composition_text.selection.set_end(kCursorPos);

  CompositionText composition_text2 =
      input_method_ash_->ExtractCompositionText(composition_text, kCursorPos);
  EXPECT_EQ(kSampleText, composition_text2.text);
  // If the cursor position is same as selection bounds, selection start
  // position become opposit side of selection from cursor.
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.start()),
            composition_text2.selection.start());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, kCursorPos),
            composition_text2.selection.end());
  ASSERT_EQ(1UL, composition_text2.ime_text_spans.size());
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.start()),
            composition_text2.ime_text_spans[0].start_offset);
  EXPECT_EQ(GetOffsetInUTF16(kSampleText, composition_text.selection.end()),
            composition_text2.ime_text_spans[0].end_offset);
  EXPECT_EQ(SK_ColorTRANSPARENT,
            composition_text2.ime_text_spans[0].underline_color);
  EXPECT_EQ(ui::ImeTextSpan::Thickness::kThick,
            composition_text2.ime_text_spans[0].thickness);
  EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT),
            composition_text2.ime_text_spans[0].background_color);
}

TEST_F(InputMethodAshTest, SurroundingText_NoSelectionTest) {
  // Click a text input form.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Set the TextInputClient behaviors.
  surrounding_text_ = u"abcdef";
  text_range_ = gfx::Range(0, 6);
  selection_range_ = gfx::Range(3, 3);

  // Set the verifier for SetSurroundingText mock call.
  SetSurroundingTextVerifier verifier(UTF16ToUTF8(surrounding_text_), 3, 3);

  input_method_ash_->OnCaretBoundsChanged(this);

  // Check the call count.
  EXPECT_EQ(1, mock_ime_engine_handler_->set_surrounding_text_call_count());
  EXPECT_EQ(surrounding_text_,
            mock_ime_engine_handler_->last_set_surrounding_text());
  EXPECT_EQ(3U, mock_ime_engine_handler_->last_set_surrounding_cursor_pos());
  EXPECT_EQ(3U, mock_ime_engine_handler_->last_set_surrounding_anchor_pos());
}

TEST_F(InputMethodAshTest, SurroundingText_SelectionTest) {
  // Click a text input form.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Set the TextInputClient behaviors.
  surrounding_text_ = u"abcdef";
  text_range_ = gfx::Range(0, 6);
  selection_range_ = gfx::Range(2, 5);

  // Set the verifier for SetSurroundingText mock call.
  SetSurroundingTextVerifier verifier(UTF16ToUTF8(surrounding_text_), 2, 5);

  input_method_ash_->OnCaretBoundsChanged(this);

  // Check the call count.
  EXPECT_EQ(1, mock_ime_engine_handler_->set_surrounding_text_call_count());
  EXPECT_EQ(surrounding_text_,
            mock_ime_engine_handler_->last_set_surrounding_text());
  EXPECT_EQ(2U, mock_ime_engine_handler_->last_set_surrounding_cursor_pos());
  EXPECT_EQ(5U, mock_ime_engine_handler_->last_set_surrounding_anchor_pos());
}

TEST_F(InputMethodAshTest, SurroundingText_PartialText) {
  // Click a text input form.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Set the TextInputClient behaviors.
  surrounding_text_ = u"abcdefghij";
  text_range_ = gfx::Range(5, 10);
  selection_range_ = gfx::Range(7, 9);

  input_method_ash_->OnCaretBoundsChanged(this);

  // Check the call count.
  EXPECT_EQ(1, mock_ime_engine_handler_->set_surrounding_text_call_count());
  // Set the verifier for SetSurroundingText mock call.
  // Here (2, 4) is selection range in expected surrounding text coordinates.
  EXPECT_EQ(u"fghij", mock_ime_engine_handler_->last_set_surrounding_text());
  EXPECT_EQ(2U, mock_ime_engine_handler_->last_set_surrounding_cursor_pos());
  EXPECT_EQ(4U, mock_ime_engine_handler_->last_set_surrounding_anchor_pos());
}

TEST_F(InputMethodAshTest, SurroundingText_BecomeEmptyText) {
  // Click a text input form.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Set the TextInputClient behaviors.
  // If the surrounding text becomes empty, text_range become (0, 0) and
  // selection range become invalid.
  surrounding_text_ = u"";
  text_range_ = gfx::Range(0, 0);
  selection_range_ = gfx::Range::InvalidRange();

  input_method_ash_->OnCaretBoundsChanged(this);

  // Check the call count.
  EXPECT_EQ(0, mock_ime_engine_handler_->set_surrounding_text_call_count());

  // Should not be called twice with same condition.
  input_method_ash_->OnCaretBoundsChanged(this);
  EXPECT_EQ(0, mock_ime_engine_handler_->set_surrounding_text_call_count());
}

TEST_F(InputMethodAshTest, SurroundingText_EventOrder) {
  ::testing::NiceMock<NiceMockIMEEngine> mock_engine;
  IMEBridge::Get()->SetCurrentEngineHandler(&mock_engine);

  {
    // Switches the text input client.
    ::testing::InSequence seq;
    EXPECT_CALL(mock_engine, Blur);
    EXPECT_CALL(mock_engine, Focus);
    EXPECT_CALL(mock_engine, SetSurroundingText);

    surrounding_text_ = u"a";
    text_range_ = gfx::Range(0, 1);
    selection_range_ = gfx::Range(0, 0);

    input_type_ = TEXT_INPUT_TYPE_TEXT;
    input_method_ash_->OnWillChangeFocusedClient(nullptr, this);
    input_method_ash_->OnDidChangeFocusedClient(nullptr, this);
  }

  {
    // Changes text input type.
    ::testing::InSequence seq;
    EXPECT_CALL(mock_engine, Blur);
    EXPECT_CALL(mock_engine, Focus);
    EXPECT_CALL(mock_engine, SetSurroundingText);

    surrounding_text_ = u"b";
    text_range_ = gfx::Range(0, 1);
    selection_range_ = gfx::Range(0, 0);

    input_type_ = TEXT_INPUT_TYPE_EMAIL;
    input_method_ash_->OnTextInputTypeChanged(this);
  }
  IMEBridge::Get()->SetCurrentEngineHandler(nullptr);
}

TEST_F(InputMethodAshTest, SetCompositionRange_InvalidRange) {
  // Focus on a text field.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Insert some text and place the cursor.
  surrounding_text_ = u"abc";
  text_range_ = gfx::Range(0, 3);
  selection_range_ = gfx::Range(1, 1);

  EXPECT_FALSE(input_method_ash_->SetCompositionRange(0, 4, {}));
  EXPECT_EQ(0U, composition_text_.text.length());
}

TEST_F(InputMethodAshTest,
       SetCompositionRangeWithSelectedTextAccountsForSelection) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  fake_text_input_client.SetTextAndSelection(u"01234", gfx::Range(1, 4));
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  // before/after are relative to the selection start/end, respectively.
  EXPECT_TRUE(ime.SetCompositionRange(/*before=*/1, /*after=*/1, {}));

  EXPECT_EQ(fake_text_input_client.composition_range(), gfx::Range(0, 5));
  EXPECT_THAT(fake_text_input_client.ime_text_spans(),
              testing::ElementsAre(
                  ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition,
                                  /*start_offset=*/0, /*end_offset=*/5)));
}

TEST_F(InputMethodAshTest, ConfirmComposition_NoComposition) {
  // Focus on a text field.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  input_method_ash_->ConfirmComposition(/* reset_engine */ true);

  EXPECT_TRUE(confirmed_text_.text.empty());
  EXPECT_TRUE(composition_text_.text.empty());
}

TEST_F(InputMethodAshTest, ConfirmComposition_SetComposition) {
  // Focus on a text field.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  CompositionText composition_text;
  composition_text.text = u"hello";
  SetCompositionText(composition_text);
  input_method_ash_->ConfirmComposition(/* reset_engine */ true);

  EXPECT_EQ(u"hello", confirmed_text_.text);
  EXPECT_TRUE(composition_text_.text.empty());
}

TEST_F(InputMethodAshTest, ConfirmComposition_SetCompositionRange) {
  // Focus on a text field.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Place some text.
  surrounding_text_ = u"abc";
  text_range_ = gfx::Range(0, 3);

  // "abc" is in composition. Put the two characters in composition.
  input_method_ash_->SetCompositionRange(0, 2, {});
  input_method_ash_->ConfirmComposition(/* reset_engine */ true);

  EXPECT_EQ(u"ab", confirmed_text_.text);
  EXPECT_TRUE(composition_text_.text.empty());
}

TEST_F(InputMethodAshTest, SetAutocorrectRange_SuccessfulSet) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  InsertText(u"a",
             TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  bool callback_called = false;
  bool callback_result = false;

  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1), base::BindOnce(
                            [](bool* called, bool* result, bool success) {
                              *called = true;
                              *result = success;
                            },
                            &callback_called, &callback_result));

  EXPECT_TRUE(callback_called);
  EXPECT_TRUE(callback_result);
  EXPECT_EQ(gfx::Range(0, 1), GetAutocorrectRange());
}

TEST_F(InputMethodAshTest, SetAutocorrectRange_FailedSet) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  bool callback_called = false;
  bool callback_result = false;

  // Set range on empty text must fail.
  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1), base::BindOnce(
                            [](bool* called, bool* result, bool success) {
                              *called = true;
                              *result = success;
                            },
                            &callback_called, &callback_result));

  EXPECT_TRUE(callback_called);
  EXPECT_FALSE(callback_result);
  EXPECT_TRUE(GetAutocorrectRange().is_empty());
}

class InputMethodAshKeyEventTest : public InputMethodAshTest {
 public:
  InputMethodAshKeyEventTest() = default;

  InputMethodAshKeyEventTest(const InputMethodAshKeyEventTest&) = delete;
  InputMethodAshKeyEventTest& operator=(const InputMethodAshKeyEventTest&) =
      delete;

  ~InputMethodAshKeyEventTest() override = default;
};

TEST_F(InputMethodAshKeyEventTest, KeyEventDelayResponseTest) {
  const int kFlags = ui::EF_SHIFT_DOWN;
  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, kFlags);

  // Do key event.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  input_method_ash_->DispatchKeyEvent(&event);

  // Check before state.
  const ui::KeyEvent* key_event =
      mock_ime_engine_handler_->last_processed_key_event();
  EXPECT_EQ(1, mock_ime_engine_handler_->process_key_event_call_count());
  EXPECT_EQ(ui::VKEY_A, key_event->key_code());
  EXPECT_EQ(kFlags, key_event->flags());
  EXPECT_EQ(0, input_method_ash_->process_key_event_post_ime_call_count());

  static_cast<TextInputTarget*>(input_method_ash_.get())
      ->CommitText(
          u"A",
          TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  EXPECT_EQ(0, inserted_char_);

  // Do callback.
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  // Check the results
  EXPECT_EQ(1, input_method_ash_->process_key_event_post_ime_call_count());
  const ui::KeyEvent stored_event =
      input_method_ash_->process_key_event_post_ime_args().event;
  EXPECT_EQ(ui::VKEY_A, stored_event.key_code());
  EXPECT_EQ(kFlags, stored_event.flags());
  EXPECT_EQ(input_method_ash_->process_key_event_post_ime_args().handled_state,
            ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(L'A', inserted_char_);
}

TEST_F(InputMethodAshKeyEventTest, MultiKeyEventDelayResponseTest) {
  ui::ScopedKeyboardLayout keyboard_layout(ui::KEYBOARD_LAYOUT_ENGLISH_US);

  // Preparation
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  const int kFlags = ui::EF_SHIFT_DOWN;
  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_B, kFlags);

  // Do key event.
  input_method_ash_->DispatchKeyEvent(&event);
  const ui::KeyEvent* key_event =
      mock_ime_engine_handler_->last_processed_key_event();
  EXPECT_EQ(ui::VKEY_B, key_event->key_code());
  EXPECT_EQ(kFlags, key_event->flags());

  KeyEventCallback first_callback =
      mock_ime_engine_handler_->last_passed_callback();

  // Do key event again.
  ui::KeyEvent event2(ui::ET_KEY_PRESSED, ui::VKEY_C, kFlags);

  input_method_ash_->DispatchKeyEvent(&event2);
  const ui::KeyEvent* key_event2 =
      mock_ime_engine_handler_->last_processed_key_event();
  EXPECT_EQ(ui::VKEY_C, key_event2->key_code());
  EXPECT_EQ(kFlags, key_event2->flags());

  // Check before state.
  EXPECT_EQ(2, mock_ime_engine_handler_->process_key_event_call_count());
  EXPECT_EQ(0, input_method_ash_->process_key_event_post_ime_call_count());

  CompositionText comp;
  comp.text = u"B";
  (static_cast<TextInputTarget*>(input_method_ash_.get()))
      ->UpdateCompositionText(comp, comp.text.length(), true);

  EXPECT_EQ(0, composition_text_.text[0]);

  // Do callback for first key event.
  std::move(first_callback).Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(comp.text, composition_text_.text);

  // Check the results for first key event.
  EXPECT_EQ(1, input_method_ash_->process_key_event_post_ime_call_count());
  ui::KeyEvent stored_event =
      input_method_ash_->process_key_event_post_ime_args().event;
  EXPECT_EQ(ui::VKEY_B, stored_event.key_code());
  EXPECT_EQ(kFlags, stored_event.flags());
  EXPECT_EQ(input_method_ash_->process_key_event_post_ime_args().handled_state,
            ui::ime::KeyEventHandledState::kHandledByIME);
  EXPECT_EQ(0, inserted_char_);

  // Do callback for second key event.
  mock_ime_engine_handler_->last_passed_callback().Run(
      ui::ime::KeyEventHandledState::kNotHandled);

  // Check the results for second key event.
  EXPECT_EQ(2, input_method_ash_->process_key_event_post_ime_call_count());
  stored_event = input_method_ash_->process_key_event_post_ime_args().event;
  EXPECT_EQ(ui::VKEY_C, stored_event.key_code());
  EXPECT_EQ(kFlags, stored_event.flags());
  EXPECT_EQ(input_method_ash_->process_key_event_post_ime_args().handled_state,
            ui::ime::KeyEventHandledState::kNotHandled);

  EXPECT_EQ(L'C', inserted_char_);
}

TEST_F(InputMethodAshKeyEventTest, StopPropagationTest) {
  // Preparation
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  // Do key event with event being stopped propagation.
  stop_propagation_post_ime_ = true;
  ui::KeyEvent eventA(ui::ET_KEY_PRESSED, ui::VKEY_A, EF_NONE);
  eventA.set_character(L'A');
  input_method_ash_->DispatchKeyEvent(&eventA);
  mock_ime_engine_handler_->last_passed_callback().Run(
      ui::ime::KeyEventHandledState::kNotHandled);

  const ui::KeyEvent* key_event =
      mock_ime_engine_handler_->last_processed_key_event();
  EXPECT_EQ(ui::VKEY_A, key_event->key_code());
  EXPECT_EQ(0, inserted_char_);

  // Do key event with event not being stopped propagation.
  stop_propagation_post_ime_ = false;
  input_method_ash_->DispatchKeyEvent(&eventA);
  mock_ime_engine_handler_->last_passed_callback().Run(
      ui::ime::KeyEventHandledState::kNotHandled);

  key_event = mock_ime_engine_handler_->last_processed_key_event();
  EXPECT_EQ(ui::VKEY_A, key_event->key_code());
  EXPECT_EQ(L'A', inserted_char_);
}

TEST_F(InputMethodAshKeyEventTest, DeadKeyPressTest) {
  // Preparation.
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);

  ui::KeyEvent eventA(ET_KEY_PRESSED,
                      VKEY_OEM_4,  // '['
                      DomCode::BRACKET_LEFT, 0,
                      DomKey::DeadKeyFromCombiningCharacter('^'),
                      EventTimeForNow());
  input_method_ash_->ProcessKeyEventPostIME(
      &eventA, ui::ime::KeyEventHandledState::kHandledByIME, true);

  const ui::KeyEvent& key_event = dispatched_key_event_;

  EXPECT_EQ(ET_KEY_PRESSED, key_event.type());
  EXPECT_EQ(VKEY_PROCESSKEY, key_event.key_code());
  EXPECT_EQ(eventA.code(), key_event.code());
  EXPECT_EQ(eventA.flags(), key_event.flags());
  EXPECT_EQ(DomKey::PROCESS, key_event.GetDomKey());
  EXPECT_EQ(eventA.time_stamp(), key_event.time_stamp());
}

TEST_F(InputMethodAshKeyEventTest,
       SingleCharAssistiveSuggesterKeyEventDispatchesProcessKey) {
  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, EF_NONE);
  input_type_ = TEXT_INPUT_TYPE_TEXT;

  input_method_ash_->OnTextInputTypeChanged(this);
  input_method_ash_->DispatchKeyEvent(&event);
  static_cast<TextInputTarget*>(input_method_ash_.get())
      ->CommitText(
          u"b",
          TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByAssistiveSuggester);

  const ui::KeyEvent& key_event = dispatched_key_event_;
  EXPECT_EQ(ET_KEY_PRESSED, key_event.type());
  EXPECT_EQ(VKEY_PROCESSKEY, key_event.key_code());
  EXPECT_EQ(event.code(), key_event.code());
  EXPECT_EQ(event.flags(), key_event.flags());
  EXPECT_EQ(DomKey::PROCESS, key_event.GetDomKey());
  EXPECT_EQ(event.time_stamp(), key_event.time_stamp());
}

TEST_F(InputMethodAshKeyEventTest, JP106KeyTest) {
  ui::KeyEvent eventConvert(ET_KEY_PRESSED, VKEY_CONVERT, EF_NONE);
  input_method_ash_->DispatchKeyEvent(&eventConvert);
  EXPECT_FALSE(input_method_manager_->state()->is_jp_kbd());
  EXPECT_TRUE(input_method_manager_->state()->is_jp_ime());

  ui::KeyEvent eventNonConvert(ET_KEY_PRESSED, VKEY_NONCONVERT, EF_NONE);
  input_method_ash_->DispatchKeyEvent(&eventNonConvert);
  EXPECT_TRUE(input_method_manager_->state()->is_jp_kbd());
  EXPECT_FALSE(input_method_manager_->state()->is_jp_ime());

  ui::KeyEvent eventDbeSbc(ET_KEY_PRESSED, VKEY_DBE_SBCSCHAR, EF_NONE);
  input_method_ash_->DispatchKeyEvent(&eventDbeSbc);
  EXPECT_FALSE(input_method_manager_->state()->is_jp_kbd());
  EXPECT_TRUE(input_method_manager_->state()->is_jp_ime());

  ui::KeyEvent eventDbeDbc(ET_KEY_PRESSED, VKEY_DBE_DBCSCHAR, EF_NONE);
  input_method_ash_->DispatchKeyEvent(&eventDbeDbc);
  EXPECT_TRUE(input_method_manager_->state()->is_jp_kbd());
  EXPECT_FALSE(input_method_manager_->state()->is_jp_ime());
}

TEST_F(InputMethodAshKeyEventTest, SetAutocorrectRangeRunsAfterKeyEvent) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  input_method_ash_->CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  input_method_ash_->DispatchKeyEvent(&event);

  bool callback_called = false;
  bool callback_result = false;

  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1), base::BindOnce(
                            [](bool* called, bool* result, bool success) {
                              *called = true;
                              *result = success;
                            },
                            &callback_called, &callback_result));
  EXPECT_FALSE(callback_called);

  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(gfx::Range(0, 1), GetAutocorrectRange());
  EXPECT_TRUE(callback_called);
  EXPECT_TRUE(callback_result);
}

TEST_F(InputMethodAshKeyEventTest, SetAutocorrectRangeRunsAfterCommitText) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  input_method_ash_->DispatchKeyEvent(&event);

  input_method_ash_->CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  bool callback_called = false;
  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1),
      base::BindOnce([](bool* called, bool result) { *called = true; },
                     (&callback_called)));
  EXPECT_FALSE(callback_called);

  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(L'a', inserted_char_);
  EXPECT_TRUE(callback_called);
  EXPECT_EQ(gfx::Range(0, 1), GetAutocorrectRange());
}

TEST_F(InputMethodAshKeyEventTest,
       SetAutocorrectRangeCallsCallbackOnFailureAfterKeyEvent) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  input_method_ash_->CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  // Disable autocorrect range to make it return false.
  set_autocorrect_enabled(false);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  input_method_ash_->DispatchKeyEvent(&event);

  bool callback_called = false;
  bool callback_result = false;

  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1), base::BindOnce(
                            [](bool* called, bool* result, bool success) {
                              *called = true;
                              *result = success;
                            },
                            &callback_called, &callback_result));
  EXPECT_FALSE(callback_called);

  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(gfx::Range(), GetAutocorrectRange());
  EXPECT_TRUE(callback_called);
  EXPECT_FALSE(callback_result);
}

TEST_F(
    InputMethodAshKeyEventTest,
    LatestSetAutocorrectRangeOverridesPreviousRequestsWhileHandlingKeyEvent) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  input_method_ash_->OnTextInputTypeChanged(this);
  input_method_ash_->CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  input_method_ash_->DispatchKeyEvent(&event);

  bool first_set_callback_called = false;
  bool first_set_callback_result = false;
  bool second_set_callback_called = false;
  bool second_set_callback_result = false;

  auto set_range_callback = [](bool* called, bool* result, bool success) {
    *called = true;
    *result = success;
  };

  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1),
      base::BindOnce(set_range_callback, &first_set_callback_called,
                     &first_set_callback_result));
  EXPECT_FALSE(first_set_callback_called);

  // Override first call.
  input_method_ash_->SetAutocorrectRange(
      gfx::Range(0, 1),
      base::BindOnce(set_range_callback, &second_set_callback_called,
                     &second_set_callback_result));
  EXPECT_FALSE(second_set_callback_called);
  EXPECT_TRUE(first_set_callback_called);
  EXPECT_FALSE(first_set_callback_result);

  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(gfx::Range(0, 1), GetAutocorrectRange());
  EXPECT_TRUE(second_set_callback_result);
}

TEST_F(InputMethodAshKeyEventTest,
       MultipleCommitTextsWhileHandlingKeyEventCoalescesIntoOne) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  ime.DispatchKeyEvent(&event);
  ime.CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ime.CommitText(
      u"b", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ime.CommitText(
      u"cde", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(fake_text_input_client.text(), u"abcde");
  EXPECT_EQ(fake_text_input_client.selection(), gfx::Range(5, 5));
}

TEST_F(InputMethodAshKeyEventTest,
       MultipleCommitTextsWhileHandlingKeyEventCoalescesByCaretBehavior) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  ime.DispatchKeyEvent(&event);
  ime.CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorBeforeText);
  ime.CommitText(
      u"b", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ime.CommitText(
      u"c", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ime.CommitText(
      u"d", TextInputClient::InsertTextCursorBehavior::kMoveCursorBeforeText);
  ime.CommitText(
      u"e", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(fake_text_input_client.text(), u"bceda");
  EXPECT_EQ(fake_text_input_client.selection(), gfx::Range(3, 3));
}

TEST_F(InputMethodAshKeyEventTest, CommitTextEmptyRunsAfterKeyEvent) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);
  ui::CompositionText composition;
  composition.text = u"hello";
  ime.UpdateCompositionText(composition, /*cursor_pos=*/5, /*visible=*/true);

  ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  ime.DispatchKeyEvent(&event);
  ime.CommitText(
      u"", TextInputClient::InsertTextCursorBehavior::kMoveCursorBeforeText);
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(fake_text_input_client.text(), u"");
  EXPECT_FALSE(fake_text_input_client.HasCompositionText());
  EXPECT_EQ(fake_text_input_client.selection(), gfx::Range(0, 0));
}

TEST_F(InputMethodAshTest, CommitTextReplacesSelection) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  fake_text_input_client.SetTextAndSelection(u"hello", gfx::Range(0, 5));
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ime.CommitText(
      u"", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  EXPECT_EQ(fake_text_input_client.text(), u"");
}

TEST_F(InputMethodAshTest, ResetsEngineWithComposition) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  fake_text_input_client.SetTextAndSelection(u"hello ", gfx::Range(6, 6));
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ui::CompositionText composition;
  composition.text = u"world";
  ime.UpdateCompositionText(composition, /*cursor_pos=*/5, /*visible=*/true);
  ime.CancelComposition(&fake_text_input_client);

  EXPECT_EQ(mock_ime_engine_handler_->reset_call_count(), 1);
}

TEST_F(InputMethodAshTest, DoesNotResetEngineWithNoComposition) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ime.CommitText(
      u"hello",
      TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ime.CancelComposition(&fake_text_input_client);

  EXPECT_EQ(mock_ime_engine_handler_->reset_call_count(), 0);
}

TEST_F(InputMethodAshTest, CommitTextThenKeyEventOnlyInsertsOnce) {
  FakeTextInputClient fake_text_input_client(TEXT_INPUT_TYPE_TEXT);
  InputMethodAsh ime(this);
  ime.SetFocusedTextInputClient(&fake_text_input_client);

  ime.CommitText(
      u"a", TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
  ui::KeyEvent key(ET_KEY_PRESSED, VKEY_A, EF_NONE);
  ime.DispatchKeyEvent(&key);
  std::move(mock_ime_engine_handler_->last_passed_callback())
      .Run(ui::ime::KeyEventHandledState::kHandledByIME);

  EXPECT_EQ(fake_text_input_client.text(), u"a");
}

TEST_F(InputMethodAshTest, AddsAndClearsGrammarFragments) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  std::vector<GrammarFragment> fragments;
  fragments.emplace_back(gfx::Range(0, 1), "fake");
  fragments.emplace_back(gfx::Range(3, 10), "test");
  input_method_ash_->AddGrammarFragments(fragments);
  EXPECT_EQ(get_grammar_fragments(), fragments);
  input_method_ash_->ClearGrammarFragments(gfx::Range(0, 10));
  EXPECT_EQ(get_grammar_fragments().size(), 0u);
}

TEST_F(InputMethodAshTest, GetsGrammarFragments) {
  input_type_ = TEXT_INPUT_TYPE_TEXT;
  GrammarFragment fragment(gfx::Range(0, 5), "fake");
  input_method_ash_->AddGrammarFragments({fragment});

  input_method_ash_->SetEditableSelectionRange(gfx::Range(3, 3));
  EXPECT_EQ(input_method_ash_->GetGrammarFragmentAtCursor(), fragment);
  input_method_ash_->SetEditableSelectionRange(gfx::Range(2, 4));
  EXPECT_EQ(input_method_ash_->GetGrammarFragmentAtCursor(), fragment);

  input_method_ash_->SetEditableSelectionRange(gfx::Range(7, 7));
  EXPECT_EQ(input_method_ash_->GetGrammarFragmentAtCursor(), absl::nullopt);
  input_method_ash_->SetEditableSelectionRange(gfx::Range(4, 7));
  EXPECT_EQ(input_method_ash_->GetGrammarFragmentAtCursor(), absl::nullopt);
}

}  // namespace ui


text:
package com.softwaremill.common.test.web.soap;

import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.model.support.PropertiesMap;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestRunner;
import com.eviware.soapui.model.testsuite.TestSuite;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Base class used to create web service test base on soapUI Test Suites
 */
public class AbstractWebServiceTest {

    private ArtifactPublisherListener listener;

    public AbstractWebServiceTest() {
        listener = new ArtifactPublisherListener();
    }

    /**
     * Runs all the tests defined in the given soapUI Test Suite,
     *
     * @param soapUITestSuite specify it like for example: System.getProperty("resources.dir") + "/src/test/resources/SoapUITestSuite.xml"
     * @throws Exception any exception
     */
    protected void run(String soapUITestSuite) throws Exception {
        run(new WsdlProject(soapUITestSuite));
    }

    /**
     * Runs SoapUI TestCase project
     *
     * @param project new WsdlProject("/path/to/soapui/testcase.xml")
     */
    protected void run(WsdlProject project) {
        for (TestSuite testSuite : project.getTestSuiteList()) {
            run(testSuite);
        }
    }

    /**
     * Runs all test cases in given SoapUI TestSuite
     *
     * @param testSuite SoapUI TestSuite
     */
    protected void run(TestSuite testSuite) {
        run(testSuite.getTestCaseList());
    }

    /**
     * Runs specified list of TestCases one by one
     *
     * @param testCases list of TestCases
     */
    protected void run(List<TestCase> testCases) {
        for (TestCase testCase : testCases) {
            run(testCase);
        }
    }

    /**
     * Runs one soapUI TestCase
     *
     * @param testCase single TestCase
     */
    protected void run(TestCase testCase) {
        testCase.addTestRunListener(listener);
        TestRunner runner = testCase.run(new PropertiesMap(), false);
        assertThat(runner.getStatus())
                .describedAs("TestCase [" + testCase.getLabel() + "] failed because of [" + runner.getReason() + "]")
                .isEqualTo(TestRunner.Status.FINISHED);
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Write a program to calculate n! for each n in the range [1..100].
using System;
using System.Text;

class Factorial
{
    static string NumberMultiplyer(string number, int digit)
    {
        string result = null;
        int carry = 0;
        for (int i = number.Length - 1; i >= 0; i--)
        {
            int currDigit = int.Parse(number[i].ToString());
            int currProduct = currDigit * digit;
            if (currProduct + carry < 10)
            {
                result = (currProduct + carry) + result;
                carry = 0;
            }
            else
            {
                result = ((currProduct + carry) % 10) + result;
                carry = (currProduct + carry) / 10;
            }
        }

        if (carry != 0)
        {
            result = carry + result;
        }

        return result;
    }

    public static void Main()
    {

        string answer = "1";

        for (int i = 2; i <= 100; i++)
        {
            answer = NumberMultiplyer(answer, i);
        }
        Console.WriteLine(answer);
    }
}


text:
package com.example.applock.bean;

import org.litepal.crud.DataSupport;

/**
 * Created by 我的 on 2017/8/11.
 */

public class FaviterInfo extends DataSupport {
    private String packageName;

    public FaviterInfo() {
    }

    public FaviterInfo( String packageName ){
        this.packageName = packageName;
    }

    public String getPackageName(){
        return packageName;
    }

    public void setPackageName( String packageName ){
        this.packageName = packageName;
    }
}


text:
#ifndef _POWERPC_POWERMAC_POWERMAC_THERMAL_H
#define _POWERPC_POWERMAC_POWERMAC_THERMAL_H

#define ZERO_C_TO_K 2732

struct pmac_fan {
	int min_rpm, max_rpm, default_rpm;

	char name[32];
	int zone;

	int (*read)(struct pmac_fan *);
	int (*set)(struct pmac_fan *, int value);
};

struct pmac_therm {
	int target_temp, max_temp;	/* Tenths of a degree K */

	char name[32];
	int zone;

	int (*read)(struct pmac_therm *);
};

void pmac_thermal_fan_register(struct pmac_fan *);
void pmac_thermal_sensor_register(struct pmac_therm *);

#endif


text:
package errors

import "fmt"

// Source contain references to the source of the error
type Source struct {
	Pointer   string `json:"pointer,omitempty"`
	Parameter string `json:"parameter,omitempty"`
}

// Link should lead to further details about this error
type Link struct {
	About string `json:"about,omitempty"`
}

// Error provides additional information about problems encountered while
// performing an operation.
type Error struct {
	Code   int                    `json:"code,string,omitempty"`
	Debug  map[string]interface{} `json:"debug,omitempty"`
	Detail string                 `json:"detail"`
	ID     string                 `json:"id,omitempty"`
	Links  *Link                  `json:"links,omitempty"`
	Meta   map[string]interface{} `json:"meta,omitempty"`
	Source *Source                `json:"source,omitempty"`
	Status int                    `json:"status,string"`
	Title  string                 `json:"title,omitempty"`
}

func (e *Error) Error() string {
	return fmt.Sprintf("%d: %s", e.Status, e.Detail)
}

func (e *Error) SetAboutLink(link string) {
	l := &Link{link}
	e.Links = l
}

func (e *Error) AddSourceNode() *Source {
	s := &Source{}
	e.Source = s

	return s
}

func (e *Error) SetPointer(pointer string) *Error {
	if e.Source == nil {
		e.AddSourceNode()
	}

	e.Source.Pointer = pointer

	return e
}

func (e *Error) SetParameter(parameter string) *Error {
	if e.Source == nil {
		e.AddSourceNode()
	}

	e.Source.Parameter = parameter

	return e
}

func NewError(status int, detail string) *Error {
	return &Error{
		Status: status,
		Detail: detail,
	}
}

type Bag struct {
	Errors []*Error `json:"errors"`
	Status int      `json:"status,string,omitempty"`
}

func (b *Bag) Add(err *Error) *Error {
	b.Errors = append(b.Errors, err)

	if len(b.Errors) == 1 {
		b.Status = err.Status

		return err
	}

	if b.Status != err.Status {
		if statusClass := GetErrorClass(b.Status); statusClass == GetErrorClass(err.Status) {
			b.Status = statusClass
		} else {
			b.Status = 400
		}
	}

	return err
}

func (b *Bag) AddError(status int, detail string) *Error {
	return b.Add(NewError(status, detail))
}

// NewBag returns a new Bag
func NewBag() *Bag {
	return &Bag{}
}

// NewBagWithError is a shorthand to `errors.NewBag().Add(status, detail)`
func NewBagWithError(status int, detail string) *Bag {
	bag := &Bag{}
	bag.AddError(status, detail)

	return bag
}

// GetErrorClass returns 400 or 500 depending of the error code passed.
// If the error code is less than 400 or greater or equal to 600 it returns 0.
func GetErrorClass(err int) int {
	if err < 400 || err >= 600 {
		return 0
	}

	if err >= 400 && err < 500 {
		return 400
	}

	return 500
}


text:
N = 5; %filter order
[B,A] = butter(N,1,'s'); %prototype with cutoff=1 rad/s
[Bnew,Anew]=lp2lp(B,A,100); %convert to cutoff=100 rad/s
freqs(Bnew,Anew) %plot mag (linear scale) and phase


text:
import Component from 'ember-component';
import Ember from 'ember';
import {equal} from 'ember-computed';
import observer from 'ember-metal/observer';
import run from 'ember-runloop';

// ember-cli-shims doesn't export Ember.Testing
const {testing} = Ember;

export default Component.extend({
    tagName: 'button',
    buttonText: '',
    submitting: false,
    showSpinner: false,
    showSpinnerTimeout: null,
    autoWidth: true,

    // Disable Button when isLoading equals true
    attributeBindings: ['disabled', 'type', 'tabindex'],

    // Must be set on the controller
    disabled: equal('showSpinner', true),

    click() {
        if (this.get('action')) {
            this.sendAction('action');
            return false;
        }
        return true;
    },

    toggleSpinner: observer('submitting', function () {
        let submitting = this.get('submitting');
        let timeout = this.get('showSpinnerTimeout');
        let delay = testing ? 10 : 1000;

        if (submitting) {
            this.set('showSpinner', true);
            this.set('showSpinnerTimeout', run.later(this, function () {
                if (!this.get('submitting')) {
                    this.set('showSpinner', false);
                }
                this.set('showSpinnerTimeout', null);
            }, delay));
        } else if (!submitting && timeout === null) {
            this.set('showSpinner', false);
        }
    }),

    setSize: observer('showSpinner', function () {
        if (this.get('showSpinner') && this.get('autoWidth')) {
            this.$().width(this.$().width());
            this.$().height(this.$().height());
        } else {
            this.$().width('');
            this.$().height('');
        }
    }),

    willDestroy() {
        this._super(...arguments);
        run.cancel(this.get('showSpinnerTimeout'));
    }
});


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerJoinEvent.cs">
//   Copyright © 2012 All Rights Reserved
// </copyright>
// <summary>
//   In-game event signalling when a player has joined.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Starcraft2.ReplayParser
{
    using System.Collections.Generic;

    using Streams;

    /// <summary>
    /// In-game event signalling when a player has joined.
    /// </summary>
    public class PlayerJoinEvent : GameEventBase
    {
        public PlayerJoinEvent(BitReader bitReader, Replay replay, int playerIndex)
        {
            this.EventType = GameEventType.Inactive;

            // This should probably be a series of {shl; or} on .Read(1)
            // to make it version-independent
            if (replay.ReplayBuild < 22612)
            {
                this.JoinFlags = (int)bitReader.Read(4);
            }
            else
            {
                this.JoinFlags = (int)bitReader.Read(12); // unknown
            }

            // Initialize player if not exists (true for observers)
            Player player = replay.GetPlayerById(playerIndex);
            if (player == null)
            {
                var p = new Player { PlayerType = PlayerType.Spectator };
                replay.ClientList[playerIndex] = player = p;
            }

            // Initialize wireframe
            player.Wireframe = new List<Unit>();
            player.WireframeSubgroup = 0;

            // Initialize control groups
            player.Hotkeys = new List<Unit>[10];
        }

        public int JoinFlags { get; private set; }
    }
}


text: from .interfaces import ISparcYamlDocuments


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28772_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans25.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Company: XTO ENERGY Lease/Well: RANGER/21X-18A
Rig Name: H&P 456 5U RVEY State/County: NORTH DAKOTA/MCKENZIE '
Latitude: 47.905, Longitude: -103.406 Directions are relative '(0 True North
VS-Azi: 0.000 Degrees

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Depth Reference : RKB 25 FEET
DRILLOG Ms GYRO SURVEY CALCULATIONS Fllename: msgyro_run02—01-de_01.ut Minimum Curvature Method Report Date/Time: 10/9/2014/ 09:23
VES Survey International

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Measured Depth

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
FT Deg Deg Fr Fr Deg Deg/1 00 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 *"* 92.250 0.259 116.813 92.250 -0.094 0.186 -0.094 0.209 116.813 0.281 184.500 0.480 64.620 184.498 -0.023 0.722 -0.023 0.722 91.804 0.413 276.750 0.572 34.902 276.744 0.521 1.335 0.521 1.433 68.690 0.308 369.000 0.636 358.198 368.989 1.410 1.582 1.410 2.119 48.296 0.417

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">461.250 553.500 645.750 738.000 830.250

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1 383.750 1476.000 1 568.250 1660.500 1752.750
1845.000

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.674 -6.027
Page 1 of 2 VES Survey Date: 09/26/2014

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">VCD aurvey Imernauunal Dickinson, ND 701-483-0674
Surveyor: Andrew Meadville Hanger 21 X-18A/ API 33-053-06056

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Incl Angle

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.558 0.305 0.270 0.341 0.252

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">922.500 1014.750 1107.000 1199.250 1291.500

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.846 0.789 0.477 0.152 0.274

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Drift Direction

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">353.230 340.011 264.623 204.376 115.610

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.478 0.643 0.771 0.824 1 .1 15

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">275.082 267.357 308.399 329.026 345.261
327.312

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.423

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">TVD

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">461 .234 553.482 645.731 737.980 330.229

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">145.354 168.536 239.290 273.030 293.368

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1383.682 1475.923 1568.168 1660.416 1752.666

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">+Nl-S

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.367 3.044 3.254 2.984 2.647

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">922.477 1014.723 1106.967 1199.209 1291.446

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1.272 1.303 1.512 1.855 2.173

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1 844.91 4

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">+E/-W

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1.513 1.376 1 .075 0.746 0.815

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.243 1.419 0.594 0.381 0.843

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">-3.056 -4.369 -5.304 -5.668 -5.787

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Vertical Section

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.367 3.044 3.254 2.934 2.647

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1.216 1.538 1.107 -0.082 -1.557

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1.272 1.303 1.512 1.855 2.173

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Closure Distance

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.809 3.340 3.428 3.076 2.769

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.243 1 .41 9 0.594 0.381 0.848

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3.310 4.559 5.516 5.964 6.182

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.674

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Closure Direction

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">32.588 24.327 18.287 14.029 17.116

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.551 2.092 1.257 0.390 1 .773

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">292.593 286.604 285.909 288.1 22 290.584

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6.594

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dogleg Severlty

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.101 0.292 0.383 0.339 0.454

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">28.477 47.31 6 61 .784 347.904 298.577

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.451 0.134 0.576 0.368 0.147

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">293.923

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.312 0.301 0.895 0.590 0.414

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.198


text:
/** @file
*
* @defgroup nrf_dev_radio_rx_example_main main.c
* @{
* @ingroup nrf_dev_radio_rx_example
* @brief Radio Receiver example Application main file.
*
* This file contains the source code for a sample application using the NRF_RADIO peripheral.
*
*/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include "radio_config.h"
#include "nrf_gpio.h"
#include "boards.h"
#include "bsp.h"
#include "app_timer.h"
#include "nordic_common.h"
#include "nrf_error.h"

#define APP_TIMER_PRESCALER      0                     /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE  2                     /**< Size of timer operation queues. */

#define UART_TX_BUF_SIZE 256                           /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 1                             /**< UART RX buffer size. */

static uint32_t                   packet;              /**< Packet to transmit. */

void uart_error_handle(app_uart_evt_t * p_event)
{
   // No implementation needed.
}

/**@brief Function for initialization oscillators.
 */
void clock_initialization()
{
    /* Start 16 MHz crystal oscillator */
    NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
    NRF_CLOCK->TASKS_HFCLKSTART    = 1;

    /* Wait for the external oscillator to start up */
    while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0)
    {
        // Do nothing.
    }

    /* Start low frequency crystal oscillator for app_timer(used by bsp)*/
    NRF_CLOCK->LFCLKSRC            = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
    NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
    NRF_CLOCK->TASKS_LFCLKSTART    = 1;

    while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0)
    {
        // Do nothing.
    }
}

/**@brief Function for reading packet.
 */
uint32_t read_packet()
{
    uint32_t result = 0;

    NRF_RADIO->EVENTS_READY = 0U;
    // Enable radio and wait for ready
    NRF_RADIO->TASKS_RXEN = 1U;

    while (NRF_RADIO->EVENTS_READY == 0U)
    {
        // wait
    }
    NRF_RADIO->EVENTS_END = 0U;
    // Start listening and wait for address received event
    NRF_RADIO->TASKS_START = 1U;

    // Wait for end of packet or buttons state changed
    while (NRF_RADIO->EVENTS_END == 0U)
    {
        // wait
    }

    if (NRF_RADIO->CRCSTATUS == 1U)
    {
        result = packet;
    }
    NRF_RADIO->EVENTS_DISABLED = 0U;
    // Disable radio
    NRF_RADIO->TASKS_DISABLE = 1U;

    while (NRF_RADIO->EVENTS_DISABLED == 0U)
    {
        // wait
    }
    return result;
}

/**
 * @brief Function for application main entry.
 * @return 0. int return type required by ANSI/ISO standard.
 */
int main(void)
{
    uint32_t err_code = NRF_SUCCESS;

    clock_initialization();
    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, NULL);

    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_ENABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud38400
    };
    APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_error_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);
    APP_ERROR_CHECK(err_code);
    err_code = bsp_init(BSP_INIT_LED, APP_TIMER_TICKS(100, APP_TIMER_PRESCALER), NULL);
    APP_ERROR_CHECK(err_code);

    // Set radio configuration parameters
    radio_configure();
    NRF_RADIO->PACKETPTR = (uint32_t)&packet;

    err_code = bsp_indication_text_set(BSP_INDICATE_USER_STATE_OFF, "Wait for first packet\n\r");
    APP_ERROR_CHECK(err_code);

    while (true)
    {
        uint32_t received = read_packet();

        err_code = bsp_indication_text_set(BSP_INDICATE_RCV_OK, "Packet was received\n\r");
        APP_ERROR_CHECK(err_code);

        printf("The contents of the package is %u\n\r", (unsigned int)received);
    }
}

/**
 *@}
 **/


text:
START_ATF_NAMESPACE
    typedef IDirect3DDevice8 *LPDIRECT3DDEVICE8;
END_ATF_NAMESPACE


text:
struct default_init_tag;

class poi::ss::formula::EvaluationTracker final
    : public ::java::lang::Object
{

public:
    typedef ::java::lang::Object super;

private:
    ::java::util::List* _evaluationFrames {  };
    ::java::util::Set* _currentlyEvaluatingCells {  };
    EvaluationCache* _cache {  };
protected:
    void ctor(EvaluationCache* cache);

public:
    bool startEvaluate(FormulaCellCacheEntry* cce);
    void updateCacheResult(::poi::ss::formula::eval::ValueEval* result);
    void endEvaluate(CellCacheEntry* cce);
    void acceptFormulaDependency(CellCacheEntry* cce);
    void acceptPlainValueDependency(int32_t bookIndex, int32_t sheetIndex, int32_t rowIndex, int32_t columnIndex, ::poi::ss::formula::eval::ValueEval* value);

    // Generated
    EvaluationTracker(EvaluationCache* cache);
protected:
    EvaluationTracker(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
package com.pivotal.gemfirexd.internal.engine.jayway.jsonpath.spi.json;

public enum Mode {

    SLACK(-1),
    STRICT(1);

    private final int mode;

    Mode(int mode) {
        this.mode = mode;
    }

    public int intValue() {
        return mode;
    }

    public Mode parse(int mode) {
        if (mode == -1) {
            return SLACK;
        } else if (mode == 1) {
            return STRICT;
        } else {
            throw new IllegalArgumentException("Mode " + mode + " not supported");
        }
    }

}


text:
SwiftModelManager
=================

This a custom singleton which initialize and manage a core data model and save it on iCloud.
It also has some methods for adding, removing and fetching entities in the data base.
For using it in your project you just have to add it and replace the string "yourDataModelName" everywhere it appears.


text:
/*global jQuery*/

var THEME_VERSION = '1.2.3';

jQuery(function ($) {
    "use strict";
    var position;

    $('.gc-full-width').click(function () {

        $(this).find('i.fa:first').toggleClass('fa-expand');
        $(this).find('i.fa:first').toggleClass('fa-compress');

        if ($(this).closest('.container').hasClass('container-full')) {
            $(this).closest('.container').removeClass('container-full');
            var scroll_top = $(this).closest('.container').offset().top - 10;
            $('html,body').animate({scrollTop: scroll_top}, 750);

            return true;
        }

        position = $(this).closest('.container').offset();

        $(this).closest('.container')
            .css('left', position.left + 'px')
            .css('top', position.top + 'px')
            .addClass('container-before-resize');

        $('html,body').animate({scrollTop: '0'}, 750);
        $(this).closest('.container').animate({
            width: '100%',
            top: '0',
            opacity: '1',
            left: '0',
            marginLeft: '0',
            paddingTop: '10px',
            background: '#FFF'
        }, 1000)
            .promise().done(function () {
                $(this).removeClass('container-before-resize');
                $(this).addClass('container-full');
                $(this).removeAttr('style');
            });
    });

    $('.minimize-maximize').click(function () {
        $(this).find('i').toggleClass('fa-caret-down');
        $(this).find('i').toggleClass('fa-caret-up');

        $(this).closest('.container').find('.table-container:first').slideToggle('slow');
    });

    $('.gc-full-width').hover(
        function () {
            $(this).find('i.fa:first').addClass('fa-lg');
        },
        function () {
            $(this).find('i.fa:first').removeClass('fa-lg');
        }
    );
});


text:
from collections import namedtuple
from map import Map, Point
from intersect import do_intersect
from graphics import save_svg
from math import sqrt
from random import random

Vector = namedtuple("Vector", ["x", "y"])

class Track():
    """Represents a track a car could take across the map."""

    def __init__(self, map):
        """
        Creates a track.

        map: the map on which the track should be
        """
        self.map = map
        self.velocity_vector = Vector(0, 0)
        self.acceleration_vectors = [Vector(0,0)]
        self.positions = [map.start]
        self.collision = False

    def __repr__(self):
        return str(self.acceleration_vectors)

    def limit_vector(self, vector):
        """Limits the vector if longer than max_acceleration."""
        length = sqrt(vector.x * vector.x + vector.y * vector.y)
        if length > self.map.max_acceleration:
            vector_x = int(vector.x * 1/length *
                           self.map.max_acceleration)
            vector_y = int(vector.y * 1/length *
                           self.map.max_acceleration)
            return Vector(vector_x, vector_y)
        else:
            return vector

    def brake_vector(self):
        """Calulates a break vector."""
        return Vector(-self.velocity_vector.x, -self.velocity_vector.y)

    def distance(self):
        """
        Calcualtes the euclidean distance
        from the last position to the target.
        """
        dist_x = self.positions[-1].x - self.map.target.x
        dist_y = self.positions[-1].y - self.map.target.y
        return sqrt(dist_x * dist_x + dist_y * dist_y)

    def accelerate(self, vector, check=True, random_braking=True, generating=False, _braking=False):
        """
        Accelerate into the given direction.

        vector: acceleration vector
        check: if set the function checks if further acceleration is
            possible/necessary
        random_braking: if set the function randomly breaks the nearer
            the track gets to the target
        generating: if set the function will reset the track if it collides
        _braking: internal parameter
        """
        vector = self.limit_vector(vector)
        self.acceleration_vectors.append(vector)
        self.velocity_vector = Vector(self.velocity_vector.x + vector.x,
                                      self.velocity_vector.y + vector.y)
        new_position = Point(self.positions[-1].x + self.velocity_vector.x,
                             self.positions[-1].y + self.velocity_vector.y)
        self.positions.append(new_position)
        if check:
            if _braking:
                if self.velocity_vector == Vector(0, 0):
                    return False
                else:
                    self.accelerate(self.brake_vector(), _braking=True)
            # brake if near enough to the target
            elif (self.distance() < self.map.max_acceleration * 2.5) and random_braking:
                if ((-1/(self.map.max_acceleration * 2.5)) * self.distance() + 1) > random():
                    self.accelerate(self.brake_vector(), _braking=True)
                else:
                    return True
            elif self.check_collisions(len(self.positions) - 1):
                if generating:
                    self.__init__(self.map)
                    return True
                else:
                    self.collision = True
                    return False
            else:
                return True

    def check_collisions(self, from_position_index=1, verbose=False):
        """
        Check if track collides with map.

        from_position_index: check only position from this index
        verbose: verbosity flag
        """
        for i in range(from_position_index, len(self.positions)):
            for wall in self.map.map:
                if do_intersect((self.positions[i-1], self.positions[i]),
                                 wall):
                    if verbose:
                        print("Collision detected.")
                    return True

        if verbose:
            print("No collision detected.")
        return False

    def approximate_positions(self, positions):
        """
        Tries to accelerate in such a way to reach the given positions.
        """
        for position in positions:
            # calculate the acceleration vector to the next position
            accelerate_vector_x = (-self.positions[-1].x
                - self.velocity_vector.x + position.x)
            accelerate_vector_y = (-self.positions[-1].y
                - self.velocity_vector.y + position.y)
            if not self.accelerate(
                Vector(accelerate_vector_x, accelerate_vector_y)):
                break


text:
package org.squarewordsolver.impl

import org.squarewordsolver.{CharToRemove, PuzzleArea, RemoveAdvice}

/**
 * Given next situation on puzzle field:
 * AB....AB
 * .      .
 * .      .
 * AB....ABCD
 *
 * then ABCD can be replaced with CD: AB cannot be there because A and B should be in upper right and lower left corners
 */
class CollisionByQuadrateFriendlyPairs(
                                        private val puzzleArea: PuzzleArea,
                                        private val friendlyPairs: Set[((Char, Char), (Int, Int), (Int, Int))]
                                        ) extends RemoveAdvice {
  private val linesCache = puzzleArea.linesCache

  override def getAdvice: List[CharToRemove] = {
    val uniqueFriendlyPairs = friendlyPairs.foldLeft(Set[(Char, Char)]())((aggregation, currFriendlyPair) => {
      val currPairOfChars = currFriendlyPair._1
      if (aggregation contains currPairOfChars.swap)
        aggregation
      else
        aggregation + currPairOfChars
    })

    val allCoordinates = for {pairOfChars <- uniqueFriendlyPairs
                              withSwapped = Set(pairOfChars, pairOfChars.swap)
                              allCoordinatesForThisPair = friendlyPairs.filter(withSwapped contains _._1)
                                .foldLeft(Set[(Int, Int)]())((aggregation, currFriendlyPair) =>
                                aggregation + currFriendlyPair._2 + currFriendlyPair._3)}
    yield (pairOfChars, allCoordinatesForThisPair)

    val interestingCoordinates = allCoordinates.filter(_._2.size > 2)

    val correctQuadrateCandidates = for {
      currPair <- interestingCoordinates
      pairOfChars = currPair._1
      setOfCoordinates = currPair._2
      basicsCoordinate <- setOfCoordinates
      first = setOfCoordinates.filter(el => el._1 == basicsCoordinate._1 && el._2 != basicsCoordinate._2)
      second = setOfCoordinates.filter(el => el._2 == basicsCoordinate._2 && el._1 != basicsCoordinate._1)
      if (first.size == 1 && second.size == 1)
    }
    yield (pairOfChars, Set(basicsCoordinate, first.head, second.head))

    val charsToRemove = for {
      correctCandidate <- correctQuadrateCandidates
      currSetOfPairs = {
        Set(correctCandidate._1._1, correctCandidate._1._2)
      }

      toList = correctCandidate._2.toList
      fourthCornerCoords = (toList(2)._1, toList(1)._2)
      fourthCornerCell = linesCache.at(fourthCornerCoords._1, fourthCornerCoords._2)
      if (fourthCornerCell.isNotSet)
      charsToRemove = currSetOfPairs & fourthCornerCell.possibleVals
      if charsToRemove.nonEmpty
    }
    yield CharToRemove(charsToRemove.head, fourthCornerCoords)

    println(charsToRemove)

    charsToRemove.toList
  }
}


text:
package me.suwash.tools.comparefiles.sv.domain;

import java.util.Map;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

/**
 * 行データの基底クラス。
 */
@Getter
@Setter
@EqualsAndHashCode
public class BaseRow {

    /** 行番号。 */
    protected long rowNum;

    /** 比較キー項目。 */
    protected Map<String, Object> keyMap;

    /** キー以外の項目。 */
    protected Map<String, Object> valueMap;

    /** 元ファイルの無変換行データ。 */
    protected String rawLine;

    /*
     * (非 Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return rawLine;
        // return JsonUtils.writeString(this);
    }
}