// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/codegen/tick-counter.h"
#include "src/compiler/compiler-source-position-table.h"
#include "src/compiler/js-context-specialization.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/js-heap-broker.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/simplified-operator.h"
#include "src/heap/factory.h"
#include "src/objects/objects-inl.h"
#include "src/objects/property.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/function-tester.h"

namespace v8 {
namespace internal {
namespace compiler {

class ContextSpecializationTester : public HandleAndZoneScope {
 public:
  explicit ContextSpecializationTester(Maybe<OuterContext> context)
      : canonical_(main_isolate()),
        graph_(new (main_zone()) Graph(main_zone())),
        common_(main_zone()),
        javascript_(main_zone()),
        machine_(main_zone()),
        simplified_(main_zone()),
        jsgraph_(main_isolate(), graph(), common(), &javascript_, &simplified_,
                 &machine_),
        reducer_(main_zone(), graph(), &tick_counter_),
        js_heap_broker_(main_isolate(), main_zone(), FLAG_trace_heap_broker),
        spec_(&reducer_, jsgraph(), &js_heap_broker_, context,
              MaybeHandle<JSFunction>()) {}

  JSContextSpecialization* spec() { return &spec_; }
  Factory* factory() { return main_isolate()->factory(); }
  CommonOperatorBuilder* common() { return &common_; }
  JSOperatorBuilder* javascript() { return &javascript_; }
  SimplifiedOperatorBuilder* simplified() { return &simplified_; }
  JSGraph* jsgraph() { return &jsgraph_; }
  Graph* graph() { return graph_; }

  void CheckChangesToValue(Node* node, Handle<HeapObject> expected_value);
  void CheckContextInputAndDepthChanges(
      Node* node, Handle<Context> expected_new_context_object,
      size_t expected_new_depth);
  void CheckContextInputAndDepthChanges(Node* node, Node* expected_new_context,
                                        size_t expected_new_depth);

  JSHeapBroker* broker() { return &js_heap_broker_; }

 private:
  TickCounter tick_counter_;
  CanonicalHandleScope canonical_;
  Graph* graph_;
  CommonOperatorBuilder common_;
  JSOperatorBuilder javascript_;
  MachineOperatorBuilder machine_;
  SimplifiedOperatorBuilder simplified_;
  JSGraph jsgraph_;
  GraphReducer reducer_;
  JSHeapBroker js_heap_broker_;
  JSContextSpecialization spec_;
};

void ContextSpecializationTester::CheckChangesToValue(
    Node* node, Handle<HeapObject> expected_value) {
  Reduction r = spec()->Reduce(node);
  CHECK(r.Changed());
  HeapObjectMatcher match(r.replacement());
  CHECK(match.HasValue());
  CHECK_EQ(*match.Value(), *expected_value);
}

void ContextSpecializationTester::CheckContextInputAndDepthChanges(
    Node* node, Handle<Context> expected_new_context_object,
    size_t expected_new_depth) {
  ContextAccess access = ContextAccessOf(node->op());
  Reduction r = spec()->Reduce(node);
  CHECK(r.Changed());

  Node* new_context = NodeProperties::GetContextInput(r.replacement());
  CHECK_EQ(IrOpcode::kHeapConstant, new_context->opcode());
  HeapObjectMatcher match(new_context);
  CHECK_EQ(Context::cast(*match.Value()), *expected_new_context_object);

  ContextAccess new_access = ContextAccessOf(r.replacement()->op());
  CHECK_EQ(new_access.depth(), expected_new_depth);
  CHECK_EQ(new_access.index(), access.index());
  CHECK_EQ(new_access.immutable(), access.immutable());
}

void ContextSpecializationTester::CheckContextInputAndDepthChanges(
    Node* node, Node* expected_new_context, size_t expected_new_depth) {
  ContextAccess access = ContextAccessOf(node->op());
  Reduction r = spec()->Reduce(node);
  CHECK(r.Changed());

  Node* new_context = NodeProperties::GetContextInput(r.replacement());
  CHECK_EQ(new_context, expected_new_context);

  ContextAccess new_access = ContextAccessOf(r.replacement()->op());
  CHECK_EQ(new_access.depth(), expected_new_depth);
  CHECK_EQ(new_access.index(), access.index());
  CHECK_EQ(new_access.immutable(), access.immutable());
}

static const int slot_index = Context::NATIVE_CONTEXT_INDEX;

TEST(ReduceJSLoadContext0) {
  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);

  // Make a context and initialize it a bit for this test.
  Handle<Context> native = t.factory()->NewNativeContext();
  Handle<Context> subcontext1 = t.factory()->NewNativeContext();
  Handle<Context> subcontext2 = t.factory()->NewNativeContext();
  subcontext2->set_previous(*subcontext1);
  subcontext1->set_previous(*native);
  Handle<Object> expected = t.factory()->InternalizeUtf8String("gboy!");
  const int slot = Context::NATIVE_CONTEXT_INDEX;
  native->set(slot, *expected);

  Node* const_context = t.jsgraph()->Constant(ObjectRef(t.broker(), native));
  Node* deep_const_context =
      t.jsgraph()->Constant(ObjectRef(t.broker(), subcontext2));
  Node* param_context = t.graph()->NewNode(t.common()->Parameter(0), start);

  {
    // Mutable slot, constant context, depth = 0 => do nothing.
    Node* load = t.graph()->NewNode(t.javascript()->LoadContext(0, 0, false),
                                    const_context, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(!r.Changed());
  }

  {
    // Mutable slot, non-constant context, depth = 0 => do nothing.
    Node* load = t.graph()->NewNode(t.javascript()->LoadContext(0, 0, false),
                                    param_context, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(!r.Changed());
  }

  {
    // Mutable slot, constant context, depth > 0 => fold-in parent context.
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, Context::GLOBAL_EVAL_FUN_INDEX, false),
        deep_const_context, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(r.Changed());
    Node* new_context_input = NodeProperties::GetContextInput(r.replacement());
    CHECK_EQ(IrOpcode::kHeapConstant, new_context_input->opcode());
    HeapObjectMatcher match(new_context_input);
    CHECK_EQ(*native, Context::cast(*match.Value()));
    ContextAccess access = ContextAccessOf(r.replacement()->op());
    CHECK_EQ(Context::GLOBAL_EVAL_FUN_INDEX, static_cast<int>(access.index()));
    CHECK_EQ(0, static_cast<int>(access.depth()));
    CHECK_EQ(false, access.immutable());
  }

  {
    // Immutable slot, constant context, depth = 0 => specialize.
    Node* load = t.graph()->NewNode(t.javascript()->LoadContext(0, slot, true),
                                    const_context, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(r.Changed());
    CHECK(r.replacement() != load);

    HeapObjectMatcher match(r.replacement());
    CHECK(match.HasValue());
    CHECK_EQ(*expected, *match.Value());
  }
}

TEST(ReduceJSLoadContext1) {
  // The graph's context chain ends in the incoming context parameter:
  //
  //   context2 <-- context1 <-- context0 (= Parameter(0))

  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()), t.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Node* context0 = t.graph()->NewNode(t.common()->Parameter(0), start);
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, false), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, true), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, true), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context0, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, true), context2, start);
    t.CheckContextInputAndDepthChanges(load, context0, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context0, 1);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, true), context2, start);
    t.CheckContextInputAndDepthChanges(load, context0, 1);
  }
}

TEST(ReduceJSLoadContext2) {
  // The graph's context chain ends in a constant context (context_object1),
  // which has another outer context (context_object0).
  //
  //   context2 <-- context1 <-- context0 (= HeapConstant(context_object1))
  //   context_object1 <~~ context_object0

  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()), t.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Handle<HeapObject> slot_value0 = t.factory()->InternalizeUtf8String("0");
  Handle<HeapObject> slot_value1 = t.factory()->InternalizeUtf8String("1");

  Handle<Context> context_object0 = t.factory()->NewNativeContext();
  Handle<Context> context_object1 = t.factory()->NewNativeContext();
  context_object1->set_previous(*context_object0);
  context_object0->set(slot_index, *slot_value0);
  context_object1->set(slot_index, *slot_value1);

  Node* context0 =
      t.jsgraph()->Constant(ObjectRef(t.broker(), context_object1));
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, false), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, true), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, true), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context0, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, true), context2, start);
    t.CheckChangesToValue(load, slot_value1);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context_object0, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, true), context2, start);
    t.CheckChangesToValue(load, slot_value0);
  }
}

TEST(ReduceJSLoadContext3) {
  // Like in ReduceJSLoadContext1, the graph's context chain ends in the
  // incoming context parameter.  However, this time we provide a concrete
  // context for this parameter as the "specialization context".  We choose
  // context_object2 from ReduceJSLoadContext2 for this, so almost all test
  // expectations are the same as in ReduceJSLoadContext2.

  HandleAndZoneScope handle_zone_scope;
  auto factory = handle_zone_scope.main_isolate()->factory();

  Handle<HeapObject> slot_value0 = factory->InternalizeUtf8String("0");
  Handle<HeapObject> slot_value1 = factory->InternalizeUtf8String("1");

  Handle<Context> context_object0 = factory->NewNativeContext();
  Handle<Context> context_object1 = factory->NewNativeContext();
  context_object1->set_previous(*context_object0);
  context_object0->set(slot_index, *slot_value0);
  context_object1->set(slot_index, *slot_value1);

  ContextSpecializationTester t(Just(OuterContext(context_object1, 0)));

  Node* start = t.graph()->NewNode(t.common()->Start(2));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()),
                          handle_zone_scope.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Node* context0 = t.graph()->NewNode(t.common()->Parameter(0), start);
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, false), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(0, slot_index, true), context2, start);
    CHECK(!t.spec()->Reduce(load).Changed());
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(1, slot_index, true), context2, start);
    t.CheckContextInputAndDepthChanges(load, context1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context_object1, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(2, slot_index, true), context2, start);
    t.CheckChangesToValue(load, slot_value1);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, false), context2, start);
    t.CheckContextInputAndDepthChanges(load, context_object0, 0);
  }

  {
    Node* load = t.graph()->NewNode(
        t.javascript()->LoadContext(3, slot_index, true), context2, start);
    t.CheckChangesToValue(load, slot_value0);
  }
}

