text:
using namespace arangodb;
using namespace arangodb::tests;

class ComputedValuesTest : public ::testing::Test {
 public:
  static void SetUpTestCase() {
    server = std::make_unique<mocks::MockAqlServer>();
  }
  static void TearDownTestCase() { server.reset(); }
  void TearDown() override {
    auto& vocbase = server->getSystemDatabase();
    auto c = vocbase.lookupCollection("test");
    if (c != nullptr) {
      vocbase.dropCollection(c->id(), false, 3.0);
    }
  }

 protected:
  static inline std::unique_ptr<mocks::MockAqlServer> server;
};

TEST_F(ComputedValuesTest, createComputedValuesFromEmptyObject) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  // cannot create ComputedValues from an Object slice
  auto res = ComputedValues::buildInstance(
      vocbase, shardKeys, velocypack::Slice::emptyObjectSlice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromNone) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  // when creating computed values from a None slice, we get no
  // error, but a nullptr back
  auto res = ComputedValues::buildInstance(vocbase, shardKeys,
                                           velocypack::Slice::noneSlice());
  ASSERT_TRUE(res.ok());
  ASSERT_EQ(nullptr, res.get());
}

TEST_F(ComputedValuesTest, createComputedValuesFromEmptyArray) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  // when creating computed values from an empty Array slice, we get no
  // error, but a nullptr back
  auto res = ComputedValues::buildInstance(
      vocbase, shardKeys, velocypack::Slice::emptyArraySlice());
  ASSERT_TRUE(res.ok());
  ASSERT_EQ(nullptr, res.get());
}

TEST_F(ComputedValuesTest, createComputedValuesFromGarbledObject) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("foo", velocypack::Value(true));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectInvalidName) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Slice::emptyArraySlice());
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value("true"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectEmptyName) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value(""));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value("true"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectMissingName) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value("true"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectMissingExpression) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("overwrite", velocypack::Value("true"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectInvalidExpression) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;

  auto expressions = {
      "",
      "RETURN",
      "LET a = 1",
      "LET a = 1 RETURN a",
      "RETURN (RETURN 1)",
      "RETURN (FOR i IN 1..10 RETURN i)",
      "RETURN TOKENS('Lörem ipsüm, DOLOR SIT Ämet.', 'text_de')"};

  for (auto const& expression : expressions) {
    velocypack::Builder b;
    b.openArray();
    b.openObject();
    b.add("name", velocypack::Value("foo"));
    b.add("expression", velocypack::Value(expression));
    b.add("overwrite", velocypack::Value("true"));
    b.close();
    b.close();

    auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
    ASSERT_FALSE(res.ok());
    ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
  }
}

TEST_F(ComputedValuesTest,
       createComputedValuesFromObjectInvalidBindParameters) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;

  auto expressions = {"RETURN @document", "RETURN @foo",
                      "LET a = @doc RETURN a", "LET a = @doc RETURN @doc"};

  for (auto const& expression : expressions) {
    velocypack::Builder b;
    b.openArray();
    b.openObject();
    b.add("name", velocypack::Value("foo"));
    b.add("expression", velocypack::Value(expression));
    b.add("overwrite", velocypack::Value("true"));
    b.close();
    b.close();

    auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
    ASSERT_FALSE(res.ok());
    ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectMissingOverwrite) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesFromObjectSimple) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  {
    velocypack::Builder b;
    cv->toVelocyPack(b);

    ASSERT_TRUE(b.slice().isArray());
    ASSERT_EQ(1, b.slice().length());

    auto s = b.slice().at(0);
    ASSERT_EQ("foo", s.get("name").stringView());
    ASSERT_EQ("RETURN 1", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());

    s = s.get("computeOn");
    ASSERT_TRUE(s.isArray());
    ASSERT_EQ(3, s.length());
    ASSERT_EQ("insert", s[0].stringView());
    ASSERT_EQ("update", s[1].stringView());
    ASSERT_EQ("replace", s[2].stringView());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesInvalidComputeOn) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add("computeOn", velocypack::Value("insert"));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesInvalidComputeOn2) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("test"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesInvalidComputeOn3) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value(""));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesEmptyComputeOn) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add("computeOn", velocypack::Slice::emptyArraySlice());
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnInsert) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN @doc"));
  b.add("overwrite", velocypack::Value(false));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("insert"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_FALSE(cv->mustComputeValuesOnUpdate());
  ASSERT_FALSE(cv->mustComputeValuesOnReplace());

  {
    velocypack::Builder b;
    cv->toVelocyPack(b);

    ASSERT_TRUE(b.slice().isArray());
    ASSERT_EQ(1, b.slice().length());

    auto s = b.slice().at(0);
    ASSERT_EQ("foo", s.get("name").stringView());
    ASSERT_EQ("RETURN @doc", s.get("expression").stringView());
    ASSERT_FALSE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());

    s = s.get("computeOn");
    ASSERT_TRUE(s.isArray());
    ASSERT_EQ(1, s.length());
    ASSERT_EQ("insert", s[0].stringView());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnUpdate) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1 + 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add("keepNull", velocypack::Value(false));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("update"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_FALSE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_FALSE(cv->mustComputeValuesOnReplace());

  {
    velocypack::Builder b;
    cv->toVelocyPack(b);

    ASSERT_TRUE(b.slice().isArray());
    ASSERT_EQ(1, b.slice().length());

    auto s = b.slice().at(0);
    ASSERT_EQ("foo", s.get("name").stringView());
    ASSERT_EQ("RETURN 1 + 1", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_FALSE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());

    s = s.get("computeOn");
    ASSERT_TRUE(s.isArray());
    ASSERT_EQ(1, s.length());
    ASSERT_EQ("update", s[0].stringView());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnReplace) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("a b"));
  b.add("expression", velocypack::Value("RETURN 'testi'"));
  b.add("overwrite", velocypack::Value(true));
  b.add("keepNull", velocypack::Value(false));
  b.add("failOnWarning", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("replace"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_FALSE(cv->mustComputeValuesOnInsert());
  ASSERT_FALSE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  {
    velocypack::Builder b;
    cv->toVelocyPack(b);

    ASSERT_TRUE(b.slice().isArray());
    ASSERT_EQ(1, b.slice().length());

    auto s = b.slice().at(0);
    ASSERT_EQ("a b", s.get("name").stringView());
    ASSERT_EQ("RETURN 'testi'", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_FALSE(s.get("keepNull").getBoolean());
    ASSERT_TRUE(s.get("failOnWarning").getBoolean());

    s = s.get("computeOn");
    ASSERT_TRUE(s.isArray());
    ASSERT_EQ(1, s.length());
    ASSERT_EQ("replace", s[0].stringView());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnMultiple) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("insert"));
  b.close();
  b.close();
  b.openObject();
  b.add("name", velocypack::Value("bar"));
  b.add("expression", velocypack::Value("RETURN 2"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("replace"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_FALSE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  velocypack::Builder bActual;
  cv->toVelocyPack(bActual);

  ASSERT_TRUE(bActual.slice().isArray());
  ASSERT_EQ(2, bActual.slice().length());

  {
    auto s = bActual.slice().at(0);
    ASSERT_EQ("foo", s.get("name").stringView());
    ASSERT_EQ("RETURN 1", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());
  }

  {
    auto s = bActual.slice().at(1);
    ASSERT_EQ("bar", s.get("name").stringView());
    ASSERT_EQ("RETURN 2", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnMultiple2) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;
  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("insert"));
  b.close();
  b.close();
  b.openObject();
  b.add("name", velocypack::Value("bar"));
  b.add("expression", velocypack::Value("RETURN 2"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("replace"));
  b.close();
  b.close();
  b.openObject();
  b.add("name", velocypack::Value("qux"));
  b.add("expression", velocypack::Value("RETURN 3"));
  b.add("overwrite", velocypack::Value(true));
  b.add(velocypack::Value("computeOn"));
  b.openArray();
  b.add(velocypack::Value("update"));
  b.close();
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_TRUE(res.ok());
  auto cv = res.get();
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  velocypack::Builder bActual;
  cv->toVelocyPack(bActual);

  ASSERT_TRUE(bActual.slice().isArray());
  ASSERT_EQ(3, bActual.slice().length());

  {
    auto s = bActual.slice().at(0);
    ASSERT_EQ("foo", s.get("name").stringView());
    ASSERT_EQ("RETURN 1", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());
  }

  {
    auto s = bActual.slice().at(1);
    ASSERT_EQ("bar", s.get("name").stringView());
    ASSERT_EQ("RETURN 2", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());
  }

  {
    auto s = bActual.slice().at(2);
    ASSERT_EQ("qux", s.get("name").stringView());
    ASSERT_EQ("RETURN 3", s.get("expression").stringView());
    ASSERT_TRUE(s.get("overwrite").getBoolean());
    ASSERT_TRUE(s.get("keepNull").getBoolean());
    ASSERT_FALSE(s.get("failOnWarning").getBoolean());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnSystemAttributes) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;

  auto fields = {"_id", "_key", "_rev", "_from", "_to"};

  for (auto const& field : fields) {
    velocypack::Builder b;
    b.openArray();
    b.openObject();
    b.add("name", velocypack::Value(field));
    b.add("expression", velocypack::Value("RETURN 1"));
    b.add("overwrite", velocypack::Value(true));
    b.close();
    b.close();

    auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
    ASSERT_FALSE(res.ok());
    ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesComputeOnShardKeys) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys{"foo", "bar", "baz"};

  for (auto const& field : shardKeys) {
    velocypack::Builder b;
    b.openArray();
    b.openObject();
    b.add("name", velocypack::Value(field));
    b.add("expression", velocypack::Value("RETURN 1"));
    b.add("overwrite", velocypack::Value(true));
    b.close();
    b.close();

    auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
    ASSERT_FALSE(res.ok());
    ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
  }
}

TEST_F(ComputedValuesTest, createComputedValuesDuplicateNames) {
  auto& vocbase = server->getSystemDatabase();

  std::vector<std::string> shardKeys;

  velocypack::Builder b;
  b.openArray();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 1"));
  b.add("overwrite", velocypack::Value(true));
  b.close();
  b.openObject();
  b.add("name", velocypack::Value("foo"));
  b.add("expression", velocypack::Value("RETURN 2"));
  b.add("overwrite", velocypack::Value(true));
  b.close();
  b.close();

  auto res = ComputedValues::buildInstance(vocbase, shardKeys, b.slice());
  ASSERT_FALSE(res.ok());
  ASSERT_EQ(TRI_ERROR_BAD_PARAMETER, res.errorNumber());
}

TEST_F(ComputedValuesTest, createCollectionNoComputedValues) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson("{\"name\":\"test\"}");

  auto c = vocbase.createCollection(b->slice());
  ASSERT_EQ(nullptr, c->computedValues());
}

TEST_F(ComputedValuesTest, createCollectionEmptyComputedValues) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": []}");

  auto c = vocbase.createCollection(b->slice());
  ASSERT_EQ(nullptr, c->computedValues());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesInsertOverwriteTrue) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN 'test'\", \"overwrite\": true}]}");

  auto c = vocbase.createCollection(b->slice());
  auto cv = c->computedValues();
  ASSERT_NE(nullptr, c->computedValues());
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc1 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"abc\"}");
  EXPECT_TRUE(trx.insert("test", doc1->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("test", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());

  auto doc2 = velocypack::Parser::fromJson("{\"_key\":\"test2\"}");
  EXPECT_TRUE(trx.insert("test", doc2->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test2",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("test", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesInsertOverwriteFalse) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN 'test'\", \"overwrite\": false}]}");

  auto c = vocbase.createCollection(b->slice());
  auto cv = c->computedValues();
  ASSERT_NE(nullptr, c->computedValues());
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc1 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"abc\"}");
  EXPECT_TRUE(trx.insert("test", doc1->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("abc", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());
  auto doc2 = velocypack::Parser::fromJson("{\"_key\":\"test2\"}");
  EXPECT_TRUE(trx.insert("test", doc2->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test2",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("test", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesUpdateOverwriteTrue) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN 'update'\", \"overwrite\": true, "
      "\"computeOn\":[\"update\"]}]}");

  auto c = vocbase.createCollection(b->slice());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc1 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"abc\"}");
  EXPECT_TRUE(trx.insert("test", doc1->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("abc", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());

  auto doc2 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"qux\"}");
  EXPECT_TRUE(trx.update("test", doc2->slice(), OperationOptions()).ok());

  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("update", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesUpdateOverwriteFalse) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN 'update'\", \"overwrite\": false, "
      "\"computeOn\":[\"update\"]}]}");

  auto c = vocbase.createCollection(b->slice());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc1 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"abc\"}");
  EXPECT_TRUE(trx.insert("test", doc1->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("abc", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());

  auto doc2 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":\"qux\"}");
  EXPECT_TRUE(trx.update("test", doc2->slice(), OperationOptions()).ok());

  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_EQ("qux", doc.get("attr").stringView());
                       return true;
                     })
                  .ok());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesFailOnWarningStatic) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN 1 / 0\", \"overwrite\": true, "
      "\"failOnWarning\": true}]}");

  auto c = vocbase.createCollection(b->slice());
  auto cv = c->computedValues();
  ASSERT_EQ(nullptr, c->computedValues());
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesFailOnWarningDynamic) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN @doc.value / 0\", \"overwrite\": true, "
      "\"failOnWarning\": true}]}");

  auto c = vocbase.createCollection(b->slice());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc = velocypack::Parser::fromJson("{\"value\":42}");
  EXPECT_THROW({ trx.insert("test", doc->slice(), OperationOptions()); },
               basics::Exception);
}

