text:
#include "tensorflow/compiler/xla/service/pattern_matcher.h"

#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/core/platform/test.h"

namespace xla {
namespace {

namespace m = match;
using PatternMatcherTest = HloTestBase;

TEST_F(PatternMatcherTest, AddOp) {
  constexpr char kModuleStr[] = R"(HloModule two_plus_two_module
    ENTRY %two_plus_two_computation () -> f32[] {
      %two = f32[] constant(2)
      ROOT %two_plus_two = f32[] add(f32[] %two, f32[] %two)
    }
  )";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));

  const HloInstruction* matched_inst;
  HloInstruction* matched_operand;
  Shape* matched_shape;
  Layout* matched_layout;

  ASSERT_TRUE(Match(
      hlo_module->entry_computation()->root_instruction(),
      match::Op(&matched_inst)
          .WithName("two_plus_two")
          .WithOpcode(HloOpcode::kAdd)
          .WithShape(
              match::Shape(&matched_shape)
                  .WithLayout(match::Layout(&matched_layout).WithDenseFormat()))
          .WithOperand(
              0,
              match::Op(&matched_operand).WithOpcode(HloOpcode::kConstant))));
  ASSERT_NE(matched_inst, nullptr);
  EXPECT_EQ(matched_inst->name(), "two_plus_two");
  EXPECT_EQ(matched_inst->opcode(), HloOpcode::kAdd);

  EXPECT_TRUE(Match(hlo_module->entry_computation()->root_instruction(),
                    match::Add(match::Constant(), match::Constant())));

  EXPECT_FALSE(Match(hlo_module->entry_computation()->root_instruction(),
                     match::Op().WithName("bad_name")));
  matched_inst = nullptr;
  EXPECT_FALSE(Match(hlo_module->entry_computation()->root_instruction(),
                     match::Multiply(&matched_inst, match::Op(), match::Op())));
}

TEST_F(PatternMatcherTest, ScalarShape) {
  auto scalar_shape = ShapeUtil::MakeShape(F32, {});
  Shape* matched_shape;
  EXPECT_TRUE(Match(&scalar_shape, match::Shape(&matched_shape).IsScalar()));
  EXPECT_EQ(matched_shape, &scalar_shape);
  EXPECT_TRUE(Match(&scalar_shape, match::Shape().IsArray()));
  EXPECT_TRUE(Match(&scalar_shape, match::Shape().IsDenseArray()));
  EXPECT_FALSE(Match(&scalar_shape, match::Shape().IsTuple()));
  EXPECT_TRUE(Match(&scalar_shape, match::Shape().WithElementType(F32)));
  EXPECT_TRUE(Match(&scalar_shape, match::Shape().WithRank(0)));
  EXPECT_FALSE(Match(
      &scalar_shape,
      match::Shape().WithSubshape({0}, match::Shape()).WithElementType(F32)));
}

TEST_F(PatternMatcherTest, DenseArrayShape) {
  auto array_shape = ShapeUtil::MakeShape(F32, {2, 3, 4});
  Shape* matched_shape;
  EXPECT_TRUE(Match(&array_shape, match::Shape(&matched_shape).IsArray()));
  EXPECT_EQ(matched_shape, &array_shape);
  EXPECT_TRUE(Match(&array_shape, match::Shape().IsDenseArray()));
  EXPECT_FALSE(Match(&array_shape, match::Shape().IsScalar()));
  EXPECT_FALSE(Match(&array_shape, match::Shape().IsTuple()));
  EXPECT_TRUE(Match(&array_shape, match::Shape().WithElementType(F32)));
  EXPECT_TRUE(Match(&array_shape, match::Shape().WithRank(3)));
  EXPECT_FALSE(
      Match(&array_shape, match::Shape().WithSubshape({0}, match::Shape())));
  Layout* matched_layout;
  EXPECT_TRUE(Match(&array_shape,
                    match::Shape().WithLayout(
                        match::Layout(&matched_layout).WithDenseFormat())));
  EXPECT_EQ(matched_layout, &array_shape.layout());
}

TEST_F(PatternMatcherTest, TupleShape) {
  auto tuple_shape = ShapeUtil::MakeTupleShape({
      ShapeUtil::MakeShape(F32, {1, 2, 3}),
      ShapeUtil::MakeShape(S32, {4, 5}),
  });
  EXPECT_TRUE(Match(&tuple_shape, match::Shape().IsTuple()));
  EXPECT_FALSE(Match(&tuple_shape, match::Shape().IsArray()));
  EXPECT_FALSE(Match(&tuple_shape, match::Shape().IsScalar()));

  Shape* subshape;
  ASSERT_TRUE(Match(
      &tuple_shape,
      match::Shape().WithSubshape(
          {0}, match::Shape(&subshape).WithElementType(F32).WithRank(3))));
  ASSERT_NE(subshape, nullptr);
  EXPECT_TRUE(
      ShapeUtil::Equal(*subshape, ShapeUtil::GetSubshape(tuple_shape, {0})));
  EXPECT_TRUE(Match(&tuple_shape,
                    match::Shape().WithSubshape(
                        {0}, match::Shape().EqualTo(
                                 &ShapeUtil::GetSubshape(tuple_shape, {0})))));
  EXPECT_FALSE(Match(&tuple_shape,
                     match::Shape().WithSubshape(
                         {0}, match::Shape().EqualTo(
                                  &ShapeUtil::GetSubshape(tuple_shape, {1})))));

  ASSERT_TRUE(Match(
      &tuple_shape,
      match::Shape().WithSubshape(
          {1}, match::Shape(&subshape).WithElementType(S32).WithRank(2))));
  ASSERT_NE(subshape, nullptr);
  EXPECT_TRUE(
      ShapeUtil::Equal(*subshape, ShapeUtil::GetSubshape(tuple_shape, {1})));
  EXPECT_TRUE(Match(&tuple_shape,
                    match::Shape().WithSubshape(
                        {1}, match::Shape().EqualTo(
                                 &ShapeUtil::GetSubshape(tuple_shape, {1})))));
  EXPECT_FALSE(Match(&tuple_shape,
                     match::Shape().WithSubshape(
                         {1}, match::Shape().EqualTo(
                                  &ShapeUtil::GetSubshape(tuple_shape, {0})))));

  EXPECT_FALSE(
      Match(&tuple_shape, match::Shape().WithSubshape({2}, match::Shape())));
  EXPECT_FALSE(
      Match(&tuple_shape, match::Shape().WithSubshape({0, 0}, match::Shape())));
}

TEST_F(PatternMatcherTest, FusionKind) {
  constexpr char kModuleStr[] = R"(
    HloModule test_module

    fused_computation {
      ROOT fp0 = f32[] parameter(0)
    }

    ENTRY while.v11 {
      p0 = f32[] parameter(0)
      ROOT fusion = f32[] fusion(p0), kind=kLoop, calls=fused_computation
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));

  auto* root = hlo_module->entry_computation()->root_instruction();
  EXPECT_TRUE(Match(
      root, match::Op().WithFusionKind(HloInstruction::FusionKind::kLoop)));
  EXPECT_FALSE(Match(
      root, match::Op().WithFusionKind(HloInstruction::FusionKind::kInput)));
  EXPECT_FALSE(Match(root->operand(0), match::Op().WithFusionKind(
                                           HloInstruction::FusionKind::kLoop)));
}

TEST_F(PatternMatcherTest, GetTupleElement) {
  constexpr char kModuleStr[] = R"(
    HloModule test_module

    ENTRY while.v11 {
      p0 = (f32[], f32[], f32[]) parameter(0)
      ROOT gte = f32[] get-tuple-element(p0), index=1
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));

  auto* root = hlo_module->entry_computation()->root_instruction();
  EXPECT_FALSE(Match(root, match::Op().WithTupleIndex(0)));
  EXPECT_TRUE(Match(root, match::Op().WithTupleIndex(1)));
  EXPECT_FALSE(Match(root, match::Op().WithTupleIndex(2)));
  EXPECT_FALSE(Match(root, match::GetTupleElement(match::Op(), 0)));
  EXPECT_TRUE(Match(root, match::GetTupleElement(match::Op(), 1)));
}

