text:
using testing::_;
using testing::AtLeast;
using testing::Return;

namespace {

std::string UpdateGURLScheme(GURL url, const char scheme[]) {
  GURL::Replacements replacements;
  replacements.SetSchemeStr(scheme);
  return url.ReplaceComponents(replacements).spec();
}

class FakeContentTranslateDriver
    : public translate::mojom::ContentTranslateDriver {
 public:
  FakeContentTranslateDriver() = default;
  ~FakeContentTranslateDriver() override = default;

  void BindHandle(mojo::ScopedMessagePipeHandle handle) {
    receivers_.Add(
        this, mojo::PendingReceiver<translate::mojom::ContentTranslateDriver>(
                  std::move(handle)));
  }

  // translate::mojom::ContentTranslateDriver implementation.
  void RegisterPage(
      mojo::PendingRemote<translate::mojom::TranslateAgent> translate_agent,
      const translate::LanguageDetectionDetails& details,
      bool page_level_translation_critiera_met) override {
    called_new_page_ = true;
    details_ = details;
    page_level_translation_critiera_met_ = page_level_translation_critiera_met;
  }
  void GetLanguageDetectionModel(
      GetLanguageDetectionModelCallback callback) override {}

  void ResetNewPageValues() {
    called_new_page_ = false;
    details_ = absl::nullopt;
    page_level_translation_critiera_met_ = false;
  }

  bool called_new_page_ = false;
  bool page_level_translation_critiera_met_ = false;
  absl::optional<translate::LanguageDetectionDetails> details_;

 private:
  mojo::ReceiverSet<translate::mojom::ContentTranslateDriver> receivers_;
};

// Load the model file at the provided file path.
base::File LoadModelFile(const base::FilePath& model_file_path) {
  if (!base::PathExists(model_file_path))
    return base::File();

  return base::File(model_file_path,
                    base::File::FLAG_OPEN | base::File::FLAG_READ);
}

base::FilePath model_file_path() {
  base::FilePath source_root_dir;
  base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_dir);
  return source_root_dir.AppendASCII("components")
      .AppendASCII("test")
      .AppendASCII("data")
      .AppendASCII("translate")
      .AppendASCII("valid_model.tflite");
}

}  // namespace

class TestTranslateAgent : public translate::TranslateAgent {
 public:
  explicit TestTranslateAgent(content::RenderFrame* render_frame)
      : translate::TranslateAgent(render_frame,
                                  ISOLATED_WORLD_ID_TRANSLATE,
                                  extensions::kExtensionScheme) {}

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

  base::TimeDelta AdjustDelay(int delayInMs) override {
    // Just returns base::TimeDelta() which has initial value 0.
    // Tasks doesn't need to be delayed in tests.
    return base::TimeDelta();
  }

  void TranslatePage(const std::string& source_lang,
                     const std::string& target_lang,
                     const std::string& translate_script) {
    // Reset result values firstly.
    page_translated_ = false;
    trans_result_cancelled_ = false;
    trans_result_source_lang_ = absl::nullopt;
    trans_result_translated_lang_ = absl::nullopt;
    trans_result_error_type_ = translate::TranslateErrors::NONE;

    // Will get new result values via OnPageTranslated.
    TranslateFrame(translate_script, source_lang, target_lang,
                   base::BindOnce(&TestTranslateAgent::OnPageTranslated,
                                  base::Unretained(this)));
  }

  bool GetPageTranslatedResult(std::string* source_lang,
                               std::string* target_lang,
                               translate::TranslateErrors::Type* error) {
    if (!page_translated_)
      return false;
    if (source_lang)
      *source_lang = *trans_result_source_lang_;
    if (target_lang)
      *target_lang = *trans_result_translated_lang_;
    if (error)
      *error = trans_result_error_type_;
    return true;
  }

  MOCK_METHOD0(IsTranslateLibAvailable, bool());
  MOCK_METHOD0(IsTranslateLibReady, bool());
  MOCK_METHOD0(HasTranslationFinished, bool());
  MOCK_METHOD0(HasTranslationFailed, bool());
  MOCK_METHOD0(GetPageSourceLanguage, std::string());
  MOCK_METHOD0(GetErrorCode, int64_t());
  MOCK_METHOD0(StartTranslation, bool());
  MOCK_METHOD1(ExecuteScript, void(const std::string&));
  MOCK_METHOD2(ExecuteScriptAndGetBoolResult, bool(const std::string&, bool));
  MOCK_METHOD1(ExecuteScriptAndGetStringResult,
               std::string(const std::string&));
  MOCK_METHOD1(ExecuteScriptAndGetDoubleResult, double(const std::string&));
  MOCK_METHOD1(ExecuteScriptAndGetIntegerResult, int64_t(const std::string&));

