text:
#include "tensorflow/core/grappler/optimizers/layout_optimizer.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/grappler/clusters/virtual_cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/protobuf/device_properties.pb.h"

namespace tensorflow {
namespace grappler {
namespace {

class LayoutOptimizerTest : public ::testing::Test {
 protected:
  void SetUp() override {
    DeviceProperties device_properties;
    device_properties.set_type("GPU");
    device_properties.mutable_environment()->insert({"architecture", "6"});
    virtual_cluster_.reset(new VirtualCluster({{"/GPU:0", device_properties}}));
  }

  Output SimpleConv2D(tensorflow::Scope* s, int input_size, int filter_size,
                      const string& padding) {
    return SimpleConv2D(s, input_size, filter_size, padding, "");
  }

  Output SimpleConv2D(tensorflow::Scope* s, int input_size, int filter_size,
                      const string& padding, const string& device) {
    int batch_size = 8;
    int input_height = input_size;
    int input_width = input_size;
    int input_depth = 3;
    int filter_count = 2;
    int stride = 1;
    TensorShape input_shape(
        {batch_size, input_height, input_width, input_depth});
    Tensor input_data(DT_FLOAT, input_shape);
    test::FillIota<float>(&input_data, 1.0f);
    Output input =
        ops::Const(s->WithOpName("Input"), Input::Initializer(input_data));

    TensorShape filter_shape(
        {filter_size, filter_size, input_depth, filter_count});
    Tensor filter_data(DT_FLOAT, filter_shape);
    test::FillIota<float>(&filter_data, 1.0f);
    Output filter =
        ops::Const(s->WithOpName("Filter"), Input::Initializer(filter_data));

    Output conv = ops::Conv2D(s->WithOpName("Conv2D").WithDevice(device), input,
                              filter, {1, stride, stride, 1}, padding);
    return conv;
  }

  Output SimpleConv2DBackpropInput(tensorflow::Scope* s, int input_size,
                                   int filter_size, const string& padding) {
    return SimpleConv2DBackpropInput(s, input_size, filter_size, padding, true);
  }

  Output SimpleConv2DBackpropInput(tensorflow::Scope* s, int input_size,
                                   int filter_size, const string& padding,
                                   bool const_input_size) {
    int batch_size = 128;
    int input_height = input_size;
    int input_width = input_size;
    int input_depth = 3;
    int filter_count = 2;
    int stride = 1;
    TensorShape input_sizes_shape({4});
    Tensor input_data(DT_INT32, input_sizes_shape);
    test::FillValues<int>(&input_data,
                          {batch_size, input_height, input_width, input_depth});
    Output input_sizes =
        ops::Const(s->WithOpName("InputSizes"), Input::Initializer(input_data));

    TensorShape filter_shape(
        {filter_size, filter_size, input_depth, filter_count});
    Tensor filter_data(DT_FLOAT, filter_shape);
    test::FillIota<float>(&filter_data, 1.0f);
    Output filter =
        ops::Const(s->WithOpName("Filter"), Input::Initializer(filter_data));

    int output_height = input_height;
    int output_width = input_width;
    TensorShape output_shape(
        {batch_size, output_height, output_width, filter_count});
    Tensor output_data(DT_FLOAT, output_shape);
    test::FillIota<float>(&output_data, 1.0f);
    Output output =
        ops::Const(s->WithOpName("Output"), Input::Initializer(output_data));

    Output conv_backprop_input;
    Output input_sizes_i =
        ops::Identity(s->WithOpName("InputSizesIdentity"), input_sizes);
    if (const_input_size) {
      conv_backprop_input = ops::Conv2DBackpropInput(
          s->WithOpName("Conv2DBackpropInput"), input_sizes, filter, output,
          {1, stride, stride, 1}, padding);
    } else {
      conv_backprop_input = ops::Conv2DBackpropInput(
          s->WithOpName("Conv2DBackpropInput"), input_sizes_i, filter, output,
          {1, stride, stride, 1}, padding);
    }
    return conv_backprop_input;
  }

  Tensor GetAttrValue(const NodeDef& node) {
    Tensor tensor;
    CHECK(tensor.FromProto(node.attr().at({"value"}).tensor()));
    return tensor;
  }

  Output SimpleFusedBatchNormGrad(tensorflow::Scope* s, bool is_training) {
    int batch_size = 16;
    int input_height = 8;
    int input_width = 8;
    int input_channels = 3;
    TensorShape shape({batch_size, input_height, input_width, input_channels});
    Tensor data(DT_FLOAT, shape);
    test::FillIota<float>(&data, 1.0f);
    Output x = ops::Const(s->WithOpName("Input"), Input::Initializer(data));
    Output y_backprop =
        ops::Const(s->WithOpName("YBackprop"), Input::Initializer(data));

    TensorShape shape_vector({input_channels});
    Tensor data_vector(DT_FLOAT, shape_vector);
    test::FillIota<float>(&data_vector, 2.0f);
    Output scale =
        ops::Const(s->WithOpName("Scale"), Input::Initializer(data_vector));
    Output reserve1 =
        ops::Const(s->WithOpName("Reserve1"), Input::Initializer(data_vector));
    Output reserve2 =
        ops::Const(s->WithOpName("Reserve2"), Input::Initializer(data_vector));

    ops::FusedBatchNormGrad::Attrs attrs;
    attrs.is_training_ = is_training;
    auto output =
        ops::FusedBatchNormGrad(s->WithOpName("FusedBatchNormGrad"), y_backprop,
                                x, scale, reserve1, reserve2, attrs);
    return output.x_backprop;
  }

  std::unique_ptr<VirtualCluster> virtual_cluster_;
};

TEST_F(LayoutOptimizerTest, Conv2DBackpropInput) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2DBackpropInput(&s, 7, 2, "SAME");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;

  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  string input_name = AddPrefixToNodeName("Conv2DBackpropInput-InputSizes",
                                          "LayoutOptimizer", "-");
  auto input_sizes_node = node_map.GetNode(input_name);
  CHECK(input_sizes_node);
  auto conv2d_backprop_node = node_map.GetNode("Conv2DBackpropInput");
  CHECK(conv2d_backprop_node);
  EXPECT_EQ(input_name, conv2d_backprop_node->input(0));
  auto input_sizes = GetAttrValue(*input_sizes_node);
  Tensor input_sizes_expected(DT_INT32, {4});
  test::FillValues<int>(&input_sizes_expected, {128, 3, 7, 7});
  test::ExpectTensorEqual<int>(input_sizes_expected, input_sizes);
}

TEST_F(LayoutOptimizerTest, Conv2DBackpropInputNonConstInputSizes) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2DBackpropInput(&s, 7, 2, "SAME", false);
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;

  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv2d_backprop_node = node_map.GetNode("Conv2DBackpropInput");
  CHECK(conv2d_backprop_node);
  EXPECT_EQ(conv2d_backprop_node->input(0),
            "LayoutOptimizerVecPermuteNHWCToNCHW_Conv2DBackpropInput_0");
  auto input_sizes_node = node_map.GetNode(
      "LayoutOptimizerVecPermuteNHWCToNCHW_Conv2DBackpropInput_0");
  CHECK(input_sizes_node);
  EXPECT_EQ(input_sizes_node->input(0), "InputSizesIdentity");
  EXPECT_EQ(input_sizes_node->op(), "DataFormatVecPermute");
}

TEST_F(LayoutOptimizerTest, FilterSizeIsOne) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 2, 1, "SAME");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  EXPECT_FALSE(
      node_map.GetNode("LayoutOptimizerTransposeNHWCToNCHW-Conv2D-Input"));
}

TEST_F(LayoutOptimizerTest, FilterSizeNotOne) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 2, 1, "SAME");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  EXPECT_FALSE(
      node_map.GetNode("LayoutOptimizerTransposeNHWCToNCHW-Conv2D-Input"));
}

TEST_F(LayoutOptimizerTest, EqualSizeWithValidPadding) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 2, 2, "VALID");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  EXPECT_FALSE(
      node_map.GetNode("LayoutOptimizerTransposeNHWCToNCHW-Conv2D-Input"));
}

TEST_F(LayoutOptimizerTest, EqualSizeWithSamePadding) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 2, 2, "SAME");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  EXPECT_TRUE(node_map.GetNode("LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0"));
}

TEST_F(LayoutOptimizerTest, NotEqualSizeWithValidPadding) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  EXPECT_TRUE(node_map.GetNode("LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0"));
}

TEST_F(LayoutOptimizerTest, Pad) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto c = ops::Const(s.WithOpName("c"), {1, 2, 3, 4, 5, 6, 7, 8}, {4, 2});
  auto p = ops::Pad(s.WithOpName("p"), conv, c);
  auto o = ops::Identity(s.WithOpName("o"), p);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);

  auto pad = node_map.GetNode("p");
  EXPECT_EQ(pad->input(0), "Conv2D");

  auto pad_const = node_map.GetNode("LayoutOptimizer-p-c");
  EXPECT_TRUE(pad_const);
  EXPECT_TRUE(pad_const->attr().find("value") != pad_const->attr().end());
  Tensor tensor;
  EXPECT_TRUE(
      tensor.FromProto(pad_const->mutable_attr()->at({"value"}).tensor()));
  Tensor tensor_expected(DT_INT32, {4, 2});
  test::FillValues<int>(&tensor_expected, {1, 2, 7, 8, 3, 4, 5, 6});
  test::ExpectTensorEqual<int>(tensor_expected, tensor);
}