TEST_F(PatternMatcherTest, AnyOf) {
  constexpr char kModuleStr[] = R"(
    HloModule test_module ENTRY test { ROOT constant = f16[] constant(1) })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  EXPECT_TRUE(
      Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(0),
                                               match::ConstantScalar(1))));
  EXPECT_TRUE(
      Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(1),
                                               match::ConstantScalar(0))));
  EXPECT_FALSE(
      Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(0),
                                               match::ConstantScalar(2))));
}

TEST_F(PatternMatcherTest, ConstantScalar) {
  using match::ConstantEffectiveScalar;
  using match::ConstantScalar;
  using match::Op;
  using match::Tuple;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      a = s32[] constant(1)
      b = s32[1,1] constant({{2}})
      c = s32[1,2] constant({{2,2}})
      d = f32[] constant(1)
      e = f32[] constant(1.25)
      ROOT tuple = (s32[], s32[1,1], s32[1,2], f32[], f32[]) tuple(a,b,c,d,e)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  const HloInstruction* a = root->operand(0);
  const HloInstruction* b = root->operand(1);
  const HloInstruction* c = root->operand(2);
  const HloInstruction* d = root->operand(3);
  const HloInstruction* e = root->operand(4);
  EXPECT_TRUE(Match(a, ConstantScalar()));
  EXPECT_TRUE(Match(a, ConstantScalar(1)));
  EXPECT_TRUE(Match(a, ConstantEffectiveScalar()));
  EXPECT_TRUE(Match(a, ConstantEffectiveScalar(1)));
  EXPECT_FALSE(Match(a, ConstantScalar(2)));
  EXPECT_FALSE(Match(a, ConstantScalar(2.01)));
  EXPECT_FALSE(Match(a, ConstantEffectiveScalar(2)));
  EXPECT_FALSE(Match(a, ConstantEffectiveScalar(1.01)));

  EXPECT_FALSE(Match(b, ConstantScalar()));
  EXPECT_FALSE(Match(b, ConstantScalar(2)));
  EXPECT_TRUE(Match(b, ConstantEffectiveScalar()));
  EXPECT_TRUE(Match(b, ConstantEffectiveScalar(2)));

  EXPECT_FALSE(Match(c, ConstantScalar()));
  EXPECT_FALSE(Match(c, ConstantScalar(2)));
  EXPECT_FALSE(Match(c, ConstantEffectiveScalar()));
  EXPECT_FALSE(Match(c, ConstantEffectiveScalar(2)));

  EXPECT_TRUE(Match(d, ConstantScalar(1)));
  EXPECT_TRUE(Match(d, ConstantEffectiveScalar(1)));
  EXPECT_TRUE(Match(d, ConstantScalar(1.0)));
  EXPECT_TRUE(Match(d, ConstantEffectiveScalar(1.0)));

  EXPECT_TRUE(Match(e, ConstantScalar(1.25f)));
  EXPECT_TRUE(Match(e, ConstantScalar(1.25)));
  EXPECT_TRUE(Match(e, ConstantEffectiveScalar(1.25)));
  EXPECT_FALSE(Match(e, ConstantScalar(1)));
  EXPECT_FALSE(Match(e, ConstantEffectiveScalar(1)));

  const HloInstruction* instr = nullptr;
  EXPECT_TRUE(Match(a, ConstantScalar(&instr)));
  EXPECT_EQ(instr, a);

  instr = nullptr;
  EXPECT_TRUE(Match(a, ConstantScalar(&instr, 1)));
  EXPECT_EQ(instr, a);

  instr = nullptr;
  EXPECT_TRUE(Match(a, ConstantEffectiveScalar(&instr)));
  EXPECT_EQ(instr, a);

  instr = nullptr;
  EXPECT_TRUE(Match(a, ConstantEffectiveScalar(&instr, 1)));
  EXPECT_EQ(instr, a);
}

TEST_F(PatternMatcherTest, MultiplyAnyOrder) {
  using match::ConstantScalar;
  using match::MultiplyAnyOrder;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      lhs = f16[] constant(42)
      rhs = f16[] constant(52)
      ROOT multiply = f16[] multiply(lhs, rhs)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();
  const HloInstruction* instr;

  EXPECT_TRUE(Match(
      root, MultiplyAnyOrder(&instr, ConstantScalar(42), ConstantScalar(52))));
  EXPECT_TRUE(Match(
      root, MultiplyAnyOrder(&instr, ConstantScalar(52), ConstantScalar(42))));

  // Check that MultiplyAnyOrder exposes the same API as Op(), so we can call
  // e.g. IsNonConstant() on it.
  EXPECT_TRUE(Match(
      root, MultiplyAnyOrder(&instr, ConstantScalar(42), ConstantScalar(52))
                .IsNonConstant()));
  EXPECT_TRUE(
      Match(root, MultiplyAnyOrder(ConstantScalar(42), ConstantScalar(52))
                      .IsNonConstant()));
}

TEST_F(PatternMatcherTest, AnyOfShortCircuit) {
  using match::AnyOf;
  using match::Multiply;
  using match::Op;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      lhs = f16[] constant(42)
      rhs = f16[] constant(52)
      ROOT multiply = f16[] multiply(lhs, rhs)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  {
    const HloInstruction* mul = nullptr;
    const HloInstruction* any = nullptr;

    ASSERT_TRUE(Match(
        root, AnyOf<HloInstruction>(Multiply(&mul, Op(), Op()), Op(&any))));
    EXPECT_NE(nullptr, mul);
    EXPECT_EQ(nullptr, any);
  }
  {
    const HloInstruction* mul = nullptr;
    const HloInstruction* any = nullptr;

    ASSERT_TRUE(Match(
        root, AnyOf<HloInstruction>(Op(&any), Multiply(&mul, Op(), Op()))));
    EXPECT_NE(nullptr, any);
    EXPECT_EQ(nullptr, mul);
  }
}

TEST_F(PatternMatcherTest, AllOf) {
  using match::AllOf;
  using match::Broadcast;
  using match::Constant;
  using match::Op;

  constexpr char kModuleStr[] = R"(
    HloModule test_module ENTRY test { ROOT constant = f16[] constant(1) })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  auto f16_scalar = ShapeUtil::MakeShape(F16, {});
  auto f16_pattern = Constant().WithShapeEqualTo(&f16_scalar);
  auto f16_compatible_pattern = Constant().WithShapeCompatibleTo(&f16_scalar);
  auto scalar_pattern = Constant().WithShape(match::Shape().IsScalar());
  ASSERT_TRUE(Match(root, scalar_pattern));
  ASSERT_TRUE(Match(root, f16_pattern));
  ASSERT_TRUE(Match(root, f16_compatible_pattern));
  EXPECT_TRUE(Match(root, AllOf<HloInstruction>(scalar_pattern, f16_pattern,
                                                f16_compatible_pattern)));
  EXPECT_TRUE(
      Match(root, AllOf<HloInstruction>(f16_pattern, f16_compatible_pattern,
                                        scalar_pattern)));
  EXPECT_FALSE(
      Match(root, AllOf<HloInstruction>(Broadcast(Op()), f16_pattern)));
  EXPECT_FALSE(Match(
      root, AllOf<HloInstruction>(Broadcast(Op()), f16_compatible_pattern)));
  EXPECT_FALSE(
      Match(root, AllOf<HloInstruction>(Broadcast(Op()), scalar_pattern)));
}