 private:
  void OnPageTranslated(bool cancelled,
                        const std::string& source_lang,
                        const std::string& translated_lang,
                        translate::TranslateErrors::Type error_type) {
    page_translated_ = true;
    trans_result_cancelled_ = cancelled;
    trans_result_source_lang_ = source_lang;
    trans_result_translated_lang_ = translated_lang;
    trans_result_error_type_ = error_type;
  }

  bool page_translated_;
  bool trans_result_cancelled_;
  absl::optional<std::string> trans_result_source_lang_;
  absl::optional<std::string> trans_result_translated_lang_;
  translate::TranslateErrors::Type trans_result_error_type_;
};

class TranslateAgentBrowserTest : public ChromeRenderViewTest {
 public:
  TranslateAgentBrowserTest() : translate_agent_(nullptr) {}

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

 protected:
  void SetUp() override {
    ChromeRenderViewTest::SetUp();
    scoped_feature_list_.InitAndEnableFeature(
        translate::kTFLiteLanguageDetectionEnabled);
    translate_agent_ = new TestTranslateAgent(GetMainRenderFrame());

    GetMainRenderFrame()->GetBrowserInterfaceBroker()->SetBinderForTesting(
        translate::mojom::ContentTranslateDriver::Name_,
        base::BindRepeating(&FakeContentTranslateDriver::BindHandle,
                            base::Unretained(&fake_translate_driver_)));
    base::File model_file = LoadModelFile(model_file_path());
    translate_agent_->SeedLanguageDetectionModelForTesting(
        std::move(model_file));
  }

  void TearDown() override {
    GetMainRenderFrame()->GetBrowserInterfaceBroker()->SetBinderForTesting(
        translate::mojom::ContentTranslateDriver::Name_, {});

    delete translate_agent_;
    ChromeRenderViewTest::TearDown();
  }

  TestTranslateAgent* translate_agent_;
  FakeContentTranslateDriver fake_translate_driver_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

// Tests that the browser gets notified of the translation failure if the
// translate library fails/times-out during initialization.
TEST_F(TranslateAgentBrowserTest, TranslateLibNeverReady) {
  // We make IsTranslateLibAvailable true so we don't attempt to inject the
  // library.
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_CALL(*translate_agent_, IsTranslateLibReady())
      .Times(AtLeast(5))  // See kMaxTranslateInitCheckAttempts in
                          // translate_agent.cc
      .WillRepeatedly(Return(false));

  EXPECT_CALL(*translate_agent_, GetErrorCode())
      .Times(AtLeast(5))
      .WillRepeatedly(Return(translate::TranslateErrors::NONE));

  translate_agent_->TranslatePage("en", "fr", std::string());
  base::RunLoop().RunUntilIdle();

  translate::TranslateErrors::Type error;
  ASSERT_TRUE(
      translate_agent_->GetPageTranslatedResult(nullptr, nullptr, &error));
  EXPECT_EQ(translate::TranslateErrors::TRANSLATION_TIMEOUT, error);
}

// Tests that the browser gets notified of the translation success when the
// translation succeeds.
TEST_F(TranslateAgentBrowserTest, TranslateSuccess) {
  // We make IsTranslateLibAvailable true so we don't attempt to inject the
  // library.
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_CALL(*translate_agent_, IsTranslateLibReady())
      .WillOnce(Return(false))
      .WillOnce(Return(true));

  EXPECT_CALL(*translate_agent_, GetErrorCode())
      .WillOnce(Return(translate::TranslateErrors::NONE));

  EXPECT_CALL(*translate_agent_, StartTranslation()).WillOnce(Return(true));

  // Succeed after few checks.
  EXPECT_CALL(*translate_agent_, HasTranslationFailed())
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*translate_agent_, HasTranslationFinished())
      .WillOnce(Return(false))
      .WillOnce(Return(false))
      .WillOnce(Return(true));

  // V8 call for performance monitoring should be ignored.
  EXPECT_CALL(*translate_agent_, ExecuteScriptAndGetDoubleResult(_)).Times(3);

  std::string source_lang("en");
  std::string target_lang("fr");
  translate_agent_->TranslatePage(source_lang, target_lang, std::string());
  base::RunLoop().RunUntilIdle();

  std::string received_source_lang;
  std::string received_target_lang;
  translate::TranslateErrors::Type error;
  ASSERT_TRUE(translate_agent_->GetPageTranslatedResult(
      &received_source_lang, &received_target_lang, &error));
  EXPECT_EQ(source_lang, received_source_lang);
  EXPECT_EQ(target_lang, received_target_lang);
  EXPECT_EQ(translate::TranslateErrors::NONE, error);
}