TEST_F(LayoutOptimizerTest, Connectivity) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto i1 = ops::Identity(s.WithOpName("i1"), conv);
  auto i2 = ops::Identity(s.WithOpName("i2"), i1);
  auto i3 = ops::Identity(s.WithOpName("i3"), i2);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  // Make the graph not in topological order to test the handling of multi-hop
  // connectivity (here we say two nodes are connected if all nodes in the
  // middle are layout agnostic). If the graph is already in topological order,
  // the problem is easier, where layout optimizer only needs to check
  // single-hop connectivity.
  NodeMap node_map_original(&item.graph);
  auto node_i1 = node_map_original.GetNode("i1");
  auto node_i2 = node_map_original.GetNode("i2");
  node_i2->Swap(node_i1);
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map_output(&output);
  auto node_i2_output = node_map_output.GetNode("i2");
  // Layout optimizer should process i2, as it detects i2 is connected with the
  // Conv2D node two hops away. Similarly i1 is processed as well, as i1 is
  // directly connected to the Conv2D node. The two added transposes between
  // i1 and i2 should cancel each other, and as a result i2 is directly
  // connected to i1.
  EXPECT_EQ(node_i2_output->input(0), "i1");
}

TEST_F(LayoutOptimizerTest, ConnectivityBinaryOpWithInputScalarAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto i1 = ops::Identity(s.WithOpName("i1"), conv);
  auto i2 = ops::Identity(s.WithOpName("i2"), i1);
  auto scalar_sub = ops::Const(s.WithOpName("scalar_sub"), 3.0f, {});
  auto sub = ops::Sub(s.WithOpName("sub"), scalar_sub, i2);
  auto i3 = ops::Identity(s.WithOpName("i3"), sub);
  auto i4 = ops::Identity(s.WithOpName("i4"), i3);
  auto i5 = ops::Identity(s.WithOpName("i5"), i4);
  auto scalar_mul = ops::Const(s.WithOpName("scalar_mul"), 3.0f, {});
  auto mul = ops::Mul(s.WithOpName("mul"), scalar_mul, i5);
  auto i6 = ops::Identity(s.WithOpName("i6"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  // Make the graph not in topological order to test the handling of multi-hop
  // connectivity (here we say two nodes are connected if all nodes in the
  // middle are layout agnostic). If the graph is already in topological order,
  // the problem is easier, where layout optimizer only needs to check
  // single-hop connectivity.
  NodeMap node_map_original(&item.graph);
  auto node_i1 = node_map_original.GetNode("i1");
  auto node_mul = node_map_original.GetNode("mul");
  node_mul->Swap(node_i1);
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map_output(&output);
  auto mul_node = node_map_output.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "scalar_mul");
  EXPECT_EQ(mul_node->input(1), "i5");
}

TEST_F(LayoutOptimizerTest, PreserveFetch) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto i = ops::Identity(s.WithOpName("i"), conv);
  GrapplerItem item;
  item.fetch.push_back("Conv2D");
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("Conv2D");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NHWC");
}

TEST_F(LayoutOptimizerTest, EmptyDevice) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("Conv2D");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NCHW");
}

TEST_F(LayoutOptimizerTest, GPUDevice) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv =
      SimpleConv2D(&s, 4, 2, "VALID", "/job:w/replica:0/task:0/device:gpu:0");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("Conv2D");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NCHW");
}

TEST_F(LayoutOptimizerTest, CPUDeviceLowercase) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv =
      SimpleConv2D(&s, 4, 2, "VALID", "/job:w/replica:0/task:0/device:cpu:0");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("Conv2D");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NHWC");
}

TEST_F(LayoutOptimizerTest, CPUDeviceUppercase) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID", "/CPU:0");
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {conv});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("Conv2D");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NHWC");
}

TEST_F(LayoutOptimizerTest, FusedBatchNormGradTrainingTrue) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto x_backprop = SimpleFusedBatchNormGrad(&s, true);
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {x_backprop});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("FusedBatchNormGrad");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NCHW");
}

TEST_F(LayoutOptimizerTest, FusedBatchNormGradTrainingFalse) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto x_backprop = SimpleFusedBatchNormGrad(&s, false);
  Output fetch = ops::Identity(s.WithOpName("Fetch"), {x_backprop});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto conv_node = node_map.GetNode("FusedBatchNormGrad");
  EXPECT_EQ(conv_node->attr().at({"data_format"}).s(), "NHWC");
}

TEST_F(LayoutOptimizerTest, SplitDimC) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto c = ops::Const(s.WithOpName("c"), 3, {});
  auto split = ops::Split(s.WithOpName("split"), c, conv, 2);
  auto i = ops::Identity(s.WithOpName("i"), split[0]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto split_node = node_map.GetNode("split");
  EXPECT_EQ(split_node->input(0), "LayoutOptimizer-split-c");
  EXPECT_EQ(split_node->input(1), "Conv2D");
  auto split_const = node_map.GetNode("LayoutOptimizer-split-c");
  EXPECT_EQ(split_const->op(), "Const");
  EXPECT_EQ(split_const->attr().at({"value"}).tensor().int_val(0), 1);
}

TEST_F(LayoutOptimizerTest, SplitDimH) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 6, 2, "SAME");
  auto c = ops::Const(s.WithOpName("c"), 1, {});
  auto split = ops::Split(s.WithOpName("split"), c, conv, 2);
  auto i = ops::Identity(s.WithOpName("i"), split[0]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto split_node = node_map.GetNode("split");
  EXPECT_EQ(split_node->input(0), "LayoutOptimizer-split-c");
  EXPECT_EQ(split_node->input(1), "Conv2D");
  auto split_const = node_map.GetNode("LayoutOptimizer-split-c");
  EXPECT_EQ(split_const->op(), "Const");
  EXPECT_EQ(split_const->attr().at({"value"}).tensor().int_val(0), 2);
}

TEST_F(LayoutOptimizerTest, SplitDimW) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto c = ops::Const(s.WithOpName("c"), 2, {});
  auto split = ops::Split(s.WithOpName("split"), c, conv, 2);
  auto i = ops::Identity(s.WithOpName("i"), split[0]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto split_node = node_map.GetNode("split");
  EXPECT_EQ(split_node->input(0), "LayoutOptimizer-split-c");
  EXPECT_EQ(split_node->input(1), "Conv2D");
  auto split_const = node_map.GetNode("LayoutOptimizer-split-c");
  EXPECT_EQ(split_const->op(), "Const");
  EXPECT_EQ(split_const->attr().at({"value"}).tensor().int_val(0), 3);
}

TEST_F(LayoutOptimizerTest, SplitDimN) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto c = ops::Const(s.WithOpName("c"), 0, {});
  auto split = ops::Split(s.WithOpName("split"), c, conv, 2);
  auto i = ops::Identity(s.WithOpName("i"), split[0]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto split_node = node_map.GetNode("split");
  EXPECT_EQ(split_node->input(0), "LayoutOptimizer-split-c");
  EXPECT_EQ(split_node->input(1), "Conv2D");
  auto split_const = node_map.GetNode("LayoutOptimizer-split-c");
  EXPECT_EQ(split_const->op(), "Const");
  EXPECT_EQ(split_const->attr().at({"value"}).tensor().int_val(0), 0);
}

TEST_F(LayoutOptimizerTest, SplitNonConstDim) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto c = ops::Const(s.WithOpName("c"), 0, {});
  auto i1 = ops::Identity(s.WithOpName("i1"), c);
  auto split = ops::Split(s.WithOpName("split"), i1, conv, 2);
  auto i2 = ops::Identity(s.WithOpName("i"), split[0]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto split_node = node_map.GetNode("split");
  EXPECT_EQ(split_node->input(0), "LayoutOptimizerDimMapNHWCToNCHW_split_0");
  EXPECT_EQ(split_node->input(1), "Conv2D");
  auto map_node = node_map.GetNode("LayoutOptimizerDimMapNHWCToNCHW_split_0");
  EXPECT_EQ(map_node->op(), "DataFormatDimMap");
  EXPECT_EQ(map_node->input(0), "i1");
}

TEST_F(LayoutOptimizerTest, SplitSamePortToMultipleInputsOfSameNode) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto axis = ops::Const(s.WithOpName("axis"), 3);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat =
      ops::Concat(s.WithOpName("concat"), {split[1], split[1], split[1]}, axis);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split:1");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "split:1");
  EXPECT_EQ(concat_node->input(3), "LayoutOptimizer-concat-axis");
  auto concat_dim = node_map.GetNode("LayoutOptimizer-concat-axis");
  EXPECT_EQ(concat_dim->attr().at({"value"}).tensor().int_val(0), 1);
}

TEST_F(LayoutOptimizerTest, ConcatDimH) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "SAME");
  auto axis = ops::Const(s.WithOpName("axis"), 1);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat = ops::Concat(s.WithOpName("concat"), {split[0], split[1]}, axis);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "LayoutOptimizer-concat-axis");
  auto concat_dim = node_map.GetNode("LayoutOptimizer-concat-axis");
  EXPECT_EQ(concat_dim->attr().at({"value"}).tensor().int_val(0), 2);
}

TEST_F(LayoutOptimizerTest, ConcatNonConst) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "SAME");
  auto axis = ops::Const(s.WithOpName("axis"), 1);
  auto i = ops::Identity(s.WithOpName("i"), axis);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat = ops::Concat(s.WithOpName("concat"), {split[0], split[1]}, i);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "LayoutOptimizerDimMapNHWCToNCHW_concat_2");
  auto concat_dim =
      node_map.GetNode("LayoutOptimizerDimMapNHWCToNCHW_concat_2");
  EXPECT_EQ(concat_dim->op(), "DataFormatDimMap");
  EXPECT_EQ(concat_dim->input(0), "i");
}

TEST_F(LayoutOptimizerTest, ConcatDimW) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "SAME");
  auto axis = ops::Const(s.WithOpName("axis"), 2);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat = ops::Concat(s.WithOpName("concat"), {split[0], split[1]}, axis);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "LayoutOptimizer-concat-axis");
  auto concat_dim = node_map.GetNode("LayoutOptimizer-concat-axis");
  EXPECT_EQ(concat_dim->attr().at({"value"}).tensor().int_val(0), 3);
}