TEST_F(PatternMatcherTest, AllOfNoCaptureIfNotMatch) {
  using match::AllOf;
  using match::Broadcast;
  using match::Constant;
  using match::Op;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      ROOT v = f16[] constant(42)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  const HloInstruction* constant = nullptr;
  ASSERT_FALSE(
      Match(root, AllOf<HloInstruction>(Constant(&constant), Broadcast(Op()))));
  EXPECT_EQ(nullptr, constant);
  ASSERT_TRUE(Match(root, Constant(&constant)));
  EXPECT_NE(nullptr, constant);
}

TEST_F(PatternMatcherTest, TestNoCapture) {
  using match::Constant;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      ROOT v = f16[] constant(42)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  const HloInstruction* constant = nullptr;
  ASSERT_TRUE(Match(root, Constant(&constant), {/*capture=*/false}));
  EXPECT_EQ(nullptr, constant);
}

TEST_F(PatternMatcherTest, TestCaptureMatchedSubPatternForAnyOf) {
  using match::Add;
  using match::AddAnyOrder;
  using match::AnyOf;
  using match::Op;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      u = f16[] parameter(0)
      v = f16[] parameter(1)
      ROOT add = f16[] add(u, v)
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  const HloInstruction* addend0 = nullptr;
  const HloInstruction* addend1 = nullptr;
  const HloInstruction* addend2 = nullptr;
  auto add2_pattern = Add(Op(&addend0), Op(&addend1));
  auto add3_pattern = AnyOf<HloInstruction>(
      AddAnyOrder(add2_pattern, Op(&addend2)), add2_pattern, Op(&addend0));

  ASSERT_TRUE(Match(root, add3_pattern));
  EXPECT_NE(nullptr, addend0);
  EXPECT_NE(nullptr, addend1);
  EXPECT_EQ(nullptr, addend2);
}

TEST_F(PatternMatcherTest, TestConcat) {
  using match::Concatenate;
  using match::ConstantScalar;
  using match::Op;
  using match::Reshape;

  constexpr char kModuleStr[] = R"(
    HloModule test_module
    ENTRY test {
      c1 = u32[] constant(1)
      c2 = u32[] constant(2)
      c3 = u32[] constant(3)
      c4 = u32[] constant(4)
      r1 = u32[1] reshape(c1)
      r2 = u32[1] reshape(c2)
      r3 = u32[1] reshape(c3)
      r4 = u32[1] reshape(c4)
      ROOT concat = u32[4] concatenate(r1, r2, r3, r4), dimensions={0}
    })";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();
  ASSERT_TRUE(Match(
      root,
      Concatenate(Reshape(ConstantScalar(1)), Reshape(ConstantScalar(2)),
                  Reshape(ConstantScalar(3)), Reshape(ConstantScalar(4)))));
  ASSERT_FALSE(Match(
      root,
      Concatenate(Reshape(ConstantScalar(2)), Reshape(ConstantScalar(1)),
                  Reshape(ConstantScalar(3)), Reshape(ConstantScalar(4)))));
  ASSERT_FALSE(Match(
      root, Concatenate(Reshape(ConstantScalar(1)), Reshape(ConstantScalar(2)),
                        Reshape(ConstantScalar(3)))));
  ASSERT_FALSE(Match(
      root, Concatenate(Reshape(ConstantScalar(2)), Reshape(ConstantScalar(3)),
                        Reshape(ConstantScalar(4)))));
}

template <typename Pattern>
string Description(const Pattern& pattern) {
  std::stringstream ss;
  pattern.DescribeTo(&ss);
  return ss.str();
}

template <typename Elem, typename Pattern>
string Explanation(Elem* elem, const Pattern& pattern) {
  std::stringstream ss;
  MatchOption options{/*.capture=*/true, /*.explain_os=*/&ss};
  Match(elem, pattern, options);
  return ss.str();
}
template <typename Elem, typename Pattern>
string Explanation(const std::unique_ptr<Elem>& elem, const Pattern& pattern) {
  return Explanation(elem.get(), pattern);
}
template <typename Elem, typename Pattern>
string Explanation(const Elem& elem, const Pattern& pattern) {
  return Explanation(&elem, pattern);
}

// Helper macro for checking a pattern's description and the explanation printed
// when attempting to match (and presumably failing) on a given object.
//
// We use a macro rather than a function because we want good line numbers in
// errors.  We use this rather than writing a helper that returns a pair of
// (description, explanation) and doing something like
//
//   EXPECT_THAT(DescAndExplanation(...), ::testing::Pair(..., ...));
//
// because EXPECT_EQ prints a unified diff if multiline string comparison fails,
// while EXPECT_THAT does not.  This unified diff makes the errors much easier
// to read.
#define EXPECT_DESC_AND_EXPLANATION(elem, pattern, expected_desc,    \
                                    expected_explanation)            \
  do {                                                               \
    EXPECT_EQ(Description(pattern), (expected_desc));                \
    EXPECT_EQ(Explanation((elem), (pattern)), expected_explanation); \
  } while (0)

TEST_F(PatternMatcherTest, LayoutDescribeToAndExplain) {
  auto layout = LayoutUtil::MakeLayout({1, 2});
  auto layout2 = LayoutUtil::MakeLayout({2, 2});

  EXPECT_DESC_AND_EXPLANATION(static_cast<const Layout*>(nullptr), m::Layout(),
                              "a layout", "Layout is null");
  EXPECT_DESC_AND_EXPLANATION(layout2, m::Layout().EqualTo(&layout),
                              "a layout equal to {1,2}",
                              "Layout {2,2} is not equal to expected {1,2}");
}

TEST_F(PatternMatcherTest, CustomCallTargetMatcherDescribeAndExplain) {
  constexpr char kModuleStr[] = R"(
    HloModule test_module

    ENTRY test {
      ROOT out = f32[] custom-call(), custom_call_target="test_target"
    }
  )";

  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));

  auto* root = hlo_module->entry_computation()->root_instruction();
  EXPECT_TRUE(Match(root, match::Op().WithCustomCallTarget("test_target")));
  EXPECT_FALSE(Match(root, match::Op().WithCustomCallTarget("other_target")));

  EXPECT_DESC_AND_EXPLANATION(
      root, match::Op().WithCustomCallTarget("other_target"),
      "an HloInstruction custom call with target 'other_target'",
      "HloInstruction is not a custom call with a target 'other_target'\nin "
      "out = f32[] custom-call(), custom_call_target=\"test_target\"");
}