// Tests that the browser gets notified of the translation failure when the
// translation fails.
TEST_F(TranslateAgentBrowserTest, TranslateFailure) {
  // We make IsTranslateLibAvailable true so we don't attempt to inject the
  // library.
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_CALL(*translate_agent_, IsTranslateLibReady()).WillOnce(Return(true));

  EXPECT_CALL(*translate_agent_, StartTranslation()).WillOnce(Return(true));

  // Fail after few checks.
  EXPECT_CALL(*translate_agent_, HasTranslationFailed())
      .WillOnce(Return(false))
      .WillOnce(Return(false))
      .WillOnce(Return(false))
      .WillOnce(Return(true));

  EXPECT_CALL(*translate_agent_, HasTranslationFinished())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(false));

  EXPECT_CALL(*translate_agent_, GetErrorCode())
      .WillOnce(Return(translate::TranslateErrors::TRANSLATION_ERROR));

  // V8 call for performance monitoring should be ignored.
  EXPECT_CALL(*translate_agent_, ExecuteScriptAndGetDoubleResult(_)).Times(2);

  translate_agent_->TranslatePage("en", "fr", std::string());
  base::RunLoop().RunUntilIdle();

  translate::TranslateErrors::Type error;
  ASSERT_TRUE(
      translate_agent_->GetPageTranslatedResult(nullptr, nullptr, &error));
  EXPECT_EQ(translate::TranslateErrors::TRANSLATION_ERROR, error);
}

// Tests that when the browser translate a page for which the language is
// undefined we query the translate element to get the language.
TEST_F(TranslateAgentBrowserTest, UndefinedSourceLang) {
  // We make IsTranslateLibAvailable true so we don't attempt to inject the
  // library.
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_CALL(*translate_agent_, IsTranslateLibReady()).WillOnce(Return(true));

  EXPECT_CALL(*translate_agent_, GetPageSourceLanguage())
      .WillOnce(Return("de"));

  EXPECT_CALL(*translate_agent_, StartTranslation()).WillOnce(Return(true));
  EXPECT_CALL(*translate_agent_, HasTranslationFailed())
      .WillOnce(Return(false));
  EXPECT_CALL(*translate_agent_, HasTranslationFinished())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  // V8 call for performance monitoring should be ignored.
  EXPECT_CALL(*translate_agent_, ExecuteScriptAndGetDoubleResult(_)).Times(3);

  translate_agent_->TranslatePage(translate::kUnknownLanguageCode, "fr",
                                  std::string());
  base::RunLoop().RunUntilIdle();

  translate::TranslateErrors::Type error;
  std::string source_lang;
  std::string target_lang;
  ASSERT_TRUE(translate_agent_->GetPageTranslatedResult(&source_lang,
                                                        &target_lang, &error));
  EXPECT_EQ("de", source_lang);
  EXPECT_EQ("fr", target_lang);
  EXPECT_EQ(translate::TranslateErrors::NONE, error);
}

// Tests that starting a translation while a similar one is pending does not
// break anything.
TEST_F(TranslateAgentBrowserTest, MultipleSimilarTranslations) {
  // We make IsTranslateLibAvailable true so we don't attempt to inject the
  // library.
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_CALL(*translate_agent_, IsTranslateLibReady())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*translate_agent_, StartTranslation())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*translate_agent_, HasTranslationFailed())
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*translate_agent_, HasTranslationFinished())
      .WillOnce(Return(true));

  // V8 call for performance monitoring should be ignored.
  EXPECT_CALL(*translate_agent_, ExecuteScriptAndGetDoubleResult(_)).Times(3);

  std::string source_lang("en");
  std::string target_lang("fr");
  translate_agent_->TranslatePage(source_lang, target_lang, std::string());
  // While this is running call again TranslatePage to make sure noting bad
  // happens.
  translate_agent_->TranslatePage(source_lang, target_lang, std::string());
  base::RunLoop().RunUntilIdle();

  std::string received_source_lang;
  std::string received_target_lang;
  translate::TranslateErrors::Type error;
  ASSERT_TRUE(translate_agent_->GetPageTranslatedResult(
      &received_source_lang, &received_target_lang, &error));
  EXPECT_EQ(source_lang, received_source_lang);
  EXPECT_EQ(target_lang, received_target_lang);
  EXPECT_EQ(translate::TranslateErrors::NONE, error);
}