TEST_F(LayoutOptimizerTest, ConcatDimN) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto axis = ops::Const(s.WithOpName("axis"), 0);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat = ops::Concat(s.WithOpName("concat"), {split[0], split[1]}, axis);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "LayoutOptimizer-concat-axis");
  auto concat_dim = node_map.GetNode("LayoutOptimizer-concat-axis");
  EXPECT_EQ(concat_dim->attr().at({"value"}).tensor().int_val(0), 0);
}

TEST_F(LayoutOptimizerTest, ConcatDimC) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto axis = ops::Const(s.WithOpName("axis"), 3);
  auto split = ops::Split(s.WithOpName("split"), axis, conv, 2);
  auto concat = ops::Concat(s.WithOpName("concat"), {split[0], split[1]}, axis);
  auto o = ops::Identity(s.WithOpName("o"), concat);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto concat_node = node_map.GetNode("concat");
  EXPECT_EQ(concat_node->input(0), "split");
  EXPECT_EQ(concat_node->input(1), "split:1");
  EXPECT_EQ(concat_node->input(2), "LayoutOptimizer-concat-axis");
  auto concat_dim = node_map.GetNode("LayoutOptimizer-concat-axis");
  EXPECT_EQ(concat_dim->attr().at({"value"}).tensor().int_val(0), 1);
}

TEST_F(LayoutOptimizerTest, Sum) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto reduction_indices =
      ops::Const(s.WithOpName("reduction_indices"), {0, 1, 2}, {3});
  auto sum = ops::Sum(s.WithOpName("sum"), conv, reduction_indices);
  auto o = ops::Identity(s.WithOpName("o"), sum);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  // TODO(yaozhang): enable SumProcessor with auto-tuning. Currently disabled
  // because of the worse performance in some cases.
  /*
  NodeMap node_map(&output);
  auto sum_node = node_map.GetNode("sum");
  EXPECT_EQ(sum_node->input(0), "Conv2D");
  EXPECT_EQ(sum_node->input(1), "LayoutOptimizer-sum-reduction_indices");
  auto sum_const = node_map.GetNode("LayoutOptimizer-sum-reduction_indices");
  Tensor tensor;
  EXPECT_TRUE(
      tensor.FromProto(sum_const->mutable_attr()->at({"value"}).tensor()));
  Tensor tensor_expected(DT_INT32, {3});
  test::FillValues<int>(&tensor_expected, {0, 2, 3});
  test::ExpectTensorEqual<int>(tensor_expected, tensor);
  */
}

TEST_F(LayoutOptimizerTest, MulScalarAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto scalar = ops::Const(s.WithOpName("scalar"), 3.0f, {});
  auto mul = ops::Mul(s.WithOpName("mul"), scalar, conv);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "scalar");
  EXPECT_EQ(mul_node->input(1), "Conv2D");
}

TEST_F(LayoutOptimizerTest, Mul4DAndScalar) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto scalar = ops::Const(s.WithOpName("scalar"), 3.0f, {});
  auto mul = ops::Mul(s.WithOpName("mul"), conv, scalar);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "Conv2D");
  EXPECT_EQ(mul_node->input(1), "scalar");
}

TEST_F(LayoutOptimizerTest, Mul4DAndUnknownRank) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto unknown_rank =
      ops::Placeholder(s.WithOpName("unknown"), DT_FLOAT,
                       ops::Placeholder::Shape(PartialTensorShape()));
  Output c = ops::Const(s.WithOpName("c"), 3.0f, {8, 2, 2, 2});
  Output mul = ops::Mul(s.WithOpName("mul"), conv, unknown_rank);
  auto o = ops::AddN(s.WithOpName("o"), {mul, c});
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  // Node mul should not be processed by layout optimizer, because one of its
  // inputs is of unknown rank.
  EXPECT_EQ(mul_node->input(0),
            "LayoutOptimizerTransposeNCHWToNHWC-Conv2D-0-0");
  EXPECT_EQ(mul_node->input(1), "unknown");
}

TEST_F(LayoutOptimizerTest, Mul4DAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto i = ops::Identity(s.WithOpName("i"), conv);
  auto mul = ops::Mul(s.WithOpName("mul"), conv, i);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "Conv2D");
  EXPECT_EQ(mul_node->input(1), "i");
}

TEST_F(LayoutOptimizerTest, Mul4DAndVector) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto vector = ops::Const(s.WithOpName("vector"), {3.0f, 7.0f}, {2});
  auto mul = ops::Mul(s.WithOpName("mul"), conv, vector);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "Conv2D");
  EXPECT_EQ(mul_node->input(1), "LayoutOptimizerReshapeNHWCToNCHW-mul-1");
  auto mul_const = node_map.GetNode("LayoutOptimizerReshapeConst-mul-1");
  Tensor tensor;
  EXPECT_TRUE(
      tensor.FromProto(mul_const->mutable_attr()->at({"value"}).tensor()));
  Tensor tensor_expected(DT_INT32, {4});
  test::FillValues<int>(&tensor_expected, {1, 2, 1, 1});
  test::ExpectTensorEqual<int>(tensor_expected, tensor);
}

TEST_F(LayoutOptimizerTest, MulVectorAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto vector = ops::Const(s.WithOpName("vector"), {3.0f, 7.0f}, {2});
  auto mul = ops::Mul(s.WithOpName("mul"), vector, conv);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto mul_node = node_map.GetNode("mul");
  EXPECT_EQ(mul_node->input(0), "LayoutOptimizerReshapeNHWCToNCHW-mul-0");
  EXPECT_EQ(mul_node->input(1), "Conv2D");
  auto mul_const = node_map.GetNode("LayoutOptimizerReshapeConst-mul-0");
  Tensor tensor;
  EXPECT_TRUE(
      tensor.FromProto(mul_const->mutable_attr()->at({"value"}).tensor()));
  Tensor tensor_expected(DT_INT32, {4});
  test::FillValues<int>(&tensor_expected, {1, 2, 1, 1});
  test::ExpectTensorEqual<int>(tensor_expected, tensor);
}

TEST_F(LayoutOptimizerTest, SliceConst) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto begin = ops::Const(s.WithOpName("begin"), {0, 2, 3, 1}, {4});
  auto size = ops::Const(s.WithOpName("size"), {4, 1, 2, 4}, {4});
  auto slice = ops::Slice(s.WithOpName("slice"), conv, begin, size);
  auto o = ops::Identity(s.WithOpName("o"), slice);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto slice_node = node_map.GetNode("slice");
  EXPECT_EQ(slice_node->input(0), "Conv2D");
  EXPECT_EQ(slice_node->input(1), "LayoutOptimizer-slice-begin");
  EXPECT_EQ(slice_node->input(2), "LayoutOptimizer-slice-size");

  auto begin_const = node_map.GetNode("LayoutOptimizer-slice-begin");
  Tensor begin_tensor;
  EXPECT_TRUE(begin_tensor.FromProto(
      begin_const->mutable_attr()->at({"value"}).tensor()));
  Tensor begin_tensor_expected(DT_INT32, {4});
  test::FillValues<int>(&begin_tensor_expected, {0, 1, 2, 3});
  test::ExpectTensorEqual<int>(begin_tensor_expected, begin_tensor);

  auto size_const = node_map.GetNode("LayoutOptimizer-slice-size");
  Tensor size_tensor;
  EXPECT_TRUE(size_tensor.FromProto(
      size_const->mutable_attr()->at({"value"}).tensor()));
  Tensor size_tensor_expected(DT_INT32, {4});
  test::FillValues<int>(&size_tensor_expected, {4, 4, 1, 2});
  test::ExpectTensorEqual<int>(size_tensor_expected, size_tensor);
}

TEST_F(LayoutOptimizerTest, SliceNonConst) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 5, 2, "VALID");
  auto begin = ops::Const(s.WithOpName("begin"), {0, 2, 3, 1}, {4});
  auto ibegin = ops::Identity(s.WithOpName("ibegin"), begin);
  auto size = ops::Const(s.WithOpName("size"), {4, 1, 2, 4}, {4});
  auto isize = ops::Identity(s.WithOpName("isize"), size);
  auto slice = ops::Slice(s.WithOpName("slice"), conv, ibegin, isize);
  auto o = ops::Identity(s.WithOpName("o"), slice);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto slice_node = node_map.GetNode("slice");
  EXPECT_EQ(slice_node->input(0), "Conv2D");
  EXPECT_EQ(slice_node->input(1),
            "LayoutOptimizerVecPermuteNHWCToNCHW_slice_1");
  EXPECT_EQ(slice_node->input(2),
            "LayoutOptimizerVecPermuteNHWCToNCHW_slice_2");
  auto perm1 = node_map.GetNode("LayoutOptimizerVecPermuteNHWCToNCHW_slice_1");
  EXPECT_EQ(perm1->op(), "DataFormatVecPermute");
  EXPECT_EQ(perm1->input(0), "ibegin");
  auto perm2 = node_map.GetNode("LayoutOptimizerVecPermuteNHWCToNCHW_slice_2");
  EXPECT_EQ(perm1->op(), "DataFormatVecPermute");
  EXPECT_EQ(perm2->input(0), "isize");
}

TEST_F(LayoutOptimizerTest, DoNotApplyOptimizerTwice) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto scalar =
      ops::Const(s.WithOpName("LayoutOptimizerAlreadyApplied"), 3.0f, {});
  auto mul = ops::Mul(s.WithOpName("mul"), scalar, scalar);
  auto o = ops::Identity(s.WithOpName("o"), mul);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  EXPECT_TRUE(errors::IsInvalidArgument(status));
}