TEST_F(PatternMatcherTest, ShapeDescribeToAndExplain) {
  auto shape = ShapeUtil::MakeShapeWithLayout(F32, {1, 2}, {0, 1});
  auto layout = shape.layout();

  EXPECT_DESC_AND_EXPLANATION(static_cast<const Shape*>(nullptr), m::Shape(),
                              "a shape", "Shape is null");
  EXPECT_DESC_AND_EXPLANATION(
      ShapeUtil::MakeShapeWithLayout(F32, {1, 2}, {1, 0}),
      m::Shape().EqualTo(&shape), "a shape equal to f32[1,2]{0,1}",
      "Shape not equal to f32[1,2]{0,1}\n"
      "in f32[1,2]{1,0}");
  EXPECT_DESC_AND_EXPLANATION(ShapeUtil::MakeShape(F32, {2, 2}),
                              m::Shape().CompatibleTo(&shape),
                              "a shape compatible with f32[1,2]",
                              "Shape not compatible with f32[1,2]\n"
                              "in f32[2,2]{1,0}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().WithElementType(F16),
                              "a shape with element type F16",
                              "Shape does not have element type F16\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().IsScalar(),
                              "a shape that represents a scalar",
                              "Shape is not a scalar\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(ShapeUtil::MakeNil(), m::Shape().IsArray(),
                              "a shape that represents an array",
                              "Shape is not an array\n"
                              "in ()");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().IsTuple(),
                              "a shape that represents a tuple",
                              "Shape is not a tuple\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().IsEffectiveScalar(),
                              "a shape that is an effective scalar",
                              "Shape is not an effective scalar\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().WithRank(42),
                              "a shape that has 42 dimensions",
                              "Shape does not have rank 42\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().WithRank(0),
                              "a shape that is a scalar",
                              "Shape is not a scalar\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(shape, m::Shape().WithRank(1).IsArray(),
                              "a shape:\n"
                              " * that has 1 dimension AND\n"
                              " * that represents an array",
                              "Shape does not have rank 1\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(ShapeUtil::MakeNil(),
                              m::Shape().IsArray().WithRank(1),
                              "a shape:\n"
                              " * that represents an array AND\n"
                              " * that has 1 dimension",
                              "Shape is not an array\n"
                              "in ()");
  EXPECT_DESC_AND_EXPLANATION(
      ShapeUtil::MakeShapeWithLayout(F32, {1, 2}, {1, 0}),
      m::Shape().WithLayoutEqualTo(&layout),
      "a shape with\n  a layout equal to {0,1}",
      "Layout {1,0} is not equal to expected {0,1}\n"
      "in f32[1,2]{1,0}");
  EXPECT_DESC_AND_EXPLANATION(shape,
                              m::Shape().WithSubshapeEqualTo({10}, &shape),
                              "a shape with subshape at index {10} which is\n"
                              "  a shape equal to f32[1,2]{0,1}",
                              "No subshape at {10}\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(
      ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {2, 2})}),
      m::Shape().WithSubshapeEqualTo({0}, &shape),
      "a shape with subshape at index {0} which is\n"
      "  a shape equal to f32[1,2]{0,1}",
      "Shape not equal to f32[1,2]{0,1}\n"
      "in f32[2,2]{1,0}\n"
      "in subshape at {0}\n"
      "in (f32[2,2])");
  EXPECT_DESC_AND_EXPLANATION(shape,
                              m::Shape().WithSubshapeCompatibleTo({10}, &shape),
                              "a shape with subshape at index {10} which is\n"
                              "  a shape compatible with f32[1,2]",
                              "No subshape at {10}\n"
                              "in f32[1,2]{0,1}");
  EXPECT_DESC_AND_EXPLANATION(
      ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {2, 2})}),
      m::Shape().WithSubshapeCompatibleTo({0}, &shape),
      "a shape with subshape at index {0} which is\n"
      "  a shape compatible with f32[1,2]",
      "Shape not compatible with f32[1,2]\n"
      "in f32[2,2]{1,0}\n"
      "in subshape at {0}\n"
      "in (f32[2,2])");
  EXPECT_DESC_AND_EXPLANATION(
      ShapeUtil::MakeTupleShape({ShapeUtil::MakeTupleShape({shape})}),
      m::Shape().WithSubshape({0, 0}, m::Shape().IsScalar()),
      "a shape with subshape at index {0,0} which is\n"
      "  a shape that represents a scalar",
      "Shape is not a scalar\n"
      "in f32[1,2]{0,1}\n"
      "in subshape at {0,0}\n"
      "in ((f32[1,2]))");
}

std::unique_ptr<HloInstruction> SetName(absl::string_view name,
                                        std::unique_ptr<HloInstruction> instr) {
  instr->SetAndSanitizeName(string(name));
  return instr;
}

TEST_F(PatternMatcherTest, HloInstructionDescribeToAndExplain) {
  std::unique_ptr<HloInstruction> iota =
      SetName("i", HloInstruction::CreateIota(ShapeUtil::MakeShape(S32, {42}),
                                              /*iota_dimension=*/0));
  std::unique_ptr<HloInstruction> constant =
      SetName("c", HloInstruction::CreateConstant(LiteralUtil::CreateR0(0)));

  EXPECT_DESC_AND_EXPLANATION(static_cast<const HloInstruction*>(nullptr),
                              m::Op(), "an HloInstruction",
                              "HloInstruction* is null");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithName("foo"),
                              "an HloInstruction named \"foo\"",
                              "HloInstruction not named \"foo\"\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithOpcode(HloOpcode::kAdd),
                              "an HloInstruction with opcode add",
                              "HloInstruction doesn't have opcode add\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(
      constant, m::Op().IsNonConstant(),
      "an HloInstruction with any opcode other than constant",
      "HloInstruction has opcode constant, expected anything else\n"
      "in c = s32[] constant(0)");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithNumOperands(42),
                              "an HloInstruction with 42 operands",
                              "HloInstruction doesn't have 42 operands\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithShape(m::Shape().IsTuple()),
                              "an HloInstruction outputting\n"
                              "  a shape that represents a tuple",
                              "Shape is not a tuple\n"
                              "in s32[42]{0}\n"
                              "in output shape\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithShape(F32, {42}),
                              "an HloInstruction outputting\n"
                              "  a shape:\n"
                              "   * with element type F32 AND\n"
                              "   * with dimensions [42]",
                              "Shape does not have element type F32\n"
                              "in s32[42]{0}\n"
                              "in output shape\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().WithShape(S32, {128}),
                              "an HloInstruction outputting\n"
                              "  a shape:\n"
                              "   * with element type S32 AND\n"
                              "   * with dimensions [128]",
                              "Shape does not have dimensions [128]\n"
                              "in s32[42]{0}\n"
                              "in output shape\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(
      iota, m::Op().WithOperand(2, m::Op().WithOpcode(HloOpcode::kAdd)),
      "an HloInstruction with operand 2 which is:\n"
      "  an HloInstruction with opcode add",
      "desired operand index 2 is out of bounds\n"
      "in i = s32[42]{0} iota(), iota_dimension=0");

  EXPECT_DESC_AND_EXPLANATION(
      SetName("a", HloInstruction::CreateBinary(ShapeUtil::MakeShape(S32, {}),
                                                HloOpcode::kAdd, constant.get(),
                                                constant.get())),
      m::Op().WithOperand(1, m::Op().IsNonConstant()),
      "an HloInstruction with operand 1 which is:\n"
      "  an HloInstruction with any opcode other than constant",
      "HloInstruction has opcode constant, expected anything else\n"
      "in c = s32[] constant(0)\n"
      "in operand 1\n"
      "in a = s32[] add(s32[] c, s32[] c)");
  EXPECT_DESC_AND_EXPLANATION(
      iota, m::Op().WithFusionKind(HloInstruction::FusionKind::kLoop),
      "an HloInstruction with fusion kind kLoop",
      "HloInstruction does not have fusion kind kLoop; it's not a fusion\n"
      "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(
      iota, m::Op().WithTupleIndex(42),
      "an HloInstruction which is a GTE with index 42",
      "HloInstruction is not a GTE with index 42; it's not a GTE at all\n"
      "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(iota, m::Op().IsConstantScalar(),
                              "an HloInstruction which is a constant scalar",
                              "HloInstruction is not a constant\n"
                              "in i = s32[42]{0} iota(), iota_dimension=0");
  EXPECT_DESC_AND_EXPLANATION(
      SetName("c", HloInstruction::CreateConstant(
                       LiteralUtil::CreateR1<int>({1, 2}))),
      m::Op().IsConstantEffectiveScalar(),
      "an HloInstruction which is a constant effective scalar",
      "HloInstruction is not an effective scalar\n"
      "in c = s32[2]{0} constant({1, 2})");
  EXPECT_DESC_AND_EXPLANATION(
      SetName("c", HloInstruction::CreateConstant(LiteralUtil::CreateR0(10))),
      m::Op().IsConstantScalar(42),
      "an HloInstruction which is a constant scalar with value 42",
      "HloInstruction's constant value 10 did not match expected value 42\n"
      "in c = s32[] constant(10)");
  EXPECT_DESC_AND_EXPLANATION(
      SetName("c", HloInstruction::CreateConstant(LiteralUtil::CreateR0(2.25))),
      m::Op().IsConstantEffectiveScalar(1.25),
      "an HloInstruction which is a constant effective scalar with value 1.25",
      "HloInstruction's constant value 2.25 did not match expected value 1.25\n"
      "in c = f64[] constant(2.25)");
  EXPECT_DESC_AND_EXPLANATION(
      constant, m::Op().Is(iota.get()),
      absl::StrCat("an HloInstruction which is 0x", absl::Hex(iota.get()),
                   " (i = s32[42]{0} iota(), iota_dimension=0)"),
      absl::StrCat("HloInstruction 0x", absl::Hex(constant.get()), " is not 0x",
                   absl::Hex(iota.get()),
                   " (i = s32[42]{0} iota(), iota_dimension=0)\n"
                   "in c = s32[] constant(0)"));
}