TEST(ReduceJSStoreContext0) {
  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);

  // Make a context and initialize it a bit for this test.
  Handle<Context> native = t.factory()->NewNativeContext();
  Handle<Context> subcontext1 = t.factory()->NewNativeContext();
  Handle<Context> subcontext2 = t.factory()->NewNativeContext();
  subcontext2->set_previous(*subcontext1);
  subcontext1->set_previous(*native);
  Handle<Object> expected = t.factory()->InternalizeUtf8String("gboy!");
  const int slot = Context::NATIVE_CONTEXT_INDEX;
  native->set(slot, *expected);

  Node* const_context = t.jsgraph()->Constant(ObjectRef(t.broker(), native));
  Node* deep_const_context =
      t.jsgraph()->Constant(ObjectRef(t.broker(), subcontext2));
  Node* param_context = t.graph()->NewNode(t.common()->Parameter(0), start);

  {
    // Mutable slot, constant context, depth = 0 => do nothing.
    Node* load = t.graph()->NewNode(t.javascript()->StoreContext(0, 0),
                                    const_context, const_context, start, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(!r.Changed());
  }

  {
    // Mutable slot, non-constant context, depth = 0 => do nothing.
    Node* load = t.graph()->NewNode(t.javascript()->StoreContext(0, 0),
                                    param_context, param_context, start, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(!r.Changed());
  }

  {
    // Immutable slot, constant context, depth = 0 => do nothing.
    Node* load = t.graph()->NewNode(t.javascript()->StoreContext(0, slot),
                                    const_context, const_context, start, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(!r.Changed());
  }

  {
    // Mutable slot, constant context, depth > 0 => fold-in parent context.
    Node* load = t.graph()->NewNode(
        t.javascript()->StoreContext(2, Context::GLOBAL_EVAL_FUN_INDEX),
        deep_const_context, deep_const_context, start, start);
    Reduction r = t.spec()->Reduce(load);
    CHECK(r.Changed());
    Node* new_context_input = NodeProperties::GetContextInput(r.replacement());
    CHECK_EQ(IrOpcode::kHeapConstant, new_context_input->opcode());
    HeapObjectMatcher match(new_context_input);
    CHECK_EQ(*native, Context::cast(*match.Value()));
    ContextAccess access = ContextAccessOf(r.replacement()->op());
    CHECK_EQ(Context::GLOBAL_EVAL_FUN_INDEX, static_cast<int>(access.index()));
    CHECK_EQ(0, static_cast<int>(access.depth()));
    CHECK_EQ(false, access.immutable());
  }
}

TEST(ReduceJSStoreContext1) {
  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()), t.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Node* context0 = t.graph()->NewNode(t.common()->Parameter(0), start);
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(0, slot_index),
                           context2, context2, start, start);
    CHECK(!t.spec()->Reduce(store).Changed());
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(1, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context1, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(2, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context0, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(3, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context0, 1);
  }
}

TEST(ReduceJSStoreContext2) {
  ContextSpecializationTester t(Nothing<OuterContext>());

  Node* start = t.graph()->NewNode(t.common()->Start(0));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()), t.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Handle<HeapObject> slot_value0 = t.factory()->InternalizeUtf8String("0");
  Handle<HeapObject> slot_value1 = t.factory()->InternalizeUtf8String("1");

  Handle<Context> context_object0 = t.factory()->NewNativeContext();
  Handle<Context> context_object1 = t.factory()->NewNativeContext();
  context_object1->set_previous(*context_object0);
  context_object0->set(slot_index, *slot_value0);
  context_object1->set(slot_index, *slot_value1);

  Node* context0 =
      t.jsgraph()->Constant(ObjectRef(t.broker(), context_object1));
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(0, slot_index),
                           context2, context2, start, start);
    CHECK(!t.spec()->Reduce(store).Changed());
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(1, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context1, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(2, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context0, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(3, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context_object0, 0);
  }
}

TEST(ReduceJSStoreContext3) {
  HandleAndZoneScope handle_zone_scope;
  auto factory = handle_zone_scope.main_isolate()->factory();

  Handle<HeapObject> slot_value0 = factory->InternalizeUtf8String("0");
  Handle<HeapObject> slot_value1 = factory->InternalizeUtf8String("1");

  Handle<Context> context_object0 = factory->NewNativeContext();
  Handle<Context> context_object1 = factory->NewNativeContext();
  context_object1->set_previous(*context_object0);
  context_object0->set(slot_index, *slot_value0);
  context_object1->set(slot_index, *slot_value1);

  ContextSpecializationTester t(Just(OuterContext(context_object1, 0)));

  Node* start = t.graph()->NewNode(t.common()->Start(2));
  t.graph()->SetStart(start);
  Handle<ScopeInfo> empty(ScopeInfo::Empty(t.main_isolate()),
                          handle_zone_scope.main_isolate());
  const i::compiler::Operator* create_function_context =
      t.javascript()->CreateFunctionContext(empty, 42, FUNCTION_SCOPE);

  Node* context0 = t.graph()->NewNode(t.common()->Parameter(0), start);
  Node* context1 =
      t.graph()->NewNode(create_function_context, context0, start, start);
  Node* context2 =
      t.graph()->NewNode(create_function_context, context1, start, start);

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(0, slot_index),
                           context2, context2, start, start);
    CHECK(!t.spec()->Reduce(store).Changed());
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(1, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context1, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(2, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context_object1, 0);
  }

  {
    Node* store =
        t.graph()->NewNode(t.javascript()->StoreContext(3, slot_index),
                           context2, context2, start, start);
    t.CheckContextInputAndDepthChanges(store, context_object0, 0);
  }
}

TEST(SpecializeJSFunction_ToConstant1) {
  FunctionTester T(
      "(function() { var x = 1; function inc(a)"
      " { return a + x; } return inc; })()");

  T.CheckCall(1.0, 0.0, 0.0);
  T.CheckCall(2.0, 1.0, 0.0);
  T.CheckCall(2.1, 1.1, 0.0);
}

TEST(SpecializeJSFunction_ToConstant2) {
  FunctionTester T(
      "(function() { var x = 1.5; var y = 2.25; var z = 3.75;"
      " function f(a) { return a - x + y - z; } return f; })()");

  T.CheckCall(-3.0, 0.0, 0.0);
  T.CheckCall(-2.0, 1.0, 0.0);
  T.CheckCall(-1.9, 1.1, 0.0);
}

TEST(SpecializeJSFunction_ToConstant3) {
  FunctionTester T(
      "(function() { var x = -11.5; function inc()"
      " { return (function(a) { return a + x; }); }"
      " return inc(); })()");

  T.CheckCall(-11.5, 0.0, 0.0);
  T.CheckCall(-10.5, 1.0, 0.0);
  T.CheckCall(-10.4, 1.1, 0.0);
}

TEST(SpecializeJSFunction_ToConstant_uninit) {
  {
    FunctionTester T(
        "(function() { if (false) { var x = 1; } function inc(a)"
        " { return x; } return inc; })()");  // x is undefined!
    i::Isolate* isolate = CcTest::i_isolate();
    CHECK(
        T.Call(T.Val(0.0), T.Val(0.0)).ToHandleChecked()->IsUndefined(isolate));
    CHECK(
        T.Call(T.Val(2.0), T.Val(0.0)).ToHandleChecked()->IsUndefined(isolate));
    CHECK(T.Call(T.Val(-2.1), T.Val(0.0))
              .ToHandleChecked()
              ->IsUndefined(isolate));
  }

  {
    FunctionTester T(
        "(function() { if (false) { var x = 1; } function inc(a)"
        " { return a + x; } return inc; })()");  // x is undefined!

    CHECK(T.Call(T.Val(0.0), T.Val(0.0)).ToHandleChecked()->IsNaN());
    CHECK(T.Call(T.Val(2.0), T.Val(0.0)).ToHandleChecked()->IsNaN());
    CHECK(T.Call(T.Val(-2.1), T.Val(0.0)).ToHandleChecked()->IsNaN());
  }
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8

{'repo_name': 'graalvm/graaljs', 'stars': '789', 'repo_language': 'C++', 'file_name': 'osr-typing-debug-change.js', 'mime_type': 'text/plain', 'hash': 8743140783329694617, 'source_dataset': 'data'}


/*
//@HEADER
// ************************************************************************
//
//                        Kokkos v. 3.0
//       Copyright (2020) National Technology & Engineering
//               Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/

#ifndef KOKKOS_TEST_HIPHOSTPINNED_HPP
#define KOKKOS_TEST_HIPHOSTPINNED_HPP

#include <gtest/gtest.h>

#define TEST_CATEGORY hip_hostpinned
#define TEST_EXECSPACE Kokkos::Experimental::HIPHostPinnedSpace

#endif

{'repo_name': 'kokkos/kokkos', 'stars': '606', 'repo_language': 'C++', 'file_name': 'FindTPLLIBNUMA.cmake', 'mime_type': 'text/plain', 'hash': 1782529081470969698, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <quatja.com.vorolay.VoronoiView
        android:id="@+id/voronoi"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        app:show_border="false"
        />

    <TextView
        android:id="@+id/elem_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="25sp"
        android:layout_centerInParent="true"/>

</RelativeLayout>

{'repo_name': 'Quatja/Vorolay', 'stars': '889', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/html', 'hash': -249468920007794074, 'source_dataset': 'data'}


// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_SELECT_H
#define EIGEN_SELECT_H

namespace Eigen {

/** \class Select
  * \ingroup Core_Module
  *
  * \brief Expression of a coefficient wise version of the C++ ternary operator ?:
  *
  * \param ConditionMatrixType the type of the \em condition expression which must be a boolean matrix
  * \param ThenMatrixType the type of the \em then expression
  * \param ElseMatrixType the type of the \em else expression
  *
  * This class represents an expression of a coefficient wise version of the C++ ternary operator ?:.
  * It is the return type of DenseBase::select() and most of the time this is the only way it is used.
  *
  * \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const
  */

namespace internal {
template<typename ConditionMatrixType, typename ThenMatrixType, typename ElseMatrixType>
struct traits<Select<ConditionMatrixType, ThenMatrixType, ElseMatrixType> >
 : traits<ThenMatrixType>
{
  typedef typename traits<ThenMatrixType>::Scalar Scalar;
  typedef Dense StorageKind;
  typedef typename traits<ThenMatrixType>::XprKind XprKind;
  typedef typename ConditionMatrixType::Nested ConditionMatrixNested;
  typedef typename ThenMatrixType::Nested ThenMatrixNested;
  typedef typename ElseMatrixType::Nested ElseMatrixNested;
  enum {
    RowsAtCompileTime = ConditionMatrixType::RowsAtCompileTime,
    ColsAtCompileTime = ConditionMatrixType::ColsAtCompileTime,
    MaxRowsAtCompileTime = ConditionMatrixType::MaxRowsAtCompileTime,
    MaxColsAtCompileTime = ConditionMatrixType::MaxColsAtCompileTime,
    Flags = (unsigned int)ThenMatrixType::Flags & ElseMatrixType::Flags & HereditaryBits,
    CoeffReadCost = traits<typename remove_all<ConditionMatrixNested>::type>::CoeffReadCost
                  + EIGEN_SIZE_MAX(traits<typename remove_all<ThenMatrixNested>::type>::CoeffReadCost,
                                   traits<typename remove_all<ElseMatrixNested>::type>::CoeffReadCost)
  };
};
}

template<typename ConditionMatrixType, typename ThenMatrixType, typename ElseMatrixType>
class Select : internal::no_assignment_operator,
  public internal::dense_xpr_base< Select<ConditionMatrixType, ThenMatrixType, ElseMatrixType> >::type
{
  public:

    typedef typename internal::dense_xpr_base<Select>::type Base;
    EIGEN_DENSE_PUBLIC_INTERFACE(Select)

    Select(const ConditionMatrixType& a_conditionMatrix,
           const ThenMatrixType& a_thenMatrix,
           const ElseMatrixType& a_elseMatrix)
      : m_condition(a_conditionMatrix), m_then(a_thenMatrix), m_else(a_elseMatrix)
    {
      eigen_assert(m_condition.rows() == m_then.rows() && m_condition.rows() == m_else.rows());
      eigen_assert(m_condition.cols() == m_then.cols() && m_condition.cols() == m_else.cols());
    }

    Index rows() const { return m_condition.rows(); }
    Index cols() const { return m_condition.cols(); }

    const Scalar coeff(Index i, Index j) const
    {
      if (m_condition.coeff(i,j))
        return m_then.coeff(i,j);
      else
        return m_else.coeff(i,j);
    }

    const Scalar coeff(Index i) const
    {
      if (m_condition.coeff(i))
        return m_then.coeff(i);
      else
        return m_else.coeff(i);
    }

    const ConditionMatrixType& conditionMatrix() const
    {
      return m_condition;
    }

    const ThenMatrixType& thenMatrix() const
    {
      return m_then;
    }

    const ElseMatrixType& elseMatrix() const
    {
      return m_else;
    }

  protected:
    typename ConditionMatrixType::Nested m_condition;
    typename ThenMatrixType::Nested m_then;
    typename ElseMatrixType::Nested m_else;
};

/** \returns a matrix where each coefficient (i,j) is equal to \a thenMatrix(i,j)
  * if \c *this(i,j), and \a elseMatrix(i,j) otherwise.
  *
  * Example: \include MatrixBase_select.cpp
  * Output: \verbinclude MatrixBase_select.out
  *
  * \sa class Select
  */
template<typename Derived>
template<typename ThenDerived,typename ElseDerived>
inline const Select<Derived,ThenDerived,ElseDerived>
DenseBase<Derived>::select(const DenseBase<ThenDerived>& thenMatrix,
                            const DenseBase<ElseDerived>& elseMatrix) const
{
  return Select<Derived,ThenDerived,ElseDerived>(derived(), thenMatrix.derived(), elseMatrix.derived());
}

/** Version of DenseBase::select(const DenseBase&, const DenseBase&) with
  * the \em else expression being a scalar value.
  *
  * \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const, class Select
  */
template<typename Derived>
template<typename ThenDerived>
inline const Select<Derived,ThenDerived, typename ThenDerived::ConstantReturnType>
DenseBase<Derived>::select(const DenseBase<ThenDerived>& thenMatrix,
                           const typename ThenDerived::Scalar& elseScalar) const
{
  return Select<Derived,ThenDerived,typename ThenDerived::ConstantReturnType>(
    derived(), thenMatrix.derived(), ThenDerived::Constant(rows(),cols(),elseScalar));
}

/** Version of DenseBase::select(const DenseBase&, const DenseBase&) with
  * the \em then expression being a scalar value.
  *
  * \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const, class Select
  */
template<typename Derived>
template<typename ElseDerived>
inline const Select<Derived, typename ElseDerived::ConstantReturnType, ElseDerived >
DenseBase<Derived>::select(const typename ElseDerived::Scalar& thenScalar,
                           const DenseBase<ElseDerived>& elseMatrix) const
{
  return Select<Derived,typename ElseDerived::ConstantReturnType,ElseDerived>(
    derived(), ElseDerived::Constant(rows(),cols(),thenScalar), elseMatrix.derived());
}

} // end namespace Eigen