TEST_F(ComputedValuesTest, createCollectionComputedValuesInvalidValuesDynamic) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"value1\", "
      "\"expression\":\"RETURN @doc.value / 0\", \"overwrite\": true, "
      "\"failOnWarning\": false}]}");

  auto c = vocbase.createCollection(b->slice());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc = velocypack::Parser::fromJson(
      "{\"_key\":\"test\", \"value1\":42, \"value2\":23}");
  EXPECT_TRUE(trx.insert("test", doc->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_TRUE(doc.get("value1").isNull());
                       EXPECT_EQ(23, doc.get("value2").getNumber<int>());
                       return true;
                     })
                  .ok());
}

TEST_F(ComputedValuesTest, insertKeepNullTrue) {
  auto& vocbase = server->getSystemDatabase();
  auto b = velocypack::Parser::fromJson(
      "{\"name\":\"test\", \"computedValues\": [{\"name\":\"attr\", "
      "\"expression\":\"RETURN @doc.value ?: null\", \"overwrite\": true, "
      "\"keepNull\": true}]}");

  auto c = vocbase.createCollection(b->slice());
  auto cv = c->computedValues();
  ASSERT_NE(nullptr, c->computedValues());
  ASSERT_TRUE(cv->mustComputeValuesOnInsert());
  ASSERT_TRUE(cv->mustComputeValuesOnUpdate());
  ASSERT_TRUE(cv->mustComputeValuesOnReplace());

  std::vector<std::string> const EMPTY;
  std::vector<std::string> collections{"test"};
  transaction::Methods trx(transaction::StandaloneContext::Create(vocbase),
                           EMPTY, collections, EMPTY, transaction::Options());

  EXPECT_TRUE(trx.begin().ok());
  auto doc1 =
      velocypack::Parser::fromJson("{\"_key\":\"test1\", \"attr\":null}");
  EXPECT_TRUE(trx.insert("test", doc1->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test1",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_TRUE(doc.get("attr").isNull());
                       return true;
                     })
                  .ok());
  auto doc2 = velocypack::Parser::fromJson(
      "{\"_key\":\"test2\", \"attr\":null, \"value\": null}");
  EXPECT_TRUE(trx.insert("test", doc2->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test2",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_TRUE(doc.get("attr").isNull());
                       return true;
                     })
                  .ok());
  auto doc3 = velocypack::Parser::fromJson(
      "{\"_key\":\"test3\", \"attr\":null, \"value\": 1}");
  EXPECT_TRUE(trx.insert("test", doc3->slice(), OperationOptions()).ok());
  EXPECT_TRUE(trx.documentFastPathLocal(
                     "test", "test3",
                     [&](LocalDocumentId const& token, velocypack::Slice doc) {
                       EXPECT_FALSE(doc.get("attr").isNull());
                       EXPECT_EQ(1, doc.get("attr").getNumber<int>());
                       return true;
                     })
                  .ok());
}


text:
using SQLite4Unity3d;

namespace Ashram.Bhajans.Database.Tables
{
    /// <summary>
    /// @author Mayank Grover
    /// </summary>

    [Table("categories")]
    public class TableCategories
    {
        [PrimaryKey, Column("id")]
        public int Id { get; set; }

        [Column("category_name")]
        public string Name { get; set; }