TEST_F(PatternMatcherTest, HloInstructionMatcherAnyOrderDescribeTo) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  EXPECT_DESC_AND_EXPLANATION(
      SetName("a", HloInstruction::CreateBinary(
                       scalar_s32, HloOpcode::kAdd,
                       SetName("b", HloInstruction::CreateConstant(
                                        LiteralUtil::CreateR0(0)))
                           .get(),
                       SetName("c", HloInstruction::CreateConstant(
                                        LiteralUtil::CreateR0(0)))
                           .get())),
      m::AddAnyOrder(m::Op().WithName("b"), m::Op().WithName("bar")),
      "an HloInstruction:\n"
      " * with opcode add AND\n"
      " * with two operands in either order:\n"
      "    - an HloInstruction named \"b\"\n"
      "    - an HloInstruction named \"bar\"",
      "HloInstruction's operands (ignoring order) did not match second "
      "matcher.  Specifically,\n"
      " - an HloInstruction named \"bar\"\n"
      "does not match LHS:\n"
      " - HloInstruction not named \"bar\"\n"
      "   in b = s32[] constant(0)\n"
      "does not match RHS:\n"
      " - HloInstruction not named \"bar\"\n"
      "   in c = s32[] constant(0)\n"
      "in a = s32[] add(s32[] b, s32[] c)");

  EXPECT_DESC_AND_EXPLANATION(
      SetName("a",
              HloInstruction::CreateBinary(
                  scalar_s32, HloOpcode::kAdd,
                  HloInstruction::CreateParameter(0, scalar_s32, "p").get(),
                  SetName("c", HloInstruction::CreateConstant(
                                   LiteralUtil::CreateR0(0)))
                      .get())),
      m::AddAnyOrder(m::Op().IsConstantScalar(), m::Op().IsConstant()),
      "an HloInstruction:\n"
      " * with opcode add AND\n"
      " * with two operands in either order:\n"
      "    - an HloInstruction which is a constant scalar\n"
      "    - an HloInstruction with opcode constant",
      "HloInstruction's LHS operand did not match either of the two matchers.  "
      "Specifically,\n"
      " - an HloInstruction which is a constant scalar\n"
      "does not match LHS:\n"
      " - HloInstruction is not a constant\n"
      "   in p = s32[] parameter(0)\n"
      "and\n"
      " - an HloInstruction with opcode constant\n"
      "does not match LHS:\n"
      " - HloInstruction doesn't have opcode constant\n"
      "   in p = s32[] parameter(0)\n"
      "in a = s32[] add(s32[] p, s32[] c)");
}

TEST_F(PatternMatcherTest, AnyOfMatcherDescribeToAndExplain) {
  EXPECT_DESC_AND_EXPLANATION(
      SetName("c", HloInstruction::CreateConstant(LiteralUtil::CreateR0(0))),
      m::AnyOf<HloInstruction>(m::Op().WithName("foo"),
                               m::Op().WithName("bar")),
      "any of:\n"
      " - an HloInstruction named \"foo\" OR\n"
      " - an HloInstruction named \"bar\"",
      "None of the following matchers succeeded:\n"
      "Matcher #1\n"
      " - an HloInstruction named \"foo\"\n"
      "failed with\n"
      " - HloInstruction not named \"foo\"\n"
      "   in c = s32[] constant(0)\n"
      "Matcher #2\n"
      " - an HloInstruction named \"bar\"\n"
      "failed with\n"
      " - HloInstruction not named \"bar\"\n"
      "   in c = s32[] constant(0)");
}

TEST_F(PatternMatcherTest, Parameter) {
  auto param =
      HloInstruction::CreateParameter(1, ShapeUtil::MakeShape(F32, {}), "p1");
  auto non_param =
      SetName("c", HloInstruction::CreateConstant(LiteralUtil::CreateR0(0)));
  EXPECT_FALSE(Match(param.get(), m::Parameter(0)));
  EXPECT_TRUE(Match(param.get(), m::Parameter()));
  EXPECT_TRUE(Match(param.get(), m::Parameter(1)));
  EXPECT_FALSE(Match(non_param.get(), m::Parameter()));
  EXPECT_FALSE(Match(non_param.get(), m::Parameter(1)));

  EXPECT_DESC_AND_EXPLANATION(non_param, m::Parameter(1),
                              "an HloInstruction:\n"
                              " * with opcode parameter AND\n"
                              " * which is parameter 1",
                              "HloInstruction doesn't have opcode parameter\n"
                              "in c = s32[] constant(0)");
  EXPECT_EQ(Explanation(HloInstruction::CreateParameter(
                            0, ShapeUtil::MakeShape(F32, {}), "p0"),
                        m::Parameter(1)),
            "HloInstruction is not parameter 1\n"
            "in p0 = f32[] parameter(0)");
}

TEST_F(PatternMatcherTest, OneUseAndOneUser) {
  auto param =
      HloInstruction::CreateParameter(0, ShapeUtil::MakeShape(F32, {}), "p0");

  EXPECT_FALSE(Match(param.get(), m::Op().WithOneUse()));
  EXPECT_DESC_AND_EXPLANATION(
      param, m::Op().WithOneUse(),
      "an HloInstruction which has exactly one use",
      "HloInstruction has 0 users, but expected exactly one.\n"
      "in p0 = f32[] parameter(0)");

  EXPECT_FALSE(Match(param.get(), m::Op().WithOneUser()));
  EXPECT_DESC_AND_EXPLANATION(
      param, m::Op().WithOneUser(),
      "an HloInstruction which has exactly one user (but possibly is used "
      "multiple times by that instruction)",
      "HloInstruction has 0 users, but expected exactly one.\n"
      "in p0 = f32[] parameter(0)");

  {
    auto reshape =
        SetName("r", HloInstruction::CreateReshape(
                         ShapeUtil::MakeShape(F32, {1}), param.get()));
    EXPECT_TRUE(Match(param.get(), m::Op().WithOneUse()));
    EXPECT_TRUE(Match(param.get(), m::Op().WithOneUser()));

    auto reshape1 =
        SetName("r1", HloInstruction::CreateReshape(
                          ShapeUtil::MakeShape(F32, {1}), param.get()));
    EXPECT_FALSE(Match(param.get(), m::Op().WithOneUse()));
    EXPECT_FALSE(Match(param.get(), m::Op().WithOneUser()));

    const char* kMultipleUserExplanation =
        "HloInstruction has 2 users, but expected exactly one.\n"
        "All users:\n"
        " - r = f32[1]{0} reshape(f32[] p0)\n"
        " - r1 = f32[1]{0} reshape(f32[] p0)\n"
        "in p0 = f32[] parameter(0)";
    EXPECT_EQ(Explanation(param.get(), m::Op().WithOneUse()),
              kMultipleUserExplanation);
    EXPECT_EQ(Explanation(param.get(), m::Op().WithOneUser()),
              kMultipleUserExplanation);
  }

  auto add = SetName("add", HloInstruction::CreateBinary(
                                ShapeUtil::MakeShape(F32, {}), HloOpcode::kAdd,
                                param.get(), param.get()));
  EXPECT_TRUE(Match(param.get(), m::Op().WithOneUser()));
  EXPECT_FALSE(Match(param.get(), m::Op().WithOneUse()));
  EXPECT_EQ(Explanation(param.get(), m::Op().WithOneUse()),
            "HloInstruction is used 2 times by its user, but is expected to be "
            "used just once: add = f32[] add(f32[] p0, f32[] p0)\n"
            "in p0 = f32[] parameter(0)");
}