#endif // EIGEN_SELECT_H

{'repo_name': 'mgschwan/blensor', 'stars': '108', 'repo_language': 'C', 'file_name': 'license.txt', 'mime_type': 'text/plain', 'hash': 855446324233461645, 'source_dataset': 'data'}


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

#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/opsets/opset4.hpp"
#include "util/type_prop.hpp"

using namespace std;
using namespace ngraph;

TEST(type_prop, gru_cell)
{
    const size_t batch_size = 2;
    const size_t input_size = 3;
    const size_t hidden_size = 3;
    const size_t gates_count = 3;

    const auto X = make_shared<op::Parameter>(element::f32, Shape{batch_size, input_size});
    const auto W =
        make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, input_size});
    const auto R =
        make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size});
    const auto H_t = make_shared<op::Parameter>(element::f32, Shape{batch_size, hidden_size});

    const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(gru_cell->get_output_element_type(0), element::f32);
    EXPECT_EQ(gru_cell->get_output_shape(0), (Shape{batch_size, hidden_size}));
}

TEST(type_prop, gru_cell_invalid_input)
{
    const size_t batch_size = 2;
    const size_t input_size = 3;
    const size_t hidden_size = 3;
    const size_t gates_count = 3;

    const auto X = make_shared<op::Parameter>(element::f32, Shape{batch_size, input_size});
    auto R =
        make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size});
    auto H_t = make_shared<op::Parameter>(element::f32, Shape{batch_size, hidden_size});

    // Invalid W tensor shape.
    auto W = make_shared<op::Parameter>(element::f32, Shape{hidden_size, input_size});
    try
    {
        const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
        FAIL() << "GRUCell node was created with invalid data.";
    }
    catch (const NodeValidationFailure& error)
    {
        EXPECT_HAS_SUBSTRING(error.what(),
                             std::string("Parameter hidden_size mistmatched in W input."));
    }

    // Invalid R tensor shape.
    W = make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, input_size});
    R = make_shared<op::Parameter>(element::f32, Shape{hidden_size, 1});
    try
    {
        const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
        FAIL() << "GRUCell node was created with invalid data.";
    }
    catch (const NodeValidationFailure& error)
    {
        EXPECT_HAS_SUBSTRING(
            error.what(),
            std::string(
                "Parameter hidden_size not matched for R and initial_hidden_state inputs."));
    }

    // Invalid H_t tensor shape.
    R = make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size});
    H_t = make_shared<op::Parameter>(element::f32, Shape{4, hidden_size});
    try
    {
        const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
        FAIL() << "GRUCell node was created with invalid data.";
    }
    catch (const NodeValidationFailure& error)
    {
        EXPECT_HAS_SUBSTRING(
            error.what(),
            std::string("Parameter batch_size not matched for X and initial_hidden_state inputs."));
    }

    // Invalid B tensor shape.
    H_t = make_shared<op::Parameter>(element::f32, Shape{batch_size, hidden_size});
    auto B = make_shared<op::Parameter>(element::f32, Shape{hidden_size});
    try
    {
        const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, B, hidden_size);
        FAIL() << "GRUCell node was created with invalid data.";
    }
    catch (const NodeValidationFailure& error)
    {
        EXPECT_HAS_SUBSTRING(error.what(),
                             std::string("Parameter hidden_size mistmatched in B input."));
    }
}

TEST(type_prop, gru_cell_dynamic_batch_size)
{
    const auto batch_size = Dimension::dynamic();
    const size_t input_size = 3;
    const size_t hidden_size = 3;
    const size_t gates_count = 3;

    const auto X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    const auto W = make_shared<op::Parameter>(element::f32,
                                              PartialShape{gates_count * hidden_size, input_size});
    const auto R = make_shared<op::Parameter>(element::f32,
                                              PartialShape{gates_count * hidden_size, hidden_size});
    const auto H_t =
        make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});

    const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(gru_cell->get_output_element_type(0), element::f32);
    EXPECT_EQ(gru_cell->get_output_partial_shape(0), (PartialShape{batch_size, hidden_size}));
}

TEST(type_prop, gru_cell_dynamic_hidden_size)
{
    const auto batch_size = 2;
    const size_t input_size = 3;
    const auto hidden_size = Dimension::dynamic();
    const size_t gates_count = 3;

    const auto X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    const auto W = make_shared<op::Parameter>(element::f32,
                                              PartialShape{hidden_size * gates_count, input_size});
    const auto R = make_shared<op::Parameter>(element::f32,
                                              PartialShape{hidden_size * gates_count, hidden_size});
    const auto H_t =
        make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});

    const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, 3);
    EXPECT_EQ(gru_cell->get_output_element_type(0), element::f32);
    EXPECT_EQ(gru_cell->get_output_partial_shape(0), (PartialShape{batch_size, hidden_size}));
}

TEST(type_prop, gru_cell_dynamic_inputs)
{
    const auto batch_size = Dimension::dynamic();
    const auto input_size = Dimension::dynamic();
    const auto hidden_size = Dimension::dynamic();

    const auto X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    const auto W = make_shared<op::Parameter>(element::f32, PartialShape{hidden_size, input_size});
    const auto R = make_shared<op::Parameter>(element::f32, PartialShape{hidden_size, hidden_size});
    const auto H_t =
        make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});

    const auto gru_cell = make_shared<opset4::GRUCell>(X, H_t, W, R, 2);

    EXPECT_EQ(gru_cell->get_output_partial_shape(0), (PartialShape{batch_size, hidden_size}));
    EXPECT_EQ(gru_cell->get_output_element_type(0), element::f32);
}

TEST(type_prop, gru_cell_invalid_input_rank0)
{
    const size_t batch_size = 2;
    const size_t input_size = 3;
    const size_t hidden_size = 3;
    const size_t gates_count = 3;

    auto X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    auto R = make_shared<op::Parameter>(element::f32,
                                        PartialShape{gates_count * hidden_size, hidden_size});
    auto H_t = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});

    // Invalid rank0 for W tensor.
    auto W = make_shared<op::Parameter>(element::f32, PartialShape{});
    ASSERT_THROW(make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size),
                 ngraph::NodeValidationFailure)
        << "GRUCell node was created with invalid data.";

    // Invalid rank0 for X tensor.
    W = make_shared<op::Parameter>(element::f32,
                                   PartialShape{gates_count * hidden_size, input_size});
    X = make_shared<op::Parameter>(element::f32, PartialShape{});
    ASSERT_THROW(make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size),
                 ngraph::NodeValidationFailure)
        << "GRUCell node was created with invalid data.";

    // Invalid rank0 for H_t tensor.
    X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    H_t = make_shared<op::Parameter>(element::f32, PartialShape{});
    ASSERT_THROW(make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size),
                 ngraph::NodeValidationFailure)
        << "GRUCell node was created with invalid data.";

    // Invalid rank0 for R tensor.
    H_t = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});
    R = make_shared<op::Parameter>(element::f32, PartialShape{});
    ASSERT_THROW(make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size),
                 ngraph::NodeValidationFailure)
        << "GRUCell node was created with invalid data.";

    // Invalid rank0 for B tensor.
    R = make_shared<op::Parameter>(element::f32,
                                   PartialShape{gates_count * hidden_size, input_size});
    auto B = make_shared<op::Parameter>(element::f32, PartialShape{});
    ASSERT_THROW(make_shared<opset4::GRUCell>(X, H_t, W, R, B, hidden_size),
                 ngraph::NodeValidationFailure)
        << "GRUCell node was created with invalid data.";
}

