text:
namespace net {

namespace {

namespace test_default {
#include "net/http/transport_security_state_static_unittest_default.h"
}

}  // anonymous namespace

class HttpSecurityHeadersTest : public testing::Test {
 public:
  ~HttpSecurityHeadersTest() override {
    SetTransportSecurityStateSourceForTesting(nullptr);
  }
};

TEST_F(HttpSecurityHeadersTest, BogusHeaders) {
  base::TimeDelta max_age;
  bool include_subdomains = false;

  EXPECT_FALSE(
      ParseHSTSHeader(std::string(), &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("    ", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("abc", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("  abc", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("  abc   ", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("  max-age", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("  max-age  ", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age=", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age  =", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age=   ", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age  =     ", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age  =     xy", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   max-age  =     3488a923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488a923  ", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-ag=3488923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-aged=3488923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age==3488923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("amax-age=3488923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=-3488923", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(
      ParseHSTSHeader("max-age=+3488923", &max_age, &include_subdomains));
  EXPECT_FALSE(
      ParseHSTSHeader("max-age=13####", &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=9223372036854775807#####", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=18446744073709551615####", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=999999999999999999999999$.&#!",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923     e", &max_age,
                               &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923     includesubdomain",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923includesubdomains",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923=includesubdomains",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923 includesubdomainx",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923 includesubdomain=",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923 includesubdomain=true",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923 includesubdomainsx",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=3488923 includesubdomains x",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=34889.23 includesubdomains",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age=34889 includesubdomains",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader(";;;; ;;;",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader(";;;; includeSubDomains;;;",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("   includeSubDomains;  ",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader(";",
                               &max_age, &include_subdomains));
  EXPECT_FALSE(ParseHSTSHeader("max-age; ;",
                               &max_age, &include_subdomains));

  // Check the out args were not updated by checking the default
  // values for its predictable fields.
  EXPECT_EQ(0, max_age.InSeconds());
  EXPECT_FALSE(include_subdomains);
}

TEST_F(HttpSecurityHeadersTest, ValidSTSHeaders) {
  base::TimeDelta max_age;
  base::TimeDelta expect_max_age;
  bool include_subdomains = false;

  EXPECT_TRUE(ParseHSTSHeader("max-age=243", &max_age,
                              &include_subdomains));
  expect_max_age = base::Seconds(243);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_FALSE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("max-age=3488923;", &max_age,
                              &include_subdomains));

  EXPECT_TRUE(ParseHSTSHeader("  Max-agE    = 567", &max_age,
                              &include_subdomains));
  expect_max_age = base::Seconds(567);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_FALSE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("  mAx-aGe    = 890      ", &max_age,
                              &include_subdomains));
  expect_max_age = base::Seconds(890);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_FALSE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("max-age=123;incLudesUbdOmains", &max_age,
                              &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("incLudesUbdOmains; max-age=123", &max_age,
                              &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("   incLudesUbdOmains; max-age=123",
                              &max_age, &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "   incLudesUbdOmains; max-age=123; pumpkin=kitten", &max_age,
                                   &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "   pumpkin=894; incLudesUbdOmains; max-age=123  ", &max_age,
                                   &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "   pumpkin; incLudesUbdOmains; max-age=123  ", &max_age,
                                   &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "   pumpkin; incLudesUbdOmains; max-age=\"123\"  ", &max_age,
                                   &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "animal=\"squirrel; distinguished\"; incLudesUbdOmains; max-age=123",
                                   &max_age, &include_subdomains));
  expect_max_age = base::Seconds(123);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader("max-age=394082;  incLudesUbdOmains",
                              &max_age, &include_subdomains));
  expect_max_age = base::Seconds(394082);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "max-age=39408299  ;incLudesUbdOmains", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 39408299u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "max-age=394082038  ; incLudesUbdOmains", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "max-age=394082038  ; incLudesUbdOmains;", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      ";; max-age=394082038  ; incLudesUbdOmains; ;", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      ";; max-age=394082038  ;", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_FALSE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      ";;    ; ; max-age=394082038;;; includeSubdomains     ;;  ;", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "incLudesUbdOmains   ; max-age=394082038 ;;", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(std::min(kMaxHSTSAgeSecs, 394082038u));
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "  max-age=0  ;  incLudesUbdOmains   ", &max_age,
      &include_subdomains));
  expect_max_age = base::Seconds(0);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);

  EXPECT_TRUE(ParseHSTSHeader(
      "  max-age=999999999999999999999999999999999999999999999  ;"
      "  incLudesUbdOmains   ", &max_age, &include_subdomains));
  expect_max_age = base::Seconds(kMaxHSTSAgeSecs);
  EXPECT_EQ(expect_max_age, max_age);
  EXPECT_TRUE(include_subdomains);
}

TEST_F(HttpSecurityHeadersTest, BogusExpectCTHeaders) {
  base::TimeDelta max_age;
  bool enforce = false;
  GURL report_uri;
  EXPECT_FALSE(
      ParseExpectCTHeader(std::string(), &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("    ", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("abc", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("  abc", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("  abc   ", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("  max-age", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("  max-age  ", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age=", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("   max-age=", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("   max-age  =", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("   max-age=   ", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("   max-age  =     ", &max_age, &enforce,
                                   &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("   max-age  =     xy", &max_age, &enforce,
                                   &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("   max-age  =     3488a923", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488a923  ", &max_age, &enforce,
                                   &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-ag=3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-aged=3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age==3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("amax-age=3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age=-3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age=+3488923", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age=13####", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=9223372036854775807#####", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=18446744073709551615####", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999999999999999999999999$.&#!",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923     e", &max_age, &enforce,
                                   &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923     includesubdomain",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923includesubdomains", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923=includesubdomains",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923 includesubdomainx",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader(
      "max-age=3488923 includesubdomain=", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923 includesubdomain=true",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923 includesubdomainsx",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=3488923 includesubdomains x",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=34889.23 includesubdomains",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=34889 includesubdomains", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader(",,,, ,,,", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader(",,,, includeSubDomains,,,", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("   includeSubDomains,  ", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader(",", &max_age, &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age, ,", &max_age, &enforce, &report_uri));

  // Test that the parser rejects misquoted or invalid report-uris.
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999, report-uri=\"http://foo;bar\'",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999, report-uri=\"foo;bar\"",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999, report-uri=\"\"", &max_age,
                                   &enforce, &report_uri));

  // Test that the parser does not fix up misquoted values.
  EXPECT_FALSE(
      ParseExpectCTHeader("max-age=\"999", &max_age, &enforce, &report_uri));

  // Test that the parser rejects headers that contain duplicate directives.
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999, enforce, max-age=99999",
                                   &max_age, &enforce, &report_uri));
  EXPECT_FALSE(ParseExpectCTHeader("enforce, max-age=999, enforce", &max_age,
                                   &enforce, &report_uri));
  EXPECT_FALSE(
      ParseExpectCTHeader("report-uri=\"http://foo\", max-age=999, enforce, "
                          "report-uri=\"http://foo\"",
                          &max_age, &enforce, &report_uri));

  // Test that the parser rejects headers with values for the valueless
  // 'enforce' directive.
  EXPECT_FALSE(ParseExpectCTHeader("max-age=999, enforce=true", &max_age,
                                   &enforce, &report_uri));

  // Check the out args were not updated by checking the default
  // values for its predictable fields.
  EXPECT_EQ(0, max_age.InSeconds());
  EXPECT_FALSE(enforce);
  EXPECT_TRUE(report_uri.is_empty());
}

TEST_F(HttpSecurityHeadersTest, ValidExpectCTHeaders) {
  base::TimeDelta max_age;
  bool enforce = false;
  GURL report_uri;

  EXPECT_TRUE(
      ParseExpectCTHeader("max-age=243", &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(243), max_age);
  EXPECT_FALSE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  EXPECT_TRUE(ParseExpectCTHeader("  Max-agE    = 567", &max_age, &enforce,
                                  &report_uri));
  EXPECT_EQ(base::Seconds(567), max_age);
  EXPECT_FALSE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  EXPECT_TRUE(ParseExpectCTHeader("  mAx-aGe    = 890      ", &max_age,
                                  &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(890), max_age);
  EXPECT_FALSE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  EXPECT_TRUE(ParseExpectCTHeader("max-age=123,enFoRce", &max_age, &enforce,
                                  &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("enFoRCE, max-age=123", &max_age, &enforce,
                                  &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("   enFORce, max-age=123", &max_age, &enforce,
                                  &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(
      "report-uri=\"https://foo.test\",   enFORce, max-age=123", &max_age,
      &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_EQ(GURL("https://foo.test"), report_uri);

  enforce = false;
  report_uri = GURL();
  EXPECT_TRUE(
      ParseExpectCTHeader("enforce,report-uri=\"https://foo.test\",max-age=123",
                          &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_EQ(GURL("https://foo.test"), report_uri);

  enforce = false;
  report_uri = GURL();
  EXPECT_TRUE(
      ParseExpectCTHeader("enforce,report-uri=https://foo.test,max-age=123",
                          &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_EQ(GURL("https://foo.test"), report_uri);

  report_uri = GURL();
  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("report-uri=\"https://foo.test\",max-age=123",
                                  &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_FALSE(enforce);
  EXPECT_EQ(GURL("https://foo.test"), report_uri);

  report_uri = GURL();
  EXPECT_TRUE(ParseExpectCTHeader("   enFORcE, max-age=123, pumpkin=kitten",
                                  &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(
      "   pumpkin=894, report-uri=     \"https://bar\", enFORce, max-age=123  ",
      &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_EQ(GURL("https://bar"), report_uri);

  enforce = false;
  report_uri = GURL();
  EXPECT_TRUE(ParseExpectCTHeader("   pumpkin, enFoRcE, max-age=123  ",
                                  &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("   pumpkin, enforce, max-age=\"123\"  ",
                                  &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(
      "animal=\"squirrel, distinguished\", enFoRce, max-age=123", &max_age,
      &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(123), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("max-age=394082,  enforce", &max_age,
                                  &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(394082), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("max-age=39408299  ,enforce", &max_age,
                                  &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  // Per RFC 7230, "a recipient MUST parse and ignore a reasonable number of
  // empty list elements".
  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(",, max-age=394082038  , enfoRce, ,",
                                  &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(",, max-age=394082038  ,", &max_age, &enforce,
                                  &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_FALSE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  EXPECT_TRUE(
      ParseExpectCTHeader(",,    , , max-age=394082038,,, enforce     ,,  ,",
                          &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("enfORce   , max-age=394082038 ,,", &max_age,
                                  &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader("  max-age=0  ,  enforce   ", &max_age,
                                  &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(0), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());

  enforce = false;
  EXPECT_TRUE(ParseExpectCTHeader(
      "  max-age=999999999999999999999999999999999999999999999  ,"
      "  enforce   ",
      &max_age, &enforce, &report_uri));
  EXPECT_EQ(base::Seconds(kMaxExpectCTAgeSecs), max_age);
  EXPECT_TRUE(enforce);
  EXPECT_TRUE(report_uri.is_empty());
}

}  // namespace net


text:
<!DOCTYPE HTML>

		<title>Photography</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

		<link rel="stylesheet" href="assets/css/main.css" />

						8th Mile RVCE

Home

Events

Sponsors

contact us

Photography

CINE SNAPS

LIGHT...CAMERA...ACTION. Show us how you could live life in technicolor in a movie spanning less than 20 min.

Know more

PHOTO STORY

A picture is worth a thousand words. Prove us right and capture your story through your lens.

Know more

Design by 8th Mile dev team

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="//fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
	<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"/>
	<link rel="stylesheet" href="bower_components/chosen/chosen.css" />
	<link rel="stylesheet" href="bower_components/seiyria-bootstrap-slider/dist/css/bootstrap-slider.min.css" />
	<link rel="stylesheet" href="app/bookworm.gui.css"/>

	<meta charset="UTF-8">
	<meta name="description" content="bookworm: Search for trends in hundreds of thousands of texts">
	<title>Bookworm</title>

bookworm:

					Search for trends in hundreds of thousands of texts at

					 Dates

Date Limits

Smoothing

t

					 Metric

Metric

 Words per Million

 Percent of Text

 Number of Words

 Number of Text

					 Case

Case

 Case-Sensitive

 Case-Insensitive

<button class='btn btn-primary search-btn search-bw' rel='tooltip' title='Search the corpus!'>
					 Search
			</button>

Copy this link

<input type="text"></input>

				<form class='dropdown-padding'>Bookworm was created by Benjamin Schmidt (Department of History, Northeastern), Matt Nicklay, Neva Cherniavsky Durand, Martin Camacho, and
					Erez Lieberman Aiden at the Cultural Observatory. It enables you to visually explore lexical trends.
					Bookworm is hosted through the generous support of the Open Science Data Cloud.
					If you use it in an academic publication, please include a link to bookworm.culturomics.org.
				</form>

Export PNG

Export PDF

							<g:plusone size="small" width="10" annotation="none" href="http://bookworm.culturomics.org"></g:plusone>

			<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Find in Texts

«

1

»

				All Metadata

Restrict search to the following texts


text:
package org.neo4j.test;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public abstract class ManagedResource<R> implements TestRule
{
    private R resource;

    public final R getResource()
    {
        R result = this.resource;
        if ( result == null )
        {
            throw new IllegalStateException( "Resource is not started." );
        }
        return result;
    }

    protected abstract R createResource( TargetDirectory.TestDirectory dir ) throws Exception;

    protected abstract void disposeResource( R resource );

    @Override
    public final Statement apply( final Statement base, Description description )
    {
        final TargetDirectory.TestDirectory dir = TargetDirectory.testDirForTest( description.getTestClass() );
        return dir.apply( new Statement()
        {
            @Override
            public void evaluate() throws Throwable
            {
                resource = createResource( dir );
                try
                {
                    base.evaluate();
                }
                finally
                {
                    R waste = resource;
                    resource = null;
                    disposeResource( waste );
                }
            }
        }, description );
    }
}


text:
{-# Language GADTs, DeriveFunctor #-}

module Music (

    Music(..),
    Note,
    Pitch(..),
    PitchEvent,
    events

  ) where

import Midi.TimeSet
import GHC.Word
import Control.Arrow (first, second, (>>>))

data Music a where
  Melody   :: [a]         -> Music a
  Chord    :: [a]         -> Music a
  Lone     :: a           -> Music a
  Pair     :: (a, a)      -> Music a
  Tripple  :: (a, a, a)   -> Music a
  Parallel :: [Music a]   -> Music a
  Sequence :: [Music a]   -> Music a

  Sharp    :: Music a     -> Music a
  Flat     :: Music a     -> Music a

  Higher   :: Word8       -> Music a -> Music a
  Longer   :: Integer     -> Music a -> Music a

  A_       :: Music a
  A        :: Music a
  A'       :: Music a
  B_       :: Music a
  B        :: Music a
  C        :: Music a
  C'       :: Music a
  D_       :: Music a
  D        :: Music a
  D'       :: Music a
  E_       :: Music a
  E        :: Music a
  F        :: Music a
  F'       :: Music a
  G_       :: Music a
  G        :: Music a
  G'       :: Music a

  deriving (Read, Show, Eq, Ord, Functor)

data SimpleMusic a = Seq [SimpleMusic a] | Par [SimpleMusic a] | Mel [a]

type Note       = (Integer, Word8) -- Length, Pitch
data Pitch      = On Word8    | Off Word8 deriving (Ord, Eq, Show)
type PitchEvent = (Integer, Pitch)

simplify :: Music Note -> SimpleMusic Note

simplify (Melody m)         = Mel m
simplify (Chord  c)         = Par $ map (Mel . return) c
simplify (Lone   n)         = Mel [n]
simplify (Pair (a,b))       = Par [Mel [a], Mel [b]]
simplify (Tripple (a,b,c))  = Par [Mel [a], Mel [b], Mel [c]]
simplify (Parallel m)       = Par $ map simplify m
simplify (Sequence m)       = Seq $ map simplify m
simplify (Sharp m)          = raise 1 $ simplify m
simplify (Flat m)           = raise (-1) $ simplify m
simplify (Higher n m)       = raise n $ simplify m
simplify (Longer n m)       = lengthen n $ simplify m

simplify A_ = pitch (-4)
simplify A  = pitch (-3)
simplify A' = pitch (-2)
simplify B_ = pitch (-2)
simplify B  = pitch (-1)
simplify C  = pitch 0
simplify C' = pitch 1
simplify D_ = pitch 1
simplify D  = pitch 2
simplify D' = pitch 3
simplify E_ = pitch 3
simplify E  = pitch 4
simplify F  = pitch 5
simplify F' = pitch 6
simplify G_ = pitch 6
simplify G  = pitch 7
simplify G' = pitch 9

pitch :: Word8 -> SimpleMusic Note
pitch n = Mel [(1, n+60)] -- Don't start pitches at 0...

pitchEventify :: Note -> [PitchEvent]
pitchEventify (a,b) = [(0, On b), (a, Off b)]

musicEventify :: SimpleMusic Note -> SimpleMusic PitchEvent
musicEventify (Seq m) = Seq . map musicEventify $ m
musicEventify (Par m) = Par . map musicEventify $ m
musicEventify (Mel m) = Mel $ concatMap pitchEventify m

raise :: Word8 -> SimpleMusic Note -> SimpleMusic Note
raise n (Seq m) = Seq . map (raise n) $ m
raise n (Par m) = Par . map (raise n) $ m
raise n (Mel m) = Mel $ map (second (+n)) m

lengthen :: Integer -> SimpleMusic Note -> SimpleMusic Note
lengthen n (Seq m) = Seq . map (lengthen n) $ m
lengthen n (Par m) = Par . map (lengthen n) $ m
lengthen n (Mel m) = Mel $ map (first (*n)) m

sequentialize :: SimpleMusic PitchEvent -> [PitchEvent]
sequentialize (Seq m) = concatMap sequentialize m
sequentialize (Par m) = normalize $ map sequentialize m
sequentialize (Mel m) = m

-- timing

events :: Music Note -> [PitchEvent]
events = simplify >>> musicEventify >>> sequentialize


text:
from io import open
import os
from setuptools import setup

with open(os.path.join(BASE_DIR, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='pptx-canvas',
    version='0.1',
    description='Canvas-like interface for drawing in PPTX files using Python',
    keywords='powerpoint ppt pptx office open xml',
    long_description=long_description,
    author='Elliott Carlson',
    author_email='x@sublim.nl',
    url='http://github.com/elliottcarlson/pptx-canvas',
    license='MIT',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=['colour','lxml','Pillow','python-pptx','XlsxWriter'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Office/Business :: Office Suites',
        'Topic :: Software Development :: Libraries'
    ]
)


text:
''' Simple lirc config files sanity tool. '''

import glob
import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

def main():
    configs = {}
    for path in glob.glob('*.conf'):
        with open(path) as f:
            cf = yaml.load(f.read(), Loader = Loader)
        if cf['config']['id'] + '.conf' != path:
            print( "Id: %s, path: %s" % (cf['config']['id'], path))
        configs[cf['config']['id']] = cf['config']
    for config in configs:
        if 'supports' in config:
            if config['supports'] == 'lirccode':
                if not 'lircd_conf' in config:
                    print('bad config:' + config['id'])
    for l in configs.keys():
        if not 'menu' in configs[l]:
            print("No menu: " + l)

if __name__ == '__main__':
    main()

# vim: set expandtab ts=4 sw=4:


text:
@extends('blog::admin.index')

@section('title')
    @lang('blog::blog.title.index')
@stop

@section('content')

            @lang('blog::admin.title.posts')

                     @lang('blog::admin.posts.action.create')

                        @lang('blog::admin.posts.field.id')
                        @lang('blog::admin.posts.field.slug')
                        @lang('blog::admin.posts.field.author')
                        @lang('blog::admin.posts.field.created_at')
                        @lang('blog::admin.posts.field.published_at')
                        @lang('blog::admin.posts.field.concealed_at')

                    @foreach($posts as $post)

                            {{ $post->id }}
                            {{ $post->slug }}  $post->slug]) }}" target="_blank">
                            @userbadge($post->user)
                            {{ $post->created_at ? $post->created_at->diffForHumans() : '-' }}
                            {{ $post->published_at ? $post->published_at->diffForHumans() : '-' }}
                            {{ $post->concealed_at ? $post->concealed_at->diffForHumans() : '-' }}

                                {!! Form::open([
                                    'class' => 'form-inline',
                                    'data-remote',
                                    'data-remote-success-message' => trans('blog::admin.posts.delete.success'),
                                    'data-remote-error-message' => trans('blog::admin.posts.delete.error'),
                                    'route' => ['blog.admin.posts.destroy', $post->id],
                                    'method' => 'DELETE'])
                                !!}
                                id) }}"> @lang('blog::admin.posts.action.edit')
                                <button class="btn btn-sm btn-danger" type="submit" data-confirm="#modal"> @lang('blog::admin.posts.action.destroy')</button>
                                {!! Form::close() !!}

                    @endforeach

            @include('blog::admin.partials.pagination', [ 'items' => $posts ])

    @include('blog::admin.posts.modal')
@stop


text:
using Laurus.UiTest;
using Laurus.UiTest.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Laurus.UiTest.Selenium.IntegrationTest
{
	public class ScreenshotAspect : IPageAspect
	{
		public ScreenshotAspect(ITest test)
		{
			_test = test;
		}

		public void BeforeControl(Type t)
		{
			_test.TakeScreenshot(Guid.NewGuid().ToString() + ".png");
		}

		public void AfterControl(Type pageType)
		{
		}

		private readonly ITest _test;
	}
}


text:
echo "Setting up version " $1
echo "You still need to use Versions to send to WP.org"

function deploy () {
	git checkout master
	rm -rf ~/Sites/timber/vendor
	cd ..
	git clone git@github.com:Upstatement/timber-starter-theme.git
	rm -rf ~/Sites/timber/timber-starter-theme/.git
	composer install --no-dev
	rm -rf ~/Sites/timber/vendor/upstatement/routes/.git
	cd ~/Sites/timber-wp
	mkdir tags/$1

	cp -r ~/Sites/timber/lib tags/$1/lib
	cp -r ~/Sites/timber/timber-starter-theme tags/$1/timber-starter-theme
	cp -r ~/Sites/timber/vendor tags/$1/vendor
	cp ~/Sites/timber/LICENSE.txt tags/$1/LICENSE.txt
	cp ~/Sites/timber/README.md tags/$1/README.md
	cp ~/Sites/timber/readme.txt tags/$1/readme.txt
	cp ~/Sites/timber/timber.php tags/$1/timber.php
	svn add tags/$1
	cd tags/$1
	svn commit -m "updating to $1"
	cd ~/Sites/timber-wp/trunk
	svn commit -m "updating to $1" readme.txt
	svn commit -m "updating to $1" README.md
	svn commit -m "updating to $1" timber.php
}

deploy $1


text:
using autofill::form_util::WebFormControlElementToFormField;
using blink::WebFormControlElement;
using blink::WebInputElement;
using blink::WebString;
using blink::WebVector;

namespace autofill {

namespace {

// The words that frequently appear in attribute values of signin forms.
const char* const kSigninTextFeatures[] = {"signin", "login", "logon", "auth"};
constexpr size_t kNumberOfSigninFeatures = arraysize(kSigninTextFeatures);

// The words that frequently appear in attribute values of signup forms.
const char* const kSignupTextFeatures[] = {"signup", "regist", "creat"};
constexpr size_t kNumberOfSignupFeatures = arraysize(kSignupTextFeatures);

// The words that frequently appear in attribute values of captcha elements.
const char* const kCaptchaFeatures[] = {"captcha", "security", "code"};
constexpr size_t kNumberOfCaptchaFeatures = arraysize(kCaptchaFeatures);

// Minimal number of input fields to classify form as signup or change password
// form. If at least one of the listed thresholds is reached or exceeded, the
// form is classified as a form where password generation should be available.
constexpr size_t MINIMAL_NUMBER_OF_TEXT_FIELDS = 2;
constexpr size_t MINIMAL_NUMBER_OF_PASSWORD_FIELDS = 2;
constexpr size_t MINIMAL_NUMBER_OF_CHECKBOX_FIELDS = 3;
constexpr size_t MINIMAL_NUMBER_OF_OTHER_FIELDS = 2;

// Removes some characters from attribute value.
void ClearAttributeValue(std::string* value) {
  value->erase(std::remove_if(value->begin(), value->end(),
                              [](char x) { return x == '-' || x == '_'; }),
               value->end());
}

// Find |features| in |element|'s attribute values. Returns true if at least one
// text feature was found.
bool FindTextFeaturesForClass(const blink::WebElement& element,
                              const char* const features[],
                              size_t number_of_features) {
  DCHECK(features);

  for (unsigned i = 0; i < element.attributeCount(); ++i) {
    std::string filtered_value =
        base::ToLowerASCII(element.attributeValue(i).utf8());
    ClearAttributeValue(&filtered_value);

    if (filtered_value.empty())
      continue;
    for (size_t j = 0; j < number_of_features; ++j) {
      if (filtered_value.find(features[j]) != std::string::npos)
        return true;
    }
  }
  return false;
}

// Returns true if at least one captcha feature was found in |element|'s
// attribute values.
bool IsCaptchaInput(const blink::WebInputElement& element) {
  return FindTextFeaturesForClass(element, kCaptchaFeatures,
                                  kNumberOfCaptchaFeatures);
}

// Finds <img>'s inside |form| and checks if <img>'s attributes contains captcha
// text features. Returns true, if at least one occurrence was found.
bool FindCaptchaInImgElements(const blink::WebElement& form,
                              bool ingnore_invisible) {
  CR_DEFINE_STATIC_LOCAL(WebString, kImageTag, ("img"));

  blink::WebElementCollection img_elements =
      form.getElementsByHTMLTagName(kImageTag);
  for (blink::WebElement element = img_elements.firstItem(); !element.isNull();
       element = img_elements.nextItem()) {
    if (ingnore_invisible && !form_util::IsWebNodeVisible(element))
      continue;
    if (FindTextFeaturesForClass(element, kCaptchaFeatures,
                                 kNumberOfCaptchaFeatures)) {
      return true;
    }
  }
  return false;
}

// Finds signin and signup features in |element|'s attribute values. Sets to
// true |found_signin_text_features| or |found_signup_text_features| if
// appropriate features were found.
void FindTextFeaturesInElement(const blink::WebElement& element,
                               bool* found_signin_text_features,
                               bool* found_signup_text_features) {
  DCHECK(found_signin_text_features);
  DCHECK(found_signup_text_features);

  if (!*found_signin_text_features) {
    *found_signin_text_features = FindTextFeaturesForClass(
        element, kSigninTextFeatures, kNumberOfSigninFeatures);
  }
  if (!*found_signup_text_features) {
    *found_signup_text_features = FindTextFeaturesForClass(
        element, kSignupTextFeatures, kNumberOfSignupFeatures);
  }
}

// Returns true if |element| has type "button" or "image".
bool IsButtonOrImageElement(const WebFormControlElement& element) {
  CR_DEFINE_STATIC_LOCAL(WebString, kButton, ("button"));
  CR_DEFINE_STATIC_LOCAL(WebString, kImage, ("image"));

  return element.formControlType() == kButton ||
         element.formControlType() == kImage;
}

// Returns true if |element| has type "submit".
bool IsSubmitElement(const WebFormControlElement& element) {
  CR_DEFINE_STATIC_LOCAL(WebString, kSubmit, ("submit"));

  return element.formControlType() == kSubmit;
}

// Returns true if |element| has type "hidden";
bool IsHiddenElement(const WebFormControlElement& element) {
  CR_DEFINE_STATIC_LOCAL(WebString, kHidden, ("hidden"));

  return element.formControlType() == kHidden;
}

// Returns true if |element| has type "select-multiple" or "select-one".
bool IsSelectElement(const WebFormControlElement& element) {
  CR_DEFINE_STATIC_LOCAL(WebString, kSelectOne, ("select-one"));
  CR_DEFINE_STATIC_LOCAL(WebString, kSelectMultiple, ("select-multiple"));

  return element.formControlType() == kSelectOne ||
         element.formControlType() == kSelectMultiple;
}

// Return true if |form| contains at least one visible password element.
bool FormContainsVisiblePasswordFields(const blink::WebFormElement& form) {
  WebVector<WebFormControlElement> control_elements;
  form.getFormControlElements(control_elements);
  for (auto& control_element : control_elements) {
    const WebInputElement* input_element = toWebInputElement(&control_element);
    if (!input_element)
      continue;
    if (input_element->isPasswordField() &&
        form_util::IsWebNodeVisible(*input_element)) {
      return true;
    }
  }
  return false;
}

}  // namespace

bool ClassifyFormAndFindGenerationField(const blink::WebFormElement& form,
                                        base::string16* generation_field) {
  DCHECK(generation_field);

  if (form.isNull())
    return false;

  bool ignore_invisible_elements = FormContainsVisiblePasswordFields(form);

  bool found_signin_text_features = false;
  bool found_signup_text_features = false;
  size_t number_of_text_input_fields = 0;
  size_t number_of_password_input_fields = 0;
  size_t number_of_checkbox_input_fields = 0;
  size_t number_of_other_input_fields = 0;
  bool found_captcha =
      FindCaptchaInImgElements(form, ignore_invisible_elements);

  FindTextFeaturesInElement(form, &found_signin_text_features,
                            &found_signup_text_features);

  std::vector<WebInputElement> passwords;
  WebVector<WebFormControlElement> control_elements;
  form.getFormControlElements(control_elements);

  for (const WebFormControlElement& control_element : control_elements) {
    if (IsHiddenElement(control_element))
      continue;
    if (ignore_invisible_elements) {
      if (!form_util::IsWebNodeVisible(control_element))
        continue;
    }

    // If type="button" or "image", skip them, because it might be a link
    // to another form.
    if (IsButtonOrImageElement(control_element))
      continue;

    FindTextFeaturesInElement(control_element, &found_signin_text_features,
                              &found_signup_text_features);

    // Since <select> is not WebInputElement, but WebSelectElement, process
    // them as a special case.
    if (IsSelectElement(control_element)) {
      number_of_other_input_fields++;
    } else {
      const WebInputElement* input_element =
          toWebInputElement(&control_element);
      if (!input_element)
        continue;

      if (input_element->isTextField()) {
        if (input_element->isPasswordField()) {
          ++number_of_password_input_fields;
          passwords.push_back(*input_element);
        } else {
          ++number_of_text_input_fields;
          found_captcha = found_captcha || IsCaptchaInput(*input_element);
        }
      } else {  // Non-text fields.
        if (input_element->isCheckbox())
          ++number_of_checkbox_input_fields;
        else if (!IsSubmitElement(*input_element))
          ++number_of_other_input_fields;
      }
    }
  }

  if (number_of_password_input_fields == 0 ||
      number_of_password_input_fields > 3)
    return false;

  if ((number_of_text_input_fields - found_captcha >=
           MINIMAL_NUMBER_OF_TEXT_FIELDS ||
       number_of_password_input_fields >= MINIMAL_NUMBER_OF_PASSWORD_FIELDS ||
       number_of_checkbox_input_fields >= MINIMAL_NUMBER_OF_CHECKBOX_FIELDS ||
       number_of_other_input_fields >= MINIMAL_NUMBER_OF_OTHER_FIELDS) ||
      (found_signup_text_features && !found_signin_text_features)) {
    WebInputElement password_creation_field;

    // TODO(crbug.com/618309): Improve local classifier to distinguish password
    // creation and password usage fields on the change password forms.
    if (passwords.size() == 3)
      password_creation_field = passwords[1];
    else
      password_creation_field = passwords[0];

    *generation_field = password_creation_field.nameForAutofill();
    return true;
  }
  return false;
}
}


text:
from . import utils
from .path import *
from .pathFinder import *
import copy

class ConnectivityMatrix:
    def __init__(self, graph):
        self._graph = graph
        self._paths = []

        self._nodes = []
        self._initialMatrix = []

        self._matrix = []

        self._rowLabels = []
        self._colLabels = []

        self._sourcesCollapsed = False
        self._targetsCollapsed = False

    def _activateMatrix(self, nodes):

        self._nodes = list(set(nodes))
        for i in range(0, len(self._nodes)):
            row = []
            for j in range(0, len(self._nodes)):
                row.append([])
            self._matrix.append(row)

        for node in self._nodes:
            self._rowLabels.append(utils.getNodeId(node, self._graph))
            self._colLabels.append(utils.getNodeId(node, self._graph))

    def _addPathToMatrix(self, path):
        source = path.nodes[0]
        target = path.nodes[len(path.nodes) - 1]
        assert source in self._nodes and target in self._nodes, 'Found a path that is not in matrix. WTF?'
        self._paths.append(path)
        sourceIndex = self._getNodeIndex(source)
        targetIndex = self._getNodeIndex(target)
        self._matrix[sourceIndex][targetIndex].append(len(self._paths) - 1)

    def _getNodeIndex(self, node):
        return self._nodes.index(node)

    def _getPathAsIndexes(self, path):
        pathIndexes = []
        for i in range(0, len(path.nodes)):
            pathIndexes.append(int(path.nodes[i].id))
            if i < len(path.edges):
                pathIndexes.append(int(path.edges[i].id))
        return pathIndexes

    def _getUsedColIndexes(self):
        usedColIndexes = []
        for i in range(0, len(self._matrix)):
            row = self._matrix[i]
            for j in range(0, len(row)):
                col = row[j]
                if len(col) is not 0 and j not in usedColIndexes:
                    usedColIndexes.append(j)
        return usedColIndexes

    def _getUsedRowIndexes(self):
        usedRowIndexes = []
        for i in range(0, len(self._matrix)):
            row = self._matrix[i]
            for j in range(0, len(row)):
                col = row[j]
                if len(col) is not 0 and i not in usedRowIndexes:
                    usedRowIndexes.append(i)
        return usedRowIndexes

    def activate(self, nodeConstraints, edgeConstraints):
        """
            Create a connectivity matrix for the given path node and edge constraints.

            _matrix[i][j] holds indexes to paths from _nodes[j] to _nodes[i]
            The paths for these indexes can be found in _paths

            :param nodeConstraints - regex of all nodes
            :param edgeConstraints - regex of all edges
        """

        # Matrix is N x N where N is the number of sources and targets.
        sources = utils.getNodesByTypeRegex(nodeConstraints[0], self._graph)
        targets = utils.getNodesByTypeRegex(nodeConstraints[len(nodeConstraints) - 1], self._graph)
        nodes = sources + targets

        self._activateMatrix(nodes)

        # Find paths for each source. Shove them into the matrix.
        for node in sources:
            pathFinder = PathFinder(self._graph)
            pathFinder.findRegexConstrainedPathsFromSource(node, edgeConstraints, nodeConstraints)
            for path in pathFinder.valid:
                self._addPathToMatrix(path)

        # Cache the initial matrix.
        self._initialMatrix = copy.deepcopy(self._matrix)

    def collapseSources(self):
        """
            Updates _matrix s.t. all rows of the same label get collapsed to a single row.
        """
        if self._sourcesCollapsed:
            return

        sourceTypes = utils.getNodesTypes(self._nodes, self._graph)
        newMatrix = []
        newCols = []
        for node in self._nodes:
            newCols.append(utils.getNodeId(node, self._graph))

        for sourceType in sourceTypes:
            newRow = [[] for node in self._nodes]
            for i in range(0, len(self._matrix)):
                rowType = utils.getNodeType(self._nodes[i], self._graph)
                row = self._matrix[i]
                if rowType == sourceType:
                    for j in range(0, len(row)):
                        col = row[j]
                        if len(col) > 0:
                            newRow[j] += col
            newMatrix.append(newRow)

        self._matrix = copy.deepcopy(newMatrix)
        self._colLabels = newCols
        self._rowLabels = sourceTypes

    def collapseTargets(self):
        """
            Updates _matrix s.t. all cols of the same label get collapsed to a single col.
        """

        if self._targetsCollapsed:
            return

        self._targetsCollapsed = True

        targetTypes = utils.getNodesTypes(self._nodes, self._graph)
        newMatrix = []

        # Initialize newMatrix
        for i in range(0, len(self._matrix)):
            newRow = []
            for j in range(0, len(targetTypes)):
                newRow.append([])
            newMatrix.append(newRow)

        # Populate new matrix
        for i in range(0, len(self._matrix)):
            row = self._matrix[i]
            for j in range(0, len(row)):
                col = row[j]
                if len(col) > 0:
                    colType = utils.getNodeType(self._nodes[j], self._graph)
                    colIndex = targetTypes.index(colType)
                    newMatrix[i][colIndex] += col

        self._matrix = copy.deepcopy(newMatrix)
        self._colLabels = targetTypes

    def getAsJsonObject(self, removeEmptyGridCells=False, replaceCellIdsWithIndexes=False):
        newMatrix = []
        rowLabels = []
        colLabels = []
        if replaceCellIdsWithIndexes and (self._targetsCollapsed or self._sourcesCollapsed):
            assert False, "Cannot replace ids with indexes if sources or targets are collapsed"

        if removeEmptyGridCells:
            usedRows = self._getUsedRowIndexes()
            usedCols = self._getUsedColIndexes()
            newMatrix = []
            for i in range(0, len(usedRows)):
                row = []
                for j in range(0, len(usedCols)):
                    row.append([])
                newMatrix.append(row)

            for i in range(0, len(self._matrix)):
                if i in usedRows:
                    newRowIndex = usedRows.index(i)
                    row = self._matrix[i]
                    for j in range(0, len(row)):
                        if j in usedCols:
                            newColIndex = usedCols.index(j)
                            col = row[j]
                            pathList = []
                            for k in range(0, len(col)):
                                pathList.append(self._getPathAsIndexes(self._paths[col[k]]))

                            newMatrix[newRowIndex][newColIndex] = pathList

            for rowIndex in usedRows:
                rowLabels.append(self._rowLabels[rowIndex])

            for colIndex in usedCols:
                colLabels.append(self._colLabels[colIndex])

        else:
            for row in self._matrix:
                newRow = []
                for col in row:
                    pathList = []
                    for k in range(0, len(col)):
                        pathList.append(self._getPathAsIndexes(self._paths[col[k]]))
                    newRow.append(pathList)
                newMatrix.append(newRow)

            rowLabels = self._rowLabels
            colLabels = self._colLabels

        if replaceCellIdsWithIndexes:
            newRowLabels = []
            for label in rowLabels:
                newRowLabels.append(int(utils.getNodeById(int(label), self._graph).id))
            rowLabels = newRowLabels

            newColLabels = []
            for label in colLabels:
                newColLabels.append(int(utils.getNodeById(int(label), self._graph).id))
            colLabels = newColLabels

        jsonObject = {}
        jsonObject['row_labels'] = rowLabels
        jsonObject['col_labels'] = colLabels
        jsonObject['matrix'] = newMatrix

        return jsonObject

    def getPathAt(self, index):
        return self._paths[index]

    def reset(self):
        self._matrix = copy.deepcopy(self._initialMatrix)

        self._rowLabels = []
        self._colLabels = []
        for node in self._nodes:
            self._rowLabels.append(utils.getNodeId(node, self._graph))
            self._colLabels.append(utils.getNodeId(node, self._graph))

        self._targetsCollapsed = False
        self._sourcesCollapsed = False


text:
from pathlib import Path
import re
import sys, os

TMP_SUFFIX = ".brace_cleanup"

def fix_brace_o(a, b):
    """Move any `{`s between the contents of line `a` and line `b` to the start of line `b`.

    :param a: A line of Lean code, ending with `\n'
    :param b: A line of Lean code, ending with `\n'

    :returns: A tuple `(anew, bnew, fix)`, where `anew` and `bnew` are `a` and `b` with corrected brace positions,
    and `fix` is a boolean indicating whether there was a change, i.e. `fix = ((anew, bnew) != (a, b))`.
    """
    astr = a.rstrip()
    if astr == "":
        return a, b, False
    if not astr[-1] == '{':
        return a, b, False
    a = astr[:-1].rstrip() + '\n'
    bstr = b.lstrip()
    indent = len(b) - len(bstr)
    indent = max(indent - 2, 0)
    b = " " * indent + "{ " + bstr
    return a, b, True

def fix_brace_c(a, b):
    """Move any `}`s between the contents of line `a` and line `b` to the end of line `a`.

    :param a: A line of Lean code, ending with `\n'
    :param b: A line of Lean code, ending with `\n'

    :returns: A tuple `(anew, bnew, merge)`, where `anew` and `bnew` are `a` and `b` with corrected brace positions,
    and `merge` is a boolean indicating if the result is a single line, returned in `bnew` (and `anew` can be ignored).
    """
    bstr = b.lstrip()
    if bstr == "":
        return a, b, False
    if not bstr[0] == '}':
        return a, b, False
    return "", a.rstrip() + " " + bstr, True

def fix_brace_pair(a, b):
    """Move any `{`s and `}`s between the contents of line `a` and line `b` to the correct position.

    :param a: A line of Lean code, ending with `\n'
    :param b: A line of Lean code, ending with `\n'

    :returns: A tuple `(anew, bnew, merge)`, where `anew` and `bnew` are `a` and `b` with corrected brace positions,
    and `merge` is a boolean indicating if the result is a single line, returned in `bnew` (and `anew` can be ignored).
    """
    anew, bnew, fix = fix_brace_o(a, b)
    if fix:  # `a` ended with a `{` that got moved to `bnew`, so `fix_brace_c` doesn't have anything to do.
        return anew, bnew, False
    else:
        return fix_brace_c(anew, bnew)

def fix_braces(filename):
    # open files for reading and writing
    fi = Path(filename).open(mode="r", encoding="utf-8", newline='\n')
    fo = Path(filename + TMP_SUFFIX).open(mode="w", encoding="utf-8", newline='\n')
    merge = False  # indicates when `ao` got merged into `bo`, so we can ignore `ao`.
    # read the first line
    ai = fi.readline()
    bo = ai # if there is only one line, the last output line is the first line
    while (bi := fi.readline()):
        ao, bo, merge = fix_brace_pair(ai, bi)
        # prepare for next iteration
        ai = bo
        if not merge:
            fo.write(ao)
    # write the last line
    fo.write(bo)
    # close the files
    fi.close()
    fo.close()
    # move the output file back to the input
    os.rename(filename + TMP_SUFFIX, filename)

for filename in sys.argv[1:]:
    fix_braces(filename)


text:
import * as L from 'leaflet';
import { IGeocoder, GeocodingCallback } from './api';
export interface OpenLocationCodeOptions {
    OpenLocationCode: OpenLocationCodeApi;
    codeLength?: number;
}
export interface OpenLocationCodeApi {
    encode(latitude: number, longitude: number, codeLength?: number): string;
    decode(code: string): CodeArea;
}
export interface CodeArea {
    latitudeLo: number;
    longitudeLo: number;
    latitudeHi: number;
    longitudeHi: number;
    latitudeCenter: number;
    longitudeCenter: number;
    codeLength: number;
}
/**
 * Implementation of the [Plus codes](https://plus.codes/) (formerly OpenLocationCode) (requires [open-location-code](https://www.npmjs.com/package/open-location-code))
 */
export declare class OpenLocationCode implements IGeocoder {
    options: OpenLocationCodeOptions;
    constructor(options?: Partial<OpenLocationCodeOptions>);
    geocode(query: string, cb: GeocodingCallback, context?: any): void;
    reverse(location: L.LatLngLiteral, scale: number, cb: GeocodingCallback, context?: any): void;
}
/**
 * [Class factory method](https://leafletjs.com/reference.html#class-class-factories) for {@link OpenLocationCode}
 * @param options the options
 */
export declare function openLocationCode(options?: Partial<OpenLocationCodeOptions>): OpenLocationCode;


text:
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "basics/basics.h"
#include "basics/strutils.h"
#include "basics/modinit.h"

TEST(StrUtilsTest, split) {
  std::vector<std::string> tokens;

  const std::string s1("how are you");
  tokens = StrUtils::split(s1, " ");
  EXPECT_EQ(static_cast<size_t>(3), tokens.size());
  EXPECT_EQ("how", tokens.at(0));
  EXPECT_EQ("are", tokens.at(1));
  EXPECT_EQ("you", tokens.at(2));

  const std::string s2("won\'t you be there");
  tokens = StrUtils::split(s2, " ");
  EXPECT_EQ(static_cast<size_t>(4), tokens.size());
  EXPECT_EQ("won\'t", tokens.at(0));
  EXPECT_EQ("you", tokens.at(1));
  EXPECT_EQ("be", tokens.at(2));
  EXPECT_EQ("there", tokens.at(3));

  const std::string s3("how");
  tokens = StrUtils::split(s3, " ");
  EXPECT_EQ(static_cast<size_t>(1), tokens.size());
  EXPECT_EQ("how", tokens.at(0));

  const std::string s4("");
  tokens = StrUtils::split(s4, " ");
  EXPECT_EQ(static_cast<size_t>(0), tokens.size());
}

int main(int argc, char **argv) {
  heron::common::Initialize(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Battery Test: battery-plugging-in-level</title>
<meta name="flags" content="interact">

Description

  This test validates that onlevelchange and level attributes exist and
  are set to correct values, with corresponding events fired,
  when the charger is plugged in.

Preconditions

    The device is unplugged from the charger before this test is run.

    The battery must not be full or reach full capacity before the time the test is run.

      Plug in the charger and wait for all the tests to complete.

      The tests may take long time since the definition of how
      often the levelchange event is fired is left to the implementation.


text:
<?php

/* FDARestautixBundle:Restautix:accueil.html.twig */
class __TwigTemplate_67ea9d45cd42b593eecfcc07a251d259 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("FDARestautixBundle::layout.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'fdarestautix_body' => array($this, 'block_fdarestautix_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "FDARestautixBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_title($context, array $blocks = array())
    {
        echo "Accueil - ";
        $this->displayParentBlock("title", $context, $blocks);
    }

    // line 5
    public function block_fdarestautix_body($context, array $blocks = array())
    {
        // line 6
        echo "
Liste des événements

        ";
        // line 9
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["eventsList"]) ? $context["eventsList"] : $this->getContext($context, "eventsList")));
        $context['_iterated'] = false;
        foreach ($context['_seq'] as $context["_key"] => $context["event"]) {
            // line 10
            echo "

            env, $this->env->getExtension('routing')->getPath("restautix_readEvent", array("id" => $this->getAttribute((isset($context["event"]) ? $context["event"] : $this->getContext($context, "event")), "id"))), "html", null, true);
            echo "\">";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["event"]) ? $context["event"] : $this->getContext($context, "event")), "titre"), "html", null, true);
            echo "
            par ";
            // line 12
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["event"]) ? $context["event"] : $this->getContext($context, "event")), "auteur"), "html", null, true);
            echo ",
            le ";
            // line 13
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["event"]) ? $context["event"] : $this->getContext($context, "event")), "date"), "d/m/Y"), "html", null, true);
            echo "

        ";
            $context['_iterated'] = true;
        }
        if (!$context['_iterated']) {
            // line 16
            echo "
Pas (encore !) d'événements

        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['event'], $context['_parent'], $context['loop']);
        $context = array_merge($_parent, array_intersect_key($context, $_parent));
        // line 18
        echo "

";
    }

    public function getTemplateName()
    {
        return "FDARestautixBundle:Restautix:accueil.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  77 => 18,  70 => 16,  62 => 13,  58 => 12,  52 => 11,  49 => 10,  44 => 9,  39 => 6,  36 => 5,  29 => 3,);
    }
}


text:
'use strict';

const asyncHook = require('../');
const assert = require('assert');

const eventOrder = [];

let throwFlag = null;

asyncHook.addHooks({
  init: function (uid, handle) {
    eventOrder.push(`init#${uid} ${handle.constructor.name}`);
  },
  pre: function (uid) {
    eventOrder.push(`pre#${uid}`);
  },
  post: function (uid, handle, didThrow) {
    throwFlag = didThrow;
    eventOrder.push(`post#${uid}`);
  },
  destroy: function (uid) {
    eventOrder.push(`destroy#${uid}`);
  }
});

asyncHook.enable();

process.once('uncaughtException', function () {
  eventOrder.push('exception');
});

setInterval(function () {
  eventOrder.push('callback');
  throw new Error('error');
});

asyncHook.disable();

process.once('exit', function () {
  assert.strictEqual(throwFlag, true);
  assert.deepEqual(eventOrder, [
    'init#-1 IntervalWrap', 'pre#-1',
    'callback', 'exception',
    'post#-1', 'destroy#-1'
  ]);
});


text:
package com.cardpay.pccredit.manager.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cardpay.pccredit.manager.filter.ManagerRiskWarningFilter;
import com.cardpay.pccredit.manager.web.ManagerRiskWarningForm;
import com.wicresoft.util.annotation.Mapper;

/**
 * ManagerRiskWarningDao类的描述
 *
 * @author 王海东
 * @created on 2014-11-12
 *
 * @version $Id:$
 */
@Mapper
public interface ManagerRiskWarningDao {

	/*
	 * 根据filter查询自己创建的客户经理警示书
	 */
	List<ManagerRiskWarningForm> findCreateManagerRiskWarningByFilter(ManagerRiskWarningFilter filter);
	/*
	 * 根据filter查询分配给自己的客户经理警示书
	 */
	List<ManagerRiskWarningForm> findReciveManagerRiskWarningByFilter(ManagerRiskWarningFilter filter);

	/*
	 * 根据filter查询自己创建以的客户经理警示书数量
	 */
	public int findCreateManagerRiskWarningCountByFilter(ManagerRiskWarningFilter filter);

	/*
	 * 根据filter查询分配给自己的客户经理警示书数量
	 */
	public int findReciveManagerRiskWarningCountByFilter(ManagerRiskWarningFilter filter);

	/*
	 * 根据id修改反馈内容
	 */
	public int updateFeedBackById(@Param("riskId")String riskId,@Param("feedback")String feedback);

}


text:
<HTML>
<HEAD>
</HEAD>
<BODY>

That gonna be help for our application!

</BODY>
</HTML>


text:
<?php

namespace Ftven\Build\Common\Feature;

use Symfony\Component\Process\Process;

/**
 * @author Olivier Hoareau <olivier@phppro.fr>
 */
trait ProcessRunnerTrait
{
    /**
     * @param string      $command
     * @param null|string $workingDirectory
     *
     * @return Process
     */
    protected function createProcess($command, $workingDirectory = null)
    {
        return new Process($command, $workingDirectory);
    }
}


text:
package moe.tristan.easyfxml.samples.button;

import org.springframework.stereotype.Component;

import moe.tristan.easyfxml.api.FxmlComponent;
import moe.tristan.easyfxml.api.FxmlController;
import moe.tristan.easyfxml.api.FxmlFile;
import moe.tristan.easyfxml.model.fxml.NoControllerClass;

@Component
public class ButtonComponent implements FxmlComponent {

    @Override
    public FxmlFile getFile() {
        return () -> "Button.fxml";
    }

    @Override
    public Class<? extends FxmlController> getControllerClass() {
        return NoControllerClass.class;
    }

}


text:
var gulp = require('gulp');
var fs = require('fs');
var path = require('path');
var vulcanize = require('gulp-vulcanize');
var replace = require('gulp-replace');
var rename = require('gulp-rename');
var header = require('gulp-header');

var HEADER_STR = '<!-- Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\
\n\
Licensed under the Apache License, Version 2.0 (the "License");\n\
you may not use this file except in compliance with the License.\n\
You may obtain a copy of the License at\n\
\n\
   http://www.apache.org/licenses/LICENSE-2.0\n\
\n\
Unless required by applicable law or agreed to in writing, software\n\
distributed under the License is distributed on an "AS IS" BASIS,\n\
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\
See the License for the specific language governing permissions and\n\
limitations under the License.\n\
============================================================================\n\
\n\
This file is generated by `gulp` & `vulcanize`. Do not directly change it.\n\
Instead, use `gulp regenerate` to create a new version with your changes.\n\
-->\n\n'

/**
 * Returns a list of non-tensorboard components inside the components
 * directory, i.e. components that don't begin with 'tf-' or 'vz-''.
 */
function getNonTensorBoardComponents() {
  return fs.readdirSync('components')
      .filter(function(file) {
        var prefix = file.slice(0,3);
        return fs.statSync(path.join('components', file)).isDirectory() &&
            prefix !== 'tf-'  && prefix !== 'vz-';
      })
      .map(function(dir) { return '/' + dir + '/'; });
}

var linkRegex = /<link rel="[^"]*" (type="[^"]*" )?href="[^"]*">\n/g;
var scriptRegex = /<script src="[^"]*"><\/script>\n/g;

module.exports = function(overwrite) {
  return function() {
    var suffix = overwrite ? '' : '.OPENSOURCE';
    // Vulcanize TensorBoard without external libraries.
    gulp.src('components/tf-tensorboard/tf-tensorboard.html')
        .pipe(vulcanize({
          inlineScripts: true,
          inlineCss: true,
          stripComments: true,
          excludes: getNonTensorBoardComponents(),
        }))
        // TODO(danmane): Remove this worrisome brittleness when vulcanize
        // fixes https://github.com/Polymer/vulcanize/issues/273
        .pipe(replace(linkRegex, ''))
        .pipe(replace(scriptRegex, ''))
        .pipe(header(HEADER_STR))
        .pipe(rename('tf-tensorboard.html' + suffix))
        .pipe(gulp.dest('./dist'));
  }
}


text:
namespace ui {
class ScopedOleInitializer;
}
#endif

namespace content {

class BrowserMainLoop;
class NotificationServiceImpl;

class BrowserMainRunnerImpl : public BrowserMainRunner {
 public:
  static std::unique_ptr<BrowserMainRunnerImpl> Create();

  BrowserMainRunnerImpl();
  ~BrowserMainRunnerImpl() override;

  // BrowserMainRunner:
  int Initialize(const MainFunctionParams& parameters) override;
#if defined(OS_ANDROID)
  void SynchronouslyFlushStartupTasks() override;
#endif
  int Run() override;
  void Shutdown() override;

 private:
  // True if we have started to initialize the runner.
  bool initialization_started_;

  // True if the runner has been shut down.
  bool is_shutdown_;

  // Prevents execution of ThreadPool tasks from the moment content is
  // entered. Handed off to |main_loop_| later so it can decide when to release
  // worker threads again.
  std::unique_ptr<base::ThreadPoolInstance::ScopedExecutionFence>
      scoped_execution_fence_;

  std::unique_ptr<NotificationServiceImpl> notification_service_;
  std::unique_ptr<BrowserMainLoop> main_loop_;
#if defined(OS_WIN)
  std::unique_ptr<ui::ScopedOleInitializer> ole_initializer_;
#endif

  DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
};

}  // namespace content

#endif  // CONTENT_BROWSER_BROWSER_MAIN_RUNNER_IMPL_H_


text:
package de.jonato.jfxc.controls.combobox;

import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * Use it like a normal ComboBox.
 * Remember that onKeyReleased is used by the class constructor to find the key.
 * @see ComboBox
 */
public class FilterComboBox<T> extends ComboBox<T> {

    private KeyCode lastKey = null;
    private int lastKeyPosition = 0;
    private int i = 0;
    private T first = null;
    private T last = null;
    private boolean reset = false;

    public FilterComboBox(ObservableList<T> items) {
        super(items);
        setOnKeyReleased(e -> findKey(e));
    }

    public FilterComboBox() {
        super();
        setOnKeyReleased(e -> findKey(e));
    }

    protected void findKey(KeyEvent e) {
        if (!e.getCode().isArrowKey()) {
            if (!e.getCode().equals(lastKey)) {
                lastKeyPosition = 0;
            }
            i = 1;
            first = null;
            reset = false;
            for (T s : getItems()) {
                if (s.toString().startsWith(e.getText().toLowerCase()) || s.toString().startsWith(e.getText().toUpperCase())) {
                    if (first == null) {
                        first = s;
                    }
                    getSelectionModel().select(s);
                    reset = s.equals(last);

                    if (i >= lastKeyPosition) {
                        if (reset) {
                            last = first;
                            lastKeyPosition = 0;
                            getSelectionModel().select(first);
                        } else {
                            last = s;
                            lastKeyPosition = i;
                            break;
                        }
                    }
                }
                i++;
            }
            lastKey = e.getCode();
        }
    }
}


text:
package main

import (
	"fmt"

	"github.com/coreos/rkt/store"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/discovery"
	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema/types"
)

func getStoreKeyFromApp(s *store.Store, img string) (string, error) {
	app, err := discovery.NewAppFromString(img)
	if err != nil {
		return "", fmt.Errorf("cannot parse the image name %q: %v", img, err)
	}
	labels, err := types.LabelsFromMap(app.Labels)
	if err != nil {
		return "", fmt.Errorf("invalid labels in the image %q: %v", img, err)
	}
	key, err := s.GetACI(app.Name, labels)
	if err != nil {
		switch err.(type) {
		case store.ACINotFoundError:
			return "", err
		default:
			return "", fmt.Errorf("cannot find image %q: %v", img, err)
		}
	}
	return key, nil
}

func getStoreKeyFromAppOrHash(s *store.Store, input string) (string, error) {
	var key string
	if _, err := types.NewHash(input); err == nil {
		key, err = s.ResolveKey(input)
		if err != nil {
			return "", fmt.Errorf("cannot resolve image ID: %v", err)
		}
	} else {
		key, err = getStoreKeyFromApp(s, input)
		if err != nil {
			return "", fmt.Errorf("cannot find image: %v", err)
		}
	}
	return key, nil
}


text:
module Main where

import System.Exit ( exitSuccess )

import Control.Monad ( when )

import Idris.AbsSyntax
import Idris.REPL
import Idris.Imports
import Idris.Error
import Idris.CmdOptions

import IRTS.System ( getLibFlags, getIdrisLibDir, getIncFlags )

import Util.System ( setupBundledCC )

import Pkg.Package

-- Main program reads command line options, parses the main program, and gets
-- on with the REPL.

main :: IO ()
main = do opts <- runArgParser
          runMain (runIdris opts)

runIdris :: [Opt] -> Idris ()
runIdris opts = do
    runIO setupBundledCC
    when (ShowLoggingCats `elem` opts)  $ runIO showLoggingCats
    when (ShowIncs `elem` opts)         $ runIO showIncs
    when (ShowLibs `elem` opts)         $ runIO showLibs
    when (ShowLibdir `elem` opts)       $ runIO showLibdir
    when (ShowPkgs `elem` opts)         $ runIO showPkgs
    case opt getClient opts of
       []    -> return ()
       (c:_) -> do setVerbose False
                   setQuiet True
                   runIO $ runClient (getPort opts) c
                   runIO exitSuccess
    case opt getPkgCheck opts of
       [] -> return ()
       fs -> do runIO $ mapM_ (checkPkg opts (WarnOnly `elem` opts) True) fs
                runIO exitSuccess
    case opt getPkgClean opts of
       [] -> return ()
       fs -> do runIO $ mapM_ (cleanPkg opts) fs
                runIO exitSuccess
    case opt getPkgMkDoc opts of                -- IdrisDoc
       [] -> return ()
       fs -> do runIO $ mapM_ (documentPkg opts) fs
                runIO exitSuccess
    case opt getPkgTest opts of
       [] -> return ()
       fs -> do runIO $ mapM_ (testPkg opts) fs
                runIO exitSuccess
    case opt getPkg opts of
       [] -> case opt getPkgREPL opts of
                  [] -> idrisMain opts
                  [f] -> replPkg opts f
                  _ -> ifail "Too many packages"
       fs -> runIO $ mapM_ (buildPkg opts (WarnOnly `elem` opts)) fs

showver :: IO b
showver = do putStrLn $ "Idris version " ++ ver
             exitSuccess

showLibs :: IO b
showLibs = do libFlags <- getLibFlags
              putStrLn $ unwords libFlags
              exitSuccess

showLibdir :: IO b
showLibdir = do putStrLn =<< getIdrisLibDir
                exitSuccess

showIncs :: IO b
showIncs = do incFlags <- getIncFlags
              putStrLn $ unwords incFlags
              exitSuccess

-- | List idris packages installed
showPkgs :: IO b
showPkgs = do mapM_ putStrLn =<< installedPackages
              exitSuccess

showLoggingCats :: IO b
showLoggingCats = do
    putStrLn loggingCatsStr
    exitSuccess


text:
layout: post
title:  "Mobile phone"
date:   2019-12-02
excerpt: "The smartphone is the signature artefact of our age"
tag:
- Article Review
comments: false
---

![6-1.jpg](https://i.loli.net/2020/01/09/z5LSROkyBtbCnMD.jpg)

To be honest, my life has been completely hijacked by the mobile phone. When Apple introduced screen time function, I am so surprised to find out that  I use my phone for 8 hours a day on average. Although I really enjoy the convenience brought by mobile phones, Such a long use time is obviously unacceptable. Not to mention that this hasn't counted the time spent on iPad and computer. I aware  that I became a slave of my phone.

There is no doubt that mobile phone strongly changed our way of living. But how we use it or how often we use it is a big question. sometimes when I spend too many time on my phone, I feel very boring. But this is the easiest way to get happiness and satisfaction, which is not real. I even used to play  phones and refused to go for a walk with my parents.

With the rapid development of 5G internet, our lives will inevitably lean towards these screens. Data fee becomes really cheap. There is one more skill list that modern people must master to learn, which is how to balance the time spent on the screen with the time in real life.

Earlier, I tried to reduce the time I use my phone. Now I managed to use 4 hours a day on average. I feel way better. It is really important to drop your phone and fully experience this world. Don't let the phone take up the time that belong to us.


text:
package io.druid.query.lookup;

import com.google.common.collect.ImmutableMap;
import io.druid.query.extraction.MapLookupExtractor;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import javax.annotation.Nullable;
import javax.ws.rs.POST;
import javax.ws.rs.core.Response;
import java.io.InputStream;

public class LookupIntrospectionResourceTest
{

  LookupReferencesManager lookupReferencesManager = EasyMock.createMock(LookupReferencesManager.class);
  LookupExtractorFactory lookupExtractorFactory = EasyMock.createMock(LookupExtractorFactory.class);
  LookupIntrospectHandler lookupIntrospectHandler = EasyMock.createMock(LookupIntrospectHandler.class);

  LookupIntrospectionResource lookupIntrospectionResource = new LookupIntrospectionResource(lookupReferencesManager);

  @Before
  public void setUp()
  {
    EasyMock.expect(lookupReferencesManager.get("lookupId")).andReturn(lookupExtractorFactory).anyTimes();
    EasyMock.expect(lookupReferencesManager.get(EasyMock.anyString())).andReturn(null).anyTimes();
    EasyMock.replay(lookupReferencesManager);
  }
  @Test
  public void testNotImplementedIntrospectLookup()
  {
    EasyMock.expect(lookupExtractorFactory.getIntrospectHandler()).andReturn(null);
    EasyMock.expect(lookupExtractorFactory.get()).andReturn(new MapLookupExtractor(ImmutableMap.<String, String>of(), false)).anyTimes();
    EasyMock.replay(lookupExtractorFactory);
    Assert.assertEquals(Response.status(Response.Status.NOT_FOUND).build().getStatus(), ((Response) lookupIntrospectionResource.introspectLookup("lookupId")).getStatus());
  }

  @Test
  public void testNotExistingLookup()
  {
    Assert.assertEquals(Response.status(Response.Status.NOT_FOUND).build().getStatus(), ((Response) lookupIntrospectionResource.introspectLookup("not there")).getStatus());
  }

  @Test public void testExistingLookup()
  {
    EasyMock.expect(lookupExtractorFactory.getIntrospectHandler()).andReturn(lookupIntrospectHandler);
    EasyMock.expect(lookupExtractorFactory.get()).andReturn(new MapLookupExtractor(ImmutableMap.<String, String>of(), false)).anyTimes();
    EasyMock.replay(lookupExtractorFactory);
    Assert.assertEquals(lookupIntrospectHandler, lookupIntrospectionResource.introspectLookup("lookupId"));
  }
  @Test
  @Ignore
  public void testIntrospection()
  {

    LookupIntrospectHandler lookupIntrospectHandler = new LookupIntrospectHandler()
    {
      @POST
      public Response postMock(InputStream inputStream){
        return Response.ok().build();
      }
    };

    LookupExtractorFactory lookupExtractorFactory1 = new LookupExtractorFactory()
    {
      final LookupExtractor mapLookup = new MapLookupExtractor(ImmutableMap.<String, String>of("key", "value"), true);

      @Override
      public boolean start()
      {
        return true;
      }

      @Override
      public boolean close()
      {
        return true;
      }

      @Override
      public boolean replaces(@Nullable LookupExtractorFactory other)
      {
        return true;
      }

      @Nullable
      @Override
      public LookupIntrospectHandler getIntrospectHandler()
      {
        return null;
      }

      @Override
      public LookupExtractor get()
      {
        return mapLookup;
      }
    };

    LookupIntrospectionResource lookupIntrospectionResource = new LookupIntrospectionResource(lookupReferencesManager);
    EasyMock.expect(lookupReferencesManager.get("lookupId1")).andReturn(lookupExtractorFactory1).anyTimes();
    EasyMock.replay(lookupReferencesManager);

  }
}


text:
**Status**: Tested
**Description**: Mongod 2.0.2
**Maintainer**:       Cloudify
**Maintainer email**: cloudifysource@gigaspaces.com
**Contributors**:    [tamirko](https://github.com/tamirko)
**Homepage**:   [http://www.cloudifysource.org](http://www.cloudifysource.org)
**License**:      Apache 2.0
**Build**: http://repository.cloudifysource.org/org/cloudifysource/2.1.1/gigaspaces-cloudify-2.1.1-ga-b1396-361.zip
**Linux* sudoer permissions**:	Not required
**Windows* Admin permissions**:  Required on Windows 7
**Release Date**: July 1st 2012

Tested on:
--------

* localCloud: Windows 7 and CentOs
* EC2: Ubuntu and CentOs
* OpenStack: CentOs
* Rackspace: CentOs

Synopsis
--------

This folder contains a service recipe for Mongos (Router).

Its default port is 30001, but it can be modified in the mongos-service.properties.


text:
<?php

namespace Qobo\Utils\ModuleConfig\Parser;

use RuntimeException;

class JsonValidationException extends RuntimeException
{

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/umeng_socialize_title_back_bt_normal" android:state_pressed="false" android:state_window_focused="false"/>
    <item android:drawable="@drawable/umeng_socialize_title_back_bt_selected" android:state_pressed="true" android:state_window_focused="true"/>
    <item android:drawable="@drawable/umeng_socialize_title_back_bt_selected" android:state_focused="true"/>

</selector><!-- From: file:/D:/Android/testPalace/miwu/social_sdk_library_project/res/drawable/umeng_socialize_title_back_bt.xml --><!-- From: file:/D:/Android/testPalace/miwu/social_sdk_library_project/build/intermediates/bundles/debug/res/drawable/umeng_socialize_title_back_bt.xml -->


text:
/* tslint:disable:no-magic-numbers */
import 'should';
import * as modelsafe from 'modelsafe';

import { Database } from './database';
import { attr } from './metadata';

/* tslint:disable:completed-docs */
@modelsafe.model()
class BadActor extends modelsafe.Model {
  @attr({ autoIncrement: true })
  @modelsafe.attr(modelsafe.INTEGER, { primary: true })
  @modelsafe.optional
  id: number;

  @modelsafe.attr(modelsafe.STRING)
  name: string;

  @modelsafe.attr(modelsafe.INTEGER)
  age: number;

  @modelsafe.assoc(modelsafe.HAS_ONE, () => BadActor)
  mentee: BadActor;

  @modelsafe.assoc(modelsafe.HAS_ONE, () => BadActor)
  duplicate: BadActor;
}
/* tslint:enable-completed-docs */

let db = new Database('sqlite://root:root@localhost/squell_test', {
  storage: ':memory:',
  logging: !!process.env.LOG_TEST_SQL
});

describe('Database', () => {
  describe('#sync', () => {
    it('should reject duplicate has-one foreign keys', async () => {
      db.define(BadActor);
      // Must throw an exception to succeed
      return db.sync({ force: true }).then(
        () => { throw new Error('Should fail'); },
        () => null);
    });
  });
});


text:
A toolbox for procedural building and positioning of objects in the Unreal Engine.

# TODO

## Sources
* Linear Array
* Radial Array
* Random 3d (w/ minimum spacing, or Poisson)
* Random 2d (w/ minimum spacing, or Poisson)

## Modifiers
* Drop to surface
* Select by distance, with probability
* Select by range, with probability
* Frozen physics

## Outputs
* Static Mesh component
* Combined geometry
* Blueprints
* Existing actors
* Spline points


text:
#import <UIKit/UIKit.h>

#import "PrivacyAlertViewController.h"

NS_ASSUME_NONNULL_BEGIN

/** ViewController for the resolve cloud anchor lobby view. */
@interface ResolveLobbyViewController : PrivacyAlertViewController

@property(nonatomic, strong) IBOutlet UIButton *nicknameButton;
@property(nonatomic, strong) IBOutlet UITableView *nicknameTableView;
@property(nonatomic, strong) IBOutlet UIButton *resolveButton;
@property(nonatomic, strong) IBOutlet UITextField *anchorIdsField;

- (IBAction)nicknameButtonPressed:(id)sender;

- (IBAction)resolveButtonPressed:(id)sender;

@end

NS_ASSUME_NONNULL_END


text:
package org.jetbrains.plugins.scala
package lang
package parser
package parsing
package statements

import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.parser.parsing.builder.ScalaPsiBuilder
import org.jetbrains.plugins.scala.lang.parser.parsing.expressions.{Block, Expr}
import org.jetbrains.plugins.scala.lang.parser.parsing.params.ParamClauses
import org.jetbrains.plugins.scala.lang.parser.parsing.types.Type
import org.jetbrains.plugins.scala.lang.parser.util.ParserPatcher

/**
* @author Alexander Podkhalyuzin
* Date: 13.02.2008
*/

/*
 * FunDef ::= FunSig [':' Type] '=' Expr
 *          | FunSig [nl] '{' Block '}'
 *          | 'this' ParamClause ParamClauses
 *            ('=' ConstrExpr | [nl] ConstrBlock)
 */
object FunDef {

  def parse(builder: ScalaPsiBuilder): Boolean = {
    val faultMarker = builder.mark
    builder.getTokenType match {
      case ScalaTokenTypes.kDEF => builder.advanceLexer()
      case _ =>
        faultMarker.drop()
        return false
    }
    builder.getTokenType match {
      case ScalaTokenTypes.tIDENTIFIER =>
        FunSig parse builder
        builder.getTokenType match {
          case ScalaTokenTypes.tCOLON =>
            builder.advanceLexer() //Ate :
            if (Type.parse(builder)) {
              builder.getTokenType match {
                case ScalaTokenTypes.tASSIGN =>
                  builder.advanceLexer() //Ate =
                  if (Expr.parse(builder)) {
                    faultMarker.drop()
                    true
                  }
                  else {
                    builder error ScalaBundle.message("wrong.expression")
                    faultMarker.drop()
                    true
                  }
                case _ =>
                  faultMarker.rollbackTo()
                  false
              }
            }
            else {
              faultMarker.rollbackTo()
              false
            }
          case ScalaTokenTypes.tASSIGN =>
            builder.advanceLexer() //Ate =
            ParserPatcher getSuitablePatcher builder parse builder
            if (Expr parse builder) {
              faultMarker.drop()
              true
            }
            else {
              builder error ScalaBundle.message("wrong.expression")
              faultMarker.drop()
              true
            }
          case ScalaTokenTypes.tLBRACE =>
            if (builder.twoNewlinesBeforeCurrentToken) {
              faultMarker.rollbackTo()
              return false
            }
            Block.parse(builder, hasBrace = true)
            faultMarker.drop()
            true
          case _ =>
            faultMarker.rollbackTo()
            false
        }
      case ScalaTokenTypes.kTHIS =>
        builder.advanceLexer() //Ate this
        ParamClauses parse(builder, true)
        builder.getTokenType match {
          case ScalaTokenTypes.tASSIGN =>
            builder.advanceLexer() //Ate =
            if (!ConstrExpr.parse(builder)) {
              builder error ScalaBundle.message("wrong.constr.expression")
            }
            faultMarker.drop()
            true
          case _ =>
            if (builder.twoNewlinesBeforeCurrentToken) {
              builder error ScalaBundle.message("constr.block.expected")
              faultMarker.drop()
              return true
            }
            if (!ConstrBlock.parse(builder)) {
              builder error ScalaBundle.message("constr.block.expected")
            }
            faultMarker.drop()
            true
        }
      case _ =>
        faultMarker.rollbackTo()
        false
    }
  }
}


text:
declare namespace com {
  namespace sun {
    namespace source {
      namespace doctree {

        interface AuthorTree extends com.sun.source.doctree.BlockTagTree {
          getName(): java.util.List<com.sun.source.doctree.DocTree>
        }

      }
    }
  }
}


text:
<?php

namespace kalibao\backend\modules\tree\components\tree\crud;

use Yii;
use kalibao\common\components\helpers\Html;
use kalibao\common\components\i18n\I18N;

/**
 * Class ListGridRow
 *
 * @package kalibao\backend\modules\tree\components\tree\crud
 * @version 1.0
 */
class ListGridRow extends \kalibao\common\components\crud\ListGridRow
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // set items
        $this->setItems([
            isset($this->model->treeI18ns[0]) ? $this->model->treeI18ns[0]->label : '',
            isset($this->model->treeI18ns[0]) ? $this->model->treeI18ns[0]->description : '',
            isset($this->model->media) ? ($this->model->media->file != '')
                ?
                $this->fileField($this->model->media->file)
                :
                '' : '',
        ]);
    }

    /**
     * creates a correct field depending on the file type :
     * if the file is a picture, it will be displayed
     * if the file is anything else, a link to the resource will be displayed.
     *
     * @param $file string file to put in the row
     * @return string the file field
     */
    public function fileField($file) {
        $filepath = $this->uploadConfig['kalibao\common\models\media\Media']['file']['baseUrl'] . '/' . $this->model->media->file;
        $text = $file;
        if (in_array(
            strtolower(pathinfo($filepath)['extension']),
            ['jpg', 'png', 'gif', '']))
            $text =  Html::img(
                $filepath,
                [
                    'alt' => isset($this->model->mediaI18ns[0]) ? $this->model->mediaI18ns[0]->title : $file,
                    'height' => '100px',
                    'class' => 'thumbnail center-block'
                ]
            );
        return Html::a(
            $text,
            $filepath,
            [
                'target' => '_blank'
            ]
        );
    }
}