TEST_F(PatternMatcherTest, Comparison) {
  auto shape = ShapeUtil::MakeShape(F32, {1});
  auto p0 = HloInstruction::CreateParameter(0, shape, "param.0");
  auto p1 = HloInstruction::CreateParameter(1, shape, "param.1");
  auto eq = HloInstruction::CreateCompare(shape, p0.get(), p1.get(),
                                          ComparisonDirection::kEq);
  auto ne = HloInstruction::CreateCompare(shape, p0.get(), p1.get(),
                                          ComparisonDirection::kNe);
  auto add =
      HloInstruction::CreateBinary(shape, HloOpcode::kAdd, p0.get(), p1.get());
  auto le = HloInstruction::CreateCompare(shape, p0.get(), add.get(),
                                          ComparisonDirection::kLe);

  EXPECT_TRUE(Match(eq.get(), m::Compare()));
  EXPECT_TRUE(Match(eq.get(), m::Eq()));
  EXPECT_TRUE(Match(eq.get(), m::Eq(m::Parameter(0), m::Parameter(1))));
  EXPECT_TRUE(Match(eq.get(), m::EqAnyOrder(m::Parameter(1), m::Parameter(0))));
  EXPECT_TRUE(Match(ne.get(), m::Compare()));
  EXPECT_TRUE(Match(ne.get(), m::Ne()));
  EXPECT_TRUE(Match(
      le.get(),
      m::Compare(m::Parameter(0), m::Add(m::Parameter(0), m::Parameter(1)))));
  EXPECT_TRUE(Match(le.get(), m::Le(m::Parameter(0),
                                    m::Add(m::Parameter(0), m::Parameter(1)))));

  EXPECT_FALSE(Match(eq.get(), m::Add()));
  EXPECT_FALSE(Match(eq.get(), m::Ne()));
  EXPECT_FALSE(
      Match(le.get(),
            m::Eq(m::Parameter(0), m::Add(m::Parameter(0), m::Parameter(1)))));
  EXPECT_FALSE(Match(eq.get(), m::Eq(m::Parameter(1), m::Parameter(0))));
  EXPECT_DESC_AND_EXPLANATION(
      eq, m::Ne().WithOneUser(),
      "an HloInstruction:\n"
      " * with opcode compare AND\n"
      " * which has comparison direction NE AND\n"
      " * which has exactly one user (but possibly is used "
      "multiple times by that instruction)",
      "HloInstruction is not comparison NE\n"
      "in compare = f32[1]{0} compare(f32[1]{0} param.0, f32[1]{0} param.1), "
      "direction=EQ");
}

TEST_F(PatternMatcherTest, CustomCallMatchers) {
  constexpr char kModuleStr[] = R"(
    HloModule test_module

    ENTRY test {
      p0 = f32[] parameter(0)
      p1 = f32[] parameter(1)
      ROOT out = f32[] custom-call(p0, p1), custom_call_target="test_target"
    }
  )";
  TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
                          ParseAndReturnVerifiedModule(kModuleStr));
  auto* root = hlo_module->entry_computation()->root_instruction();

  EXPECT_TRUE(Match(root, m::CustomCall()));
  EXPECT_TRUE(Match(root, m::CustomCall("test_target")));
  EXPECT_TRUE(Match(
      root, m::CustomCall("test_target", m::Parameter(0), m::Parameter(1))));

  HloInstruction* instr;
  EXPECT_TRUE(Match(root, m::CustomCall(&instr)));
  EXPECT_TRUE(Match(root, m::CustomCall(&instr, "test_target")));
  EXPECT_TRUE(Match(root, m::CustomCall(&instr, "test_target", m::Parameter(0),
                                        m::Parameter(1))));

  const HloInstruction* const_instr;
  EXPECT_TRUE(Match(root, m::CustomCall(&const_instr)));
  EXPECT_TRUE(Match(root, m::CustomCall(&const_instr, "test_target")));
  EXPECT_TRUE(Match(root, m::CustomCall(&const_instr, "test_target",
                                        m::Parameter(0), m::Parameter(1))));

  EXPECT_FALSE(Match(root, m::CustomCall("other_target")));
  EXPECT_FALSE(Match(
      root, m::CustomCall("test_target", m::Parameter(1), m::Parameter(0))));
}

}  // namespace
}  // namespace xla


text:
/**
 * Utility for the sales Package.
 *
 * @author The eFaps Team
 *
 */
package org.efaps.esjp.sales.util;

redpajama_set_name: RedPajamaGithub


text:
package com.intuit.wasabi.repository.cassandra.provider;

import com.datastax.driver.core.Session;
import com.datastax.driver.mapping.MappingManager;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.intuit.wasabi.cassandra.datastax.CassandraDriver;
import com.intuit.wasabi.repository.cassandra.accessor.AppRoleAccessor;

public class AppRoleAccessorProvider implements Provider<AppRoleAccessor> {
    private final Session session;
    private final MappingManager manager;

    @Inject
    public AppRoleAccessorProvider(CassandraDriver driver) {
        this.session = driver.getSession();
        this.manager = new MappingManager(session);
    }

    @Override
    public AppRoleAccessor get() {
        return manager.createAccessor(AppRoleAccessor.class);
    }
}


text:
<Record>
<Term>Erysipelas</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Skin Diseases, Bacterial</ParentTerm>
<ParentTerm>Streptococcal Infections</ParentTerm>
<ClassificationPath>Skin and Connective Tissue Diseases/Skin Diseases/Skin Diseases, Infectious/Skin Diseases, Bacterial/Erysipelas</ClassificationPath>
<ClassificationPath>Bacterial Infections and Mycoses/Bacterial Infections/Skin Diseases, Bacterial/Erysipelas</ClassificationPath>
<ClassificationPath>Bacterial Infections and Mycoses/Infection/Skin Diseases, Infectious/Skin Diseases, Bacterial/Erysipelas</ClassificationPath>
<ClassificationPath>Bacterial Infections and Mycoses/Bacterial Infections/Gram-Positive Bacterial Infections/Streptococcal Infections/Erysipelas</ClassificationPath>
<BroaderTerm>Infection</BroaderTerm>
<BroaderTerm>Skin Diseases</BroaderTerm>
<BroaderTerm>Erysipelas</BroaderTerm>
<BroaderTerm>Skin Diseases, Bacterial</BroaderTerm>
<BroaderTerm>Bacterial Infections</BroaderTerm>
<BroaderTerm>Streptococcal Infections</BroaderTerm>
<BroaderTerm>Skin Diseases, Infectious</BroaderTerm>
<BroaderTerm>Skin and Connective Tissue Diseases</BroaderTerm>
<BroaderTerm>Gram-Positive Bacterial Infections</BroaderTerm>
<BroaderTerm>Bacterial Infections and Mycoses</BroaderTerm>
<Synonym>Erysipelas</Synonym>
<Description>An acute infection of the skin caused by species of STREPTOCOCCUS. This disease most frequently affects infants, young children, and the elderly. Characteristics include pink-to-red lesions that spread rapidly and are warm to the touch. The commonest site of involvement is the face.</Description>
<Source>MeSH</Source>
</Record>


text:
using NodaTime.Text;
using NodaTime.Text.Patterns;
using NUnit.Framework;

namespace NodaTime.Test.Text
{
    [TestFixture]
    public class ParseBucketTest
    {
        [Test]
        public void IsUsed_NoMatch()
        {
            Assert.IsFalse(ParseBucket<Offset>.IsFieldUsed(PatternFields.Hours12 | PatternFields.Minutes, PatternFields.Hours24));
        }