TEST(type_prop, gru_cell_invalid_input_dynamic_rank)
{
    const size_t batch_size = 2;
    const size_t input_size = 3;
    const size_t hidden_size = 3;
    const size_t gates_count = 3;

    auto X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    auto R = make_shared<op::Parameter>(element::f32,
                                        PartialShape{gates_count * hidden_size, hidden_size});
    auto H_t = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});

    auto check_dynamic_gru = [](const shared_ptr<opset4::GRUCell>& gru) -> bool {
        return gru->output(0).get_partial_shape() == PartialShape::dynamic() &&
               gru->output(0).get_element_type() == gru->input(0).get_element_type();
    };

    // Invalid dynamic rank for W tensor.
    auto W = make_shared<op::Parameter>(element::f32, PartialShape::dynamic(Rank::dynamic()));
    auto gru_w = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(check_dynamic_gru(gru_w), true);

    // Invalid dynamic rank for X tensor.
    W = make_shared<op::Parameter>(element::f32, PartialShape{hidden_size, input_size});
    X = make_shared<op::Parameter>(element::f32, PartialShape::dynamic(Rank::dynamic()));
    auto gru_x = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(check_dynamic_gru(gru_x), true);

    // Invalid dynamic rank for H_t tensor.
    X = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, input_size});
    H_t = make_shared<op::Parameter>(element::f32, PartialShape::dynamic(Rank::dynamic()));
    auto gru_h = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(check_dynamic_gru(gru_h), true);

    // Invalid dynamic rank for R tensor.
    H_t = make_shared<op::Parameter>(element::f32, PartialShape{batch_size, hidden_size});
    R = make_shared<op::Parameter>(element::f32, PartialShape::dynamic(Rank::dynamic()));
    auto gru_r = make_shared<opset4::GRUCell>(X, H_t, W, R, hidden_size);
    EXPECT_EQ(check_dynamic_gru(gru_r), true);

    // Invalid dynamic rank for B tensor.
    R = make_shared<op::Parameter>(element::f32,
                                   PartialShape{gates_count * hidden_size, hidden_size});
    auto B = make_shared<op::Parameter>(element::f32, PartialShape::dynamic(Rank::dynamic()));
    auto gru_b = make_shared<opset4::GRUCell>(X, H_t, W, R, B, hidden_size);
    EXPECT_EQ(check_dynamic_gru(gru_b), true);
}

{'repo_name': 'openvinotoolkit/openvino', 'stars': '1453', 'repo_language': 'C++', 'file_name': 'FindITT.cmake', 'mime_type': 'text/plain', 'hash': 4236604331211301050, 'source_dataset': 'data'}


#
# Copyright 2018 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
spring.profiles.active=chaos-monkey
chaos.monkey.enabled=true
chaos.monkey.assaults.latencyActive=true
chaos.monkey.assaults.latencyRangeStart=1000
chaos.monkey.assaults.latencyRangeEnd=4500
chaos.monkey.watcher.controller=false
chaos.monkey.watcher.component=true
chaos.monkey.watcher.restController=false
chaos.monkey.watcher.service=false
chaos.monkey.watcher.repository=false
chaos.monkey.assaults.level=3
management.endpoint.chaosmonkey.enabled=true
management.endpoint.chaosmonkeyjmx.enabled=false
management.endpoints.web.exposure.include=*
management.server.port=8888

{'repo_name': 'codecentric/chaos-monkey-spring-boot', 'stars': '576', 'repo_language': 'Java', 'file_name': 'SpringServiceAspectTest.java', 'mime_type': 'text/x-c++', 'hash': 8300437025813539066, 'source_dataset': 'data'}


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\MoFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class MoFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/resources.mo';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadPlurals()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/plurals.mo';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar', 'foos' => '{0} bar|{1} bars'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.mo';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/empty.mo';
        $loader->load($resource, 'en', 'domain1');
    }

    public function testLoadEmptyTranslation()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/empty-translation.mo';
        $catalogue = $loader->load($resource, 'en', 'message');

        $this->assertEquals(array(), $catalogue->all('message'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }
}

{'repo_name': 'bestmomo/laravel5-example', 'stars': '1201', 'repo_language': 'HTML', 'file_name': 'ie10-viewport-bug-workaround.js', 'mime_type': 'text/plain', 'hash': -5664986387097071292, 'source_dataset': 'data'}


{% extends "boh/management/base_management.html" %}

{% load i18n %}

{% block title %}{% trans 'Manage Settings' %} | {% trans 'Activity Types' %}{% endblock %}

{% block manage_content %}

{% trans 'Activity Types' %}

{% trans 'Activity types define what activities are and can contain documention for how that activity should be performed. The documentation will be visible on each activity of that type, making it a great place to include standard operating procedures, links, or anything else common amongst activities.' %}

    {% if not activity_types %}

{% trans 'There are no activity types.' %}

    {% endif %}

  {% if activity_types %}

          {% trans 'Name' %}
          {% trans 'Documentation' %}
          {% trans 'Activities' %}
          {% trans 'Actions' %}

        {% for activity_type in activity_types %}

          {{ activity_type.name }}
          {% if activity_type.documentation %}{% trans 'View' %}{% endif %}
          {{ activity_type.activity_set.count }}
          {% trans 'Edit' %}

        {% endfor %}

  {% endif %}

     {% trans 'New Activity Type' %}

{% endblock manage_content %}

{'repo_name': 'aparsons/bag-of-holding', 'stars': '108', 'repo_language': 'Python', 'file_name': 'prod.txt', 'mime_type': 'text/plain', 'hash': -9075105219793230269, 'source_dataset': 'data'}


package com.lusfold.spinnerloading.Animation;

import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * @author Lusfold
 */
public class CallbackAnimation extends Animation {
    public interface TransformationListener {
        void onApplyTrans(float interpolatedTime);
    }

    private TransformationListener mListener;

    public CallbackAnimation(TransformationListener listener) {
        mListener = listener;
        if (listener == null) {
            mListener = listener;
        }
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        mListener.onApplyTrans(interpolatedTime);
    }

    public void setListener(TransformationListener listener) {
        if (listener == null) {
            return;
        }
        mListener = listener;
    }
}

{'repo_name': 'lusfold/SpinnerLoading', 'stars': '385', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/x-java', 'hash': -6034668845694427534, 'source_dataset': 'data'}


Index

A

applications

clusters

deploying (task), To Deploy an Application to a Cluster

disabling (task), To Enable or Disable an Application That Is Deployed to a Cluster

disabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Cluster

editing (task), To Edit an Application That Is Deployed to a Cluster

enabling (task), To Enable or Disable an Application That Is Deployed to a Cluster

enabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Cluster

listing (task), To List Applications That Are Deployed to a Cluster

removing (task), To Remove Applications From a Cluster

undeploying (task), To Undeploy Applications From a Cluster

standalone instances

deploying (task), To Deploy an Application to a Standalone GlassFish Server Instance

disabling (task), To Enable or Disable an Application That Is Deployed to a Standalone GlassFish Server Instance

disabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Standalone GlassFish Server Instance

editing (task), To Edit an Application That Is Deployed to a Standalone GlassFish Server Instance

enabling (task), To Enable or Disable an Application That Is Deployed to a Standalone GlassFish Server Instance

enabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Standalone GlassFish Server Instance

listing (task), To List Applications That Are Deployed to a Standalone GlassFish Server Instance

removing (task), To Remove Applications From a Standalone GlassFish Server Instance

undeploying (task), To Undeploy Applications From a Standalone GlassFish Server Instance

viewing deployed

to clusters (reference), Applications

to standalone instances (reference), Applications

viewing monitoring data

clustered instances (task), To View Application Monitoring Data for a Clustered GlassFish Server Instance

standalone instances (task), To View Application Monitoring Data for a Standalone GlassFish Server Instance

availability, clusters (task), To Configure Availability Settings for a Cluster

availability service, editing (reference), Availability Service

C

cluster, disabling availability (task), To Configure Availability Settings for a Cluster

clustered instances

application monitoring (task), To View Application Monitoring Data for a Clustered GlassFish Server Instance

creating (reference), New Clustered Server Instance

creating (task), To Add a GlassFish Server Instance to a Cluster

deleting (task), To Delete Clustered GlassFish Server Instances

listing (reference), Clustered Server Instances

managing (reference), General Information

properties (reference), Instance Properties

properties (task), To Set Instance-Only Properties for a Clustered GlassFish Server Instance

recovering transactions (task), To Recover Transactions for a Clustered GlassFish Server Instance

resource monitoring (task), To View Resource Monitoring Data for a Clustered GlassFish Server Instance

resources (reference), Resources

starting (task), To Start Clustered GlassFish Server Instances

stopping (task), To Stop Clustered GlassFish Server Instances

system properties (reference), Instance System Properties

system properties (task), To Modify the Port Numbers of a Clustered GlassFish Server Instance

viewing log files (task), To View Log Files for a Clustered GlassFish Server Instance

virtual server monitoring (task), To View Virtual-Server Monitoring Data for a Clustered GlassFish Server Instance

clusters

applications

deploying (task), To Deploy an Application to a Cluster

disabling (task), To Enable or Disable an Application That Is Deployed to a Cluster

disabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Cluster

editing (task), To Edit an Application That Is Deployed to a Cluster

enabling (task), To Enable or Disable an Application That Is Deployed to a Cluster

enabling load balancing (task), To Enable or Disable Load Balancing for an Application That Is Deployed to a Cluster

listing (task), To List Applications That Are Deployed to a Cluster

removing (task), To Remove Applications From a Cluster

undeploying (task), To Undeploy Applications From a Cluster

applications (reference), Applications

configurations

modifying (task), To Modify the Configuration of a Cluster

configuring availability settings (task), To Configure Availability Settings for a Cluster

creating (reference), New Cluster

creating (task), To Create a Cluster

deleting (task), To Delete a Cluster

enabling availability (task), To Configure Availability Settings for a Cluster

general information (reference), General Information

listing (reference), Clusters

properties (reference), Cluster Properties

resources

creating (task), To Create a Resource for a Cluster

disabling (task), To Enable or Disable a Resource Globally

editing (task), To Edit a Resource for a Cluster

enabling (task), To Enable or Disable a Resource Globally

listing (task), To List Resources for a Cluster

starting (reference), General Information

starting (task), To Start a Cluster

stopping (reference), General Information

stopping (task), To Stop a Cluster

system properties (reference), Cluster System Properties

configurations

clusters

modifying (task), To Modify the Configuration of a Cluster

creating

clustered instances (reference), New Clustered Server Instance

clustered instances (tasks), To Add a GlassFish Server Instance to a Cluster

standalone instances (reference), New Standalone Server Instance

standalone instances (tasks), To Create a Standalone GlassFish Server Instance

D

deleting

clustered instances (task), To Delete Clustered GlassFish Server Instances

standalone instances (task), To Delete Standalone GlassFish Server Instances

deployment, rolling upgrade, To Upgrade Components Without Loss of Service

E

EJB timers

migrating (reference), Migrate EJB Timers

migrating (task), To Migrate EJB Timers

G

GlassFish Server

viewing monitoring data for applications (task)

To View Application Monitoring Data for a Clustered GlassFish Server Instance

To View Application Monitoring Data for a Standalone GlassFish Server Instance

group management service

configuring for a cluster (reference), General Information

configuring for a cluster (task), To Configure Group Management Service Settings for a Cluster

configuring settings (task), To Configure the Group Management Service

disabling (task), To Enable the Group Management Service

editing (reference), Edit Group Management Service

enabling (task), To Enable the Group Management Service

Copyright © 2005, 2017, Oracle and/or its affiliates. All rights reserved. Legal Notices

{'repo_name': 'eclipse-ee4j/glassfish', 'stars': '178', 'repo_language': 'Java', 'file_name': 'build.xml', 'mime_type': 'text/plain', 'hash': 806728692065916019, 'source_dataset': 'data'}


<!DOCTYPE html>
<html>
  <link rel='stylesheet' type='text/css' href='style.css'>
  <body>
    <fieldset class="ref">
      <fieldset class="ref">
        <button class="ref"></button>
      </fieldset>
    </fieldset>
  </body>
</html>

{'repo_name': 'mozilla/positron', 'stars': '514', 'repo_language': 'None', 'file_name': 'moz.build', 'mime_type': 'text/plain', 'hash': -5403806601109418839, 'source_dataset': 'data'}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

<title>NUnit - EventListeners</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta http-equiv="Content-Language" content="en-US">
<meta name="norton-safeweb-site-verification" content="tb6xj01p4hgo5x-8wscsmq633y11-e6nhk-bnb5d987bseanyp6p0uew-pec8j963qlzj32k5x9h3r2q7wh-vmy8bbhek5lnpp5w4p8hocouuq39e09jrkihdtaeknua" />
<link rel="stylesheet" type="text/css" href="nunit.css">
<link rel="shortcut icon" href="favicon.ico">

    NUnit
    Documentation

EventListeners (NUnit 2.4.4)

Purpose

EventListeners are able to respond to events that occur in the course
of a test run, usually by recording information of some kind. Note that
EventListeners called asynchronously with respect to test execution and
are not able to affect the actual execution of the test.

Extension Point

Addins use the host to access this extension point by name:

	IExtensionPoint listeners = host.GetExtensionPoint( "EventListeners" );

Interface

The extension object passed to Install must implement the EventListener interface:

	public interface EventListener
	{
		void RunStarted( string name, int testCount );
		void RunFinished( TestResult result );
		void RunFinished( Exception exception );
		void TestStarted(TestName testName);
		void TestFinished(TestResult result);
		void SuiteStarted(TestName testName);
		void SuiteFinished(TestResult result);
		void UnhandledException( Exception exception );
		void TestOutput(TestOutput testOutput);
	}

You must provide all the methods, but the body may be empty for any
that you have no need of.

NUnit 2.6.4

Getting Started

Writing Tests

Running Tests

Extensibility

Custom Constraints

NUnit Addins

SuiteBuilders

TestcaseBuilders

TestDecorators

TestcaseProviders

DatapointProviders

EventListeners

Tips for Extenders

Release Notes

Samples

License

NUnit Test Adapter

License

Release Notes

  Copyright © 2002-2014 NUnit.org. All Rights Reserved.

{'repo_name': 'bitrise-io/osx-box-bootstrap', 'stars': '103', 'repo_language': 'HTML', 'file_name': 'install_molecule_dependencies.sh', 'mime_type': 'text/x-shellscript', 'hash': -5869263601764242739, 'source_dataset': 'data'}


#include "pch.h"
#include "ParentProcess.h"

DWORD GetExplorerPIDbyShellWindow()
{
	DWORD dwProcessId = 0;

	// Get the PID of explorer by its windows handle
	GetWindowThreadProcessId(GetShellWindow(), &dwProcessId);

	return dwProcessId;
}

DWORD GetParentProcessId()
{
	auto NtQueryInfoProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess));

	// Some locals
	NTSTATUS Status = 0;
	ALK_PROCESS_BASIC_INFORMATION pbi;
	SecureZeroMemory(&pbi, sizeof(ALK_PROCESS_BASIC_INFORMATION));

	// Now we can call NtQueryInformationProcess, the second param 0 == ProcessBasicInformation
	Status = NtQueryInfoProcess(GetCurrentProcess(), 0, (PVOID)&pbi, sizeof(ALK_PROCESS_BASIC_INFORMATION), 0);

	if (Status != 0x00000000)
		return 0;
	else
		return (DWORD)pbi.ParentProcessId;
}