// Tests that starting a translation while a different one is pending works.
TEST_F(TranslateAgentBrowserTest, MultipleDifferentTranslations) {
  EXPECT_CALL(*translate_agent_, IsTranslateLibAvailable())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*translate_agent_, IsTranslateLibReady())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*translate_agent_, StartTranslation())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*translate_agent_, HasTranslationFailed())
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*translate_agent_, HasTranslationFinished())
      .WillOnce(Return(true));

  // V8 call for performance monitoring should be ignored.
  EXPECT_CALL(*translate_agent_, ExecuteScriptAndGetDoubleResult(_)).Times(5);

  std::string source_lang("en");
  std::string target_lang("fr");
  translate_agent_->TranslatePage(source_lang, target_lang, std::string());
  // While this is running call again TranslatePage with a new target lang.
  std::string new_target_lang("de");
  translate_agent_->TranslatePage(source_lang, new_target_lang, std::string());
  base::RunLoop().RunUntilIdle();

  std::string received_source_lang;
  std::string received_target_lang;
  translate::TranslateErrors::Type error;
  ASSERT_TRUE(translate_agent_->GetPageTranslatedResult(
      &received_source_lang, &received_target_lang, &error));
  EXPECT_EQ(source_lang, received_source_lang);
  EXPECT_EQ(new_target_lang, received_target_lang);
  EXPECT_EQ(translate::TranslateErrors::NONE, error);
}

// Tests that we send the right translate language message for a page and that
// we respect the "no translate" meta-tag.
TEST_F(TranslateAgentBrowserTest, TranslatablePage) {
  LoadHTML("A random page with random content.");

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_TRUE(fake_translate_driver_.page_level_translation_critiera_met_)
      << "Page should be translatable.";
  fake_translate_driver_.ResetNewPageValues();

  // Now the page specifies the META tag to prevent translation.
  LoadHTML(
      "<meta name=\"google\" value=\"notranslate\">"
      "A random page with random content.");

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_)
      << "Page should not be translatable.";
  fake_translate_driver_.ResetNewPageValues();

  // Try the alternate version of the META tag (content instead of value).
  LoadHTML(
      "<meta name=\"google\" content=\"notranslate\">"
      "A random page with random content.");

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_)
      << "Page should not be translatable.";
}

// Tests that the language meta tag takes precedence over the CLD when reporting
// the page's language.
TEST_F(TranslateAgentBrowserTest, LanguageMetaTag) {
  LoadHTML(
      "<meta http-equiv=\"content-language\" content=\"es\">"
      "A");
  //   "Esta página está en español.");

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("es", fake_translate_driver_.details_->adopted_language);
  fake_translate_driver_.ResetNewPageValues();

  // Makes sure we support multiple languages specified.
  LoadHTML(
      "<meta http-equiv=\"content-language\" "
      "content=\" fr , es,en \">"
      "Cette page est en français.");

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("fr", fake_translate_driver_.details_->adopted_language);
}

// Tests that the language meta tag works even with non-all-lower-case.
// http://code.google.com/p/chromium/issues/detail?id=145689
TEST_F(TranslateAgentBrowserTest, LanguageMetaTagCase) {
  LoadHTML(
      "<meta http-equiv=\"Content-Language\" content=\"es\">"
      "E");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("es", fake_translate_driver_.details_->adopted_language);
  fake_translate_driver_.ResetNewPageValues();

  // Makes sure we support multiple languages specified.
  LoadHTML(
      "<meta http-equiv=\"Content-Language\" "
      "content=\" fr , es,en \">"
      "Cette page est en français.");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("fr", fake_translate_driver_.details_->adopted_language);
}

// Tests that the language meta tag is converted to Chrome standard of dashes
// instead of underscores and proper capitalization.
// http://code.google.com/p/chromium/issues/detail?id=159487
TEST_F(TranslateAgentBrowserTest, LanguageCommonMistakesAreCorrected) {
  LoadHTML(
      "<meta http-equiv='Content-Language' content='EN_us'>"
      "A random page with random content.");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("en", fake_translate_driver_.details_->adopted_language);
  fake_translate_driver_.ResetNewPageValues();

  LoadHTML(
      "<meta http-equiv='Content-Language' content='ZH_tw'>"
      "A");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("zh-TW", fake_translate_driver_.details_->adopted_language);
}

// Tests that a back navigation gets a translate language message.
TEST_F(TranslateAgentBrowserTest, BackToTranslatablePage) {
  LoadHTML(
      "<meta http-equiv=\"content-language\" content=\"es\">"
      "E");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("es", fake_translate_driver_.details_->adopted_language);
  fake_translate_driver_.ResetNewPageValues();

  blink::PageState back_state = GetCurrentPageState();

  LoadHTML(
      "<meta http-equiv=\"content-language\" content=\"fr\">"
      "E");
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("fr", fake_translate_driver_.details_->adopted_language);
  fake_translate_driver_.ResetNewPageValues();

  GoBack(GURL("data:text/html;charset=utf-8,"
              "<meta http-equiv=\"content-language\" content=\"es\">"
              "E"),
         back_state);

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_EQ("es", fake_translate_driver_.details_->adopted_language);
}