        [Test]
        public void IsUsed_SingleValueMatch()
        {
            Assert.IsTrue(ParseBucket<Offset>.IsFieldUsed(PatternFields.Hours24, PatternFields.Hours24));
        }

        [Test]
        public void IsFieldUsed_MultiValueMatch()
        {
            Assert.IsTrue(ParseBucket<Offset>.IsFieldUsed(PatternFields.Hours24 | PatternFields.Minutes, PatternFields.Hours24));
        }

        [Test]
        public void AllAreUsed_NoMatch()
        {
            Assert.IsFalse(ParseBucket<Offset>.AreAllFieldsUsed(PatternFields.Hours12 | PatternFields.Minutes,
                                                                PatternFields.Hours24 | PatternFields.Seconds));
        }

        [Test]
        public void AllAreUsed_PartialMatch()
        {
            Assert.IsFalse(ParseBucket<Offset>.AreAllFieldsUsed(PatternFields.Hours12 | PatternFields.Minutes,
                                                                PatternFields.Hours12 | PatternFields.Seconds));
        }

        [Test]
        public void AllAreUsed_CompleteMatch()
        {
            Assert.IsTrue(ParseBucket<Offset>.AreAllFieldsUsed(PatternFields.Hours12 | PatternFields.Minutes,
                                                               PatternFields.Hours12 | PatternFields.Minutes));
        }

        [Test]
        public void AllAreUsed_CompleteMatchWithMore()
        {
            Assert.IsTrue(ParseBucket<Offset>.IsFieldUsed(PatternFields.Hours24 | PatternFields.Minutes | PatternFields.Hours12,
                                                          PatternFields.Hours24 | PatternFields.Minutes));
        }
    }
}


text:
Game::Game()
{

}

Game::~Game()
{

}

void Game::run()
{
    m_window.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "GBJam3");
    m_window.setFramerateLimit(60);

    ModStream ms;
    ms.load("test.xm");

    ms.play();

    while(m_window.isOpen())
    {
        update();
        draw();
    }

    ms.stop();
}

void Game::update()
{
    sf::Event ev;
    while(m_window.pollEvent(ev))
    {
        if (ev.type == sf::Event::Closed)
            m_window.close();
        else if (ev.type == sf::Event::Resized)
        {
            float aspect = static_cast<float>(WINDOW_WIDTH) / static_cast<float>(WINDOW_HEIGHT);

            int viewWidth = ev.size.width;
            int viewHeight = (int)(ev.size.width / aspect + 0.5f);

            if (viewHeight > ev.size.height)
            {
                viewHeight = ev.size.height;
                viewWidth = (int)(ev.size.height * aspect + 0.5f);
            }

            float vpx = (ev.size.width - viewWidth) / 2;
            float vpy = (ev.size.height - viewHeight) / 2;

            sf::View v = m_window.getView();
            v.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

            sf::FloatRect viewport;

            viewport.left = vpx / ev.size.width;
            viewport.top = (ev.size.height - (vpy + viewHeight)) / ev.size.height;
            viewport.width = static_cast<float>(viewWidth) / static_cast<float>(ev.size.width);
            viewport.height = static_cast<float>(viewHeight) / static_cast<float>(ev.size.height);

            v.setViewport(viewport);

            m_window.setView(v);
        }
    }
}

void Game::draw()
{
    m_window.clear();

    m_window.display();
}


text:
namespace remoting {

namespace {

class LocalKeyboardInputMonitorChromeos : public LocalKeyboardInputMonitor {
 public:
  LocalKeyboardInputMonitorChromeos(
      scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
      scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
      LocalInputMonitor::KeyPressedCallback key_pressed_callback);

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

  ~LocalKeyboardInputMonitorChromeos() override;

 private:
  class Core : ui::PlatformEventObserver {
   public:
    Core(scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
         LocalInputMonitor::KeyPressedCallback on_key_event_callback);

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

    ~Core() override;

    void Start();

    // ui::PlatformEventObserver interface.
    void WillProcessEvent(const ui::PlatformEvent& event) override;
    void DidProcessEvent(const ui::PlatformEvent& event) override;

   private:
    scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner_;
    LocalInputMonitor::KeyPressedCallback key_pressed_callback_;
  };

  // Task runner on which ui::events are received.
  scoped_refptr<base::SingleThreadTaskRunner> input_task_runner_;
  std::unique_ptr<Core> core_;
};

LocalKeyboardInputMonitorChromeos::LocalKeyboardInputMonitorChromeos(
    scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
    LocalInputMonitor::KeyPressedCallback key_pressed_callback)
    : input_task_runner_(input_task_runner),
      core_(new Core(caller_task_runner, std::move(key_pressed_callback))) {
  input_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&Core::Start, base::Unretained(core_.get())));
}

LocalKeyboardInputMonitorChromeos::~LocalKeyboardInputMonitorChromeos() {
  input_task_runner_->DeleteSoon(FROM_HERE, core_.release());
}

LocalKeyboardInputMonitorChromeos::Core::Core(
    scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
    LocalInputMonitor::KeyPressedCallback key_pressed_callback)
    : caller_task_runner_(caller_task_runner),
      key_pressed_callback_(std::move(key_pressed_callback)) {}

void LocalKeyboardInputMonitorChromeos::Core::Start() {
  // TODO(erg): Need to handle the mus case where PlatformEventSource is null
  // because we are in mus. This class looks like it can be rewritten with mus
  // EventMatchers.
  if (ui::PlatformEventSource::GetInstance()) {
    ui::PlatformEventSource::GetInstance()->AddPlatformEventObserver(this);
  }
}

LocalKeyboardInputMonitorChromeos::Core::~Core() {
  if (ui::PlatformEventSource::GetInstance()) {
    ui::PlatformEventSource::GetInstance()->RemovePlatformEventObserver(this);
  }
}

void LocalKeyboardInputMonitorChromeos::Core::WillProcessEvent(
    const ui::PlatformEvent& event) {
  // No need to handle this callback.
}

void LocalKeyboardInputMonitorChromeos::Core::DidProcessEvent(
    const ui::PlatformEvent& event) {
  ui::EventType type = ui::EventTypeFromNative(event);
  if (type == ui::ET_KEY_PRESSED) {
    ui::DomCode dom_code = ui::CodeFromNative(event);
    uint32_t usb_keycode = ui::KeycodeConverter::DomCodeToUsbKeycode(dom_code);
    caller_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(key_pressed_callback_, usb_keycode));
  }
}

}  // namespace

std::unique_ptr<LocalKeyboardInputMonitor> LocalKeyboardInputMonitor::Create(
    scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
    LocalInputMonitor::KeyPressedCallback on_key_event_callback,
    base::OnceClosure disconnect_callback) {
  return std::make_unique<LocalKeyboardInputMonitorChromeos>(
      caller_task_runner, input_task_runner, std::move(on_key_event_callback));
}

}  // namespace remoting


text:
'use strict';
exports.mirror = require('./mirror');
exports.prepare = require('./prepare');

/*let inputOptions = {
  date: {
    type: 'date',
    pattern: ['month', 'week', 'day', 'hour']
  },
  test: {
    weight: 5
  }
};

console.log(exports.prepare(inputOptions));
let transition = exports.mirror(inputOptions);
let tarnsitioned = transition.scheme({ date: Date.now(), test: 4 });
console.log(tarnsitioned);*/


text:
import {ViewStyle} from "react-native"
import * as yoga from "yoga-layout"
import { textLines } from "./component-to-node"

import { Component, RenderedComponent } from "./index"

const renderedComponentTree = (root: Component, node: yoga.NodeInstance) => recurseTree(root, node)

export default renderedComponentTree