BOOL IsParentExplorerExe()
{
	//NOTE this check is wank because you can use an alternative file manager
	DWORD dwExplorerProcessId = GetParentProcessId();
	if (dwExplorerProcessId != GetExplorerPIDbyShellWindow())
		return TRUE;
	else
		return FALSE;
}

{'repo_name': 'LordNoteworthy/al-khaser', 'stars': '2368', 'repo_language': 'C++', 'file_name': 'pch.h', 'mime_type': 'text/x-c', 'hash': 2903056540223552931, 'source_dataset': 'data'}


from .BlockDevice import BlockDevice
from .ImageFile import ImageFile

class HDFBlockDevice(BlockDevice):
    def __init__(self, hdf_file, read_only=False, block_size=512, fobj=None):
        self.img_file = ImageFile(hdf_file, read_only, block_size, fobj)

    def create(self, geo, reserved=2):
        self._set_geometry(
            geo.cyls,
            geo.heads,
            geo.secs,
            reserved=reserved,
            block_bytes=self.img_file.block_bytes,
        )
        self.img_file.create(geo.get_num_blocks())
        self.img_file.open()

    def open(self, geo, reserved=2):
        self._set_geometry(
            geo.cyls,
            geo.heads,
            geo.secs,
            reserved=reserved,
            block_bytes=self.img_file.block_bytes,
        )
        self.img_file.open()

    def flush(self):
        pass

    def close(self):
        self.img_file.close()

    def read_block(self, blk_num):
        return self.img_file.read_blk(blk_num)

    def write_block(self, blk_num, data):
        return self.img_file.write_blk(blk_num, data)

{'repo_name': 'cnvogelg/amitools', 'stars': '140', 'repo_language': 'Python', 'file_name': 'fix_bsrl.py', 'mime_type': 'text/x-python', 'hash': -1752555172301933561, 'source_dataset': 'data'}


importance: 4

---

# Расширить элемент

В `<body>` есть элемент `<div>` с заданной шириной `width`.

Задача -- написать код, который "распахнёт" `<div>` по ширине на всю страницу.

Исходный документ (`<div>` содержит текст и прокрутку):

[iframe height=220 src="source"]

P.S. Пользоваться следует исключительно средствами JS, CSS в этой задаче менять нельзя. Также ваш код должен быть универсален и не ломаться, если цифры в CSS станут другими.

P.P.S. При расширении элемент `<div>` не должен вылезти за границу `<body>`.

{'repo_name': 'javascript-tutorial/ru.javascript.info', 'stars': '1729', 'repo_language': 'HTML', 'file_name': 'article.md', 'mime_type': 'text/plain', 'hash': -7436267593554300892, 'source_dataset': 'data'}


#
{Packet} = require './base'
C = require('../../const').openpgp
S = C.sig_subpacket
{encode_length,make_time_packet} = require '../util'
{unix_time,uint_to_buffer} = require '../../util'
{alloc_or_throw,SHA512,SHA1} = require '../../hash'
asymmetric = require '../../asymmetric'
util = require 'util'
packetsigs = require './packetsigs'
assert = require 'assert'
{SlicerBuffer} = require '../buffer'
{make_esc} = require 'iced-error'

#===========================================================

class Signature_v2_or_v3 extends Packet

  #---------------------

  constructor : ({ @key, @hasher, @key_id, @sig_data, @public_key_class,
                   @signed_hash_value_hash, @time, @sig, @type,
                   @version } ) ->
    @hasher = SHA512 unless @hasher?
    @_framed_output = null # sometimes we store the framed output here

  #---------------------

  is_signature : () -> true

  #---------------------

  get_key_id : () -> @key_id

  #---------------------

  # So this key behaves like a Sig V4
  get_key_flags : () -> 0
  get_key_expires : () -> 0

  #---------------------

  get_issuer_key_id : () -> @key_id

  #---------------------

  when_generated : () -> @time
  time_of_primary_uid_sig : () -> null

  #---------------------

  # For writing out these packets, which we'll likely never do.
  gen_prefix : () ->
    Buffer.concat [
      new Buffer [ C.versions.signature.V3, @type ],
      uint_to_buffer(32, @time),
      @key_id,
      new Buffer [ @key.type, @hasher.type ]
    ]

  #---------------------

  prepare_payload : (data_packets) ->
    bufs = (dp.to_signature_payload() for dp in data_packets)
    bufs.push(
      new Buffer([ @type ]),
      uint_to_buffer(32, @time)
    )
    Buffer.concat bufs

  #---------------------

  verify : (data_packets, cb) ->
    T = C.sig_types
    SKB = packetsigs.SubkeyBinding
    data_packets = [@primary].concat(data_packets) if (@type is T.subkey_binding)
    payload = @prepare_payload data_packets
    hash = @hasher payload
    s = new SlicerBuffer hash
    v = s.read_uint16()

    if (v isnt (b = @signed_hash_value_hash))
      err = new Error "quick hash check failed: #{v} != #{b}"
    else
      await @key.verify_unpad_and_check_hash { hash, @hasher, @sig }, defer err
      # If it's binary or text data, so that the packets have all be signed
      if err? then # noop
      else if @type in [ T.binary_doc, T.canonical_text ]
        for d in data_packets
          d.push_sig new packetsigs.Data { sig : @ }
      else if @type in [ T.subkey_binding ]
        for d in data_packets
          d.push_sig new SKB { @primary, sig : @, direction : SKB.DOWN }

    cb err

  #---------------------

#===========================================================

class Signature_v2 extends Signature_v2_or_v3

class Signature_v3 extends Signature_v2_or_v3

#===========================================================