TEST_F(TranslateAgentBrowserTest, UnsupportedTranslateSchemes) {
  GURL url("https://foo.com");
  LoadHTMLWithUrlOverride(
      "A random page with random content.",
      UpdateGURLScheme(url, content::kChromeUIScheme).c_str());

  base::RunLoop().RunUntilIdle();
  ASSERT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);

  LoadHTMLWithUrlOverride(
      "A random page with random content.",
      url::kAboutBlankURL);

  base::RunLoop().RunUntilIdle();
  ASSERT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);

  LoadHTMLWithUrlOverride(
      "A random page with random content.",
      UpdateGURLScheme(url, content::kChromeDevToolsScheme).c_str());

  base::RunLoop().RunUntilIdle();
  ASSERT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}


text:
<?php

namespace PHPSA\Visitor\Expression\Operators\Comparison;

class SmallerOrEqual extends AbstractOperator
{
    protected $name = '\PhpParser\Node\Expr\BinaryOp\SmallerOrEqual';

    /**
     * {expr} <= {expr}
     *
     * @param $left
     * @param $right
     * @return bool
     */
    public function compare($left, $right)
    {
        return $left <= $right;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package llsm

import net.imglib2.transform.integer.shear.ShearIntervalTransform
import net.imglib2.realtransform.RealShearTransform
import org.scalatest.Matchers._
import org.scalacheck.Gen

class ShearSpec extends BaseSuite {
  "A ShearIntervalTransform" should "c[shearDimension] += c[referenceDimension] * shearFactor" in forAll(
    (Gen.choose(2, 10), "nDim"),
    (Gen.choose(0, 9), "shearDimension"),
    (Gen.choose(0, 9), "referenceDimension"),
    (Gen.choose(-5, 5), "shearFactor"),
    (Gen.choose(1L, 1000L), "c"),
    maxDiscardedFactor(10)
  ) {
    (nDim: Int, shearDimension: Int, referenceDimension: Int, shearFactor: Int,
     c: Long) =>
      whenever(
        nDim > 1 && shearDimension < nDim && referenceDimension < nDim && shearDimension != referenceDimension) {
        val source: Array[Long] = Array.fill[Long](nDim)(c)
        val target: Array[Long] = Array.ofDim[Long](nDim)

        val st = new ShearIntervalTransform(nDim,
                                            shearDimension,
                                            referenceDimension,
                                            shearFactor)

        st.apply(source, target)
        target(referenceDimension) should equal(c)
        target(shearDimension) should equal(c + c * shearFactor)
      }
  }
  it should "throw an IllegalArgumentException when nDim < 2" in {
    assertThrows[IllegalArgumentException] {
      new ShearIntervalTransform(1, 0, 0, 1)
    }
  }
  it should "throw an IllegalArgumentException when the shearDimension or referenceDimension are >= nDim" in forAll(
    "nDim",
    "shearDimension",
    "referenceDimension") {
    (nDim: Int, shearDimension: Int, referenceDimension: Int) =>
      whenever(shearDimension >= nDim || referenceDimension >= nDim) {
        assertThrows[IllegalArgumentException] {
          new ShearIntervalTransform(nDim,
                                     shearDimension,
                                     referenceDimension,
                                     1)
        }
      }
  }
  it should "throw an IllegalArgumentException when shearDimension == referenceDimension" in {
    assertThrows[IllegalArgumentException] {
      new ShearIntervalTransform(5, 2, 2, 3)
    }
  }

  "A RealShearTransform" should "c[shearDimension] += c[referenceDimension] * shearFactor" in forAll(
    (Gen.choose(2, 10), "nDim"),
    (Gen.choose(0, 9), "shearDimension"),
    (Gen.choose(0, 9), "referenceDimension"),
    (Gen.choose(-5.0, 5.0), "shearFactor"),
    (Gen.choose(1.0, 1000.0), "c")
  ) {
    (nDim: Int, shearDimension: Int, referenceDimension: Int,
     shearFactor: Double, c: Double) =>
      whenever(
        nDim > 1 && shearDimension < nDim && referenceDimension < nDim && shearDimension != referenceDimension) {
        val source: Array[Double] = Array.fill[Double](nDim)(c)
        val target: Array[Double] = Array.ofDim[Double](nDim)

        val st = new RealShearTransform(nDim,
                                        shearDimension,
                                        referenceDimension,
                                        shearFactor)

        st.apply(source, target)
        target(referenceDimension) should equal(c)
        target(shearDimension) should equal(c + c * shearFactor)
      }
  }
  it should "throw an IllegalArgumentException when nDim < 2" in {
    assertThrows[IllegalArgumentException] {
      new RealShearTransform(1, 0, 0, 1.0)
    }
  }
  it should "throw an IllegalArgumentException when the shearDimension or referenceDimension are >= nDim" in forAll(
    "nDim",
    "shearDimension",
    "referenceDimension") {
    (nDim: Int, shearDimension: Int, referenceDimension: Int) =>
      whenever(shearDimension >= nDim || referenceDimension >= nDim) {
        assertThrows[IllegalArgumentException] {
          new RealShearTransform(nDim, shearDimension, referenceDimension, 1.0)
        }
      }
  }
  it should "throw an IllegalArgumentException when shearDimension == referenceDimension" in {
    assertThrows[IllegalArgumentException] {
      new RealShearTransform(5, 2, 2, 3.0)
    }
  }
}


text:
import {OsvCommandBase} from "./OsvCommandBase"
import Set from "typescript-collections/dist/lib/Set";

export class OsvCmdlineCommand extends OsvCommandBase<string> {
   typed: string = 'cmdline';

   description:string = 'print OSv application cmdline';

   help:string = 'Usage: cmdline

\
     Show OSv application cmdline.';

   matches(input: string) {
      return input === 'cmdline';
   }

   executeApi(commandArguments: string[], options: Set<string>): JQueryPromise<string> {
      return this.cmd.api.getCmdline();
  }

   handleExecutionSuccess(options:Set<string>, response:string) {
      this.cmd.displayOutput(response.toString(), true);
   }
}


text:
/* */
var baseClone = require('./_baseClone'),
    baseMatchesProperty = require('./_baseMatchesProperty');
var CLONE_DEEP_FLAG = 1;
function matchesProperty(path, srcValue) {
  return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
module.exports = matchesProperty;


text:
namespace
{
class CCoinsViewTest : public CCoinsView
{
    uint256 hashBestBlock_;
    std::map<uint256, CCoins> map_;

public:
    bool GetCoins(const uint256& txid, CCoins& coins) const
    {
        std::map<uint256, CCoins>::const_iterator it = map_.find(txid);
        if (it == map_.end()) {
            return false;
        }
        coins = it->second;
        if (coins.IsPruned() && insecure_rand() % 2 == 0) {
            // Randomly return false in case of an empty entry.
            return false;
        }
        return true;
    }

    bool HaveCoins(const uint256& txid) const
    {
        CCoins coins;
        return GetCoins(txid, coins);
    }

    uint256 GetBestBlock() const { return hashBestBlock_; }

    bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock)
    {
        for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {
            if (it->second.flags & CCoinsCacheEntry::DIRTY) {
                // Same optimization used in CCoinsViewDB is to only write dirty entries.
                map_[it->first] = it->second.coins;
                if (it->second.coins.IsPruned() && insecure_rand() % 3 == 0) {
                    // Randomly delete empty entries on write.
                    map_.erase(it->first);
                }
            }
            mapCoins.erase(it++);
        }
        if (!hashBlock.IsNull())
            hashBestBlock_ = hashBlock;
        return true;
    }

    bool GetStats(CCoinsStats& stats) const { return false; }
};

class CCoinsViewCacheTest : public CCoinsViewCache
{
public:
    CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {}

    void SelfTest() const
    {
        // Manually recompute the dynamic usage of the whole data, and compare it.
        size_t ret = memusage::DynamicUsage(cacheCoins);
        for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {
            ret += it->second.coins.DynamicMemoryUsage();
        }
        BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
    }

};

}

BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)

static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;

// This is a large randomized insert/remove simulation test on a variable-size
// stack of caches on top of CCoinsViewTest.
//
// It will randomly create/update/delete CCoins entries to a tip of caches, with
// txids picked from a limited list of random 256-bit hashes. Occasionally, a
// new tip is added to the stack of caches, or the tip is flushed and removed.
//
// During the process, booleans are kept to make sure that the randomized
// operation hits all branches.
BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
{
    // Various coverage trackers.
    bool removed_all_caches = false;
    bool reached_4_caches = false;
    bool added_an_entry = false;
    bool removed_an_entry = false;
    bool updated_an_entry = false;
    bool found_an_entry = false;
    bool missed_an_entry = false;

    // A simple map to track what we expect the cache stack to represent.
    std::map<uint256, CCoins> result;

    // The cache stack.
    CCoinsViewTest base; // A CCoinsViewTest at the bottom.
    std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
    stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.

    // Use a limited set of random transaction ids, so we do test overwriting entries.
    std::vector<uint256> txids;
    txids.resize(NUM_SIMULATION_ITERATIONS / 8);
    for (unsigned int i = 0; i < txids.size(); i++) {
        txids[i] = GetRandHash();
    }

    for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
        // Do a random modification.
        {
            uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration.
            CCoins& coins = result[txid];
            CCoinsModifier entry = stack.back()->ModifyCoins(txid);
            BOOST_CHECK(coins == *entry);
            if (insecure_rand() % 5 == 0 || coins.IsPruned()) {
                if (coins.IsPruned()) {
                    added_an_entry = true;
                } else {
                    updated_an_entry = true;
                }
                coins.nVersion = insecure_rand();
                coins.vout.resize(1);
                coins.vout[0].nValue = insecure_rand();
                *entry = coins;
            } else {
                coins.Clear();
                entry->Clear();
                removed_an_entry = true;
            }
        }

        // Once every 1000 iterations and at the end, verify the full cache.
        if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
            for (std::map<uint256, CCoins>::iterator it = result.begin(); it != result.end(); it++) {
                const CCoins* coins = stack.back()->AccessCoins(it->first);
                if (coins) {
                    BOOST_CHECK(*coins == it->second);
                    found_an_entry = true;
                } else {
                    BOOST_CHECK(it->second.IsPruned());
                    missed_an_entry = true;
                }
            }
            BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {
                test->SelfTest();
            }
        }