TEST_F(LayoutOptimizerTest, ShapeNWithInputs4DAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto shapen = ops::ShapeN(s.WithOpName("shapen"), {conv, conv});
  auto add = ops::Add(s.WithOpName("add"), shapen[0], shapen[1]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto shapen_node = node_map.GetNode("shapen");
  EXPECT_EQ(shapen_node->input(0), "Conv2D");
  EXPECT_EQ(shapen_node->input(1), "Conv2D");
  auto add_node = node_map.GetNode("add");
  EXPECT_EQ(add_node->input(0),
            "LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-0");
  EXPECT_EQ(add_node->input(1),
            "LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-1");
  auto vec_permute1 =
      node_map.GetNode("LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-0");
  EXPECT_EQ(vec_permute1->input(0), "shapen");
  EXPECT_EQ(vec_permute1->op(), "DataFormatVecPermute");
  auto vec_permute2 =
      node_map.GetNode("LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-1");
  EXPECT_EQ(vec_permute2->input(0), "shapen:1");
  EXPECT_EQ(vec_permute2->op(), "DataFormatVecPermute");
}

TEST_F(LayoutOptimizerTest, ShapeNWithInputsVectorAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto vector = ops::Const(s.WithOpName("vector"), 3.0f, {7});
  auto shapen = ops::ShapeN(s.WithOpName("shapen"), {vector, conv});
  auto add = ops::Add(s.WithOpName("add"), shapen[0], shapen[1]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto shapen_node = node_map.GetNode("shapen");
  EXPECT_EQ(shapen_node->input(0), "vector");
  EXPECT_EQ(shapen_node->input(1), "Conv2D");
  auto add_node = node_map.GetNode("add");
  EXPECT_EQ(add_node->input(0), "shapen");
  EXPECT_EQ(add_node->input(1),
            "LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-1");
  auto vec_permute =
      node_map.GetNode("LayoutOptimizerVecPermuteNCHWToNHWC-shapen-0-1");
  EXPECT_EQ(vec_permute->input(0), "shapen:1");
  EXPECT_EQ(vec_permute->op(), "DataFormatVecPermute");
}

TEST_F(LayoutOptimizerTest, ShapeNWithInputs4DAndNoNeedToTransform4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto tensor_4d = ops::Const(s.WithOpName("tensor_4d"), 3.0f, {1, 1, 1, 3});
  auto i1 = ops::Identity(s.WithOpName("i1"), tensor_4d);
  Output i2 = ops::Identity(s.WithOpName("i2"), i1);
  auto shapen = ops::ShapeN(s.WithOpName("shapen"), {conv, i2});
  auto add = ops::Add(s.WithOpName("add"), shapen[0], shapen[1]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto shapen_node = node_map.GetNode("shapen");
  EXPECT_EQ(shapen_node->input(0), "Conv2D");
  EXPECT_EQ(shapen_node->input(1), "i2");
}

TEST_F(LayoutOptimizerTest, Switch) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  ops::Variable ctrl(s.WithOpName("ctrl"), {}, DT_BOOL);
  auto sw = ops::Switch(s.WithOpName("switch"), conv, ctrl);
  auto i1 = ops::Identity(s.WithOpName("i1"), sw.output_true);
  auto i2 = ops::Identity(s.WithOpName("i2"), sw.output_false);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto switch_node = node_map.GetNode("switch");
  EXPECT_EQ(switch_node->input(0), "Conv2D");
  EXPECT_EQ(switch_node->input(1), "ctrl");
  auto i1_node = node_map.GetNode("i1");
  auto i2_node = node_map.GetNode("i2");
  auto trans1 = node_map.GetNode(i1_node->input(0));
  EXPECT_EQ(trans1->input(0), "switch:1");
  auto trans2 = node_map.GetNode(i2_node->input(0));
  EXPECT_EQ(trans2->input(0), "switch");
}

TEST_F(LayoutOptimizerTest, MergeBothInputsConvertible) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  Output i1 = ops::Identity(s.WithOpName("i1"), conv);
  auto merge = ops::Merge(s.WithOpName("merge"), {conv, i1});
  auto i2 = ops::Identity(s.WithOpName("i2"), merge.output);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto merge_node = node_map.GetNode("merge");
  EXPECT_EQ(merge_node->input(0), "Conv2D");
  EXPECT_EQ(merge_node->input(1), "i1");
  auto i2_node = node_map.GetNode("i2");
  EXPECT_EQ(i2_node->input(0), "LayoutOptimizerTransposeNCHWToNHWC-merge-0-0");
  auto transpose =
      node_map.GetNode("LayoutOptimizerTransposeNCHWToNHWC-merge-0-0");
  EXPECT_EQ(transpose->input(0), "merge");
}

TEST_F(LayoutOptimizerTest, MergeOneInputNotConvertible) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto tensor_4d = ops::Const(s.WithOpName("tensor_4d"), 3.0f, {1, 1, 1, 3});
  auto merge = ops::Merge(s.WithOpName("merge"), {tensor_4d, conv});
  auto i2 = ops::Identity(s.WithOpName("i2"), merge.output);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto merge_node = node_map.GetNode("merge");
  EXPECT_EQ(merge_node->input(0), "tensor_4d");
  EXPECT_EQ(merge_node->input(1),
            "LayoutOptimizerTransposeNCHWToNHWC-Conv2D-0-1");
}

TEST_F(LayoutOptimizerTest, Complex) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto comp = ops::Complex(s.WithOpName("complex"), conv, conv);
  auto i = ops::Identity(s.WithOpName("i"), comp);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto merge_node = node_map.GetNode("complex");
  EXPECT_EQ(merge_node->input(0), "Conv2D");
  EXPECT_EQ(merge_node->input(1), "Conv2D");
  auto trans =
      node_map.GetNode("LayoutOptimizerTransposeNCHWToNHWC-complex-0-0");
  EXPECT_EQ(trans->attr().at("T").type(), DT_COMPLEX64);
}

TEST_F(LayoutOptimizerTest, IdentityNWithInputsVectorAnd4D) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  auto conv = SimpleConv2D(&s, 4, 2, "VALID");
  auto vector = ops::Const(s.WithOpName("vector"), 3.0f, {2});
  auto identity_n = ops::IdentityN(s.WithOpName("identity_n"), {vector, conv});
  auto add = ops::Add(s.WithOpName("add"), identity_n[0], identity_n[1]);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  LayoutOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(virtual_cluster_.get(), item, &output);
  NodeMap node_map(&output);
  auto i = node_map.GetNode("identity_n");
  EXPECT_EQ(i->input(0), "vector");
  EXPECT_EQ(i->input(1), "Conv2D");
  auto trans =
      node_map.GetNode("LayoutOptimizerTransposeNCHWToNHWC-identity_n-0-1");
  EXPECT_EQ(trans->input(0), "identity_n:1");
  auto add_node = node_map.GetNode("add");
  EXPECT_EQ(add_node->input(0), "identity_n");
  EXPECT_EQ(add_node->input(1),
            "LayoutOptimizerTransposeNCHWToNHWC-identity_n-0-1");
}
}  // namespace
}  // namespace grappler
}  // namespace tensorflow


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 StockManagement.ObjectModel.MangeObject;

import StockManagement.ObjectModel.ValueObject.Stock;
import StockManagement.ObjectModel.ValueObject.Product;
import StockManagement.ObjectModel.ValueObject.StockProduct;
import StockManagement.ObjectModel.ValueObject.Branch;
import StockManagement.ObjectModel.ValueObject.BranchProduct;
import StockManagement.ObjectModel.ObjectInterface.IProduct;
import StockManagement.ObjectModel.Utilities.HibernateUtil;
import StockManagement.ObjectModel.Utilities.StatusEnum;
import StockManagement.ObjectModel.ValueObject.Brand;
import StockManagement.ObjectModel.ValueObject.Order;
import StockManagement.ObjectModel.ValueObject.Supplier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author mfaour
 */
public class ProductController implements IProduct {

    private SessionFactory _sessionFactory;
    private Session _session;

    public ProductController() {
        _sessionFactory = HibernateUtil.getSessionFactory();
        _session = _sessionFactory.openSession();
    }

    @Override
    public Product get(int prCode) {
        Object objProduct = _session.get(Product.class, prCode);
        if (null == objProduct) {
            return null;
        }
        Product original = (Product) objProduct;
        Product copy = new Product();
        copy.setCostPrice(original.getCostPrice());
        copy.setPrBarCode(original.getPrBarCode());
        copy.setPrCode(original.getPrCode());
        copy.setPrFamily(original.getPrFamily());
        copy.setPrName(original.getPrName());
        copy.setPrSeason(original.getPrSeason());
        copy.setPrStatus(original.isPrStatus());
        copy.setPrType(original.getPrType());
        copy.setSellingPrice(original.getSellingPrice());

        return copy;
    }

    @Override
    public Product getByBarcode(String prBarcode) {
        List<Product> products = _session.createQuery("From Product where PrBarCode = " + prBarcode).list();

        if (null == products || products.isEmpty()) {
            return null;
        }
        return products.get(0);
    }

    @Override
    public List<Product> getByType(int prType) {
        List<Product> products = _session.createQuery("From Product where PrType = " + prType).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        return products;
    }

    @Override
    public List<Product> getAll() {
        List<Product> prdts = _session.createQuery("From Product").list();
        if (null == prdts || prdts.isEmpty()) {
            return null;
        }
        return prdts;
    }

    @Override
    public List<Product> getAll(StatusEnum status) {
        String query = "From Product";
        if (status == StatusEnum.Active) {
            query += " where PrStatus =1";
        } else if (status == StatusEnum.Inactive) {
            query += " where PrStatus =0";
        }

        List<Product> products = _session.createQuery(query).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        return products;
    }