class Signature extends Packet

  #---------------------

  constructor : ({ @key, @hasher, @key_id, @sig_data, @public_key_class,
                   @signed_hash_value_hash, @hashed_subpackets, @time, @sig, @type,
                   @unhashed_subpackets, @version } ) ->
    @hasher = SHA512 unless @hasher?
    @hashed_subpackets = [] unless @hashed_subpackets?
    @unhashed_subpackets = [] unless @unhashed_subpackets?
    @subpacket_index = @_make_subpacket_index()

    @_framed_output = null # sometimes we store the framed output here

  #---------------------

  get_key_id : () ->
    if @key_id then @key_id
    else @subpacket_index.all[S.issuer]?.id

  #---------------------

  _make_subpacket_index : () ->
    ret = { hashed : {}, unhashed : {}, all : {} }
    for p in @hashed_subpackets
      ret.hashed[p.type] = p
      ret.all[p.type] = p
    for p in @unhashed_subpackets
      ret.unhashed[p.type] = p
      ret.all[p.type] = p
    ret

  #---------------------

  prepare_payload : (data) ->
    flatsp = Buffer.concat( s.to_buffer() for s in @hashed_subpackets )

    prefix = Buffer.concat [
      new Buffer([ C.versions.signature.V4, @type, @key.type, @hasher.type ]),
      uint_to_buffer(16, flatsp.length),
      flatsp
    ]
    trailer = Buffer.concat [
      new Buffer([ C.versions.signature.V4, 0xff ]),
      uint_to_buffer(32, prefix.length)
    ]

    payload = Buffer.concat [ data, prefix, trailer ]
    hvalue = @hasher payload

    return { prefix, payload, hvalue }

  #---------------------

  # See write_message_signature in packet.signature.js
  write_unframed : (data, cb) ->
    esc = make_esc cb, "write_unframed"
    uhsp = Buffer.concat( s.to_buffer() for s in @unhashed_subpackets )

    { prefix, payload, hvalue } = @prepare_payload data
    await @key.pad_and_sign payload, { @hasher }, esc defer sig
    result2 = Buffer.concat [
      uint_to_buffer(16, uhsp.length),
      uhsp,
      new Buffer([hvalue.readUInt8(0), hvalue.readUInt8(1) ]),
      sig
    ]
    results = Buffer.concat [ prefix, result2 ]
    cb null, results

  #---------------------

  write : (data, cb) ->
    await @write_unframed data, defer err, unframed
    unless err?
      @_framed_output = ret = @frame_packet C.packet_tags.signature, unframed
    cb err, ret

  #-----------------

  # This is why we store the framed_output inside the packet after we write it
  # (see above in write).  Sometimes, in the case of public keys, we don't have the
  # capacity to regenerate signatures, so we just need to replay what we fetched.  But
  # other times, we want to rewrite the output. Through this mechanism we can handle both
  # cases.
  get_framed_output : () -> @_framed_output or @replay()

  #-----------------

  @parse : (slice) -> (new Parser slice).parse()

  #-----------------

  extract_key : (data_packets) ->
    for p in data_packets
      if p.key?
        @key = p.key
        break

  #-----------------

  verify : (data_packets, cb, opts) ->
    await @_verify data_packets, defer(err), opts
    for p in @unhashed_subpackets when (not err? and (s = p.to_sig())?)
      if s.type isnt C.sig_types.primary_binding
        err = new Error "unknown subpacket signature type: #{s.type}"
      else if data_packets.length isnt 1
        err = new Error "Needed 1 data packet for a primary_binding signature"
      else
        subkey = data_packets[0]
        s.primary = @primary
        s.key = subkey.key
        await s._verify [ subkey ], defer(err), opts
    cb err

  #-----------------

  _verify : (data_packets, cb, opts) ->
    err = null
    T = C.sig_types

    subkey = null

    # It's worth it to be careful here and check that we're getting the
    # right expected number of packets.
    @data_packets = switch @type
      when T.binary_doc, T.canonical_text then data_packets

      when T.issuer, T.personal, T.casual, T.positive, T.certificate_revocation

        if (n = data_packets.length) isnt 1
          err = new Error "Only expecting one UserID-style packet in a self-sig (got #{n})"
          []
        else
          # We need to use the primary key maybe several times,
          # so we unshift it onto the front of all sequences of data
          # packets.
          [ @primary ].concat data_packets

      when T.subkey_binding, T.primary_binding, T.subkey_revocation
        packets = []
        if data_packets.length isnt 1
          err =  new Error "Wrong number of data packets; expected only 1"
        else if not @primary?
          err = new Error "Need a primary key for subkey signature"
        else
          subkey = data_packets[0]
          packets = [ @primary, subkey ]
        packets

      when T.direct
        [ @primary].concat data_packets

      else
        err = new Error "cannot verify sigtype #{@type}"
        []

    # Now actually check that the signature worked.
    unless err?
      buffers = (dp.to_signature_payload() for dp in @data_packets)
      data = Buffer.concat buffers
      { payload, hvalue } = @prepare_payload data
      await @key.verify_unpad_and_check_hash { @sig, hash : hvalue, @hasher }, defer err

    # Check that our keys are not expired
    #
    # This is used to test if this (potential subkey) is expired as of the time
    # of the signature.  To use this feature, you have to enable 'time_travel' or specify 'now'
    # when you import the underlying pgp key in the first place. Otherwise the
    # subkey will simply fail to import (since it will assume 'unix_time()`).
    if not err? and @key_manager?
      err = @key_manager.pgp_check_not_expired { @subkey_material, now : opts?.now }

    # If we're signing a key, check key expiration now
    unless err?
      opts or= {}
      opts.subkey = subkey
      [err, key_expiration, sig_expiration] = @_check_key_sig_expiration opts
      opts.subkey = null

    # Now mark the object that was vouched for
    sig = @
    unless err?
      SKB = packetsigs.SubkeyBinding
      switch @type
        when T.binary_doc, T.canonical_text
          for d in @data_packets
            d.push_sig new packetsigs.Data { sig }

        when T.issuer, T.personal, T.casual, T.positive
          ps = null
          if (userid = @data_packets[1].to_userid())?
            ps = new packetsigs.SelfSig { @type, userid, sig }
            userid.push_sig ps
          else if (user_attribute = @data_packets[1].to_user_attribute())?
            ps = new packetsigs.SelfSig { @type, user_attribute, sig, key_expiration, sig_expiration }
            user_attribute.push_sig ps
          @primary.push_sig ps if ps

        when T.subkey_binding
          subkey.push_sig new SKB { @primary, sig, direction : SKB.DOWN, key_expiration, sig_expiration}

        when T.primary_binding
          subkey.push_sig new SKB { @primary, sig, direction : SKB.UP, key_expiration, sig_expiration}

        when T.subkey_revocation
          subkey.mark_revoked sig

    cb err

  #-----------------

  is_signature : () -> true

  #-----------------

  when_generated   : () -> @subpacket_index.hashed[S.creation_time]?.time
  get_key_expires : () -> @subpacket_index.hashed[S.key_expiration_time]?.time
  get_sig_expires : () -> @subpacket_index.hashed[S.expiration_time]?.time

  #-----------------

  time_primary_pair : () ->
    T = C.sig_types
    if @type in [ T.issuer, T.personal, T.casual, T.positive ]
      [ @when_generated(), !!(@subpacket_index.hashed[S.primary_user_id]?.flag) ]
    else
      null

  #-----------------

  # See Issue #28
  #   https://github.com/keybase/kbpgp/issues/28
  _check_key_sig_expiration : (opts) ->
    err = null
    T = C.sig_types
    key_expiration = 0
    sig_expiration = 0

    if @type in [ T.issuer, T.personal, T.casual, T.positive, T.subkey_binding, T.primary_binding ]

      key_creation = (opts.subkey or @primary).timestamp
      key_expiration_packet = @subpacket_index.hashed[S.key_expiration_time]
      sig_creation_packet = @subpacket_index.hashed[S.creation_time]
      sig_expiration_packet = @subpacket_index.hashed[S.sig_expiration_time]

      # We can set now back in time for some operations, like testing people's
      # old keys
      now = if (n = opts?.now)? then n else unix_time()

      if key_creation? and key_expiration_packet?.time
        key_expiration = key_creation + key_expiration_packet.time
      if sig_creation_packet? and sig_expiration_packet?.time
        sig_expiration = sig_creation_packet.time + sig_expiration_packet.time

      if key_expiration and not(opts.time_travel) and now > key_expiration
        err = new Error "Key expired #{now - key_expiration}s ago"
      if sig_expiration and not(opts.time_travel) and now > sig_expiration
        err = new Error "Sig expired #{now - key_expiration}s ago"

    return [err, key_expiration, sig_expiration]

  #-----------------

  get_key_flags : () ->
    @subpacket_index?.hashed?[C.sig_subpacket.key_flags]?.all_flags() or 0

  #-----------------

  get_issuer_key_id : () ->
    @subpacket_index?.all[C.sig_subpacket.issuer]?.id

#===========================================================

class SubPacket
  constructor : (@type) ->
    @critical = false
    @five_byte_len = false
  set_opts : (d) ->
    (@[k] = v for k,v of d)
    true
  to_buffer : () ->
    inner = @_v_to_buffer()
    Buffer.concat [
      encode_length(inner.length + 1, @five_byte_len),
      uint_to_buffer(8, (@type | (if @critical then 0x80 else 0x00))),
      inner
    ]
  to_sig : () -> null
  export_to_option : () -> null

#------------

# Ignore for the most part
class Experimental extends SubPacket
  constructor : (@buf, @type) ->
  @parse : (slice, type) ->
    new Experimental slice.consume_rest_to_buffer(), type
  _v_to_buffer : () -> @buf

#------------

class Time extends SubPacket
  constructor : (type, @time) ->
    @never_expires = (@time is 0)
    super type
  @parse : (slice, klass) -> new klass slice.read_uint32()
  _v_to_buffer : () -> uint_to_buffer 32, @time

#------------

class Preference extends SubPacket
  constructor : (type, @v) ->
    super type
    # No 'undefined' or null values allowed...
    for e in @v
      assert e?

  @parse : (slice, klass) ->
    v = (c for c in slice.consume_rest_to_buffer())
    new klass v
  _v_to_buffer : () -> new Buffer (e for e in @v)

#------------

class CreationTime extends Time
  constructor : (t) ->
    super S.creation_time, t
  @parse : (slice) -> Time.parse slice, CreationTime

#------------

class ExpirationTime extends Time
  constructor : (t) ->
    super S.expiration_time, t
  @parse : (slice) -> Time.parse slice, ExpirationTime

#------------

class Exportable extends SubPacket
  constructor : (@flag) ->
    super S.exportable_certificate
  @parse : (slice) -> new Exportable slice.read_uint8()
  _v_to_buffer : () -> uint_to_buffer 8, @flag

#------------

class Trust extends SubPacket
  constructor : (@level, @amount) ->
    super S.trust_signature
  @parse : (slice) -> new Trust slice.read_uint8(), slice.read_uint8()
  _v_to_buffer : () ->
    Buffer.concat [
      uint_to_buffer(8, @level),
      uint_to_buffer(8, @amount),
    ]

#------------

class RegularExpression extends SubPacket
  constructor : (@re) ->
    super S.regular_expression
  @parse : (slice) ->
    ret = new RegularExpression slice.consume_rest_to_buffer().toString 'utf8'
    ret
  _v_to_buffer : () -> new Buffer @re, 'utf8'

#------------

class Revocable extends SubPacket
  constructor : (@flag) ->
    super S.revocable
  @parse : (slice) -> new Revocable slice.read_uint8()
  _v_to_buffer : () -> uint_to_buffer 8, @flag

#------------

class KeyExpirationTime extends Time
  constructor : (t) ->
    super S.key_expiration_time, t
  @parse : (slice) -> Time.parse slice, KeyExpirationTime

#------------

class PreferredSymmetricAlgorithms extends Preference
  constructor : (v) ->
    super S.preferred_symmetric_algorithms, v
  @parse : (slice) -> Preference.parse slice, PreferredSymmetricAlgorithms

#------------