        if (insecure_rand() % 100 == 0) {
            // Every 100 iterations, flush an intermediate cache
            if (stack.size() > 1 && insecure_rand() % 2 == 0) {
                unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
                stack[flushIndex]->Flush();
            }
        }
        if (insecure_rand() % 100 == 0) {
            // Every 100 iterations, change the cache stack.
            if (stack.size() > 0 && insecure_rand() % 2 == 0) {
                //Remove the top cache
                stack.back()->Flush();
                delete stack.back();
                stack.pop_back();
            }
            if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
                //Add a new cache
                CCoinsView* tip = &base;
                if (stack.size() > 0) {
                    tip = stack.back();
                } else {
                    removed_all_caches = true;
                }
                stack.push_back(new CCoinsViewCacheTest(tip));
                if (stack.size() == 4) {
                    reached_4_caches = true;
                }
            }
        }
    }

    // Clean up the stack.
    while (stack.size() > 0) {
        delete stack.back();
        stack.pop_back();
    }

    // Verify coverage.
    BOOST_CHECK(removed_all_caches);
    BOOST_CHECK(reached_4_caches);
    BOOST_CHECK(added_an_entry);
    BOOST_CHECK(removed_an_entry);
    BOOST_CHECK(updated_an_entry);
    BOOST_CHECK(found_an_entry);
    BOOST_CHECK(missed_an_entry);
}