    @Override
    public List<Product> getBySupplier(int supCode) {
        List<Product> products = _session.createQuery("From Product where supCode = " + supCode).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        List<Product> newList = new ArrayList();
        for (int i = 0; i < products.size(); i++) {
            Product original = products.get(i);
            Product copy = new Product();
            copy.setCostPrice(original.getCostPrice());
            copy.setPrBarCode(original.getPrBarCode());
            copy.setPrCode(original.getPrCode());
            copy.setPrFamily(original.getPrFamily());
            copy.setPrName(original.getPrName());
            copy.setPrSeason(original.getPrSeason());
            copy.setPrStatus(original.isPrStatus());
            copy.setPrType(original.getPrType());
            copy.setSellingPrice(original.getSellingPrice());
            newList.add(copy);
        }
        return newList;

    }

    @Override
    public List<StockProduct> getStockProductByStock(int stkCode) {
        List<StockProduct> products = _session.createQuery("from StockProduct where stkCode = " + stkCode).list();
        if (null == products || products.isEmpty()) {
            return null;
        }

        for (int i = 0; i < products.size(); i++) {
            StockProduct sp = new StockProduct();
            sp.setStkPrQty(products.get(i).getStkPrQty());
        }
        return products;
    }

    @Override
    public List<Product> getByStock(int stkCode) {
        List<Product> products = _session.createQuery("select P from Product P,StockProduct SP where P.prCode= SP.product.prCode and SP.stock.stkCode = " + stkCode).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        List<Product> newList = new ArrayList();
        for (int i = 0; i < products.size(); i++) {
            Product original = products.get(i);
            Product copy = new Product();
            copy.setCostPrice(original.getCostPrice());
            copy.setPrBarCode(original.getPrBarCode());
            copy.setPrCode(original.getPrCode());
            copy.setPrFamily(original.getPrFamily());
            copy.setPrName(original.getPrName());
            copy.setPrSeason(original.getPrSeason());
            copy.setPrStatus(original.isPrStatus());
            copy.setPrType(original.getPrType());
            copy.setSellingPrice(original.getSellingPrice());
            Set spObject = original.getStockProducts();
            StockProduct sp = null;
            if (spObject != null && !spObject.isEmpty()) {
                sp = (StockProduct) spObject.iterator().next();
            }
            if (sp != null) {
                copy.setPrQty(sp.getStkPrQty());
            }

            Supplier supObject = original.getSupplier();
            if (supObject != null) {
                copy.setSupplierName(supObject.getSupName());
            }

            newList.add(copy);
        }
        return newList;
    }

    @Override
    public List<Product> getByBrand(int brdCode) {
        List<Product> products = _session.createQuery("From Product where BrdCode = " + brdCode).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        return products;
    }

    @Override
    public List<Product> getByBranch(int brCode) {
        List<Product> products = _session.createQuery("Select Product.* From Product join BranchProduct "
                + "where Product.PrCode = BranchProduct.PrCode and BranchProduct.BrCode = " + brCode).list();
        if (null == products || products.isEmpty()) {
            return null;
        }
        return products;
    }

    @Override
    public int add(Product product) {
        try {
            Transaction tx = _session.beginTransaction();
            _session.save(product);
            tx.commit();
            return product.getPrCode();
        } catch (Exception e) {
            throw (e);
        } finally {
            /* if (!_sessionFactory.isClosed()) {
                _sessionFactory.close();
            }*/
        }
    }