export const recurseTree = (component: Component, node: yoga.NodeInstance) => {

  const newChildren = [] as RenderedComponent[]

  if (component.children) {
    for (let index = 0; index < component.children.length; index++) {
      const childComponent = component.children[index]
      const childNode = node.getChild(index)
      // Don't go into Text nodes
      if (component.type !== "Text" && typeof childComponent !== "string") {
        const renderedChildComponent = recurseTree(childComponent, childNode)
        newChildren.push(renderedChildComponent)
      }
    }
  }

  return {
    type: component.type,
    props: component.props,
    children: newChildren,
    [textLines]: component[textLines],
    layout : {
      left: node.getComputedLeft(),
      right: node.getComputedRight(),
      top: node.getComputedTop(),
      bottom: node.getComputedBottom(),
      width: node.getComputedWidth(),
      height: node.getComputedHeight()
    }
  } as RenderedComponent
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"
             xmlns:e="urn:import:org.ovirt.engine.ui.common.widget.editor"
             xmlns:ge="urn:import:org.ovirt.engine.ui.common.widget.editor.generic"
             xmlns:w="urn:import:org.ovirt.engine.ui.common.widget"
             xmlns:d="urn:import:org.ovirt.engine.ui.common.widget.dialog">

  <ui:with field='constants' type='org.ovirt.engine.ui.common.CommonApplicationConstants' />

  <ui:style type="org.ovirt.engine.ui.common.widget.uicommon.popup.vm.SerialNumberPolicyWidget.Style">
    .container {
      width: 100%;
      position: relative;
      left: 9px;
    }

    .hPanel {
      position: relative;
      top: -8px;
    }

    .serialNumberPolicy {
      float: left;
      -moz-box-sizing: content-box;
    }

    .customSerialNumber {
      width: 230px;
      float: left;
      padding-top: 50px;
      margin-right: 9px;
      padding-bottom: 20px;
      padding-left: 15px;
    }

    .serialNumberInfoIcon {
      display: inline;
      float: left;
      position: relative;
      top: 9px;
    }

    .checkbox {
      margin-left: -9px;
    }

    .checkbox div {
      width: 100%;
    }

  </ui:style>

  <g:FlowPanel addStyleNames="{style.container}">
    <g:HorizontalPanel addStyleNames="{style.hPanel}">
      <ge:EntityModelCheckBoxEditor ui:field="overrideSerialNumberPolicy" label="{constants.overrideSerialNumberPolicy}" addStyleNames="{style.checkbox}" />
      <d:InfoIcon ui:field="serialNumberInfoIcon" addStyleNames="{style.serialNumberInfoIcon}" />
    </g:HorizontalPanel>
    <e:EnumRadioEditor ui:field="serialNumberPolicy" />
    <ge:StringEntityModelTextBoxOnlyEditor ui:field="customSerialNumber" addStyleNames="{style.customSerialNumber}" />
  </g:FlowPanel>

</ui:UiBinder>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace MMDB.Azure.Management.AzureDto.AzureCloudService
{
    [XmlType("HostedService")]
    public class HostedService
    {
        public string Url { get; set; }
        public string ServiceName { get; set; }

        [XmlElement("HostedServiceProperties")]
        public HostedServiceProperties Properties{ get; set; }

        [XmlArray("Deployments")]
        public List<DeploymentItem> DeploymentList { get; set; }

        public string DefaultWinRmCertificateThumbprint { get; set; }
    }
}


text:
require 'yt/collections/base'
require 'yt/models/status'

module Yt
  module Collections
    class Statuses < Base

    private

      # @return [Yt::Models::Status] a new status initialized with
      #   one of the items returned by asking YouTube for a list of statuses,
      #   of a resource, for instance a channel.
      # @see https://developers.google.com/youtube/v3/docs/playlists#resource
      def new_item(data)
        Yt::Status.new data: data['status']
      end

      # @return [Hash] the parameters to submit to YouTube to get the status
      #   of a resource, for instance a channel.
      # @see https://developers.google.com/youtube/v3/docs/channels/list
      def list_params
        super.tap{|params| params[:params] = {id: @parent.id, part: 'status'}}
      end

      # @private
      # @note Statuses overrides +list_resources+ since the endpoint is not
      #   '/statuses' but the endpoint related to the snippet's resource.
      def list_resources
        @parent.class.to_s.pluralize
      end
    end
  end
end


text:
import React from "react";
import { getSpeakerPageForTopic } from "../utils/speakers";
import { Link } from "react-router";
import { prefixLink } from "gatsby-helpers";
import Avatar from "./avatar";
import "../css/topic.css";

export default function({ topic }) {
  const speakerPage = getSpeakerPageForTopic(topic);

  return (

{topic.headline}

{topic.abstract}

      <Avatar
          diameter={120}
          src={prefixLink(speakerPage.data.avatar)}
          alt={speakerPage.data.name}
        />
        <Link to={prefixLink(speakerPage.path)}>

{speakerPage.data.name}

        </Link>

  );
}


text:
typedef void (^DMImageOperationCompetitionBlock)(UIImage *image);
typedef void (^DMImageOperationProgressBlock)(NSNumber *progress);
typedef void (^DMImageOperationFailureBlock)(NSError *error);
typedef UIImage * (^DMImageOperationProcessingBlock)(UIImage *image);

@interface DMImageOperation : NSOperation

@property (nonatomic, copy) DMImageOperationProgressBlock progressBlock;
@property (nonatomic, copy) DMImageOperationFailureBlock failureBlock;
@property (nonatomic, copy) DMImageOperationProcessingBlock processingBlock;

@property (assign, nonatomic) CGSize thumbSize;
@property (assign, nonatomic) BOOL cropThumb;

@property (assign, nonatomic) BOOL returnPostprocessingImage;

#pragma mark - Cache properties

@property (assign, nonatomic) BOOL cacheImage; // NO
@property (strong, nonatomic) NSString *cacheName; // @"default"
@property (strong, nonatomic) NSString *cacheSuffix; // nill

@property (strong, nonatomic) DMImageCacheManager *cacheManager;

- (id) initWithImagePath: (NSString *) imagePath identifer: (NSString *) identifier andBlock: (DMImageOperationCompetitionBlock) block;

- (NSString *) path;
- (NSString *) identifier;

- (BOOL) imageExist;

- (NSURL *) downloadURL;
- (void) setDownloadURL: (NSURL *) url;

+ (CGSize) resize: (CGSize) originalSize toSize: (CGSize) maxSize withCroping: (BOOL) cropImage;

@end


text:
/* eslint func-names: "off"*/
/* eslint no-unused-vars: "off"*/
import faker from 'faker';
const config = require('../../../nightwatch.conf.js');

module.exports = {
  // '@disabled': true,

  'Regular Users View Document': function (browser) {
    browser
      .resizeWindow(1280, 800)
      .url('http://localhost:8000/login')
      .waitForElementVisible('body')
      .waitForElementVisible('input[type=email]')
      .setValue('input[type=email]', 'seun.martins@andela.com')
      .setValue('input[type=password]', 'testing')
      .click('button[name=submit]')
      .waitForElementVisible('.toast')
      .assert.visible('.toast')
      .assert.urlEquals('http://localhost:8000/dashboard')
      .waitForElementVisible('i[class="material-icons add"]')
      .waitForElementVisible('i[class="Small material-icons docify-menu"]')
      .waitForElementVisible('i[class="fa fa-folder"]')
      .waitForElementVisible('a[class="card white"]')
      .click('a[class="card white"]')
      .waitForElementVisible('a[class="btn-small waves-effect waves-light docify-view"]')
      .assert.visible('a[class="btn-small waves-effect waves-light docify-view"]')
      .click('a[class="btn-small waves-effect waves-light docify-view"]')
      .waitForElementVisible('button[class="btn waves-effect waves-light btn-flat modal-action modal-close"]')
      .assert.visible('button[class="btn waves-effect waves-light btn-flat modal-action modal-close"]')
      .pause(500)
      .end();
  }
};