class RevocationKey extends SubPacket
  constructor : (@key_class, @alg, @fingerprint) ->
    super S.revocation_key
  @parse : (slice) ->
    kc = slice.read_uint8()
    ka = slice.read_uint8()
    fp = slice.read_buffer SHA1.output_length
    return new RevocationKey kc, ka, fp
  _v_to_buffer : () ->
    Buffer.concat [
      uint_to_buffer(8, @key_class),
      uint_to_buffer(8, @alg),
      new Buffer(@fingerprint)
    ]

#------------

class Issuer extends SubPacket
  constructor : (@id) ->
    super S.issuer
  @parse : (slice) -> new Issuer slice.read_buffer 8
  _v_to_buffer : () -> new Buffer @id

#------------

class NotationData extends SubPacket
  constructor : (@flags, @name, @value) ->
    super S.notation_data
  @parse : (slice) ->
    flags = slice.read_uint32()
    nl = slice.read_uint16()
    vl = slice.read_uint16()
    name = slice.read_buffer nl
    value = slice.read_buffer vl
    new NotationData flags, name, value
  _v_to_buffer : () ->
    Buffer.concat [
      uint_to_buffer(32, @flags),
      uint_to_buffer(16, @name.length),
      uint_to_buffer(16, @value.length),
      new Buffer(@name),
      new Buffer(@value)
    ]

#------------

class PreferredHashAlgorithms extends Preference
  constructor : (v) ->
    super S.preferred_hash_algorithms, v
  @parse : (slice) -> Preference.parse slice, PreferredHashAlgorithms

#------------

class PreferredCompressionAlgorithms extends Preference
  constructor : (v) ->
    super S.preferred_compression_algorithms, v
  @parse : (slice) -> Preference.parse slice, PreferredCompressionAlgorithms

#------------

class KeyServerPreferences extends Preference
  constructor : (v) ->
    super S.key_server_preferences, v
  @parse : (slice) -> Preference.parse slice, KeyServerPreferences

#------------

class Features extends Preference
  constructor : (v) ->
    super S.features, v
  @parse : (slice) -> Preference.parse slice, Features

#------------

class PreferredKeyServer extends SubPacket
  constructor : (@server) ->
    super S.preferred_key_server
  @parse : (slice) -> new PreferredKeyServer slice.consume_rest_to_buffer()
  _v_to_buffer : () -> @server

#------------

class PrimaryUserId extends SubPacket
  constructor : (@flag) ->
    super S.primary_user_id
  @parse : (slice) -> new PrimaryUserId slice.read_uint8()
  _v_to_buffer : () -> uint_to_buffer(8, @flag)

#------------

class PolicyURI extends SubPacket
  constructor : (@flag) ->
    super S.policy_uri
  @parse : (slice) -> new PolicyURI slice.consume_rest_to_buffer()
  _v_to_buffer : () -> @flag

#------------

class KeyFlags extends Preference
  constructor : (v) ->
    super S.key_flags, v
  @parse : (slice) -> Preference.parse slice, KeyFlags
  all_flags : () ->
    ret = 0
    ret |= e for e in @v
    ret

#------------

class SignersUserID extends SubPacket
  constructor : (@uid) ->
    super S.signers_user_id
  @parse : (slice) -> new SignersUserID slice.consume_rest_to_buffer()
  _v_to_buffer : () -> @uid

#------------

class ReasonForRevocation extends SubPacket
  constructor : (@flag, @reason) ->
    super S.reason_for_revocation
  @parse : (slice) ->
    flag = slice.read_uint8()
    reason = slice.consume_rest_to_buffer()
    return new ReasonForRevocation flag, reason
  _v_to_buffer : () ->
    Buffer.concat [ uint_to_buffer(8, @flag), @reason ]

#------------

class SignatureTarget extends SubPacket
  constructor : (@pub_key_alg, @hasher, @hval) ->
    super S.signature_target
  @parse : (slice) ->
    pka = slice.read_uint8()
    hasher = alloc_or_throw slice.read_uint8()
    hval = slice.read_buffer hasher.output_length
    new SignatureTarget pka, hasher, hval
  _v_to_buffer : () ->
    Buffer.concat [
      uint_to_buffer(8, @pub_key_alg),
      uint_to_buffer(8, @hasher.type),
      @hval
    ]

#------------

class EmbeddedSignature extends SubPacket
  constructor : ({@sig, @rawsig}) ->
    super S.embedded_signature
  _v_to_buffer : () -> @rawsig
  to_sig : () -> @sig
  @parse : (slice) ->
    rawsig = slice.peek_rest_to_buffer()
    sig = Signature.parse(slice)
    new EmbeddedSignature { sig, rawsig }

#===========================================================

exports.Signature = Signature

#===========================================================

class Parser

  constructor : (@slice) ->

  parse_v2_or_v3 : (v, klass) ->
    throw new error "Bad one-octet length" unless @slice.read_uint8() is 5
    o = {}
    o.type = @slice.read_uint8()
    o.time = @slice.read_uint32()
    o.sig_data = @slice.peek_rest_to_buffer()
    o.key_id = @slice.read_buffer 8
    o.public_key_class = asymmetric.get_class @slice.read_uint8()
    o.hasher = alloc_or_throw @slice.read_uint8()
    o.signed_hash_value_hash = @slice.read_uint16()
    o.sig = o.public_key_class.parse_sig @slice
    o.version = v
    new klass o

  parse_v4 : () ->
    o = {}
    o.type = @slice.read_uint8()
    o.public_key_class = asymmetric.get_class @slice.read_uint8()
    o.hasher = alloc_or_throw @slice.read_uint8()
    hashed_subpacket_count = @slice.read_uint16()
    end = @slice.i + hashed_subpacket_count
    o.sig_data = @slice.peek_to_buffer hashed_subpacket_count
    o.hashed_subpackets = (@parse_subpacket() while @slice.i < end)
    unhashed_subpacket_count = @slice.read_uint16()
    end = @slice.i + unhashed_subpacket_count
    o.unhashed_subpackets = (@parse_subpacket() while @slice.i < end)
    o.signed_hash_value_hash = @slice.read_uint16()
    o.sig = o.public_key_class.parse_sig @slice
    o.version = 4
    new Signature o

  parse_subpacket : () ->
    [len, five_byte_len] = @slice.read_v4_length()
    raw_type = @slice.read_uint8()
    type = (raw_type & 0x7f)
    critical = !!(raw_type & 0x80)
    # (len - 1) since we don't want the packet tag to count toward the len
    end = @slice.clamp (len - 1)
    klass = switch type
      when S.creation_time then CreationTime
      when S.expiration_time then ExpirationTime
      when S.exportable_certificate then Exportable
      when S.trust_signature then Trust
      when S.regular_expression then RegularExpression
      when S.revocable then Revocable
      when S.key_expiration_time then KeyExpirationTime
      when S.preferred_symmetric_algorithms then PreferredSymmetricAlgorithms
      when S.revocation_key then RevocationKey
      when S.issuer then Issuer
      when S.notation_data then NotationData
      when S.preferred_hash_algorithms  then PreferredHashAlgorithms
      when S.preferred_compression_algorithms then PreferredCompressionAlgorithms
      when S.key_server_preferences then KeyServerPreferences
      when S.preferred_key_server then PreferredKeyServer
      when S.primary_user_id then PrimaryUserId
      when S.policy_uri then PolicyURI
      when S.key_flags then KeyFlags
      when S.signers_user_id then SignersUserID
      when S.reason_for_revocation then ReasonForRevocation
      when S.features then Features
      when S.signature_target then SignatureTarget
      when S.embedded_signature then EmbeddedSignature
      else
        if type >= S.experimental_low and type <= S.experimental_high then Experimental
        else throw new Error "Unknown signature subpacket: #{type}"
    ret = klass.parse @slice, type
    ret.set_opts { critical, five_byte_len }
    @slice.unclamp end
    ret

  parse : () ->
    version = @slice.read_uint8()
    switch version
      when C.versions.signature.V2 then @parse_v2_or_v3 version, Signature_v2
      when C.versions.signature.V3 then @parse_v2_or_v3 version, Signature_v3
      when C.versions.signature.V4 then @parse_v4()
      else throw new Error "Unknown signature version: #{version}"

#===========================================================

exports.CreationTime = CreationTime
exports.KeyFlags = KeyFlags
exports.KeyExpirationTime = KeyExpirationTime
exports.PreferredSymmetricAlgorithms = PreferredSymmetricAlgorithms
exports.PreferredHashAlgorithms = PreferredHashAlgorithms
exports.PreferredCompressionAlgorithms = PreferredCompressionAlgorithms
exports.Features = Features
exports.KeyServerPreferences = KeyServerPreferences
exports.Issuer = Issuer
exports.EmbeddedSignature = EmbeddedSignature
exports.PrimaryUserId = PrimaryUserId

#===========================================================

{'repo_name': 'keybase/node-client', 'stars': '298', 'repo_language': 'CoffeeScript', 'file_name': 'versions.iced', 'mime_type': 'text/plain', 'hash': -1529300340039642718, 'source_dataset': 'data'}


--TEST--
Testing 'self', 'parent' as type-hint
--FILE--
<?php

interface iTest { }

class baz implements iTest {}

class bar { }

class foo extends bar {
    public function testFoo(self $obj) {
        var_dump($obj);
    }
    public function testBar(parent $obj) {
        var_dump($obj);
    }
    public function testBaz(iTest $obj) {
        var_dump($obj);
    }
}

$foo = new foo;
$foo->testFoo(new foo);
$foo->testBar(new bar);
$foo->testBaz(new baz);
$foo->testFoo(new stdClass); // Catchable fatal error

?>
--EXPECTF--
object(foo)#%d (0) {
}
object(bar)#%d (0) {
}
object(baz)#%d (0) {
}

Catchable fatal error: Argument 1 passed to foo::testFoo() must be an instance of foo, instance of stdClass given, called in %s on line %d and defined in %s on line %d

{'repo_name': 'hippyvm/hippyvm', 'stars': '870', 'repo_language': 'PHP', 'file_name': 'jithip.py', 'mime_type': 'text/x-python', 'hash': -8080965991570103874, 'source_dataset': 'data'}


//===========================================
// The following is for 8192E 1ANT BT Co-exist definition
//===========================================
#define	BT_AUTO_REPORT_ONLY_8192E_1ANT				1

#define	BT_INFO_8192E_1ANT_B_FTP						BIT7
#define	BT_INFO_8192E_1ANT_B_A2DP					BIT6
#define	BT_INFO_8192E_1ANT_B_HID						BIT5
#define	BT_INFO_8192E_1ANT_B_SCO_BUSY				BIT4
#define	BT_INFO_8192E_1ANT_B_ACL_BUSY				BIT3
#define	BT_INFO_8192E_1ANT_B_INQ_PAGE				BIT2
#define	BT_INFO_8192E_1ANT_B_SCO_ESCO				BIT1
#define	BT_INFO_8192E_1ANT_B_CONNECTION				BIT0

#define	BT_INFO_8192E_1ANT_A2DP_BASIC_RATE(_BT_INFO_EXT_)	\
		(((_BT_INFO_EXT_&BIT0))? TRUE:FALSE)