// This test is similar to the previous test
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
// In particular it is tested that spending a duplicate coinbase tx
// has the expected effect (the other duplicate is overwitten at all cache levels)
BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
{
    bool spent_a_duplicate_coinbase = false;
    // A simple map to track what we expect the cache stack to represent.
    std::map<uint256, CCoins> result;

    // The cache stack.
    CCoinsViewTest base; // A CCoinsViewTest at the bottom.
    std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
    stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.

    // Track the txids we've used and whether they have been spent or not
    std::map<uint256, CAmount> coinbaseids;
    std::set<uint256> alltxids;
    std::set<uint256> duplicateids;

    for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
        {
            CMutableTransaction tx;
            tx.vin.resize(1);
            tx.vout.resize(1);
            tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
            unsigned int height = insecure_rand();

            // 1/10 times create a coinbase
            if (insecure_rand() % 10 == 0 || coinbaseids.size() < 10) {
                // 1/100 times create a duplicate coinbase
                if (insecure_rand() % 10 == 0 && coinbaseids.size()) {
                    std::map<uint256, CAmount>::iterator coinbaseIt = coinbaseids.lower_bound(GetRandHash());
                    if (coinbaseIt == coinbaseids.end()) {
                        coinbaseIt = coinbaseids.begin();
                    }
                    //Use same random value to have same hash and be a true duplicate
                    tx.vout[0].nValue = coinbaseIt->second;
                    assert(tx.GetHash() == coinbaseIt->first);
                    duplicateids.insert(coinbaseIt->first);
                }
                else {
                    coinbaseids[tx.GetHash()] = tx.vout[0].nValue;
                }
                assert(CTransaction(tx).IsCoinBase());
            }
            // 9/10 times create a regular tx
            else {
                uint256 prevouthash;
                // equally likely to spend coinbase or non coinbase
                std::set<uint256>::iterator txIt = alltxids.lower_bound(GetRandHash());
                if (txIt == alltxids.end()) {
                    txIt = alltxids.begin();
                }
                prevouthash = *txIt;

                // Construct the tx to spend the coins of prevouthash
                tx.vin[0].prevout.hash = prevouthash;
                tx.vin[0].prevout.n = 0;

                // Update the expected result of prevouthash to know these coins are spent
                CCoins& oldcoins = result[prevouthash];
                oldcoins.Clear();

                // It is of particular importance here that once we spend a coinbase tx hash
                // it is no longer available to be duplicated (or spent again)
                // BIP 34 in conjunction with enforcing BIP 30 (at least until BIP 34 was active)
                // results in the fact that no coinbases were duplicated after they were already spent
                alltxids.erase(prevouthash);
                coinbaseids.erase(prevouthash);

                // The test is designed to ensure spending a duplicate coinbase will work properly
                // if that ever happens and not resurrect the previously overwritten coinbase
                if (duplicateids.count(prevouthash))
                    spent_a_duplicate_coinbase = true;

                assert(!CTransaction(tx).IsCoinBase());
            }
            // Track this tx to possibly spend later
            alltxids.insert(tx.GetHash());

            // Update the expected result to know about the new output coins
            CCoins &coins = result[tx.GetHash()];
            coins.FromTx(tx, height);

            CValidationState dummy;
            UpdateCoins(tx, dummy, *(stack.back()), height);
        }

        // Once every 1000 iterations and at the end, verify the full cache.
        if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
            for (std::map<uint256, CCoins>::iterator it = result.begin(); it != result.end(); it++) {
                const CCoins* coins = stack.back()->AccessCoins(it->first);
                if (coins) {
                    BOOST_CHECK(*coins == it->second);
                 } else {
                    BOOST_CHECK(it->second.IsPruned());
                 }
            }
        }

        if (insecure_rand() % 100 == 0) {
            // Every 100 iterations, flush an intermediate cache
            if (stack.size() > 1 && insecure_rand() % 2 == 0) {
                unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
                stack[flushIndex]->Flush();
            }
        }
        if (insecure_rand() % 100 == 0) {
            // Every 100 iterations, change the cache stack.
            if (stack.size() > 0 && insecure_rand() % 2 == 0) {
                stack.back()->Flush();
                delete stack.back();
                stack.pop_back();
            }
            if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
                CCoinsView* tip = &base;
                if (stack.size() > 0) {
                    tip = stack.back();
                }
                stack.push_back(new CCoinsViewCacheTest(tip));
           }
        }
    }

    // Clean up the stack.
    while (stack.size() > 0) {
        delete stack.back();
        stack.pop_back();
    }

    // Verify coverage.
    BOOST_CHECK(spent_a_duplicate_coinbase);
}