        public override string ToString()
        {
            return string.Format("[Category] {0}: {1}", Id, Name);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Samples for bmr client.
"""

import logging
import os
import sys
import time

file_path = os.path.normpath(os.path.dirname(__file__))
sys.path.append(file_path + '/../../')

import bmr_sample_conf
from baidubce.services.bmr import bmr_client as bmr
from baidubce import exception as ex

logging.basicConfig(level=logging.DEBUG, filename='./bmr_sample.log', filemode='w')
LOG = logging.getLogger(__name__)
CONF = bmr_sample_conf

def wait_for_cluster_ready(bmr_client, cluster_id):
    """
    wait for the cluster to be active.
    """
    try:
        retry_time = 0
        status = None
        while retry_time <= CONF.check_cluster_max_retry_time:
            response = bmr_client.get_cluster(new_cluster_id)
            status = response.status.state
            LOG.debug('check cluster %s: status %s' % (new_cluster_id, status))
            if status == 'Waiting':
                break
            LOG.debug('wait for cluster getting ready. at %d retry time.' % retry_time)
            retry_time += 1
            time.sleep(CONF.check_cluster_interval_sec)
    except ex.BceHttpClientError as e:
        if isinstance(e.last_error, ex.BceServerError):
            LOG.error('get_cluster failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('get_cluster failed. Unknown exception: %s' % e)

    if retry_time > CONF.check_cluster_max_retry_time or status is None:
        LOG.error('check cluster status failed. Skip following requests.')
        sys.exit(1)

if __name__ == '__main__':
    bmr_client = bmr.BmrClient(CONF.config)
    try:
        # list clusters
        LOG.debug('\n\n\nSample 1: LIST CLUSTERS\n\n\n')
        response = bmr_client.list_clusters(max_keys=5)
        print response.is_truncated, response.next_marker
        LOG.debug('list total %s clusters' % len(response.clusters))
        for cluster in response.clusters:
            LOG.debug('cluster: %s' % cluster)

        page = 1
        next_marker = None
        max_keys = 5
        is_truncated = True
        while is_truncated:
            response = bmr_client.list_clusters(marker=next_marker, max_keys=max_keys)
            LOG.debug('list %s clusters on Page %s' % (len(response.clusters), page))
            page += 1
            is_truncated = response.is_truncated
            next_marker = response.next_marker

        LOG.debug('\n\n\nSample 2: CREATE CLUSTER\n\n\n')
        new_cluster_id = None
        response = bmr_client.create_cluster(
            image_type='hadoop',
            image_version='0.1.0',
            instance_groups=[
                bmr.instance_group(
                    group_type='Master',
                    instance_type='g.small',
                    instance_count=1,
                    name='ig-master'
                ),
                bmr.instance_group(
                    group_type='Core',
                    instance_type='g.small',
                    instance_count=2,
                    name='ig-core'
                )
            ],
            applications=[
                bmr.application(name='hive', version='0.13.0'),
                bmr.application(name='pig', version='0.11.0'),
                bmr.application(name='hbase', version='0.98.0',
                                properties={'backupLocation': 'bos://test/hbase_backup',
                                            'backupStartDateTime': '2015-08-18T23:00:00Z',
                                            'backupEnabled': 'true',
                                            'backupIntervalInMinutes': 300})
            ],
            auto_terminate=False,
            log_uri='bos://test01/cluster_logs/',
            name='python-sdk',
            steps=[
                bmr.step(
                    step_type='Java',
                    action_on_failure='Continue',
                    properties=bmr.java_step_properties(
                        'bos://bmr/samples/mapreduce/libs/hadoop-mapreduce-examples.jar',
                        'org.apache.hadoop.examples.WordCount',
                        'bos://bmr/samples/mapreduce/wordcount/hamlet.txt bos://test/output'
                    ),
                    name='sdk-job-00'
                )
            ])
        LOG.debug('create cluster response: %s' % response)
        new_cluster_id = response.cluster_id

        if new_cluster_id is None:
            LOG.error('failed to create cluster. Skip following requests.')
            sys.exit(1)

        # get cluster
        LOG.debug('\n\n\nSample 3: GET CLUSTER\n\n\n')
        response = bmr_client.get_cluster(new_cluster_id)
        status = response.status.state
        LOG.debug('check cluster %s: status %s' % (new_cluster_id, status))
        # wait for the cluster getting ready, then add steps to the cluster.
        wait_for_cluster_ready(bmr_client, new_cluster_id)

        # add steps
        LOG.debug('\n\n\nSample 4: ADD STEPS\n\n\n')

        steps=[
                bmr.step(
                    'Java',
                    'Continue',
                    bmr.java_step_properties(
                        'bos://benchmark/hadoop/hadoop-mapreduce-examples.jar',
                        'org.apache.hadoop.examples.WordCount',
                        'bos://helloworld/input/install.log bos://tester01/sdk/output_java/out1'
                    ),
                    'sdk-job-01'
                ),
                bmr.step(
                    'Streaming',
                    'Continue',
                    bmr.streaming_step_properties(
                        'bos://helloworld/input/install.log',
                        'bos://test/sdk/output_streaming/out1',
                        'cat'
                    ),
                    'sdk-job-02'
                ),
                bmr.step(
                    'Hive',
                    'Continue',
                    bmr.hive_step_properties(
                        'bos://chy3/hive/hql/hive_src.hql',
                        '--hivevar LOCAT=bos://chy3/hive/tables/src',
                        'bos://chy3/hive/data/hive_src.data',
                        'bos://tester01/sdk/output_hive/out1'
                    ),
                    'sdk-job-03'
                ),
                bmr.step(
                    'Pig',
                    'Continue',
                    bmr.pig_step_properties(
                        'bos://chy3/pig/script/pig_grep.pig',
                        input='bos://chy3/pig/data/pig_grep.data',
                        output='bos://tester01/sdk/output_pig/out1'
                    ),
                    'sdk-job-04'
                )
            ]
        response = bmr_client.add_steps(
            cluster_id=new_cluster_id,
            steps=steps
        )
        LOG.debug('add steps response: %s' % response)

        # list steps
        LOG.debug('\n\n\nSample 5: LIST STEPS\n\n\n')
        response = bmr_client.list_steps(new_cluster_id, max_keys=50)
        LOG.debug('list steps response: %s' % response)

        # get step
        steps = response.steps
        if steps is not None and len(steps) > 0:
            LOG.debug('\n\n\nSample 6: GET STEP\n\n\n')
            step_id = steps[0].id
            response = bmr_client.get_step(new_cluster_id, step_id)
            LOG.debug('get step response: %s' % response)

        # terminate cluster
        LOG.debug('\n\n\nSample 7: TERMINATE CLUSTER\n\n\n')
        response = bmr_client.terminate_cluster(new_cluster_id)
        LOG.debug('terminate cluster %s: status %s' % (new_cluster_id, response.status))
    except ex.BceHttpClientError as e:
        if isinstance(e.last_error, ex.BceServerError):
            LOG.error('send request failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('send request failed. Unknown exception: %s' % e)


text:
package com.kpw.providers;

import android.app.Activity;
import android.os.Bundle;
import java.security.Provider;
import java.security.Security;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);

        Provider[] providers = Security.getProviders();
        for(int i = 0; i < providers.length; i++){
        	tv.setText(tv.getText() + " Provider " + (i + 1) + " [" + providers[i].getName() + " " + providers[i].getVersion() + "] ");
        	tv.setText(tv.getText() + " Info: " + providers[i].getInfo());
        }
        setContentView(tv);
    }
}


text:
wuphf
=====

social share service


text:
config = {}
config['batch_size'] = 50 #number of samples taken per each update
config['hidden_size'] = 128 # number of hidden units per layer
config['num_layers'] = 2
config['learning_rate'] = 0.002
config['learning_rate_decay'] = 0.97 # set to 0 to not decay learning

config['decay_rate'] = 0.95
config['step_clipping'] = 1.0
config['dropout'] = 0

config['model'] = 'gru'  # 'rnn' or 'gru' 'lstm'
config['nepochs'] = 1000

config['seq_length'] = 50
config['hdf5_file'] = 'input.hdf5'
config['source_file'] = 'post.txt'
config['target_file'] = 'cmnt.txt'
config['train_size'] = 0.95
config['save_path'] = '{0}_best.pkl'.format(config['model'])
config['load_path'] = '{0}_saved.pkl'.format(config['model'])
config['last_path'] = '{0}_last.pkl'.format(config['model'])


text:
<!DOCTYPE html>

		<title>three.js webgl - geometry - terrain</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

Generating world...

three.js - webgl terrain raycasting demo


text:
package io.reactivesw.catalog.product.application.model.mapper;

import io.reactivesw.catalog.product.application.model.Product;
import io.reactivesw.catalog.product.application.model.ProductDraft;
import io.reactivesw.catalog.product.domain.entity.ProductEntity;
import io.reactivesw.catalog.producttype.application.model.mapper.ProductTypeMapper;
import io.reactivesw.catalog.taxcategory.application.model.mapper.TaxCategoryMapper;

/**
 * Created by Davis on 16/12/14.
 */
public final class ProductMapper {

  /**
   * convert ProductDraft to ProductEntity.
   *
   * @param model the ProductDraft
   * @return the ProductEntity
   */
  public static ProductEntity modelToEntity(ProductDraft model) {
    ProductEntity entity = new ProductEntity();

    entity.setKey(model.getKey());
    if (model.getState() != null) {
      entity.setState(model.getState().getId());
    }
    entity.setProductType(model.getProductType().getId());
    if (model.getTaxCategory() != null) {
      entity.setTaxCategory(model.getTaxCategory().getId());
    }
    entity.setMasterData(ProductCatalogDataMapper.modelToEntity(model));

    return entity;
  }

  /**
   * convert ProductEntity to Product.
   *
   * @param entity the ProductEntity
   * @return the Product
   */
  public static Product entityToModel(ProductEntity entity) {
    Product model = new Product();

    model.setCreatedAt(entity.getCreatedAt());
    model.setLastModifiedAt(entity.getLastModifiedAt());
    model.setId(entity.getId());
    model.setKey(entity.getKey());
    model.setVersion(entity.getVersion());
    model.setTaxCategory(TaxCategoryMapper.entityToReference(entity.getTaxCategory()));
    model.setProductType(ProductTypeMapper.entityToReference(entity.getProductType()));
//    model.setState(entity.getState());
//    model.setReviewRatingStatistics();
    model.setMasterData(ProductCatalogDataMapper.entityToModel(entity.getMasterData()));

    return model;
  }
}


text:
	<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  	<link rel="stylesheet" href="<?= base_url()?>assets/css/reserva/filtrar.css" type="text/css">

	<meta charset="utf-8">

	<fieldset>

Filtrado

		Categoría
		<select name="categoria" id="categoria">
			<option value="todas" selected>Todas</option>
			<?php foreach ($categorias as $categoria):?>
				<?php foreach($categoria as $categ=>$nombre): ?>
					<option value="<?= $nombre ?>"><?= $nombre ?></option>
			<?php endforeach; ?>
		<?php endforeach;?>
		</select>

        Red <input type="checkbox" name="red" id="red" />

		Proyector <input type="checkbox" name="proyector" id="proyector" />

  			Número de equipos:
  			<input type="text" id="equipos" name="equipos" readonly style="border:0; color:#f6931f; font-weight:bold;">

  			Capacidad del aula:
  			<input type="text" id="capacidad" name="capacidad" readonly style="border:0; color:#f6931f; font-weight:bold;">

        <input type="submit" value="Enviar" onclick="verOR()" />

	</fieldset>

Aulas disponibles


text:
package com.github.czyzby.lml.uedi.assets;

import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.github.czyzby.lml.uedi.assets.impl.AbstractAssetProvider;
import com.github.czyzby.lml.uedi.assets.impl.InjectingAssetManager;

/** Provides {@link BitmapFont} instances.
 *
 * @author MJ */
public class BitmapFontProvider extends AbstractAssetProvider<BitmapFont> {
    public static final String[] EXTENSIONS = new String[] { "fnt" };

    /** @param assetManager will be used to load the assets. */
    public BitmapFontProvider(final InjectingAssetManager assetManager) {
        super(assetManager);
    }

    @Override
    public Class<? extends BitmapFont> getType() {
        return BitmapFont.class;
    }

    @Override
    protected String getFolder() {
        return "font";
    }

    @Override
    protected String[] getExtensions() {
        return EXTENSIONS;
    }
}


text:
<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
    <title>Test Store</title>
    <link rel="self" href="http://www.example.com"/>

    <entry>
        <g:id>DB_1</g:id>
        <g:title>Dog Bowl In Blue</g:title>
        <g:description>Solid plastic Dog Bowl in marine blue color</g:description>
        <g:link>http://www.example.com/bowls/db-1.html</g:link>
        <g:image_link>http://images.example.com/DB_1.png</g:image_link>
        <g:brand>Example</g:brand>
        <g:condition>new</g:condition>
        <g:availability>in stock</g:availability>
        <g:price>9.99 GBP</g:price>
        <g:shipping>
            <g:country>UK</g:country>
            <g:service>Standard</g:service>
            <g:price>4.95 GBP</g:price>
        </g:shipping>

        <g:google_product_category>Animals > Pet Supplies</g:google_product_category>
    </entry>
</feed>


text:
<!DOCTYPE html>

    <title>polar coordinates</title>
    <link rel="stylesheet" type="text/css" href="rect.css" />


text:
#include "net/mac_address.h"

#include <cstring>
#include <cstdio>
#if defined(__linux__)
# include <netinet/ether.h>
#endif

#include "base/parse_object.h"

using namespace std;

const MacAddress MacAddress::kZeroMac;
const MacAddress MacAddress::kBroadcastMac(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);

MacAddress::MacAddress() {
    addr_ = kZeroMac;
}

MacAddress::MacAddress(const uint8_t *data) {
    memcpy(&addr_, data, sizeof(addr_));
}

bool MacAddress::IsZero() const {
    return CompareTo(ZeroMac()) == 0;
}

bool MacAddress::IsBroadcast() const {
    return CompareTo(BroadcastMac()) == 0;
}

MacAddress::MacAddress(unsigned int a, unsigned int b, unsigned int c,
                       unsigned int d, unsigned int e, unsigned int f) {
    u_int8_t *p = (u_int8_t *)&addr_;

    p[0] = a; p[1] = b; p[2] = c; p[3] = d; p[4] = e; p[5] = f;
}

MacAddress::MacAddress(const std::string &s,
                       boost::system::error_code *errorp) {
    this->addr_ = FromString(s, errorp);
}

string MacAddress::ToString() const {
    char temp[32];
    const u_int8_t *a = (u_int8_t *)&addr_;
    snprintf(temp, sizeof(temp), "%02x:%02x:%02x:%02x:%02x:%02x",
        a[0], a[1], a[2], a[3], a[4], a[5]);
    return temp;
}

MacAddress MacAddress::FromString(const std::string &str,
                                  boost::system::error_code *errorp) {
    struct ether_addr a;
    u_int8_t *p = (u_int8_t*)&a;
    char extra;

    int ret = sscanf(str.c_str(), "%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx%c",
        &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &extra);
    if ((size_t)ret != size() || strchr(str.c_str(), 'x') || strchr(str.c_str(), 'X')) {
        if (errorp != NULL)
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        return MacAddress();
    }
    return MacAddress(a);
}

int MacAddress::CompareTo(const MacAddress &rhs) const {
    return memcmp(&addr_, &rhs.addr_, sizeof(addr_));
}

bool MacAddress::ToArray(u_int8_t *p, size_t s) const {
    if (s < size())
        return false;
    memcpy(p, &addr_, size());
    return true;
}

MacAddress &MacAddress::operator=(const u_int8_t *c) {
    memcpy(&addr_, c, size());
    return *this;
}

MacAddress &MacAddress::operator=(const struct sockaddr *sa) {
    memcpy(&addr_, sa->sa_data, size());
    return *this;
}


text:
#pragma once

#include <cstdint>
#include <functional>
#include <memory>
#include <unordered_map>
#include <utility>

#include <ABI43_0_0cxxreact/ABI43_0_0JSModulesUnbundle.h>

#ifndef ABI43_0_0RN_EXPORT
#define ABI43_0_0RN_EXPORT __attribute__((visibility("default")))
#endif

namespace ABI43_0_0facebook {
namespace ABI43_0_0React {

class ABI43_0_0RN_EXPORT RAMBundleRegistry {
 public:
  constexpr static uint32_t MAIN_BUNDLE_ID = 0;

  static std::unique_ptr<RAMBundleRegistry> singleBundleRegistry(
      std::unique_ptr<JSModulesUnbundle> mainBundle);
  static std::unique_ptr<RAMBundleRegistry> multipleBundlesRegistry(
      std::unique_ptr<JSModulesUnbundle> mainBundle,
      std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory);

  explicit RAMBundleRegistry(
      std::unique_ptr<JSModulesUnbundle> mainBundle,
      std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory =
          nullptr);

  RAMBundleRegistry(RAMBundleRegistry &&) = default;
  RAMBundleRegistry &operator=(RAMBundleRegistry &&) = default;

  void registerBundle(uint32_t bundleId, std::string bundlePath);
  JSModulesUnbundle::Module getModule(uint32_t bundleId, uint32_t moduleId);
  virtual ~RAMBundleRegistry(){};

 private:
  JSModulesUnbundle *getBundle(uint32_t bundleId) const;

  std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> m_factory;
  std::unordered_map<uint32_t, std::string> m_bundlePaths;
  std::unordered_map<uint32_t, std::unique_ptr<JSModulesUnbundle>> m_bundles;
};

} // namespace ABI43_0_0React
} // namespace ABI43_0_0facebook


text:
I have to halt development temporarily due to lack of time. I am planning to add single logout support and do other required modifications to pac4j 1.5.1 and play-pac4j 1.2.1 which works with Play 2.2.2.

# play-samlsso

SAML 2.0 SSO for Play Framework with OAuth2 grant support. Only supports Play Java and tested with WSO2 Identity Server.

This project was inspired by [play-pac4j](https://github.com/leleuj/play-pac4j) library. Also some parts are directly
based on SAML implementation of [pac4j](https://github.com/leleuj/pac4j). Main reason behind creating this library is to
  understand SAML SSO internals and have more control over how SSO is done. Also I am planning to implement [AML 2.0
    Profile for OAuth2 Client Authentication and Authorization Grants](http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-21) on top of this.

## Design and Usage

### Authentication Flow

1. User tries to access specific URL of Play App.
2. If the above URL is secured using ```@RequiresAuthentication``` annotation, ```RequiresAuthenticationAction``` will get invoked.
3. This action will check for whether there is a existing session and whether required user profile information is there
 in the session.

 3.1 If there is a valida session, action will hand over the request to actual web action.

 3.2 If no valid session is found, action will start the SSO process from step 4.

4. ```RequiresAuthenticationAction``` will get the URL for the current request and pass that to ```SAMLSSOManager``` for
building authentication request.
5. Using the service providers key information, configuration and identity provider meta data, ```SAMLSSOManager``` will
  build authentication request (Redirect response) and send it back to user's browser as the response.
6. This redirect response will take user to identity provider and identity provider may ask for authenticating into it.
After successful authentication, user will get redirected to service providers callback URL with *RelayState* parameter.
7. Once the SSO authentication response is received at the service provider, SP will validate the response, setup the session and redirect
user to correct URL based on RelayState.

Your Play controllers must extend ```SAMLSSOJavaController``` class for Play Java application.

```
public class MyApplication extends SAMLSSOJavaController {
    ...
}
```

Specific actions of your Play Java application can be protected by using ```RequiresAuthentication``` annotation.

```
@RequiresAuthentication
public static Result protectedResource(){
    // User profile is avaibale only if this session is authenticated with Identity Provider
    UserProfile userProfile = getUserProfile()
}
```

```SAMLSSOJavaController``` defines methods needed to handle SAML SSO related callbacks.

 * ```authenticatedCB``` - Identity provider should redirect back to this action after the authentication is done as a request from service provider.
 * ```singleLogoutCB``` - Identity provider will send a request to this URL to complete single logout request from a other service provider.
 * ```singleLogout``` - If you need single logout support in your application, you can call this action.

Copyright © 2014 Milinda Pathirage

Distributed under the Apache License Version 2.0.


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Directive, ElementRef, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { CoreUtils } from '@services/utils/utils';

/**
 * Directive to listen for element resize events.
 */
@Directive({
    selector: '[onResize]',
})
export class CoreOnResizeDirective implements OnInit, OnDestroy {

    @Output() onResize = new EventEmitter();

    private element: HTMLElement;
    private resizeObserver?: ResizeObserver;
    private mutationObserver?: MutationObserver;

    constructor(element: ElementRef) {
        this.element = element.nativeElement;
    }

    /**
     * @inheritdoc
     */
    ngOnInit(): void {
        'ResizeObserver' in window
            ? this.watchResize()
            : this.watchMutations();
    }

    /**
     * @inheritdoc
     */
    ngOnDestroy(): void {
        this.resizeObserver?.disconnect();
        this.mutationObserver?.disconnect();
    }

    /**
     * Watch resize events.
     */
    private watchResize(): void {
        this.resizeObserver = new ResizeObserver(() => this.onResize.emit());

        this.resizeObserver.observe(this.element);
    }

    /**
     * Watch mutation events to detect resizing.
     */
    private watchMutations(): void {
        let size = this.getElementSize();
        const onMutation = () => {
            const newSize = this.getElementSize();

            if (newSize.width !== size.width || newSize.height !== size.height) {
                size = newSize;

                this.onResize.emit();
            }
        };

        // Debounce 20ms to let mutations resolve before checking the new size.
        this.mutationObserver = new MutationObserver(CoreUtils.debounce(onMutation, 20));

        this.mutationObserver.observe(this.element, {
            subtree: true,
            childList: true,
            characterData: true,
        });
    }

    /**
     * Get element size.
     *
     * @returns Element size.
     */
    private getElementSize(): { width: number; height: number } {
        return {
            width: this.element.clientWidth,
            height: this.element.clientHeight,
        };
    }

}


text:
import * as plurals from "make-plural/plurals"
import bcp47 from "bcp-47"

export type LocaleInfo = {
  locale: string
  language: string
}

/**
 * Check that locale is valid according to BCP47 and we have plurals for it
 * @param locale: string - Locale in BCP47 format
 * @return {boolean}
 */
export function isValid(locale: string): boolean {
  const localeData = parse(locale)
  return (
    localeData !== null &&
    localeData !== undefined &&
    localeData.language in plurals
  )
}

/**
 * Parse locale in BCP47 format and
 * @param locale - Locale in BCP47 format
 * @return {LocaleInfo}
 */
export function parse(locale: string): LocaleInfo | null {
  if (typeof locale !== "string") return null

  const schema = bcp47.parse(locale.replace("_", "-"))
  if (!schema.language) return null

  return {
    locale: bcp47.stringify(schema),
    language: schema.language,
  }
}


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { DropdownButton, MenuItem, FormControl, Button } from 'react-bootstrap';
import { getTopics, getTopicPendingQuestions } from '../actions';

class StickyHeader extends Component {
  constructor(props) {
    super(props);
    this.state = {topicValue: '', userValue: ''};
  }

  componentDidMount() {
    this.props.getTopics();
  }

  onTopicListSelect(eventKey) {
    this.props.getQuestionList(eventKey);
  }

  onTopicValueChange(e) {
    this.setState({topicValue: e.target.value});
  }

  onTopicButtonClick() {
    this.props.getTopicPendingQuestions(this.state.topicValue);
  }

  onUserValueChange(e) {
    this.setState({userValue: e.target.value});
  }

  onUserButtonClick() {
    this.props.getUserQuestionList(this.state.userValue);
  }

  render() {
    var topics = null;
    if (this.props.topics instanceof Array) {
      topics = this.props.topics.map(topic =>
        <MenuItem
          key={topic}
          eventKey={topic}
          onSelect={this.onTopicListSelect.bind(this)}>
          {topic}
        </MenuItem>
      );
    }
    return (

          <input
            type='text'
            value={this.state.topicValue}
            onChange={this.onTopicValueChange.bind(this)} />
          <Button onClick={this.onTopicButtonClick.bind(this)}>Browse Topic</Button>
          <input
            type='text'
            value={this.state.userValue}
            onChange={this.onUserValueChange.bind(this)} />
          <Button onClick={this.onUserButtonClick.bind(this)}>Browse User</Button>

    );
  }
}

function mapStateToProps(state) {
  return { topics: state.main.topics };
}
export default connect(mapStateToProps, { getTopics, getTopicPendingQuestions })(StickyHeader);


text:
package permafrost.tundra.lang;

import permafrost.tundra.collection.CollectionHelper;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * A collection of convenience methods for working with two dimensional arrays.
 */
public final class TableHelper {
    /**
     * The default separator string between rows of a table when converting it to a string.
     */
    public final static String DEFAULT_ROW_SEPARATOR = ", ";

    /**
     * Disallow instantiation of this class.
     */
    private TableHelper() {}

    /**
     * Returns a new table with all null elements removed.
     *
     * @param table The two dimensional array to be compacted.
     * @param <T>   The class of the items in the array.
     * @return      A copy of the given array with all null items removed.
     */
    public static <T> T[][] compact(T[][] table) {
        if (table == null) return null;

        List<T[]> list = new ArrayList<T[]>(table.length);

        for (T[] row : table) {
            if (row != null) list.add(ArrayHelper.compact(row));
        }

        return CollectionHelper.arrayify(list, table);
    }

    /**
     * Returns a string created by concatenating each element of the given table.
     *
     * @param table             The table whose contents are to be joined.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table) {
        return join(table, null);
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param separator         An optional separator string to be used between rows of the table and items of a row.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table, String separator) {
        return join(table, separator, separator);
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param separator         An optional separator string to be used between rows of the table and items of a row.
     * @param mode              The type of compaction to be applied to the array, if any.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table, String separator, Sanitization mode) {
        return join(table, separator, separator, null, null, mode);
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param rowSeparator      An optional separator string to be used between rows of the table.
     * @param itemSeparator     An optional separator string to be used between items of a row.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table, String rowSeparator, String itemSeparator) {
        return join(table, rowSeparator, itemSeparator, null, (String)null);
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param rowSeparator      An optional separator string to be used between rows of the table.
     * @param itemSeparator     An optional separator string to be used between items of a row.
     * @param tableDefaultValue An optional value used when the table is null or empty.
     * @param rowDefaultValue   An optional value used when a table row is null or empty.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table, String rowSeparator, String itemSeparator, String tableDefaultValue, String rowDefaultValue) {
        return join(table, rowSeparator, itemSeparator, tableDefaultValue, rowDefaultValue, null);
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param rowSeparator      An optional separator string to be used between rows of the table.
     * @param itemSeparator     An optional separator string to be used between items of a row.
     * @param tableDefaultValue An optional value used when the table is null or empty.
     * @param rowDefaultValue   An optional value used when a table row is null or empty.
     * @param sanitization      The type of sanitization required, if any.
     * @param <T>               The class of items stored in the table.
     * @return                  A string representation of the given table created by concatenating together the string
     *                          representation of each item in order.
     */
    public static <T> String join(T[][] table, String rowSeparator, String itemSeparator, String tableDefaultValue, String rowDefaultValue, Sanitization sanitization) {
        table = sanitize(table, sanitization);

        if (table == null || table.length == 0) return tableDefaultValue;

        StringBuilder builder = new StringBuilder();
        join(table, rowSeparator, itemSeparator, rowDefaultValue, builder);
        return builder.toString();
    }

    /**
     * Returns a string created by concatenating each element of the given table, separated by the given separator
     * string.
     *
     * @param table             The table whose contents are to be joined.
     * @param rowSeparator      An optional separator string to be used between rows of the table.
     * @param itemSeparator     An optional separator string to be used between items of the table.
     * @param rowDefaultValue   An optional value used when a table row is null or empty.
     * @param builder           The StringBuilder to which resulting string is written.
     * @param <T>               The class of items stored in the table.
     */
    public static <T> void join(T[][] table, String rowSeparator, String itemSeparator, String rowDefaultValue, StringBuilder builder) {
        if (table == null || builder == null) return;

        for (int i = 0; i < table.length; i++) {
            if (rowSeparator != null && i > 0) builder.append(rowSeparator);
            if (table[i] == null) {
                builder.append(rowDefaultValue);
            } else {
                ArrayHelper.join(table[i], itemSeparator, builder);
            }
        }
    }

    /**
     * Returns a string representation of the given table.
     *
     * @param table             The table to be stringified.
     * @param <T>               The class of items stored in the array.
     * @return                  A string representation of the given array.
     */
    public static <T> String stringify(T[][] table) {
        return stringify(table, null, null);
    }

    /**
     * Returns a string representation of the given table.
     *
     * @param table             The table to be stringified.
     * @param separator         The separator string to be used between rows, and between items of a row.
     * @param <T>               The class of items stored in the array.
     * @return                  A string representation of the given array.
     */
    public static <T> String stringify(T[][] table, String separator) {
        return stringify(table, separator, separator, (Sanitization)null);
    }

    /**
     * Returns a string representation of the given table.
     *
     * @param table             The table to be stringified.
     * @param separator         The separator string to be used between rows, and between items of a row.
     * @param sanitization      The type of sanitization required, if any.
     * @param <T>               The class of items stored in the array.
     * @return                  A string representation of the given array.
     */
    public static <T> String stringify(T[][] table, String separator, Sanitization sanitization) {
        return stringify(table, separator, separator, sanitization);
    }

    /**
     * Returns a string representation of the given table.
     *
     * @param table             The table to be stringified.
     * @param rowSeparator      The separator string to be used between rows of the table.
     * @param itemSeparator     The separator string to be used between items of a row.
     * @param sanitization      The type of sanitization required, if any.
     * @param <T>               The class of items stored in the array.
     * @return                  A string representation of the given array.
     */
    public static <T> String stringify(T[][] table, String rowSeparator, String itemSeparator, Sanitization sanitization) {
        table = sanitize(table, sanitization);

        if (table == null) return null;

        StringBuilder builder = new StringBuilder();
        stringify(table, rowSeparator, itemSeparator, builder);
        return builder.toString();
    }

    /**
     * Returns a string representation of the given table.
     *
     * @param table             The table to be stringified.
     * @param rowSeparator      The separator string to be used between rows of the table.
     * @param itemSeparator     The separator string to be used between items of a row.
     * @param builder           The string builder to use when building the string.
     * @param <T>               The class of items stored in the array.
     */
    public static <T> void stringify(T[][] table, String rowSeparator, String itemSeparator, StringBuilder builder) {
        if (table == null || builder == null) return;

        if (rowSeparator == null) rowSeparator = DEFAULT_ROW_SEPARATOR;
        if (itemSeparator == null) itemSeparator = ArrayHelper.DEFAULT_ITEM_SEPARATOR;

        builder.append("[");
        for (int i = 0; i < table.length; i++) {
            if (i > 0) builder.append(rowSeparator);

            if (table[i] == null) {
                builder.append(table[i]);
            } else {
                ArrayHelper.stringify(table[i], itemSeparator, builder);
            }
        }
        builder.append("]");
    }

    /**
     * Compacts the given table using the given compaction method.
     *
     * @param table         The table to be compacted.
     * @param sanitization  The type of sanitization required, if any.
     * @param <T>           The class of item stored in the array.
     * @return              The resulting compacted table.
     */
    public static <T> T[][] sanitize(T[][] table, Sanitization sanitization) {
        if (table != null && sanitization != null) {
            if (sanitization == Sanitization.REMOVE_NULLS) {
                table = compact(table);
            } else if (sanitization == Sanitization.REMOVE_NULLS_AND_BLANKS) {
                table = squeeze(table);
            } else if (sanitization == Sanitization.CONVERT_NULLS_TO_BLANKS) {
                table = blankify(table);
            }
        }

        return table;
    }

    /**
     * Returns a new table with all empty or null elements removed.
     *
     * @param table A table to be squeezed.
     * @param <T>   The type of item in the table.
     * @return A new table that is the given table squeezed.
     */
    public static <T> T[][] squeeze(T[][] table) {
        if (table == null || table.length == 0) return null;

        List<T[]> list = new ArrayList<T[]>(table.length);

        for (T[] row : table) {
            row = ArrayHelper.squeeze(row);
            if (row != null) list.add(row);
        }

        table = CollectionHelper.arrayify(list, table);

        return table.length == 0 ? null : table;
    }

    /**
     * Converts each string in the given table to null if it only contains whitespace characters.
     *
     * @param table     The table to be nullified.
     * @param <T>       The component type of the table.
     * @return          The nullified table.
     */
    public static <T> T[][] nullify(T[][] table) {
        if (table == null || table.length == 0) return null;

        List<T[]> list = new ArrayList<T[]>(table.length);

        for (T[] row : table) {
            row = ArrayHelper.nullify(row);
            if (row != null) list.add(row);
        }

        table = CollectionHelper.arrayify(list, table);

        return table.length == 0 ? null : table;
    }

    /**
     * Replaces nulls with blank strings in the given table.
     *
     * @param table The table to be processed.
     * @param <T>   The component class of the table.
     * @return      A new table containing all items in the given table but with nulls replaced with blank strings.
     * @throws IllegalArgumentException If given table is not an instance of String[][].
     */
    public static <T> T[][] blankify(T[][] table) {
        if (table == null || table.length == 0) return null;

        if (table instanceof String[][]) {
            List<T[]> list = new ArrayList<T[]>(table.length);

            for (T[] row : table) {
                list.add(ArrayHelper.blankify(row));
            }

            table = CollectionHelper.arrayify(list, table);

            return table.length == 0 ? null : table;
        } else {
            throw new IllegalArgumentException("table must be an instance of class String[][]; class provided: " + table.getClass().getName());
        }
    }

    /**
     * Converts the given two dimensional array of objects to a string table.
     *
     * @param table The two dimensional array to be converted.
     * @param <T>   The type of item in the given array.
     * @return The converted string table.
     */
    public static <T> String[][] toStringTable(T[][] table) {
        if (table == null) return null;

        String[][] stringTable = new String[table.length][];
        for (int i = 0; i < table.length; i++) {
            stringTable[i] = ArrayHelper.toStringArray(table[i]);
        }

        return stringTable;
    }

    /**
     * Returns a new table whose class is the nearest ancestor class of all contained items.
     *
     * @param table The table to be normalized.
     * @param <T>   The type of item in the table.
     * @return      A new copy of the given table whose class is the nearest ancestor of all contained items.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[][] normalize(T[][] table) {
        if (table == null) return null;

        List<T[]> list = new ArrayList<T[]>(table.length);
        Set<Class<?>> classes = new HashSet<Class<?>>();

        for (T[] row : table) {
            Class<?> nearestAncestor = ObjectHelper.getNearestAncestor(row);
            classes.add(nearestAncestor);
            list.add(ArrayHelper.normalize(row, nearestAncestor));
        }

        Class nearestAncestor = ClassHelper.getNearestAncestor(classes);

        return list.toArray((T[][])instantiate(nearestAncestor, 0, 0));
    }

    /**
     * Returns a new table whose class is the nearest ancestor class of all contained items.
     *
     * @param table The table to be normalized.
     * @param <T>   The type of item in the table.
     * @return      A new copy of the given table whose class is the nearest ancestor of all contained items.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[][] normalize(Collection<T[]> table) {
        if (table == null) return null;

        List<T[]> list = new ArrayList<T[]>(table.size());
        Set<Class<?>> classes = new HashSet<Class<?>>();

        for (T[] row : table) {
            Class<?> nearestAncestor = ObjectHelper.getNearestAncestor(row);
            classes.add(nearestAncestor);
            list.add(ArrayHelper.normalize(row, nearestAncestor));
        }

        Class nearestAncestor = ClassHelper.getNearestAncestor(classes);

        return list.toArray((T[][])instantiate(nearestAncestor, 0, 0));
    }

    /**
     * Dynamically instantiates a new array of the given class with the given length.
     *
     * @param componentClass    The class of items to be stored in the array.
     * @param dimensions        The desired length of the returned array.
     * @param <T>               The class of items to be stored in the array.
     * @return                  A new array of the given class with the given length.
     */
    @SuppressWarnings("unchecked")
    public static <T> Object instantiate(Class<T> componentClass, int... dimensions) {
        return Array.newInstance(componentClass, dimensions);
    }
}


text:
package com.pacific.mapper;

import com.pacific.domain.entity.ErrorLogRecord;

import java.util.Date;
import java.util.List;

public interface ErrorLogRecordMapper {
    int deleteByPrimaryKey(Long id);

    int insert(ErrorLogRecord record);

    int batchInsert(List<ErrorLogRecord> errorLogRecordList);

    int insertSelective(ErrorLogRecord record);

    ErrorLogRecord selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(ErrorLogRecord record);

    int updateByPrimaryKeyWithBLOBs(ErrorLogRecord record);

    int updateByPrimaryKey(ErrorLogRecord record);

    ErrorLogRecord queryNewErrorLogRecordApplicationCode(String applicationCode);

    List<ErrorLogRecord> queryHasNoAlarmErrorLogRecord();
}


text:
require 'test/unit'

class SyncTest < Test::Unit::TestCase
  def test_truth
    assert true
  end
end


text:
package com.hyperfresh.mcuniverse.packets;

import com.hyperfresh.mcuniverse.UniverseAPI;
import com.hyperfresh.mcuniverse.minecraft.MinecraftPlayer;
import com.hyperfresh.mcuniverse.minecraft.MinecraftUser;

/**
 * @author Octopod - octopodsquad@gmail.com
 */

/**
 * This will tell a server that this player has left the server.
 */
public class PacketInPlayerLeave extends Packet
{
	String UUID;

	public PacketInPlayerLeave(MinecraftPlayer player)
	{
		UUID = player.getUUID();
	}

	public MinecraftUser getPlayer()
	{
		return UniverseAPI.getInstance().getInterface().getOfflinePlayer(UUID);
	}

	public String getUUID()
	{
		return UUID;
	}
}


text:
namespace update_client {

const char kArchAmd64[] = "x86_64";
const char kArchIntel[] = "x86";
const char kArchArm64[] = "arm64";

bool HasDiffUpdate(const Component& component) {
  return !component.crx_diffurls().empty();
}

bool IsHttpServerError(int status_code) {
  return 500 <= status_code && status_code < 600;
}

bool DeleteFileAndEmptyParentDirectory(const base::FilePath& filepath) {
  if (!base::DeleteFile(filepath))
    return false;

  return DeleteEmptyDirectory(filepath.DirName());
}

bool DeleteEmptyDirectory(const base::FilePath& dir_path) {
  if (!base::IsDirectoryEmpty(dir_path))
    return true;

  return base::DeleteFile(dir_path);
}

std::string GetCrxComponentID(const CrxComponent& component) {
  return component.app_id.empty() ? GetCrxIdFromPublicKeyHash(component.pk_hash)
                                  : component.app_id;
}

std::string GetCrxIdFromPublicKeyHash(const std::vector<uint8_t>& pk_hash) {
  const std::string result =
      crx_file::id_util::GenerateIdFromHash(&pk_hash[0], pk_hash.size());
  DCHECK(crx_file::id_util::IdIsValid(result));
  return result;
}

bool VerifyFileHash256(const base::FilePath& filepath,
                       const std::string& expected_hash_str) {
  std::vector<uint8_t> expected_hash;
  if (!base::HexStringToBytes(expected_hash_str, &expected_hash) ||
      expected_hash.size() != crypto::kSHA256Length) {
    return false;
  }

  std::unique_ptr<crypto::SecureHash> hasher(
      crypto::SecureHash::Create(crypto::SecureHash::SHA256));

  int64_t file_size = 0;
  if (!base::GetFileSize(filepath, &file_size))
    return false;
  if (file_size > 0) {
    base::MemoryMappedFile mmfile;
    if (!mmfile.Initialize(filepath))
      return false;
    hasher->Update(mmfile.data(), mmfile.length());
  }

  uint8_t actual_hash[crypto::kSHA256Length] = {0};
  hasher->Finish(actual_hash, sizeof(actual_hash));

  return memcmp(actual_hash, &expected_hash[0], sizeof(actual_hash)) == 0;
}

bool IsValidBrand(const std::string& brand) {
  const size_t kMaxBrandSize = 4;
  return brand.empty() ||
         (brand.size() == kMaxBrandSize &&
          base::ranges::all_of(brand, &base::IsAsciiAlpha<char>));
}

// Helper function.
// Returns true if |part| matches the expression
// ^[<special_chars>a-zA-Z0-9]{min_length,max_length}$
bool IsValidInstallerAttributePart(const std::string& part,
                                   const std::string& special_chars,
                                   size_t min_length,
                                   size_t max_length) {
  return part.size() >= min_length && part.size() <= max_length &&
         base::ranges::all_of(part, [&special_chars](char ch) {
           return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) ||
                  base::Contains(special_chars, ch);
         });
}

// Returns true if the |name| parameter matches ^[-_a-zA-Z0-9]{1,256}$ .
bool IsValidInstallerAttributeName(const std::string& name) {
  return IsValidInstallerAttributePart(name, "-_", 1, 256);
}

// Returns true if the |value| parameter matches ^[-.,;+_=$a-zA-Z0-9]{0,256}$ .
bool IsValidInstallerAttributeValue(const std::string& value) {
  return IsValidInstallerAttributePart(value, "-.,;+_=$", 0, 256);
}

bool IsValidInstallerAttribute(const InstallerAttribute& attr) {
  return IsValidInstallerAttributeName(attr.first) &&
         IsValidInstallerAttributeValue(attr.second);
}

void RemoveUnsecureUrls(std::vector<GURL>* urls) {
  DCHECK(urls);
  base::EraseIf(*urls,
                [](const GURL& url) { return !url.SchemeIsCryptographic(); });
}

CrxInstaller::Result InstallFunctionWrapper(
    base::OnceCallback<bool()> callback) {
  return CrxInstaller::Result(std::move(callback).Run()
                                  ? InstallError::NONE
                                  : InstallError::GENERIC_ERROR);
}

// TODO(cpu): add a specific attribute check to a component json that the
// extension unpacker will reject, so that a component cannot be installed
// as an extension.
base::Value ReadManifest(const base::FilePath& unpack_path) {
  base::FilePath manifest =
      unpack_path.Append(FILE_PATH_LITERAL("manifest.json"));
  if (!base::PathExists(manifest))
    return base::Value();
  JSONFileValueDeserializer deserializer(manifest);
  std::string error;
  std::unique_ptr<base::Value> root = deserializer.Deserialize(nullptr, &error);
  if (!root)
    return base::Value();
  return base::Value::FromUniquePtrValue(std::move(root));
}

std::string GetArchitecture() {
#if BUILDFLAG(IS_WIN)
  const base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();
  return (os_info->IsWowX86OnARM64() || os_info->IsWowAMD64OnARM64())
             ? kArchArm64
             : base::SysInfo().OperatingSystemArchitecture();
#else   // BUILDFLAG(IS_WIN)
  return base::SysInfo().OperatingSystemArchitecture();
#endif  // BUILDFLAG(IS_WIN)
}

}  // namespace update_client


text:
package org.beatific.daram.design;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DesignHolder {

	private static Map<String, Design> holder = new LinkedHashMap<String, Design>();

	public static void hold(Design design) {
		if(holder.containsKey(design.getName()))return;
		design.save();
		holder.put(design.getName(), design);
	}

	public static void reload() {
		Long monitorId = null;
		for(Entry<String, Design> entry : holder.entrySet()) {
			monitorId = entry.getValue().loadDesign(monitorId);
		}
	}

	public static Map<String, Design> getDesigns() {
		return holder;
	}

	public static Design getDesign(String name) {
		return holder.get(name);
	}
}


text:
EventStore PHP client
=====================

PHP client for [EventStore 3.x HTTP API](https://github.com/eventstore/eventstore/wiki/Getting-Started-HTTP)

[![Latest Stable Version](https://poser.pugx.org/dbellettini/eventstore-client/v/stable.svg)](https://packagist.org/packages/dbellettini/eventstore-client) [![Total Downloads](https://poser.pugx.org/dbellettini/eventstore-client/downloads.svg)](https://packagist.org/packages/dbellettini/eventstore-client) [![Latest Unstable Version](https://poser.pugx.org/dbellettini/eventstore-client/v/unstable.svg)](https://packagist.org/packages/dbellettini/eventstore-client) [![License](https://poser.pugx.org/dbellettini/eventstore-client/license.svg)](https://packagist.org/packages/dbellettini/eventstore-client)

[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/dbellettini/php-eventstore-client/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/dbellettini/php-eventstore-client/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/dbellettini/php-eventstore-client/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/dbellettini/php-eventstore-client/?branch=master)
[![Build Status](https://travis-ci.org/dbellettini/php-eventstore-client.svg?branch=master)](https://travis-ci.org/dbellettini/php-eventstore-client)
Roadmap
-------

Development started in April 2014. Not ready for production use. Things may break between versions.

API can currently:

- Read from streams
- Navigate streams
- Read events
- Write to streams
- Delete streams

Integrations
------------
* [EventStore Client Bundle](https://github.com/dbellettini/eventstore-client-bundle) integrates this project in Symfony 2
* [Broadway Integration](https://github.com/dbellettini/broadway-eventstore)

Documentation
-------------
See our [wiki](https://github.com/dbellettini/php-eventstore-client/wiki)

Contributing
------------

See [CONTRIBUTING](/CONTRIBUTING.md) file.

License
-------

EventStore PHP Client is released under the MIT License. See the bundled
[LICENSE](/LICENSE) file for details.

Disclaimer
----------

This project is not endorsed by Event Store LLP.


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>articledownloader.articledownloader module — article-downloader 1.0 documentation</title>

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="prev" title="article-downloader documentation" href="index.html" />

             article-downloader

                1.0

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

articledownloader.articledownloader module

          article-downloader

Docs »

articledownloader.articledownloader module

             View page source

articledownloader.articledownloader module¶

class articledownloader.articledownloader.ArticleDownloader(els_api_key=None, sleep_sec=1, timeout_sec=30)[source]¶

get_abstract_from_doi(**keywords)[source]¶

Returns abstract as a unicode string given a DOI

<col class="field-name" />
<col class="field-body" />

Parameters:

doi (str) – DOI string for the article we want to grab metadata for

mode (str) – Only supports 'elsevier' for now

Returns:
An abstract (or None on failure)

Return type:
unicode

get_dois_from_journal_issn(**keywords)[source]¶

Grabs a set of unique DOIs based on a journal ISSN using the CrossRef API

<col class="field-name" />
<col class="field-body" />

Parameters:

issn (str) – The ISSN of the journal

rows (str) – the maximum number of DOIs to find

pub_after (int) – the minimum publication year for DOIs returned

mailto – mailto address for API

Returns:
the unique set of DOIs as a list

Return type:
list

get_dois_from_search(**keywords)[source]¶

Grabs a set of unique DOIs based on a search query using the CrossRef API

<col class="field-name" />
<col class="field-body" />

Parameters:

query (str) – the search string

rows (str) – the maximum number of DOIs to find

mailto – mailto address for API

Returns:
the unique set of DOIs as a list

Return type:
list

get_html_from_doi(**keywords)[source]¶

Downloads and writes an HTML article to a file, given a DOI and operating mode

<col class="field-name" />
<col class="field-body" />

Parameters:

doi (str) – DOI string for the article we want to download

writefile (file) – file object to write to

mode (str) – choose from {'elsevier' | 'springer' | 'acs' | 'ecs' | 'rsc' | 'nature' | 'wiley' | 'aaas' | 'emerald'}, depending on how we wish to access the file

Returns:
True on successful write, False otherwise

Return type:
bool

get_metadata_from_journal_issn(**keywords)[source]¶

Grabs metadata based on a journal ISSN using the CrossRef API

<col class="field-name" />
<col class="field-body" />

Parameters:

issn (str) – The ISSN of the journal

rows (str) – the maximum number of DOIs to find

pub_after (int) – the minimum publication year for DOIs returned

mailto – mailto address for API

Returns:
the metadata for the articles according to this ISSN

Return type:
list

get_pdf_from_doi(**keywords)[source]¶

Downloads and writes a PDF article to a file, given a DOI and operating mode

<col class="field-name" />
<col class="field-body" />

Parameters:

doi (str) – DOI string for the article we want to download

writefile (file) – file object to write to

mode (str) – choose from {'crossref' | 'elsevier' | 'rsc' | 'springer' | 'ecs' | 'nature' | 'acs'}, depending on how we wish to access the file

Returns:
True on successful write, False otherwise

Return type:
bool

get_title_from_doi(**keywords)[source]¶

Returns title of an article as a unicode string given a DOI

<col class="field-name" />
<col class="field-body" />

Parameters:

doi (str) – DOI string for the article we want to grab metadata for

mode (str) – Only supports 'crossref' for now

Returns:
A title (or None on failure)

Return type:
unicode

get_xml_from_doi(**keywords)[source]¶

Downloads and writes an HTML article to a file, given a DOI and operating mode

<col class="field-name" />
<col class="field-body" />

Parameters:

doi (str) – DOI string for the article we want to download

writefile (file) – file object to write to

mode (str) – choose from {'elsevier' | 'aps'}, depending on how we wish to access the file

Returns:
True on successful write, False otherwise

Return type:
bool

load_queries_from_csv(**keywords)[source]¶

Loads a list of queries from a CSV file

<col class="field-name" />
<col class="field-body" />

Parameters:	csvf (file) – file object containing a CSV file with one query per line

Returns:	a list of queries, processed to be insertable into REST API (GET) calls

Return type:	list

         Previous

        © Copyright 2015, MIT DMSE.

  Built with Sphinx using a theme provided by Read the Docs.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.hugo.sistema.services;

import br.hugo.sistema.dao.LoginDao;
import br.hugo.sistema.model.Login;
import br.hugo.sistema.utils.HibernateUtil;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author hugo
 */
@ManagedBean(name = "loginService")
@ApplicationScoped
public class LoginService implements LoginDao, Serializable {

    private static final long serialVersionUID = 2171240336847509801L;

    @Override
    public Login getLogin(String user, String pass) {

        Login login = null;

        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            login = (Login) session.createQuery("SELECT l from Login l where l.login = :login and l.senha = :senha")
                    .setParameter("login", user)
                    .setParameter("senha", pass).uniqueResult();

        } catch (RuntimeException ex) {
            Logger.getLogger(LoginService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            session.flush();
            session.close();
        }
        return login;
    }

    public Login geIDLogin(int id) {
        Login login = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            login = (Login) session.get(Login.class, id);
            //usuario = (Login) session.load(Login.class, id);
        } catch (RuntimeException ex) {
            Logger.getLogger(LoginService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            session.flush();
            session.close();
        }
        return login;
    }

    public void update(Login login) {
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            transaction = session.beginTransaction();

            /*session.createQuery("Update Login set login = :username, senha = :password where idLogin = :id")
                    .setParameter("username", login.getLogin())
                    .setParameter("password", login.getSenha())
                    .setParameter("id", login.getIdLogin()).executeUpdate();*/

            session.update(login);

            session.getTransaction().commit();

        } catch (RuntimeException ex) {

            //Verifica a sessao e seu problema tenta novamente
            if (transaction != null) {
                transaction.rollback();
            } else {
                Logger.getLogger(LoginService.class.getName()).log(Level.SEVERE, null, ex);
            }

        } finally {
            //Finaliza e fecha a sessao
            session.flush();
            session.close();
        }
    }

     public void update(int id, String login , String pass) {
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            transaction = session.beginTransaction();

            session.createQuery("Update Login set login = :username, senha = :password where idLogin = :id")
                    .setParameter("username", login)
                    .setParameter("password", pass)
                    .setParameter("id", id).executeUpdate();

            session.update(login);

            session.getTransaction().commit();

        } catch (RuntimeException ex) {

            //Verifica a sessao e seu problema tenta novamente
            if (transaction != null) {
                transaction.rollback();
            } else {
                Logger.getLogger(LoginService.class.getName()).log(Level.SEVERE, null, ex);
            }

        } finally {
            //Finaliza e fecha a sessao
            session.flush();
            session.close();
        }
    }

    public void save(Login login) {
        //Abre a sessao
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            transaction = session.beginTransaction();

            //Salva a sessao
            session.save(login);
            //Escreve no banco
            session.getTransaction().commit();

        } catch (RuntimeException ex) {
            //Verifica a sessao e seu problema tenta novamente
            if (transaction != null) {
                transaction.rollback();
            } else {
                Logger.getLogger(LoginService.class.getName()).log(Level.SEVERE, null, ex);
            }

        } finally {
            //Finaliza e fecha a sessao
            session.flush();
            session.close();
        }

    }

}