#define	BTC_RSSI_COEX_THRESH_TOL_8192E_1ANT		2

#define  BT_8192E_1ANT_WIFI_NOISY_THRESH								30   //max: 255

typedef enum _BT_INFO_SRC_8192E_1ANT{
	BT_INFO_SRC_8192E_1ANT_WIFI_FW			= 0x0,
	BT_INFO_SRC_8192E_1ANT_BT_RSP				= 0x1,
	BT_INFO_SRC_8192E_1ANT_BT_ACTIVE_SEND		= 0x2,
	BT_INFO_SRC_8192E_1ANT_MAX
}BT_INFO_SRC_8192E_1ANT,*PBT_INFO_SRC_8192E_1ANT;

typedef enum _BT_8192E_1ANT_BT_STATUS{
	BT_8192E_1ANT_BT_STATUS_NON_CONNECTED_IDLE	= 0x0,
	BT_8192E_1ANT_BT_STATUS_CONNECTED_IDLE		= 0x1,
	BT_8192E_1ANT_BT_STATUS_INQ_PAGE				= 0x2,
	BT_8192E_1ANT_BT_STATUS_ACL_BUSY				= 0x3,
	BT_8192E_1ANT_BT_STATUS_SCO_BUSY				= 0x4,
	BT_8192E_1ANT_BT_STATUS_ACL_SCO_BUSY			= 0x5,
	BT_8192E_1ANT_BT_STATUS_MAX
}BT_8192E_1ANT_BT_STATUS,*PBT_8192E_1ANT_BT_STATUS;

typedef enum _BT_8192E_1ANT_WIFI_STATUS{
	BT_8192E_1ANT_WIFI_STATUS_NON_CONNECTED_IDLE				= 0x0,
	BT_8192E_1ANT_WIFI_STATUS_NON_CONNECTED_ASSO_AUTH_SCAN		= 0x1,
	BT_8192E_1ANT_WIFI_STATUS_CONNECTED_SCAN					= 0x2,
	BT_8192E_1ANT_WIFI_STATUS_CONNECTED_SPECIAL_PKT				= 0x3,
	BT_8192E_1ANT_WIFI_STATUS_CONNECTED_IDLE					= 0x4,
	BT_8192E_1ANT_WIFI_STATUS_CONNECTED_BUSY					= 0x5,
	BT_8192E_1ANT_WIFI_STATUS_MAX
}BT_8192E_1ANT_WIFI_STATUS,*PBT_8192E_1ANT_WIFI_STATUS;

typedef enum _BT_8192E_1ANT_COEX_ALGO{
	BT_8192E_1ANT_COEX_ALGO_UNDEFINED			= 0x0,
	BT_8192E_1ANT_COEX_ALGO_SCO				= 0x1,
	BT_8192E_1ANT_COEX_ALGO_HID				= 0x2,
	BT_8192E_1ANT_COEX_ALGO_A2DP				= 0x3,
	BT_8192E_1ANT_COEX_ALGO_A2DP_PANHS		= 0x4,
	BT_8192E_1ANT_COEX_ALGO_PANEDR			= 0x5,
	BT_8192E_1ANT_COEX_ALGO_PANHS			= 0x6,
	BT_8192E_1ANT_COEX_ALGO_PANEDR_A2DP		= 0x7,
	BT_8192E_1ANT_COEX_ALGO_PANEDR_HID		= 0x8,
	BT_8192E_1ANT_COEX_ALGO_HID_A2DP_PANEDR	= 0x9,
	BT_8192E_1ANT_COEX_ALGO_HID_A2DP			= 0xa,
	BT_8192E_1ANT_COEX_ALGO_MAX				= 0xb,
}BT_8192E_1ANT_COEX_ALGO,*PBT_8192E_1ANT_COEX_ALGO;

typedef struct _COEX_DM_8192E_1ANT{
	// fw mechanism
	BOOLEAN		bCurIgnoreWlanAct;
	BOOLEAN		bPreIgnoreWlanAct;
	u1Byte		prePsTdma;
	u1Byte		curPsTdma;
	u1Byte		psTdmaPara[5];
	u1Byte		psTdmaDuAdjType;
	BOOLEAN		bAutoTdmaAdjust;
	BOOLEAN		bPrePsTdmaOn;
	BOOLEAN		bCurPsTdmaOn;
	BOOLEAN		bPreBtAutoReport;
	BOOLEAN		bCurBtAutoReport;
	u1Byte		preLps;
	u1Byte		curLps;
	u1Byte		preRpwm;
	u1Byte		curRpwm;

	// sw mechanism
	BOOLEAN 	bPreLowPenaltyRa;
	BOOLEAN		bCurLowPenaltyRa;
	u4Byte		preVal0x6c0;
	u4Byte		curVal0x6c0;
	u4Byte		preVal0x6c4;
	u4Byte		curVal0x6c4;
	u4Byte		preVal0x6c8;
	u4Byte		curVal0x6c8;
	u1Byte		preVal0x6cc;
	u1Byte		curVal0x6cc;
	BOOLEAN		bLimitedDig;

	u4Byte		backupArfrCnt1;	// Auto Rate Fallback Retry cnt
	u4Byte		backupArfrCnt2;	// Auto Rate Fallback Retry cnt
	u2Byte		backupRetryLimit;
	u1Byte		backupAmpduMaxTime;

	// algorithm related
	u1Byte		preAlgorithm;
	u1Byte		curAlgorithm;
	u1Byte		btStatus;
	u1Byte		wifiChnlInfo[3];

	u4Byte		preRaMask;
	u4Byte		curRaMask;
	u1Byte		preArfrType;
	u1Byte		curArfrType;
	u1Byte		preRetryLimitType;
	u1Byte		curRetryLimitType;
	u1Byte		preAmpduTimeType;
	u1Byte		curAmpduTimeType;
	u4Byte		nArpCnt;

	u1Byte		errorCondition;
} COEX_DM_8192E_1ANT, *PCOEX_DM_8192E_1ANT;

typedef struct _COEX_STA_8192E_1ANT{
	BOOLEAN					bBtLinkExist;
	BOOLEAN					bScoExist;
	BOOLEAN					bA2dpExist;
	BOOLEAN					bHidExist;
	BOOLEAN					bPanExist;

	BOOLEAN					bUnderLps;
	BOOLEAN					bUnderIps;
	u4Byte					specialPktPeriodCnt;
	u4Byte					highPriorityTx;
	u4Byte					highPriorityRx;
	u4Byte					lowPriorityTx;
	u4Byte					lowPriorityRx;
	s1Byte					btRssi;
	BOOLEAN					bBtTxRxMask;
	u1Byte					preBtRssiState;
	u1Byte					preWifiRssiState[4];
	BOOLEAN					bC2hBtInfoReqSent;
	u1Byte					btInfoC2h[BT_INFO_SRC_8192E_1ANT_MAX][10];
	u4Byte					btInfoC2hCnt[BT_INFO_SRC_8192E_1ANT_MAX];
	BOOLEAN					bC2hBtInquiryPage;
	BOOLEAN					bC2hBtPage;				//Add for win8.1 page out issue
	BOOLEAN					bWiFiIsHighPriTask;		//Add for win8.1 page out issue
	u1Byte					btRetryCnt;
	u1Byte					btInfoExt;
	u4Byte					popEventCnt;
	u1Byte					nScanAPNum;

	u4Byte					nCRCOK_CCK;
	u4Byte					nCRCOK_11g;
	u4Byte					nCRCOK_11n;
	u4Byte					nCRCOK_11nAgg;

	u4Byte					nCRCErr_CCK;
	u4Byte					nCRCErr_11g;
	u4Byte					nCRCErr_11n;
	u4Byte					nCRCErr_11nAgg;

	BOOLEAN					bCCKLock;
	BOOLEAN					bPreCCKLock;
	u1Byte					nCoexTableType;

	BOOLEAN					bForceLpsOn;
}COEX_STA_8192E_1ANT, *PCOEX_STA_8192E_1ANT;

//===========================================
// The following is interface which will notify coex module.
//===========================================
VOID
EXhalbtc8192e1ant_PowerOnSetting(
	IN	PBTC_COEXIST		pBtCoexist
	);
VOID
EXhalbtc8192e1ant_PreLoadFirmware(
	IN	PBTC_COEXIST		pBtCoexist
	);
VOID
EXhalbtc8192e1ant_InitHwConfig(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	BOOLEAN				bWifiOnly
	);
VOID
EXhalbtc8192e1ant_InitCoexDm(
	IN	PBTC_COEXIST		pBtCoexist
	);
VOID
EXhalbtc8192e1ant_IpsNotify(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	u1Byte			type
	);
VOID
EXhalbtc8192e1ant_LpsNotify(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	u1Byte			type
	);
VOID
EXhalbtc8192e1ant_ScanNotify(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	u1Byte			type
	);
VOID
EXhalbtc8192e1ant_ConnectNotify(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	u1Byte			type
	);
VOID
EXhalbtc8192e1ant_MediaStatusNotify(
	IN	PBTC_COEXIST			pBtCoexist,
	IN	u1Byte				type
	);
VOID
EXhalbtc8192e1ant_SpecialPacketNotify(
	IN	PBTC_COEXIST			pBtCoexist,
	IN	u1Byte				type
	);
VOID
EXhalbtc8192e1ant_BtInfoNotify(
	IN	PBTC_COEXIST		pBtCoexist,
	IN	pu1Byte			tmpBuf,
	IN	u1Byte			length
	);
VOID
EXhalbtc8192e1ant_RfStatusNotify(
	IN	PBTC_COEXIST			pBtCoexist,
	IN	u1Byte					type
	);
VOID
EXhalbtc8192e1ant_HaltNotify(
	IN	PBTC_COEXIST			pBtCoexist
	);
VOID
EXhalbtc8192e1ant_PnpNotify(
	IN	PBTC_COEXIST			pBtCoexist,
	IN	u1Byte				pnpState
	);
VOID
EXhalbtc8192e1ant_CoexDmReset(
	IN	PBTC_COEXIST			pBtCoexist
	);
VOID
EXhalbtc8192e1ant_Periodical(
	IN	PBTC_COEXIST			pBtCoexist
	);
VOID
EXhalbtc8192e1ant_DisplayCoexInfo(
	IN	PBTC_COEXIST		pBtCoexist
	);
VOID
EXhalbtc8192e1ant_DbgControl(
	IN	PBTC_COEXIST			pBtCoexist,
	IN	u1Byte				opCode,
	IN	u1Byte				opLen,
	IN	pu1Byte 			pData
	);

{'repo_name': 'OLIMEX/DIY-LAPTOP', 'stars': '358', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': 3146791293285543652, 'source_dataset': 'data'}


transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  vgroupMapping.my_test_tx_group = "default"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

{'repo_name': 'seata/seata-samples', 'stars': '1035', 'repo_language': 'Java', 'file_name': 'OrderServiceImpl.java', 'mime_type': 'text/x-java', 'hash': 8882373669466520698, 'source_dataset': 'data'}