BOOST_AUTO_TEST_SUITE_END()


text:
Vim Bootstrap is generator provides a simple method of generating a .vimrc configuration for vim, NeoVim, MacVim and GVim.

Official repo: https://github.com/avelino/vim-bootstrap


text:
'use strict';

const path = require('path');

const babel = require('babel-core');
const coffee = require('coffee-script');

const tsPreprocessor = require('./typescript/preprocessor');
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');

// Use require.resolve to be resilient to file moves, npm updates, etc
const pathToBabel = path.join(
  require.resolve('babel-core'),
  '..',
  'package.json'
);
const pathToBabelPluginDevWithCode = require.resolve(
  '../error-codes/minify-error-messages'
);
const pathToBabelPluginWrapWarning = require.resolve(
  '../babel/wrap-warning-with-env-check'
);
const pathToBabelPluginAsyncToGenerator = require.resolve(
  'babel-plugin-transform-async-to-generator'
);
const pathToBabelrc = path.join(__dirname, '..', '..', '.babelrc');
const pathToErrorCodes = require.resolve('../error-codes/codes.json');

const babelOptions = {
  plugins: [
    // For Node environment only. For builds, Rollup takes care of ESM.
    require.resolve('babel-plugin-transform-es2015-modules-commonjs'),

    pathToBabelPluginDevWithCode,
    pathToBabelPluginWrapWarning,

    // Keep stacks detailed in tests.
    // Don't put this in .babelrc so that we don't embed filenames
    // into ReactART builds that include JSX.
    // TODO: I have not verified that this actually works.
    require.resolve('babel-plugin-transform-react-jsx-source'),

    require.resolve('../babel/transform-prevent-infinite-loops'),
  ],
  retainLines: true,
};

module.exports = {
  process: function(src, filePath) {
    if (filePath.match(/\.coffee$/)) {
      return coffee.compile(src, {bare: true});
    }
    if (filePath.match(/\.ts$/) && !filePath.match(/\.d\.ts$/)) {
      return tsPreprocessor.compile(src, filePath);
    }
    if (!filePath.match(/\/third_party\//)) {
      // for test files, we also apply the async-await transform, but we want to
      // make sure we don't accidentally apply that transform to product code.
      const isTestFile = !!filePath.match(/\/__tests__\//);
      return babel.transform(
        src,
        Object.assign(
          {filename: path.relative(process.cwd(), filePath)},
          babelOptions,
          isTestFile
            ? {
                plugins: [pathToBabelPluginAsyncToGenerator].concat(
                  babelOptions.plugins
                ),
              }
            : {}
        )
      ).code;
    }
    return src;
  },

  getCacheKey: createCacheKeyFunction([
    __filename,
    pathToBabel,
    pathToBabelrc,
    pathToBabelPluginDevWithCode,
    pathToBabelPluginWrapWarning,
    pathToErrorCodes,
  ]),
};