    @Override
    public boolean addToStock(Product product, Stock stock, int qty) {
        try {
            StockProduct stockProduct = new StockProduct();
            stockProduct.setProduct(product);
            stockProduct.setStock(stock);
            stockProduct.setStkPrQty(qty);

            Transaction tx = _session.beginTransaction();
            _session.save(stockProduct);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean addToStock(StockProduct stockproduct) {
        try {
            if (null == stockproduct
                    || null == stockproduct.getStock()
                    || null == stockproduct.getProduct()) {
                return false;
            }
            Transaction tx = _session.beginTransaction();
            _session.save(stockproduct);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean addToBranch(Product product, Branch branch, int qty) {
        try {

            BranchProduct productBranch = new BranchProduct();
            productBranch.setProduct(product);
            productBranch.setBranch(branch);
            productBranch.setQty(qty);

            Transaction tx = _session.beginTransaction();
            _session.save(productBranch);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean addToBranch(BranchProduct branchProduct) {
        try {
            if (null == branchProduct
                    || null == branchProduct.getBranch()
                    || null == branchProduct.getProduct()) {
                return false;
            }
            Transaction tx = _session.beginTransaction();
            _session.save(branchProduct);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean delete(Product product) {
        try {
            Transaction tx = _session.beginTransaction();
            _session.delete(product);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean delete(int prCode) {
        try {
            Transaction tx = _session.beginTransaction();
            _session.createQuery("delete from Product where prCode= " + prCode).executeUpdate();
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public boolean update(Product product) {
        try {
            Transaction tx = _session.beginTransaction();
            _session.update(product);
            tx.commit();
            return true;
        } catch (Exception e) {
            throw (e);
        }
    }

    @Override
    public List<Brand> getAllBrands() {
        BrandController controller = new BrandController();
        return controller.getAll();
    }

    @Override
    public Stock getStock(int stkCode) {
        List<Stock> stocks = _session.createQuery("From Stock where stkCode = " + stkCode).list();
        if (null == stocks || stocks.isEmpty()) {
            return null;
        }
        Stock original = stocks.get(0);
        Stock copy = new Stock();
        copy.setStkAddress(original.getStkAddress());
        copy.setStkCode(original.getStkCode());
        copy.setStkName(original.getStkName());
        copy.setStkTel(original.getStkTel());
        return copy;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#!/bin/bash
set -x
basedir=$(realpath $1)
tag=${2:-"master"}
cd $basedir
if [[ ! -e smartentry ]]; then
    git clone https://github.com/gaoyifan/smartentry.git smartentry
fi
cd smartentry
git fetch origin --tag
commit_id=$(git rev-list -n 1 $tag)
git reset --hard $commit_id
cd $basedir
find $basedir -mindepth 2 -maxdepth 2 -type d -not -path '*/.git/*' -not -path '*/smartentry/*' |
while read dir; do
    cp $basedir/smartentry/smartentry.sh $dir;
done
git commit -a -m $commit_id
git tag $tag


text:
package edu.gemini.obslog.config;

import edu.gemini.obslog.config.model.OlConfiguration;
import edu.gemini.obslog.config.model.OlModelException;
import edu.gemini.obslog.config.xml.OlXmlConfiguration;

import java.io.Serializable;
import java.util.logging.Logger;

//
// Gemini Observatory/AURA
// $Id: OlDefaultConfigurationProducer.java,v 1.3 2005/03/17 06:04:33 gillies Exp $
//

public class OlDefaultConfigurationProducer implements OlConfigurationProducer, Serializable {
    public static final Logger LOG = Logger.getLogger(OlDefaultConfigurationProducer.class.getName());

    static private String _CONFIG_FILE = "/ObsLogConfig.xml";

    private OlConfiguration _configuration;

    /**
     * Default constructor uses default config file
     */
    public OlDefaultConfigurationProducer() {
    }

    public OlDefaultConfigurationProducer(String configFile) {
        if (configFile == null) throw new IllegalArgumentException();

        _CONFIG_FILE = configFile;
    }

    public synchronized OlConfiguration getModel() throws OlConfigException, OlModelException {
        if (_configuration == null) {
            LOG.fine("Reading the config file: " + _CONFIG_FILE);
            OlXmlConfiguration _cr = new OlXmlConfiguration(_CONFIG_FILE);
            _configuration = _cr.getModel();
        }
        return _configuration;
    }

}


text:
if readlink /proc/$$/exe | grep -qs "dash"; then
	echo "This script needs to be run with bash, not sh"
	exit 1
fi

if [[ "$EUID" -ne 0 ]]; then
	echo "Sorry, you need to run this as root"
	exit 2
fi

if [[ ! -e /dev/net/tun ]]; then
	echo "TUN is not available"
	exit 3
fi

if grep -qs "CentOS release 5" "/etc/redhat-release"; then
	echo "CentOS 5 is too old and not supported"
	exit 4
fi
if [[ -e /etc/debian_version ]]; then
	OS=debian
	GROUPNAME=nogroup
	RCLOCAL='/etc/rc.local'
elif [[ -e /etc/centos-release || -e /etc/redhat-release ]]; then
	OS=centos
	GROUPNAME=nobody
	RCLOCAL='/etc/rc.d/rc.local'
else
	echo "Looks like you aren't running this installer on a Debian, Ubuntu or CentOS system"
	exit 5
fi

newclient () {
	# Generates the custom client.ovpn
	cp /etc/openvpn/client-common.txt ~/$1.ovpn
	echo "<ca>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/ca.crt >> ~/$1.ovpn
	echo "</ca>" >> ~/$1.ovpn
	echo "<cert>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/issued/$1.crt >> ~/$1.ovpn
	echo "</cert>" >> ~/$1.ovpn
	echo "<key>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/private/$1.key >> ~/$1.ovpn
	echo "</key>" >> ~/$1.ovpn
	echo "<tls-auth>" >> ~/$1.ovpn
	cat /etc/openvpn/ta.key >> ~/$1.ovpn
	echo "</tls-auth>" >> ~/$1.ovpn
}

# Try to get our IP from the system and fallback to the Internet.
# I do this to make the script compatible with NATed servers (lowendspirit.com)
# and to avoid getting an IPv6.
IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
if [[ "$IP" = "" ]]; then
		IP=$(wget -4qO- "http://whatismyip.akamai.com/")
fi

if [[ -e /etc/openvpn/server.conf ]]; then
	while :
	do
	clear
		echo "OpenVPN já está instalado"
		echo ""
		echo "O que você deseja fazer?"
		echo "   1) Adicionar novo usuário"
		echo "   2) Remover um usuário"
		echo "   3) Remover OpenVPN"
		echo "   4) Sair"
		read -p "Selecione a opção [1-4]: " option
		case $option in
			1)
			echo ""
			echo "Diga-me um nome para o usuario"
			echo "Use somente o nome sem caracteres especiais"
			read -p "Client name: " -e -i client CLIENT
			cd /etc/openvpn/easy-rsa/
			./easyrsa build-client-full $CLIENT nopass
			# Generates the custom client.ovpn
			newclient "$CLIENT"
			echo ""
			echo "Client $CLIENT added, configuration is available at" ~/"$CLIENT.ovpn"
			exit
			;;
			2)
			# This option could be documented a bit better and maybe even be simplimplified
			# ...but what can I say, I want some sleep too
			NUMBEROFCLIENTS=$(tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep -c "^V")
			if [[ "$NUMBEROFCLIENTS" = '0' ]]; then
				echo ""
				echo "Você não tem usuarios existentes!"
				exit 6
			fi
			echo ""
			echo "Selecione um usuario para remover"
			tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | nl -s ') '
			if [[ "$NUMBEROFCLIENTS" = '1' ]]; then
				read -p "Selecione um usuario [1]: " CLIENTNUMBER
			else
				read -p "Selecione um usuario [1-$NUMBEROFCLIENTS]: " CLIENTNUMBER
			fi
			CLIENT=$(tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | sed -n "$CLIENTNUMBER"p)
			cd /etc/openvpn/easy-rsa/
			./easyrsa --batch revoke $CLIENT
			./easyrsa gen-crl
			rm -rf pki/reqs/$CLIENT.req
			rm -rf pki/private/$CLIENT.key
			rm -rf pki/issued/$CLIENT.crt
			rm -rf /etc/openvpn/crl.pem
			cp /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn/crl.pem
			# CRL is read with each client connection, when OpenVPN is dropped to nobody
			chown nobody:$GROUPNAME /etc/openvpn/crl.pem
			echo ""
			echo "Usuario removido"
			exit
			;;
			3)
			echo ""
			read -p "Você deseja remover OpenVPN? [y/n]: " -e -i n REMOVE
			if [[ "$REMOVE" = 'y' ]]; then
				PORT=$(grep '^port ' /etc/openvpn/server.conf | cut -d " " -f 2)
				PROTOCOL=$(grep '^proto ' /etc/openvpn/server.conf | cut -d " " -f 2)
				IP=$(grep 'iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to ' $RCLOCAL | cut -d " " -f 11)
				if pgrep firewalld; then
					# Using both permanent and not permanent rules to avoid a firewalld reload.
					firewall-cmd --zone=public --remove-port=$PORT/$PROTOCOL
					firewall-cmd --zone=trusted --remove-source=10.8.0.0/24
					firewall-cmd --permanent --zone=public --remove-port=$PORT/$PROTOCOL
					firewall-cmd --permanent --zone=trusted --remove-source=10.8.0.0/24
				fi
				if iptables -L -n | grep -qE 'REJECT|DROP|ACCEPT'; then
					iptables -D INPUT -p $PROTOCOL --dport $PORT -j ACCEPT
					iptables -D FORWARD -s 10.8.0.0/24 -j ACCEPT
					iptables -D FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
					sed -i "/iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT/d" $RCLOCAL
					sed -i "/iptables -I FORWARD -s 10.8.0.0\/24 -j ACCEPT/d" $RCLOCAL
					sed -i "/iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT/d" $RCLOCAL
				fi
				iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP
				sed -i '/iptables -t nat -A POSTROUTING -s 10.8.0.0\/24 -j SNAT --to /d' $RCLOCAL
				if hash sestatus 2>/dev/null; then
					if sestatus | grep "Current mode" | grep -qs "enforcing"; then
						if [[ "$PORT" != '1194' || "$PROTOCOL" = 'tcp' ]]; then
							semanage port -d -t openvpn_port_t -p $PROTOCOL $PORT
						fi
					fi
				fi
				if [[ "$OS" = 'debian' ]]; then
					apt-get remove --purge -y openvpn openvpn-blacklist
				else
					yum remove openvpn -y
				fi
				rm -rf /etc/openvpn
				rm -rf /usr/share/doc/openvpn*
				echo ""
				echo "OpenVPN removido!"
			else
				echo ""
				echo "Remoção abordada!"
			fi
			exit
			;;
			4) exit;;
		esac
	done
else
	clear
	echo 'Bem vindo ao instalador OpenVPN "@Guilhermevps" installer'
	echo ""
	# OpenVPN instalador e criação do primeiro usuario
	echo "Responda as perguntas para iniciar a instalação"
	echo "Responda corretamente"
	echo ""
	echo "Primeiro precisaremos do ip de sua maquina,este ip está correto ?"
	echo "listening to."
	read -p "IP address: " -e -i $IP IP
	echo ""
	echo "Qual protocolo você deseja para as conexões OPENVPN ?"
	echo "   1) UDP"
	echo "   2) TCP (Recomendado)"
	read -p "Protocol [1-2]: " -e -i 2 PROTOCOL
	case $PROTOCOL in
		1)
		PROTOCOL=udp
		;;
		2)
		PROTOCOL=tcp
		;;
	esac
	echo ""
	echo "Qual porta você deseja usar ?"
	read -p "Port: " -e -i 1194 PORT
	echo ""
	echo "Qual DNS você deseja usar ?"
	echo "   1) Sistema(Recomendado)"
	echo "   2) Google"
	echo "   3) OpenDNS"
	echo "   4) NTT"
	echo "   5) Hurricane Electric"
	echo "   6) Verisign"
	read -p "DNS [1-6]: " -e -i 1 DNS
	echo ""
	echo "Agora,digite o nome de seu primeiro usuario"
	echo "Use somente o nome,sem caracteres especiais"
	read -p "Client name: " -e -i client CLIENT
	echo ""
	echo "Okay, você está pronto para executar o openvpn "
	read -n1 -r -p "Pressione uma tecla para continuar..."
	if [[ "$OS" = 'debian' ]]; then
		apt-get upgrade
		apt-get install openvpn iptables openssl ca-certificates -y
	else
		# Else, the distro is CentOS
		yum install epel-release -y
		yum install openvpn iptables openssl wget ca-certificates -y
	fi
	# An old version of easy-rsa was available by default in some openvpn packages
	if [[ -d /etc/openvpn/easy-rsa/ ]]; then
		rm -rf /etc/openvpn/easy-rsa/
	fi
	# Adquirindo easy-rsa
	wget -O ~/EasyRSA-3.0.1.tgz "https://github.com/OpenVPN/easy-rsa/releases/download/3.0.1/EasyRSA-3.0.1.tgz"
	tar xzf ~/EasyRSA-3.0.1.tgz -C ~/
	mv ~/EasyRSA-3.0.1/ /etc/openvpn/
	mv /etc/openvpn/EasyRSA-3.0.1/ /etc/openvpn/easy-rsa/
	chown -R root:root /etc/openvpn/easy-rsa/
	rm -rf ~/EasyRSA-3.0.1.tgz
	cd /etc/openvpn/easy-rsa/
	# Create the PKI, set up the CA, the DH params and the server + client certificates
	./easyrsa init-pki
	./easyrsa --batch build-ca nopass
	./easyrsa gen-dh
	./easyrsa build-server-full server nopass
	./easyrsa build-client-full $CLIENT nopass
	./easyrsa gen-crl
	# Move the stuff we need
	cp pki/ca.crt pki/private/ca.key pki/dh.pem pki/issued/server.crt pki/private/server.key /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn
	# CRL is read with each client connection, when OpenVPN is dropped to nobody
	chown nobody:$GROUPNAME /etc/openvpn/crl.pem
	# Generando key for tls-auth
	openvpn --genkey --secret /etc/openvpn/ta.key
	# Generando server.conf
	echo "port $PORT
proto $PROTOCOL
dev tun
sndbuf 0
rcvbuf 0
ca ca.crt
cert server.crt
key server.key
dh dh.pem
tls-auth ta.key 0
topology subnet
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt" > /etc/openvpn/server.conf
	echo 'push "redirect-gateway def1 bypass-dhcp"' >> /etc/openvpn/server.conf
	# DNS
	case $DNS in
		1)
		# Obtain the resolvers from resolv.conf and use them for OpenVPN
		grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
			echo "push \"dhcp-option DNS $line\"" >> /etc/openvpn/server.conf
		done
		;;
		2)
		echo 'push "dhcp-option DNS 8.8.8.8"' >> /etc/openvpn/server.conf
		echo 'push "dhcp-option DNS 8.8.4.4"' >> /etc/openvpn/server.conf
		;;
		3)
		echo 'push "dhcp-option DNS 208.67.222.222"' >> /etc/openvpn/server.conf
		echo 'push "dhcp-option DNS 208.67.220.220"' >> /etc/openvpn/server.conf
		;;
		4)
		echo 'push "dhcp-option DNS 129.250.35.250"' >> /etc/openvpn/server.conf
		echo 'push "dhcp-option DNS 129.250.35.251"' >> /etc/openvpn/server.conf
		;;
		5)
		echo 'push "dhcp-option DNS 74.82.42.42"' >> /etc/openvpn/server.conf
		;;
		6)
		echo 'push "dhcp-option DNS 64.6.64.6"' >> /etc/openvpn/server.conf
		echo 'push "dhcp-option DNS 64.6.65.6"' >> /etc/openvpn/server.conf
		;;
	esac
	echo "keepalive 10 120
cipher AES-256-CBC
comp-lzo
user nobody
group $GROUPNAME
persist-key
persist-tun
status openvpn-status.log
verb 3
crl-verify crl.pem" >> /etc/openvpn/server.conf
	# Enable net.ipv4.ip_forward for the system
	sed -i '/\<net.ipv4.ip_forward\>/c\net.ipv4.ip_forward=1' /etc/sysctl.conf
	if ! grep -q "\<net.ipv4.ip_forward\>" /etc/sysctl.conf; then
		echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf
	fi
	# Avoid an unneeded reboot
	echo 1 > /proc/sys/net/ipv4/ip_forward
	# Needed to use rc.local with some systemd distros
	if [[ "$OS" = 'debian' && ! -e $RCLOCAL ]]; then
		echo '#!/bin/sh -e
exit 0' > $RCLOCAL
	fi
	chmod +x $RCLOCAL
	# Set NAT for the VPN subnet
	iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP
	sed -i "1 a\iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP" $RCLOCAL
	if pgrep firewalld; then
		# We don't use --add-service=openvpn because that would only work with
		# the default port and protocol. Using both permanent and not permanent
		# rules to avoid a firewalld reload.
		firewall-cmd --zone=public --add-port=$PORT/$PROTOCOL
		firewall-cmd --zone=trusted --add-source=10.8.0.0/24
		firewall-cmd --permanent --zone=public --add-port=$PORT/$PROTOCOL
		firewall-cmd --permanent --zone=trusted --add-source=10.8.0.0/24
	fi
	if iptables -L -n | grep -qE 'REJECT|DROP'; then
		# If iptables has at least one REJECT rule, we asume this is needed.
		# Not the best approach but I can't think of other and this shouldn't
		# cause problems.
		iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT
		iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT
          iptables -F
		iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
		sed -i "1 a\iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT" $RCLOCAL
		sed -i "1 a\iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT" $RCLOCAL
		sed -i "1 a\iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT" $RCLOCAL
	fi
	# If SELinux is enabled and a custom port or TCP was selected, we need this
	if hash sestatus 2>/dev/null; then
		if sestatus | grep "Current mode" | grep -qs "enforcing"; then
			if [[ "$PORT" != '1194' || "$PROTOCOL" = 'tcp' ]]; then
				# semanage isn't available in CentOS 6 by default
				if ! hash semanage 2>/dev/null; then
					yum install policycoreutils-python -y
				fi
				semanage port -a -t openvpn_port_t -p $PROTOCOL $PORT
			fi
		fi
	fi
	# And finally, restart OpenVPN
	if [[ "$OS" = 'debian' ]]; then
		# Little hack to check for systemd
		if pgrep systemd-journal; then
			systemctl restart openvpn@server.service
		else
			/etc/init.d/openvpn restart
		fi
	else
		if pgrep systemd-journal; then
			systemctl restart openvpn@server.service
			systemctl enable openvpn@server.service
		else
			service openvpn restart
			chkconfig openvpn on
		fi
	fi
	# Try to detect a NATed connection and ask about it to potential LowEndSpirit users
	EXTERNALIP=$(wget -4qO- "http://whatismyip.akamai.com/")
	if [[ "$IP" != "$EXTERNALIP" ]]; then
		echo ""
		echo "Looks like your server is behind a NAT!"
		echo ""
		echo "If your server is NATed (e.g. LowEndSpirit), I need to know the external IP"
		echo "If that's not the case, just ignore this and leave the next field blank"
		read -p "External IP: " -e USEREXTERNALIP
		if [[ "$USEREXTERNALIP" != "" ]]; then
			IP=$USEREXTERNALIP
		fi
	fi
	# client-common.txt is created so we have a template to add further users later
	echo "client
dev tun
proto $PROTOCOL
sndbuf 0
rcvbuf 0
remote $IP $PORT
http-proxy-option CUSTOM-HEADER X-Online-Host  sdp.vivo.com.br
http-proxy $IP 80
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
setenv opt block-outside-dns
key-direction 1
verb 3" > /etc/openvpn/client-common.txt
	# Generates the custom client.ovpn
	newclient "$CLIENT"
	echo ""
	echo "Concluido!"
	echo ""
	echo "Seu arquivo está disponivel em" ~/"$CLIENT.ovpn"
	echo "Para mais opções digite (bash openvivo.sh)!"
fi


text:
using System;

namespace TwinPairs.Core
{
    [System.Diagnostics.DebuggerDisplay("Row {Row} Column {Column}")]
    public class Position
    {
        public int Row { get; set; }
        public int Column { get; set; }

        public Position(int row, int column)
        {
            if (row < 0)
                throw new ArgumentOutOfRangeException(nameof(row));

            if (column < 0)
                throw new ArgumentOutOfRangeException(nameof(column));

            this.Row = row;
            this.Column = column;
        }

        public override bool Equals(object obj)
        {
            return this.Equals(obj as Position);
        }

        public bool Equals(Position obj)
        {
            if (obj == null)
                return false;

            return int.Equals(obj.Row, this.Row) && int.Equals(obj.Column, this.Column);
        }

        public override int GetHashCode()
        {
            return HashCombiner.CombineHashCodes(this.Row, this.Column);
        }
    }
}


text:
package net.bither.charts.entity;

public interface IMeasurable {
    double getHigh();

    double getLow();
}


text:
package de.hub.clickwatch.main.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.name.Names;

import de.hub.clickwatch.ClickWatchModule;
import de.hub.clickwatch.ClickWatchModuleUtil;
import de.hub.clickwatch.ClickWatchModuleUtil.ClickWatchModuleBuilder;
import de.hub.clickwatch.ClickWatchModuleUtil.HandlerBehaviour;
import de.hub.clickwatch.ClickWatchModuleUtil.ValueType;
import de.hub.clickwatch.connection.adapter.values.StringValueAdapter;
import de.hub.clickwatch.connection.adapter.values.XmlValueAdapter;
import de.hub.clickwatch.main.IClickWatchContextAdapter;
import de.hub.clickwatch.main.IInjectorProvider;
import de.hub.clickwatch.recorder.ClickWatchRecorderModule;
import de.hub.clickwatch.recorder.recorder.HBaseDataBaseAdapter;
import de.hub.clickwatch.recorder.recorder.IDataBaseAdapter;
import de.hub.clickwatch.specificmodels.brn.BrnValueAdapter;
import de.hub.clickwatch.util.ILogger;
import de.hub.clickwatch.util.Throwables;

public class InjectorProvider implements IClickWatchContextAdapter,
		IInjectorProvider {

	public enum DataBaseType {
		HBASE
	};

	private HandlerBehaviour handlerBehaviour;
	private int remoteUpdateInterval;
	private int localUpdateInterval;
	private ValueType valueType;
	private int debugLevel; // 1,2,3,4
	private String logFile = null;

	private DataBaseType dataBaseType;
	private int handlerPerRecord;

	private URI recordURI;

	private Injector injector = null;
	private boolean useSpecificDataValues;

	@Override
	public List<Option> getCommandLineOptions() {
		List<Option> options = new ArrayList<Option>();
		options.add(new Option("d", "debug", false, "recorder logs extensive"));
		options.add(new Option("lf", "log-file", true, "name of a logfile"));

		options.add(new Option("c", "compound-handler", false,
				"use the compound handler of nodes instead of reading each handler seperated"));
		options.add(new Option("cr", "compound-handler-records", false,
				"use compound handler, compound handler records values"));
		options.add(new Option(
				"crc",
				"compound-handler-records-changes-only",
				false,
				"use compound handler compound handler records values and delivers only changes"));
		options.add(new Option("ru", "remote-update-interval", true,
				"interval used on node by compound handler."));
		options.add(new Option("lu", "local-update-interval", true,
				"default interval used between requests, if not given otherwise"));

		options.add(new Option("h", "handler-per-record", true,
				"determines the estimated record size in handler count per record"));
		options.add(new Option("db", true,
				"choose the database: hbase for hbase, log for log-file, emf for emf"));

		options.add(new Option("x", "xml-values", false,
				"use xml values instead of string values"));
		options.add(new Option("s", "brn-specific-values", false,
				"use brn-specific values when possible, xml-values are used otherwise."));
		options.add(new Option("ds", "brn-specific-data-values", false,
				"use brn-specific data values when possible, xml-values are used otherwise."));

		options.add(new Option("r", "use-record", true,
				"uses the given clickwatch model to emulate an actual network"));
		return options;
	}

	@Override
	public void initialize(CommandLine commandLine) throws ParseException {
		try {
			boolean useCompoundHandler = commandLine.hasOption("c")
					| commandLine.hasOption("cr")
					|| commandLine.hasOption("crc");
			boolean withRecord = commandLine.hasOption("cr")
					|| commandLine.hasOption("crc");
			boolean withChangesOnly = commandLine.hasOption("crc");
			remoteUpdateInterval = 500;
			if (commandLine.hasOption("ru")) {
				remoteUpdateInterval = Integer.parseInt(commandLine
						.getOptionValue("ru"));
			}
			localUpdateInterval = 2000;
			if (commandLine.hasOption("lu")) {
				localUpdateInterval = Integer.parseInt(commandLine
						.getOptionValue("lu"));
			}

			if (useCompoundHandler && withRecord && withChangesOnly) {
				handlerBehaviour = HandlerBehaviour.COMPOUND_RECORDING_DIFFERENCES;
			} else if (useCompoundHandler && withRecord && !withChangesOnly) {
				handlerBehaviour = HandlerBehaviour.COMPOUND_RECORDING;
			} else if (useCompoundHandler && !withRecord) {
				handlerBehaviour = HandlerBehaviour.COMPOUND;
			} else if (!useCompoundHandler) {
				handlerBehaviour = HandlerBehaviour.DEFAULT;
			}

			debugLevel = commandLine.hasOption("d") ? 4 : 2;
			if (commandLine.hasOption("log-file")) {
				logFile = commandLine.getOptionValue("log-file");
			}

			boolean useXml = commandLine.hasOption("x");
			boolean useSpecificValues = commandLine.hasOption("s");
			useSpecificDataValues = commandLine.hasOption("ds");
			if (useXml) {
				valueType = ValueType.XML;
			} else if (useSpecificValues || useSpecificDataValues) {
				valueType = ValueType.SPECIFIC;
			} else {
				valueType = ValueType.STRING;
			}

			String db = null;
			if (commandLine.hasOption("db")) {
				db = commandLine.getOptionValue("db");
			} else {
				db = "hbase";
			}
			if (db.equals("hbase")) {
				dataBaseType = DataBaseType.HBASE;
			} else {
				throw new IllegalArgumentException();
			}

			if (commandLine.hasOption("h")) {
				handlerPerRecord = new Integer(commandLine.getOptionValue("h"));
			} else {
				handlerPerRecord = 2000;
			}

			if (commandLine.hasOption("r")) {
				recordURI = URI.createFileURI(commandLine.getOptionValue("r"));
			}
		} catch (Exception e) {
			throw new ParseException(e.getMessage());
		}
	}

	public void initialize(ValueType valueType, int debugLevel) {
		this.handlerBehaviour = HandlerBehaviour.DEFAULT;
		this.valueType = valueType;
		this.debugLevel = debugLevel;
		this.dataBaseType = DataBaseType.HBASE;
		this.handlerPerRecord = 2000;
		this.recordURI = null;
	}

	public void initialize(HandlerBehaviour handlerBehaviour,
			ValueType valueType, int debugLevel, DataBaseType dataBaseType,
			int handlerPerRecord, URI recordURI, Integer localUpdateInterval,
			Integer remoteUpdateInterval) {
		this.handlerBehaviour = handlerBehaviour;
		this.valueType = valueType;
		this.debugLevel = debugLevel;
		this.dataBaseType = dataBaseType;
		this.handlerPerRecord = handlerPerRecord;
		this.recordURI = recordURI;
		this.localUpdateInterval = localUpdateInterval;
		this.remoteUpdateInterval = remoteUpdateInterval;
	}

	public void initialize(HandlerBehaviour handlerBehaviour,
			ValueType valueType, int debugLevel, DataBaseType dataBaseType,
			int handlerPerRecord, URI recordURI) {
		this.handlerBehaviour = handlerBehaviour;
		this.valueType = valueType;
		this.debugLevel = debugLevel;
		this.dataBaseType = dataBaseType;
		this.handlerPerRecord = handlerPerRecord;
		this.recordURI = recordURI;
	}

	@Override
	public void initialize(IConfigurationElement configurationElement,
			EObject selection) {
		String debugStr = configurationElement.getAttribute("debug");
		String compoundStr = configurationElement.getAttribute("compound");
		String withRecordStr = configurationElement.getAttribute("with_record");
		String withChangesOnlyStr = configurationElement
				.getAttribute("with_changes_only");
		String xmlValuesStr = configurationElement.getAttribute("xml_values");
		String specificModelsStr = configurationElement
				.getAttribute("specific_models");

		int debug = "true".equals(debugStr) ? 4 : 2;
		HandlerBehaviour handlerBehaviour = HandlerBehaviour.DEFAULT;
		if ("true".equals(compoundStr)) {
			handlerBehaviour = HandlerBehaviour.COMPOUND;
			if ("true".equals(withRecordStr)) {
				handlerBehaviour = HandlerBehaviour.COMPOUND_RECORDING;
				if ("true".equals(withChangesOnlyStr)) {
					handlerBehaviour = HandlerBehaviour.COMPOUND_RECORDING_DIFFERENCES;
				}
			}
		}
		ValueType valueType = ValueType.STRING;
		if ("true".equals(xmlValuesStr)) {
			valueType = ValueType.XML;
		}
		if ("true".equals(specificModelsStr)) {
			valueType = ValueType.SPECIFIC;
		}

		initialize(handlerBehaviour, valueType, debug, DataBaseType.HBASE,
				2000, null /* TODO */);
	}

	public Injector getInjector() {
		if (injector == null) {
			injector = createInjector();
		}
		return injector;
	}

	private Injector createInjector() {

		ClickWatchModuleBuilder builder = ClickWatchModuleUtil
				.newBuilder()
				.wDebug(debugLevel, logFile)
				.wHandlerBhvr(handlerBehaviour, localUpdateInterval,
						remoteUpdateInterval);
		if (valueType == ValueType.XML) {
			builder.wValueAdapterClass(XmlValueAdapter.class);
		} else if (valueType == ValueType.STRING) {
			builder.wValueAdapterClass(StringValueAdapter.class);
		} else if (valueType == ValueType.SPECIFIC) {
			if (!useSpecificDataValues) {
				builder.wValueAdapterClass(BrnValueAdapter.class);
			} else {
				builder.wValueAdapterClass(de.hub.clickwatch.specificmodels.brn.BrnValueAdapter.class);
			}
		} else {
			builder.wValueAdapterClass(XmlValueAdapter.class);
		}
		builder.wRecord(recordURI);

		ClickWatchModule clickWatchModule = builder.build();
		ClickWatchRecorderModule cwRecorderModule = new ClickWatchRecorderModule() {

			@Override
			protected void configureDataBaseAdapter() {
				if (dataBaseType == DataBaseType.HBASE) {
					bind(IDataBaseAdapter.class).to(HBaseDataBaseAdapter.class);
				} else {
					throw new IllegalArgumentException(
							"unknown database-adatper");
				}
			}

			@Override
			protected void configurePutsBufferSize() {
				bind(int.class).annotatedWith(Names.named(I_PUTS_BUFFER_SIZE))
						.toInstance(handlerPerRecord);
			}
		};
		Injector result = Guice.createInjector(clickWatchModule,
				cwRecorderModule);
		Throwables.logger = result.getInstance(ILogger.class);
		return result;
	}

	@Override
	public Class<?> getAdpaterClass() {
		return IInjectorProvider.class;
	}
}


text:
namespace MyInfluxDbClient.Meta
{
    internal static class RetentionPolicySchema
    {
        internal const string Name = "name";
        internal const string Duration = "duration";
        internal const string ReplicaN = "replicaN";
        internal const string IsDefault = "default";
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
    <name>SettingsPage</name>
    <message>
        <location filename="../assets/SettingsPage.qml" line="5"/>
        <source>Settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="10"/>
        <source>Default Settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="26"/>
        <source>Notification Options</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="46"/>
        <source>Vibration</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="74"/>
        <source>LED</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="60"/>
        <source>Hub</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="87"/>
        <source>Notify When</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="93"/>
        <source>Battery level less than in %</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="110"/>
        <source>Battery temperature greater than in Celsius</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="127"/>
        <source>Cellular signal less than in dBm</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="144"/>
        <source>Memory level</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="148"/>
        <location filename="../assets/SettingsPage.qml" line="178"/>
        <source>less than</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="151"/>
        <location filename="../assets/SettingsPage.qml" line="181"/>
        <source>128 MB</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="156"/>
        <location filename="../assets/SettingsPage.qml" line="186"/>
        <source>256 MB</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="161"/>
        <location filename="../assets/SettingsPage.qml" line="191"/>
        <source>512 MB</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="166"/>
        <location filename="../assets/SettingsPage.qml" line="196"/>
        <source>1024 MB</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="174"/>
        <source>Filesystem level</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/SettingsPage.qml" line="42"/>
        <source></source>
        <translation></translation>
    </message>
</context>
<context>
    <name>main</name>
    <message>
        <location filename="../assets/main.qml" line="87"/>
        <source>Monitor</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/main.qml" line="11"/>
        <source>Settings</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>registration</name>
    <message>
        <location filename="../assets/registration.qml" line="57"/>
        <source>Connect to BBM</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/registration.qml" line="66"/>
        <source>Continue</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
var toString = require('../lang/toString');
var trim = require('./trim');
    /**
     * Limit number of chars.
     */
    function truncate(str, maxChars, append, onlyFullWords){
	str = toString(str);
	append = append || '...';
	maxChars = onlyFullWords? maxChars + 1 : maxChars;

	str = trim(str);
	if(str.length <= maxChars){
	    return str;
	}
	str = str.substr(0, maxChars - append.length);
	//crop at last space or remove trailing whitespace
	str = onlyFullWords? str.substr(0, str.lastIndexOf(' ')) : trim(str);
	return str + append;
    }
    module.exports = truncate;


text:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

import app              from './app';
import users            from './users';
import usersCategories  from './users-categories';
import space            from './space';
import spaceRooms       from './space-rooms';
import roomsUsers       from './rooms-users';
import roomsMessages    from './rooms-messages';
import connections      from './connections';

export default combineReducers({
  app,
  users,
  usersCategories,
  space,
  spaceRooms,
  roomsUsers,
  roomsMessages,
  connections,
  routing: routerReducer,
});


text:
'use strict';

//Setting up route
angular.module('endpoints').config(['$stateProvider',
	function($stateProvider) {
		// Endpoints state routing
		$stateProvider.
		state('listEndpoints', {
			url: '/endpoints',
			templateUrl: 'modules/endpoints/views/list-endpoints.client.view.html'
		}).
		state('createEndpoint', {
			url: '/endpoints/create',
			templateUrl: 'modules/endpoints/views/create-endpoint.client.view.html'
		}).
		state('viewEndpoint', {
			url: '/endpoints/:endpointId',
			templateUrl: 'modules/endpoints/views/view-endpoint.client.view.html'
		}).
		state('editEndpoint', {
			url: '/endpoints/:endpointId/edit',
			templateUrl: 'modules/endpoints/views/edit-endpoint.client.view.html'
		});
	}
]);


text: rm -rf /var/log/loader* /usr/share/loader* /etc/loader*