text:
using namespace v8;
namespace i = v8::internal;

TEST(PerIsolateState) {
  HandleScope scope(CcTest::isolate());
  LocalContext context1(CcTest::isolate());

  Local<Value> foo = v8_str("foo");
  context1->SetSecurityToken(foo);

  CompileRun(
      "var count = 0;"
      "var calls = 0;"
      "var observer = function(records) { count = records.length; calls++ };"
      "var obj = {};"
      "Object.observe(obj, observer);");
  Handle<Value> observer = CompileRun("observer");
  Handle<Value> obj = CompileRun("obj");
  Handle<Value> notify_fun1 = CompileRun(
      "(function() { obj.foo = 'bar'; })");
  Handle<Value> notify_fun2;
  {
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(foo);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            obj);
    notify_fun2 = CompileRun(
        "(function() { obj.foo = 'baz'; })");
  }
  Handle<Value> notify_fun3;
  {
    LocalContext context3(CcTest::isolate());
    context3->SetSecurityToken(foo);
    context3->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            obj);
    notify_fun3 = CompileRun(
        "(function() { obj.foo = 'bat'; })");
  }
  {
    LocalContext context4(CcTest::isolate());
    context4->SetSecurityToken(foo);
    context4->Global()->Set(
        String::NewFromUtf8(CcTest::isolate(), "observer"), observer);
    context4->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "fun1"),
                            notify_fun1);
    context4->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "fun2"),
                            notify_fun2);
    context4->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "fun3"),
                            notify_fun3);
    CompileRun("fun1(); fun2(); fun3(); Object.deliverChangeRecords(observer)");
  }
  CHECK_EQ(1, CompileRun("calls")->Int32Value());
  CHECK_EQ(3, CompileRun("count")->Int32Value());
}

TEST(EndOfMicrotaskDelivery) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun(
      "var obj = {};"
      "var count = 0;"
      "var observer = function(records) { count = records.length };"
      "Object.observe(obj, observer);"
      "obj.foo = 'bar';");
  CHECK_EQ(1, CompileRun("count")->Int32Value());
}

TEST(DeliveryOrdering) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun(
      "var obj1 = {};"
      "var obj2 = {};"
      "var ordering = [];"
      "function observer2() { ordering.push(2); };"
      "function observer1() { ordering.push(1); };"
      "function observer3() { ordering.push(3); };"
      "Object.observe(obj1, observer1);"
      "Object.observe(obj1, observer2);"
      "Object.observe(obj1, observer3);"
      "obj1.foo = 'bar';");
  CHECK_EQ(3, CompileRun("ordering.length")->Int32Value());
  CHECK_EQ(1, CompileRun("ordering[0]")->Int32Value());
  CHECK_EQ(2, CompileRun("ordering[1]")->Int32Value());
  CHECK_EQ(3, CompileRun("ordering[2]")->Int32Value());
  CompileRun(
      "ordering = [];"
      "Object.observe(obj2, observer3);"
      "Object.observe(obj2, observer2);"
      "Object.observe(obj2, observer1);"
      "obj2.foo = 'baz'");
  CHECK_EQ(3, CompileRun("ordering.length")->Int32Value());
  CHECK_EQ(1, CompileRun("ordering[0]")->Int32Value());
  CHECK_EQ(2, CompileRun("ordering[1]")->Int32Value());
  CHECK_EQ(3, CompileRun("ordering[2]")->Int32Value());
}

TEST(DeliveryOrderingReentrant) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun(
      "var obj = {};"
      "var reentered = false;"
      "var ordering = [];"
      "function observer1() { ordering.push(1); };"
      "function observer2() {"
      "  if (!reentered) {"
      "    obj.foo = 'baz';"
      "    reentered = true;"
      "  }"
      "  ordering.push(2);"
      "};"
      "function observer3() { ordering.push(3); };"
      "Object.observe(obj, observer1);"
      "Object.observe(obj, observer2);"
      "Object.observe(obj, observer3);"
      "obj.foo = 'bar';");
  CHECK_EQ(5, CompileRun("ordering.length")->Int32Value());
  CHECK_EQ(1, CompileRun("ordering[0]")->Int32Value());
  CHECK_EQ(2, CompileRun("ordering[1]")->Int32Value());
  CHECK_EQ(3, CompileRun("ordering[2]")->Int32Value());
  // Note that we re-deliver to observers 1 and 2, while observer3
  // already received the second record during the first round.
  CHECK_EQ(1, CompileRun("ordering[3]")->Int32Value());
  CHECK_EQ(2, CompileRun("ordering[1]")->Int32Value());
}

TEST(DeliveryOrderingDeliverChangeRecords) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun(
      "var obj = {};"
      "var ordering = [];"
      "function observer1() { ordering.push(1); if (!obj.b) obj.b = true };"
      "function observer2() { ordering.push(2); };"
      "Object.observe(obj, observer1);"
      "Object.observe(obj, observer2);"
      "obj.a = 1;"
      "Object.deliverChangeRecords(observer2);");
  CHECK_EQ(4, CompileRun("ordering.length")->Int32Value());
  // First, observer2 is called due to deliverChangeRecords
  CHECK_EQ(2, CompileRun("ordering[0]")->Int32Value());
  // Then, observer1 is called when the stack unwinds
  CHECK_EQ(1, CompileRun("ordering[1]")->Int32Value());
  // observer1's mutation causes both 1 and 2 to be reactivated,
  // with 1 having priority.
  CHECK_EQ(1, CompileRun("ordering[2]")->Int32Value());
  CHECK_EQ(2, CompileRun("ordering[3]")->Int32Value());
}

TEST(ObjectHashTableGrowth) {
  HandleScope scope(CcTest::isolate());
  // Initializing this context sets up initial hash tables.
  LocalContext context(CcTest::isolate());
  Handle<Value> obj = CompileRun("obj = {};");
  Handle<Value> observer = CompileRun(
      "var ran = false;"
      "(function() { ran = true })");
  {
    // As does initializing this context.
    LocalContext context2(CcTest::isolate());
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            obj);
    context2->Global()->Set(
        String::NewFromUtf8(CcTest::isolate(), "observer"), observer);
    CompileRun(
        "var objArr = [];"
        // 100 objects should be enough to make the hash table grow
        // (and thus relocate).
        "for (var i = 0; i < 100; ++i) {"
        "  objArr.push({});"
        "  Object.observe(objArr[objArr.length-1], function(){});"
        "}"
        "Object.observe(obj, observer);");
  }
  // obj is now marked "is_observed", but our map has moved.
  CompileRun("obj.foo = 'bar'");
  CHECK(CompileRun("ran")->BooleanValue());
}

struct RecordExpectation {
  Handle<Value> object;
  const char* type;
  const char* name;
  Handle<Value> old_value;
};

// TODO(adamk): Use this helper elsewhere in this file.
static void ExpectRecords(v8::Isolate* isolate,
                          Handle<Value> records,
                          const RecordExpectation expectations[],
                          int num) {
  CHECK(records->IsArray());
  Handle<Array> recordArray = records.As<Array>();
  CHECK_EQ(num, static_cast<int>(recordArray->Length()));
  for (int i = 0; i < num; ++i) {
    Handle<Value> record = recordArray->Get(i);
    CHECK(record->IsObject());
    Handle<Object> recordObj = record.As<Object>();
    CHECK(expectations[i].object->StrictEquals(
        recordObj->Get(String::NewFromUtf8(isolate, "object"))));
    CHECK(String::NewFromUtf8(isolate, expectations[i].type)->Equals(
        recordObj->Get(String::NewFromUtf8(isolate, "type"))));
    if (strcmp("splice", expectations[i].type) != 0) {
      CHECK(String::NewFromUtf8(isolate, expectations[i].name)->Equals(
          recordObj->Get(String::NewFromUtf8(isolate, "name"))));
      if (!expectations[i].old_value.IsEmpty()) {
        CHECK(expectations[i].old_value->Equals(
            recordObj->Get(String::NewFromUtf8(isolate, "oldValue"))));
      }
    }
  }
}

#define EXPECT_RECORDS(records, expectations)                \
  ExpectRecords(CcTest::isolate(), records, expectations, \
                ARRAY_SIZE(expectations))

TEST(APITestBasicMutation) {
  v8::Isolate* v8_isolate = CcTest::isolate();
  HandleScope scope(v8_isolate);
  LocalContext context(v8_isolate);
  Handle<Object> obj = Handle<Object>::Cast(CompileRun(
      "var records = [];"
      "var obj = {};"
      "function observer(r) { [].push.apply(records, r); };"
      "Object.observe(obj, observer);"
      "obj"));
  obj->Set(String::NewFromUtf8(v8_isolate, "foo"),
           Number::New(v8_isolate, 7));
  obj->Set(1, Number::New(v8_isolate, 2));
  // ForceSet should work just as well as Set
  obj->ForceSet(String::NewFromUtf8(v8_isolate, "foo"),
                Number::New(v8_isolate, 3));
  obj->ForceSet(Number::New(v8_isolate, 1), Number::New(v8_isolate, 4));
  // Setting an indexed element via the property setting method
  obj->Set(Number::New(v8_isolate, 1), Number::New(v8_isolate, 5));
  // Setting with a non-String, non-uint32 key
  obj->Set(Number::New(v8_isolate, 1.1),
           Number::New(v8_isolate, 6), DontDelete);
  obj->Delete(String::NewFromUtf8(v8_isolate, "foo"));
  obj->Delete(1);
  obj->ForceDelete(Number::New(v8_isolate, 1.1));

  // Force delivery
  // TODO(adamk): Should the above set methods trigger delivery themselves?
  CompileRun("void 0");
  CHECK_EQ(9, CompileRun("records.length")->Int32Value());
  const RecordExpectation expected_records[] = {
    { obj, "add", "foo", Handle<Value>() },
    { obj, "add", "1", Handle<Value>() },
    // Note: use 7 not 1 below, as the latter triggers a nifty VS10 compiler bug
    // where instead of 1.0, a garbage value would be passed into Number::New.
    { obj, "update", "foo", Number::New(v8_isolate, 7) },
    { obj, "update", "1", Number::New(v8_isolate, 2) },
    { obj, "update", "1", Number::New(v8_isolate, 4) },
    { obj, "add", "1.1", Handle<Value>() },
    { obj, "delete", "foo", Number::New(v8_isolate, 3) },
    { obj, "delete", "1", Number::New(v8_isolate, 5) },
    { obj, "delete", "1.1", Number::New(v8_isolate, 6) }
  };
  EXPECT_RECORDS(CompileRun("records"), expected_records);
}

TEST(HiddenPrototypeObservation) {
  v8::Isolate* v8_isolate = CcTest::isolate();
  HandleScope scope(v8_isolate);
  LocalContext context(v8_isolate);
  Handle<FunctionTemplate> tmpl = FunctionTemplate::New(v8_isolate);
  tmpl->SetHiddenPrototype(true);
  tmpl->InstanceTemplate()->Set(
      String::NewFromUtf8(v8_isolate, "foo"), Number::New(v8_isolate, 75));
  Handle<Object> proto = tmpl->GetFunction()->NewInstance();
  Handle<Object> obj = Object::New(v8_isolate);
  obj->SetPrototype(proto);
  context->Global()->Set(String::NewFromUtf8(v8_isolate, "obj"), obj);
  context->Global()->Set(String::NewFromUtf8(v8_isolate, "proto"),
                         proto);
  CompileRun(
      "var records;"
      "function observer(r) { records = r; };"
      "Object.observe(obj, observer);"
      "obj.foo = 41;"  // triggers a notification
      "proto.foo = 42;");  // does not trigger a notification
  const RecordExpectation expected_records[] = {
    { obj, "update", "foo", Number::New(v8_isolate, 75) }
  };
  EXPECT_RECORDS(CompileRun("records"), expected_records);
  obj->SetPrototype(Null(v8_isolate));
  CompileRun("obj.foo = 43");
  const RecordExpectation expected_records2[] = {
    { obj, "add", "foo", Handle<Value>() }
  };
  EXPECT_RECORDS(CompileRun("records"), expected_records2);
  obj->SetPrototype(proto);
  CompileRun(
      "Object.observe(proto, observer);"
      "proto.bar = 1;"
      "Object.unobserve(obj, observer);"
      "obj.foo = 44;");
  const RecordExpectation expected_records3[] = {
    { proto, "add", "bar", Handle<Value>() }
    // TODO(adamk): The below record should be emitted since proto is observed
    // and has been modified. Not clear if this happens in practice.
    // { proto, "update", "foo", Number::New(43) }
  };
  EXPECT_RECORDS(CompileRun("records"), expected_records3);
}

static int NumberOfElements(i::Handle<i::JSWeakMap> map) {
  return i::ObjectHashTable::cast(map->table())->NumberOfElements();
}

TEST(ObservationWeakMap) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun(
      "var obj = {};"
      "Object.observe(obj, function(){});"
      "Object.getNotifier(obj);"
      "obj = null;");
  i::Isolate* i_isolate = CcTest::i_isolate();
  i::Handle<i::JSObject> observation_state =
      i_isolate->factory()->observation_state();
  i::Handle<i::JSWeakMap> callbackInfoMap =
      i::Handle<i::JSWeakMap>::cast(i::Object::GetProperty(
          i_isolate, observation_state, "callbackInfoMap").ToHandleChecked());
  i::Handle<i::JSWeakMap> objectInfoMap =
      i::Handle<i::JSWeakMap>::cast(i::Object::GetProperty(
          i_isolate, observation_state, "objectInfoMap").ToHandleChecked());
  i::Handle<i::JSWeakMap> notifierObjectInfoMap =
      i::Handle<i::JSWeakMap>::cast(i::Object::GetProperty(
          i_isolate, observation_state, "notifierObjectInfoMap")
              .ToHandleChecked());
  CHECK_EQ(1, NumberOfElements(callbackInfoMap));
  CHECK_EQ(1, NumberOfElements(objectInfoMap));
  CHECK_EQ(1, NumberOfElements(notifierObjectInfoMap));
  i_isolate->heap()->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
  CHECK_EQ(0, NumberOfElements(callbackInfoMap));
  CHECK_EQ(0, NumberOfElements(objectInfoMap));
  CHECK_EQ(0, NumberOfElements(notifierObjectInfoMap));
}

static int TestObserveSecurity(Handle<Context> observer_context,
                               Handle<Context> object_context,
                               Handle<Context> mutation_context) {
  Context::Scope observer_scope(observer_context);
  CompileRun("var records = null;"
             "var observer = function(r) { records = r };");
  Handle<Value> observer = CompileRun("observer");
  {
    Context::Scope object_scope(object_context);
    object_context->Global()->Set(
        String::NewFromUtf8(CcTest::isolate(), "observer"), observer);
    CompileRun("var obj = {};"
               "obj.length = 0;"
               "Object.observe(obj, observer,"
                   "['add', 'update', 'delete','reconfigure','splice']"
               ");");
    Handle<Value> obj = CompileRun("obj");
    {
      Context::Scope mutation_scope(mutation_context);
      mutation_context->Global()->Set(
          String::NewFromUtf8(CcTest::isolate(), "obj"), obj);
      CompileRun("obj.foo = 'bar';"
                 "obj.foo = 'baz';"
                 "delete obj.foo;"
                 "Object.defineProperty(obj, 'bar', {value: 'bot'});"
                 "Array.prototype.push.call(obj, 1, 2, 3);"
                 "Array.prototype.splice.call(obj, 1, 2, 2, 4);"
                 "Array.prototype.pop.call(obj);"
                 "Array.prototype.shift.call(obj);");
    }
  }
  return CompileRun("records ? records.length : 0")->Int32Value();
}

TEST(ObserverSecurityAAA) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA = Context::New(isolate);
  CHECK_EQ(8, TestObserveSecurity(contextA, contextA, contextA));
}

TEST(ObserverSecurityA1A2A3) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);

  v8::Local<Context> contextA1 = Context::New(isolate);
  v8::Local<Context> contextA2 = Context::New(isolate);
  v8::Local<Context> contextA3 = Context::New(isolate);

  Local<Value> foo = v8_str("foo");
  contextA1->SetSecurityToken(foo);
  contextA2->SetSecurityToken(foo);
  contextA3->SetSecurityToken(foo);

  CHECK_EQ(8, TestObserveSecurity(contextA1, contextA2, contextA3));
}

TEST(ObserverSecurityAAB) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);
  CHECK_EQ(0, TestObserveSecurity(contextA, contextA, contextB));
}

TEST(ObserverSecurityA1A2B) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);

  v8::Local<Context> contextA1 = Context::New(isolate);
  v8::Local<Context> contextA2 = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);

  Local<Value> foo = v8_str("foo");
  contextA1->SetSecurityToken(foo);
  contextA2->SetSecurityToken(foo);

  CHECK_EQ(0, TestObserveSecurity(contextA1, contextA2, contextB));
}

TEST(ObserverSecurityABA) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);
  CHECK_EQ(0, TestObserveSecurity(contextA, contextB, contextA));
}

TEST(ObserverSecurityA1BA2) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA1 = Context::New(isolate);
  v8::Local<Context> contextA2 = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);

  Local<Value> foo = v8_str("foo");
  contextA1->SetSecurityToken(foo);
  contextA2->SetSecurityToken(foo);

  CHECK_EQ(0, TestObserveSecurity(contextA1, contextB, contextA2));
}

TEST(ObserverSecurityBAA) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);
  CHECK_EQ(0, TestObserveSecurity(contextB, contextA, contextA));
}

TEST(ObserverSecurityBA1A2) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA1 = Context::New(isolate);
  v8::Local<Context> contextA2 = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);

  Local<Value> foo = v8_str("foo");
  contextA1->SetSecurityToken(foo);
  contextA2->SetSecurityToken(foo);

  CHECK_EQ(0, TestObserveSecurity(contextB, contextA1, contextA2));
}

TEST(ObserverSecurityNotify) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<Context> contextA = Context::New(isolate);
  v8::Local<Context> contextB = Context::New(isolate);

  Context::Scope scopeA(contextA);
  CompileRun("var obj = {};"
             "var recordsA = null;"
             "var observerA = function(r) { recordsA = r };"
             "Object.observe(obj, observerA);");
  Handle<Value> obj = CompileRun("obj");

  {
    Context::Scope scopeB(contextB);
    contextB->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"), obj);
    CompileRun("var recordsB = null;"
               "var observerB = function(r) { recordsB = r };"
               "Object.observe(obj, observerB);");
  }

  CompileRun("var notifier = Object.getNotifier(obj);"
             "notifier.notify({ type: 'update' });");
  CHECK_EQ(1, CompileRun("recordsA ? recordsA.length : 0")->Int32Value());

  {
    Context::Scope scopeB(contextB);
    CHECK_EQ(0, CompileRun("recordsB ? recordsB.length : 0")->Int32Value());
  }
}

TEST(HiddenPropertiesLeakage) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun("var obj = {};"
             "var records = null;"
             "var observer = function(r) { records = r };"
             "Object.observe(obj, observer);");
  Handle<Value> obj =
      context->Global()->Get(String::NewFromUtf8(CcTest::isolate(), "obj"));
  Handle<Object>::Cast(obj)
      ->SetHiddenValue(String::NewFromUtf8(CcTest::isolate(), "foo"),
                       Null(CcTest::isolate()));
  CompileRun("");  // trigger delivery
  CHECK(CompileRun("records")->IsNull());
}

TEST(GetNotifierFromOtherContext) {
  HandleScope scope(CcTest::isolate());
  LocalContext context(CcTest::isolate());
  CompileRun("var obj = {};");
  Handle<Value> instance = CompileRun("obj");
  {
    LocalContext context2(CcTest::isolate());
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            instance);
    CHECK(CompileRun("Object.getNotifier(obj)")->IsNull());
  }
}

TEST(GetNotifierFromOtherOrigin) {
  HandleScope scope(CcTest::isolate());
  Handle<Value> foo = String::NewFromUtf8(CcTest::isolate(), "foo");
  Handle<Value> bar = String::NewFromUtf8(CcTest::isolate(), "bar");
  LocalContext context(CcTest::isolate());
  context->SetSecurityToken(foo);
  CompileRun("var obj = {};");
  Handle<Value> instance = CompileRun("obj");
  {
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(bar);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            instance);
    CHECK(CompileRun("Object.getNotifier(obj)")->IsNull());
  }
}

TEST(GetNotifierFromSameOrigin) {
  HandleScope scope(CcTest::isolate());
  Handle<Value> foo = String::NewFromUtf8(CcTest::isolate(), "foo");
  LocalContext context(CcTest::isolate());
  context->SetSecurityToken(foo);
  CompileRun("var obj = {};");
  Handle<Value> instance = CompileRun("obj");
  {
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(foo);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            instance);
    CHECK(CompileRun("Object.getNotifier(obj)")->IsObject());
  }
}

static int GetGlobalObjectsCount() {
  int count = 0;
  i::HeapIterator it(CcTest::heap());
  for (i::HeapObject* object = it.next(); object != NULL; object = it.next())
    if (object->IsJSGlobalObject()) count++;
  return count;
}

static void CheckSurvivingGlobalObjectsCount(int expected) {
  // We need to collect all garbage twice to be sure that everything
  // has been collected.  This is because inline caches are cleared in
  // the first garbage collection but some of the maps have already
  // been marked at that point.  Therefore some of the maps are not
  // collected until the second garbage collection.
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
  CcTest::heap()->CollectAllGarbage(i::Heap::kMakeHeapIterableMask);
  int count = GetGlobalObjectsCount();
#ifdef DEBUG
  if (count != expected) CcTest::heap()->TracePathToGlobal();
#endif
  CHECK_EQ(expected, count);
}

TEST(DontLeakContextOnObserve) {
  HandleScope scope(CcTest::isolate());
  Handle<Value> foo = String::NewFromUtf8(CcTest::isolate(), "foo");
  LocalContext context(CcTest::isolate());
  context->SetSecurityToken(foo);
  CompileRun("var obj = {};");
  Handle<Value> object = CompileRun("obj");
  {
    HandleScope scope(CcTest::isolate());
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(foo);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            object);
    CompileRun("function observer() {};"
               "Object.observe(obj, observer, ['foo', 'bar', 'baz']);"
               "Object.unobserve(obj, observer);");
  }

  v8::V8::ContextDisposedNotification();
  CheckSurvivingGlobalObjectsCount(1);
}

TEST(DontLeakContextOnGetNotifier) {
  HandleScope scope(CcTest::isolate());
  Handle<Value> foo = String::NewFromUtf8(CcTest::isolate(), "foo");
  LocalContext context(CcTest::isolate());
  context->SetSecurityToken(foo);
  CompileRun("var obj = {};");
  Handle<Value> object = CompileRun("obj");
  {
    HandleScope scope(CcTest::isolate());
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(foo);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            object);
    CompileRun("Object.getNotifier(obj);");
  }

  v8::V8::ContextDisposedNotification();
  CheckSurvivingGlobalObjectsCount(1);
}

TEST(DontLeakContextOnNotifierPerformChange) {
  HandleScope scope(CcTest::isolate());
  Handle<Value> foo = String::NewFromUtf8(CcTest::isolate(), "foo");
  LocalContext context(CcTest::isolate());
  context->SetSecurityToken(foo);
  CompileRun("var obj = {};");
  Handle<Value> object = CompileRun("obj");
  Handle<Value> notifier = CompileRun("Object.getNotifier(obj)");
  {
    HandleScope scope(CcTest::isolate());
    LocalContext context2(CcTest::isolate());
    context2->SetSecurityToken(foo);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "obj"),
                            object);
    context2->Global()->Set(String::NewFromUtf8(CcTest::isolate(), "notifier"),
                            notifier);
    CompileRun("var obj2 = {};"
               "var notifier2 = Object.getNotifier(obj2);"
               "notifier2.performChange.call("
                   "notifier, 'foo', function(){})");
  }

  v8::V8::ContextDisposedNotification();
  CheckSurvivingGlobalObjectsCount(1);
}


text:
package me.pheynix.pictures.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.pheynix.pictures.R;
import me.pheynix.pictures.other.Pictures;
import me.pheynix.pictures.third.DiskLruCache;
import me.pheynix.pictures.utils.AndroidUtil;

/**
 * adapter
 * Created by pheynix on 4/5/16.
 */
public class PictureAdapter extends RecyclerView.Adapter<PictureAdapter.PictureHolder> {
    private LruCache<String, Bitmap> lruCache = null;
    private HashSet<PictureLoader> loaderSet = new HashSet<>();
    private boolean doLoad = true;
    private DiskLruCache diskLruCache = null;

    public PictureAdapter() {
        lruCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
            @Override protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };

        try {
            diskLruCache = DiskLruCache.open(AndroidUtil.getCacheDir("bitmap"), AndroidUtil.getAppVersion(), 1, 10 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override public PictureHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture, parent, false);
        return new PictureHolder(view);
    }

    @Override public void onBindViewHolder(PictureHolder holder, int position) {
        String url = Pictures.pictures[position];
        String key = AndroidUtil.getKey(url);
        holder.ivPicture.setTag(key);//holder是循环使用的,所以一个holder可能对应多个下载任务,使用tag可以保证显示最后创建的下载任务的内容

        Bitmap bitmap = lruCache.get(key);
        if (bitmap != null) {
            holder.ivPicture.setImageBitmap(bitmap);
        } else {
            if (doLoad) {
                PictureLoader loader = new PictureLoader(holder.ivPicture);
                loaderSet.add(loader);
                loader.execute(url);
            } else {
                holder.ivPicture.setImageResource(R.drawable.ic_placeholder_error);
            }
        }
    }

    @Override public int getItemCount() {
        return Pictures.pictures.length;
    }

    public void cancelAllDownloadTask() {
        if (loaderSet != null) {
            for (PictureLoader downloader : loaderSet) {
                downloader.cancel(false);
            }
            loaderSet.clear();
        }
    }

    public HashSet<PictureLoader> getLoaderSet() {
        return loaderSet;
    }

    public boolean isDoLoad() {
        return doLoad;
    }

    public void setDoLoad(boolean doLoad) {
        this.doLoad = doLoad;
    }

    class PictureHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_picture) ImageView ivPicture;

        public PictureHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) ivPicture.getLayoutParams();
            layoutParams.height = layoutParams.width = AndroidUtil.getScreenWidthInPixel() / 3;
            ivPicture.setLayoutParams(layoutParams);
        }
    }

    /**
     * 先看DiskLruCache有没有缓存,如果没有就去网络加载回来
     * 加载回来之后先保存在DiskLruCache中,然后显示并且让LruCache持有其内存引用
     */
    class PictureLoader extends AsyncTask<String, Void, Bitmap> {
        WeakReference<ImageView> weakReference;
        String url;
        String key;

        public PictureLoader(ImageView imageView) {
            weakReference = new WeakReference<ImageView>(imageView);
        }

        @Override protected void onPreExecute() {
            super.onPreExecute();
            ImageView imageView = weakReference.get();
            if (imageView != null) {
                imageView.setImageResource(R.drawable.ic_placeholder_loading);
            }
        }

        /**
         * 先查看本地DiskLruCache是否有缓存,如果没有再去网络加载
         */
        @Override protected Bitmap doInBackground(String... params) {
            url = params[0];
            key = AndroidUtil.getKey(url);

            DiskLruCache.Snapshot snapshot = null;
            FileInputStream fileInputStream = null;
            FileDescriptor fileDescriptor = null;
            Bitmap bitmap = null;

            try {
                snapshot = diskLruCache.get(key);

                if (snapshot == null) {
                    performDownload(url, diskLruCache, key);
                    snapshot = diskLruCache.get(key);
                }

                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(0);
                    fileDescriptor = fileInputStream.getFD();
                }

                if (fileDescriptor != null) {
                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                }

                if (bitmap != null && lruCache.get(key) == null) {
                    lruCache.put(key, bitmap);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }

        @Override protected void onPostExecute(Bitmap bitmap) {
            ImageView imageView = weakReference.get();
            if (imageView != null && key.equals(imageView.getTag())) {
                imageView.setImageBitmap(bitmap);
            }
        }

        /**
         * 从网络下载图片并且放到DiskLruCache中
         */
        private void performDownload(String pictureUrl, DiskLruCache diskLruCache, String key) {
            HttpURLConnection httpURLConnection = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            DiskLruCache.Editor editor = null;

            try {
                editor = diskLruCache.edit(key);
                outputStream = editor.newOutputStream(0);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (outputStream == null) {
                return;
            }

            try {
                URL url = new URL(pictureUrl);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(15 * 1000);
                httpURLConnection.setReadTimeout(15 * 100);

                inputStream = httpURLConnection.getInputStream();

                int buffer;
                while ((buffer = inputStream.read()) != -1) {
                    outputStream.write(buffer);
                }

                try {
                    editor.commit();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return ;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            try {
                editor.abort();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.callimachusproject.script;

import info.aduna.io.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import junit.framework.TestCase;

import org.apache.http.HttpResponse;
import org.callimachusproject.annotations.script;
import org.callimachusproject.fluid.FluidBuilder;
import org.callimachusproject.fluid.FluidFactory;
import org.callimachusproject.repository.CalliRepository;
import org.openrdf.annotations.Iri;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.Repository;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.config.ObjectRepositoryConfig;
import org.openrdf.repository.object.config.ObjectRepositoryFactory;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.Sail;
import org.openrdf.sail.memory.MemoryStore;

public class ConcurrentResponseTest extends TestCase {
	private static final String THING = "http://example.com/thing";

	public static final String REDIRECT_TYPE = "http://example.com/types/Redirect";

	private File dataDir;
	private CalliRepository repository;
	private ObjectConnection con;

	@Iri(REDIRECT_TYPE)
	public interface Redirect {

		@script("return {status:302,message:'Alternate',headers:{'location':'target','cache-control':[],'content-type':'text/plain'},body:['target']};")
		public Object redirect();
	}

	public void setUp() throws Exception {
		ObjectRepositoryConfig config = new ObjectRepositoryConfig();
		config.addConcept(Redirect.class);
		dataDir = FileUtil.createTempDir("response");
		if (config.getBlobStore() == null) {
			config.setBlobStore(dataDir.toURI().toString());
		}
		repository = createRepository(dataDir, config);
		initDataset(repository);
		con = repository.getConnection();
	}

	public void testJsonResponse() throws Exception {
		Redirect thing = con.getObject(Redirect.class, THING);
		FluidBuilder fb = FluidFactory.getInstance().builder(con);
		String uri = thing.toString();
		HttpResponse response = fb.consume(thing.redirect(), uri, Object.class, "message/x-response").asHttpResponse();
		assertEquals(302, response.getStatusLine().getStatusCode());
		assertEquals("Alternate", response.getStatusLine().getReasonPhrase());
		assertEquals(1, response.getHeaders("Location").length);
		assertEquals("target", response.getFirstHeader("Location").getValue());
		assertEquals(0, response.getHeaders("Cache-Control").length);
		assertEquals(1, response.getHeaders("Content-Type").length);
		assertEquals("text/plain", response.getFirstHeader("Content-Type").getValue());
	}

	public void testResponseConcurrent() throws Throwable {
		int n = Runtime.getRuntime().availableProcessors() * 4;
		final CountDownLatch up = new CountDownLatch(1);
		final CountDownLatch down = new CountDownLatch(n);
		final List<Throwable> errors = new ArrayList<Throwable>(n);
		for (int i=0; i<n; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						up.await();
						for (int i=0; i<100; i++) {
							testJsonResponse();
						}
					} catch (Throwable e) {
						e.printStackTrace();
						synchronized (errors) {
							errors.add(e);
						}
					} finally {
						down.countDown();
					}
				}
			}).start();
		}
		up.countDown();
		down.await();
		synchronized (errors) {
			if (!errors.isEmpty()) {
				throw errors.get(0);
			}
		}
	}

	public void tearDown() throws Exception {
		con.close();
		repository.shutDown();
		FileUtil.deltree(dataDir);
	}

	private CalliRepository createRepository(File dataDir, ObjectRepositoryConfig config) throws Exception {
		Sail sail = new MemoryStore();
		Repository delegate = new SailRepository(sail);
		delegate.initialize();
		ObjectRepositoryFactory factory = new ObjectRepositoryFactory();
		Repository repo = factory.createRepository(config, delegate);
		return new CalliRepository(repo, dataDir);
	}

	private void initDataset(CalliRepository repository) throws Exception {
		ObjectConnection con = repository.getConnection();
		try {
			ValueFactory vf = con.getValueFactory();
			URI thing = vf.createURI(THING);
			con.add(thing, RDF.TYPE, vf.createURI(REDIRECT_TYPE));
		} finally {
			con.close();
		}
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cercospora rhododendri Marchal & Verpl.

### Remarks
null


text:
from __future__ import absolute_import, print_function, unicode_literals

from django.conf.urls import url

from .feeds import LatestEntriesFeed, TagFeed
from .settings import get_setting
from .views import (
    AuthorEntriesView, CategoryEntriesView, PostArchiveView, PostDetailView, PostListView,
    TaggedListView,
)

def get_urls():
    urls = get_setting('PERMALINK_URLS')
    details = []
    for urlconf in urls.values():
        details.append(
            url(urlconf, PostDetailView.as_view(), name='post-detail'),
        )
    return details

detail_urls = get_urls()

urlpatterns = [
    url(r'^$',
        PostListView.as_view(), name='posts-latest'),
    url(r'^feed/$',
        LatestEntriesFeed(), name='posts-latest-feed'),
    url(r'^(?P<year>\d{4})/$',
        PostArchiveView.as_view(), name='posts-archive'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$',
        PostArchiveView.as_view(), name='posts-archive'),
    url(r'^author/(?P<username>[\w\.@+-]+)/$',
        AuthorEntriesView.as_view(), name='posts-author'),
    url(r'^category/(?P<category>[\w\.@+-]+)/$',
        CategoryEntriesView.as_view(), name='posts-category'),
    url(r'^tag/(?P<tag>[-\w]+)/$',
        TaggedListView.as_view(), name='posts-tagged'),
    url(r'^tag/(?P<tag>[-\w]+)/feed/$',
        TagFeed(), name='posts-tagged-feed'),
] + detail_urls


text:
#ifndef __SPI_FLASH_H__
#define __SPI_FLASH_H__

#ifdef __cplusplus
extern "C" {
#endif

/** \defgroup Driver_APIs Driver APIs
  * @brief Driver APIs
  */

/** @addtogroup Driver_APIs
  * @{
  */

/** \defgroup SPI_Driver_APIs SPI Driver APIs
  * @brief SPI Flash APIs
  */

/** @addtogroup SPI_Driver_APIs
  * @{
  */

typedef enum {
    SPI_FLASH_RESULT_OK,        /**< SPI Flash operating OK */
    SPI_FLASH_RESULT_ERR,       /**< SPI Flash operating fail */
    SPI_FLASH_RESULT_TIMEOUT    /**< SPI Flash operating time out */
} SpiFlashOpResult;

#define SPI_FLASH_SEC_SIZE  4096    /**< SPI Flash sector size */

/**
  * @brief  Get ID info of SPI Flash.
  *
  * @param  null
  *
  * @return SPI Flash ID
  */
uint32 spi_flash_get_id(void);

/**
  * @brief  Read state register of SPI Flash.
  *
  * @param  uint32 *status : the read value (pointer) of state register.
  *
  * @return SpiFlashOpResult
  */
SpiFlashOpResult spi_flash_read_status(uint32 *status);

/**
  * @brief  Write state register of SPI Flash.
  *
  * @param  uint32 status_value : Write state register value.
  *
  * @return SpiFlashOpResult
  */
SpiFlashOpResult spi_flash_write_status(uint32 status_value);

/**
  * @brief  Erase the Flash sector.
  *
  * @param  uint16 sec : Sector number, the count starts at sector 0, 4KB per sector.
  *
  * @return SpiFlashOpResult
  */
SpiFlashOpResult spi_flash_erase_sector(uint16 sec);

/**
  * @brief  Write data to Flash.
  *
  * @param  uint32 des_addr  : destination address in Flash.
  * @param  uint32 *src_addr : source address of the data.
  * @param  uint32 size      : length of data
  *
  * @return SpiFlashOpResult
  */
SpiFlashOpResult spi_flash_write(uint32 des_addr, uint32 *src_addr, uint32 size);

/**
  * @brief  Read data from Flash.
  *
  * @param  uint32 src_addr  : source address of the data.
  * @param  uint32 *des_addr : destination address in Flash.
  * @param  uint32 size      : length of data
  *
  * @return SpiFlashOpResult
  */
SpiFlashOpResult spi_flash_read(uint32 src_addr, uint32 *des_addr, uint32 size);

/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif


text:
package com.taylak.wallpaper.ztmp;

import java.io.InputStream;
import java.lang.ref.WeakReference;

import com.taylak.wallpaper.helper.ISenkronSonuc;
import com.taylak.wallpaper.helper.ImgTool;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.ImageView;

public class BitmapWorkerTask2 extends AsyncTask<InputStream, Void, Bitmap> {

	private final WeakReference<ImageView> imageViewReference;
	private InputStream data;
	Context ctx;

	public int imgW = 360;
	public int imgH = 360;
	public ISenkronSonuc sonuc;

	public BitmapWorkerTask2(Context _ctx, ImageView imageView) {
		// Use a WeakReference to ensure the ImageView can be garbage collected
		imageViewReference = new WeakReference<ImageView>(imageView);
		this.ctx = _ctx;
	}

	@Override
	protected Bitmap doInBackground(InputStream... params) {
		data = params[0];

		return ImgTool.decodeSampledBitmap(data, imgW, imgH);
	}

	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}

		if (imageViewReference != null && bitmap != null) {
			final ImageView imageView = imageViewReference.get();
			final BitmapWorkerTask2 bitmapWorkerTask = getBitmapWorkerTask(imageView);
			if (this == bitmapWorkerTask && imageView != null) {
				imageView.setImageBitmap(bitmap);
			}
		}

		sonuc.isBitti(bitmap);

	}

	private static BitmapWorkerTask2 getBitmapWorkerTask(ImageView imageView) {
		if (imageView != null) {
			final Drawable drawable = imageView.getDrawable();
			if (drawable instanceof AsyncDrawable) {
				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
				return asyncDrawable.getBitmapWorkerTask();
			}
		}
		return null;
	}

	public static boolean cancelPotentialWork(InputStream data,
			ImageView imageView) {
		final BitmapWorkerTask2 bitmapWorkerTask = getBitmapWorkerTask(imageView);

		if (bitmapWorkerTask != null) {
			final InputStream bitmapData = bitmapWorkerTask.data;
			// If bitmapData is not yet set or it differs from the new data
			if (bitmapData == null || bitmapData != data) {
				// Cancel previous task
				bitmapWorkerTask.cancel(true);
			} else {
				// The same work is already in progress
				return false;
			}
		}
		// No task associated with the ImageView, or an existing task was
		// cancelled
		return true;
	}

	static class AsyncDrawable extends BitmapDrawable {

		private final WeakReference<BitmapWorkerTask2> bitmapWorkerTaskReference;

		public AsyncDrawable(Resources res, InputStream _is,
				BitmapWorkerTask2 bitmapWorkerTask) {
			super(res,_is);
			bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask2>(
					bitmapWorkerTask);
		}

		public BitmapWorkerTask2 getBitmapWorkerTask() {
			return bitmapWorkerTaskReference.get();
		}
	}

}


text:
#![deny(warnings)]

extern crate coreutils;
extern crate extra;

use std::cell::Cell; // Provide mutable fields in immutable structs
use std::env;
use std::error::Error;
use std::fs;
use std::io::{self, BufReader, Read, Stderr, StdoutLock, Write};
use std::process::exit;
use extra::option::OptionalExt;
use coreutils::ArgParser;

const MAN_PAGE: &'static str = /* @MANSTART{cat} */ r#"NAME
    cat - concatenate files and print on the standard output

SYNOPSIS
    cat [-h | --help] [-A | --show-all] [-b | --number-nonblank] [-e] [-E | --show-ends]
        [-n | --number] [-s | --squeeze-blank] [-t] [-T] FILES...

DESCRIPTION
    Concatenates all files to the standard output.

    If no file is given, or if FILE is '-', read from standard input.

OPTIONS
    -A
    --show-all
        equivalent to -vET

    -b
    --number-nonblank
        number nonempty output lines, overriding -n

    -e
        equivalent to -vE

    -E
    --show-ends
        display $ at the end of each line

    -n
    --number
        number all output lines

    -s
    --squeeze-blank
        supress repeated empty output lines

    -t
        equivalent to -vT

    -T
    --show_tabs
        display TAB characters as ^I

    -v
    --show-nonprinting
        use caret (^) and M- notation, except for LFD and TAB.

    -h
    --help
        display this help and exit

AUTHOR
    Written by Michael Murphy.
"#; /* @MANEND */

struct Program {
    exit_status:      Cell<i32>,
    number:           bool,
    number_nonblank:  bool,
    show_ends:        bool,
    show_tabs:        bool,
    show_nonprinting: bool,
    squeeze_blank:    bool,
    paths:            Vec<String>,
}

impl Program {
    /// Initialize the program's arguments and flags.
    fn initialize(stdout: &mut StdoutLock, stderr: &mut Stderr) -> Program {
        let mut parser = ArgParser::new(10).
            add_flag(&["A", "show-all"]). //vET
            add_flag(&["b", "number-nonblank"]).
            add_flag(&["e"]). //vE
            add_flag(&["E", "show-ends"]).
            add_flag(&["n", "number"]).
            add_flag(&["s", "squeeze-blank"]).
            add_flag(&["t"]). //vT
            add_flag(&["T", "show-tabs"]).
            add_flag(&["v", "show-nonprinting"]).
            add_flag(&["h", "help"]);
        parser.parse(env::args());

        let mut cat = Program {
            exit_status:      Cell::new(0i32),
            number:           false,
            number_nonblank:  false,
            show_ends:        false,
            show_tabs:        false,
            show_nonprinting: false,
            squeeze_blank:    false,
            paths:            Vec::with_capacity(parser.args.len()),
        };

        if parser.found("help") {
            stdout.write(MAN_PAGE.as_bytes()).try(stderr);
            stdout.flush().try(stderr);
            exit(0);
        }

        if parser.found("show-all") {
            cat.show_nonprinting = true;
            cat.show_ends = true;
            cat.show_tabs = true;
        }

        if parser.found("number") {
            cat.number = true;
            cat.number_nonblank = false;
        }

        if parser.found("number-nonblank") {
            cat.number_nonblank = true;
            cat.number = false;
        }

        if parser.found("show-ends") || parser.found(&'e') {
            cat.show_ends = true;
        }

        if parser.found("squeeze-blank") {
            cat.squeeze_blank = true;
        }

        if parser.found("show-tabs") || parser.found(&'t') {
            cat.show_tabs = true;
        }

        if parser.found("show-nonprinting") || parser.found(&'e') || parser.found(&'t') {
            cat.show_nonprinting = true;
        }

        if !parser.args.is_empty() {
            cat.paths = parser.args;
        }
        cat
    }

    /// Execute the parameters given to the program.
    fn and_execute(&self, stdout: &mut StdoutLock, stderr: &mut Stderr) -> i32 {
        let stdin = io::stdin();
        let line_count = &mut 0usize;
        let flags_enabled = self.number || self.number_nonblank || self.show_ends || self.show_tabs ||
                            self.squeeze_blank || self.show_nonprinting;

        if self.paths.is_empty() && flags_enabled {
            self.cat(&mut stdin.lock(), line_count, stdout, stderr);
        } else if self.paths.is_empty() {
            io::copy(&mut stdin.lock(), stdout).try(stderr);
        } else {
            for path in &self.paths {
                if flags_enabled && path == "-" {
                    self.cat(&mut stdin.lock(), line_count, stdout, stderr);
                } else if path == "-" {
                    // Copy the standard input directly to the standard output.
                    io::copy(&mut stdin.lock(), stdout).try(stderr);
                } else if fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
                    stderr.write(path.as_bytes()).try(stderr);
                    stderr.write(b": Is a directory\n").try(stderr);
                    stderr.flush().try(stderr);
                    self.exit_status.set(1i32);
                } else if flags_enabled {
                    fs::File::open(&path)
                        // Open the file and copy the file's contents to standard output based input arguments.
                        .map(|file| self.cat(BufReader::new(file), line_count, stdout, stderr))
                        // If an error occurred, print the error and set the exit status.
                        .unwrap_or_else(|message| {
                            stderr.write(path.as_bytes()).try(stderr);
                            stderr.write(b": ").try(stderr);
                            stderr.write(message.description().as_bytes()).try(stderr);
                            stderr.write(b"\n").try(stderr);
                            stderr.flush().try(stderr);
                            self.exit_status.set(1i32);
                        });
                } else {
                    // Open a file and copy the contents directly to standard output.
                    fs::File::open(&path).map(|ref mut file| { io::copy(file, stdout).try(stderr); })
                        // If an error occurs, print the error and set the exit status.
                        .unwrap_or_else(|message| {
                            stderr.write(path.as_bytes()).try(stderr);
                            stderr.write(b": ").try(stderr);
                            stderr.write(message.description().as_bytes()).try(stderr);
                            stderr.write(b"\n").try(stderr);
                            stderr.flush().try(stderr);
                            self.exit_status.set(1i32);
                        });
                }
            }
        }
        self.exit_status.get()
    }

    /// Cats either a file or stdin based on the flag arguments given to the program.
    fn cat<F: Read>(&self, file: F, line_count: &mut usize, stdout: &mut StdoutLock, stderr: &mut Stderr) {
        let mut character_count = 0;
        let mut last_line_was_blank = false;

        for byte in file.bytes().map(|x| x.unwrap()) {
            if (self.number && character_count == 0) || (character_count == 0 && self.number_nonblank && byte != b'\n') {
                stdout.write(b"     ").try(stderr);
                stdout.write(line_count.to_string().as_bytes()).try(stderr);
                stdout.write(b"  ").try(stderr);
                *line_count += 1;
            }
            match byte {
                0...8 | 11...31 => if self.show_nonprinting {
                    push_caret(stdout, stderr, byte+64);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                },
                9 => {
                    if self.show_tabs {
                        push_caret(stdout, stderr, b'I');
                    } else {
                        stdout.write(&[byte]).try(stderr);
                    }
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                }
                10 => {
                    if character_count == 0 {
                        if self.squeeze_blank && last_line_was_blank {
                            continue
                        } else if !last_line_was_blank {
                            last_line_was_blank = true;
                        }
                    } else {
                        last_line_was_blank = false;
                        character_count = 0;
                    }
                    if self.show_ends {
                        stdout.write(b"$\n").try(stderr);
                    } else {
                        stdout.write(b"\n").try(stderr);
                    }
                    stdout.flush().try(stderr);
                },
                32...126 => {
                    stdout.write(&[byte]).try(stderr);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                },
                127 => if self.show_nonprinting {
                    push_caret(stdout, stderr, b'?');
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                },
                128...159 => if self.show_nonprinting {
                    stdout.write(b"M-^").try(stderr);
                    stdout.write(&[byte-64]).try(stderr);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                } else {
                    stdout.write(&[byte]).try(stderr);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                },
                _ => if self.show_nonprinting {
                    stdout.write(b"M-").try(stderr);
                    stdout.write(&[byte-128]).try(stderr);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                } else {
                    stdout.write(&[byte]).try(stderr);
                    count_character(&mut character_count, &self.number, &self.number_nonblank);
                },
            }
        }
    }
}
/// Increase the character count by one if number printing is enabled.
fn count_character(character_count: &mut usize, number: &bool, number_nonblank: &bool) {
    if *number || *number_nonblank {
        *character_count += 1;
    }
}

/// Print a caret notation to stdout.
fn push_caret(stdout: &mut StdoutLock, stderr: &mut Stderr, notation: u8) {
    stdout.write(&[b'^']).try(stderr);
    stdout.write(&[notation]).try(stderr);
}

fn main() {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let mut stderr = io::stderr();
    exit(Program::initialize(&mut stdout, &mut stderr).and_execute(&mut stdout, &mut stderr));
}


text:
module RuboCop
  module Cop
    module Rails
      # Looks for enums written with array syntax.
      #
      # When using array syntax, adding an element in a
      # position other than the last causes all previous
      # definitions to shift. Explicitly specifying the
      # value for each key prevents this from happening.
      #
      # @example
      #   # bad
      #   enum status: [:active, :archived]
      #
      #   # good
      #   enum status: { active: 0, archived: 1 }
      #
      class EnumHash < Base
        extend AutoCorrector

        MSG = 'Enum defined as an array found in `%<enum>s` enum declaration. Use hash syntax instead.'
        RESTRICT_ON_SEND = %i[enum].freeze

        def_node_matcher :enum?, <<~PATTERN
          (send nil? :enum (hash $...))
        PATTERN

        def_node_matcher :array_pair?, <<~PATTERN
          (pair $_ $array)
        PATTERN

        def on_send(node)
          enum?(node) do |pairs|
            pairs.each do |pair|
              key, array = array_pair?(pair)
              next unless key

              add_offense(array, message: format(MSG, enum: enum_name(key))) do |corrector|
                hash = array.children.each_with_index.map do |elem, index|
                  "#{source(elem)} => #{index}"
                end.join(', ')

                corrector.replace(array.loc.expression, "{#{hash}}")
              end
            end
          end
        end

        private

        def enum_name(key)
          case key.type
          when :sym, :str
            key.value
          else
            key.source
          end
        end

        def source(elem)
          case elem.type
          when :str
            elem.value.dump
          when :sym
            elem.value.inspect
          else
            elem.source
          end
        end
      end
    end
  end
end


text:
/* eslint-disable no-console, no-process-exit */

import 'colors';
import portfinder from 'portfinder';
import { exec } from 'child-process-promise';
import ip from 'ip';

portfinder.basePort = 4000;

const SIGINT = 'SIGINT';
let processMap = {};

function output(prefix, message) {
  let formattedMessage = message.toString().trim().split('\n')
    .reduce((acc, line) => `${acc}${ acc !== '' ? '\n' : '' }${prefix} ${line}`, '');

  console.log(formattedMessage);
}

function listen({stdout, stderr}, name) {
  stdout.on('data', data => output(`[${name}] `.grey, data));
  stderr.on('data', data => output(`[${name}] `.grey, data));
}

function shutdown() {
  Object.values(processMap).forEach(process => process.kill(SIGINT));
}

function catchExec(name, err) {
  if (err.killed) {
    console.log('Shutdown: '.cyan + name.green);
    shutdown();
    return false;
  }

  console.log(`${name} -- Failed`.red);
  console.log(err.toString().red);
  return true;
}

function runCmd(name, cmd, options) {
  exec(cmd, options)
    .progress(childProcess => {
      listen(childProcess, name);
      processMap[name] = childProcess;
      return;
    })
    .then(() => console.log('Shutdown: '.cyan + name.green))
    .catch(err => {
      if (catchExec(name, err)) {
        // Restart if not explicitly shutdown
        runCmd(name, cmd, options);
      }
    });
}

console.log('Starting docs in Development mode'.cyan);

process.on(SIGINT, shutdown);

portfinder.getPorts(2, {}, (portFinderErr, [docsPort, webpackPort]) => {
  if (portFinderErr) {
    console.log('Failed to acquire ports'.red);
    process.exit(1);
  }

  runCmd('webpack-dev-server', `nodemon --watch webpack --watch webpack.docs.js --exec webpack-dev-server -- --config webpack.docs.js --color --port ${webpackPort} --debug --hot --host ${ip.address()}`);

  runCmd('docs-server', 'nodemon --watch docs --watch src --exec babel-node docs/server.js', {
    env: {
      PORT: docsPort,
      WEBPACK_DEV_PORT: webpackPort,
      ...process.env
    }
  });
});


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "LzmaDecode.h"
#include "LzmaWrapper.h"

#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
static const char *kCantReadMessage = "Can not read from source buffer";
static const char *kCantAllocateMessage = "Not enough buffer for decompression";
#endif

static size_t rpos=0, dpos=0;

static int MyReadFileAndCheck(unsigned char *src, void *dest, size_t size)
{
  if (size == 0)
    return 0;
  memcpy(dest, src + rpos, size);
  rpos += size;
  return 1;
}

int lzma_inflate(unsigned char *source, int s_len, unsigned char *dest, int *d_len)
{
  /* We use two 32-bit integers to construct 64-bit integer for file size.
     You can remove outSizeHigh, if you don't need >= 4GB supporting,
     or you can use UInt64 outSize, if your compiler supports 64-bit integers*/
  UInt32 outSize = 0;
  UInt32 outSizeHigh = 0;
  SizeT outSizeFull;
  unsigned char *outStream;

  int waitEOS = 1;
  /* waitEOS = 1, if there is no uncompressed size in headers,
   so decoder will wait EOS (End of Stream Marker) in compressed stream */

  SizeT compressedSize;
  unsigned char *inStream;

  CLzmaDecoderState state;  /* it's about 24-80 bytes structure, if int is 32-bit */
  unsigned char properties[LZMA_PROPERTIES_SIZE];

  int res;

  rpos=0; dpos=0;

  if (sizeof(UInt32) < 4)
  {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
    printf("LZMA decoder needs correct UInt32\n");
#endif
    return LZMA_RESULT_DATA_ERROR;
  }

  {
    long length=s_len;
    if ((long)(SizeT)length != length)
    {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
      printf("Too big compressed stream\n");
#endif
      return LZMA_RESULT_DATA_ERROR;
    }
    compressedSize = (SizeT)(length - (LZMA_PROPERTIES_SIZE + 8));
  }

  /* Read LZMA properties for compressed stream */

  if (!MyReadFileAndCheck(source, properties, sizeof(properties)))
  {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
    printf("%s\n", kCantReadMessage);
#endif
    return LZMA_RESULT_DATA_ERROR;
  }

  /* Read uncompressed size */
  {
    int i;
    for (i = 0; i < 8; i++)
    {
      unsigned char b;
      if (!MyReadFileAndCheck(source, &b, 1))
      {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
        printf("%s\n", kCantReadMessage);
#endif
        return LZMA_RESULT_DATA_ERROR;
      }
      if (b != 0xFF)
        waitEOS = 0;
      if (i < 4)
        outSize += (UInt32)(b) << (i * 8);
      else
        outSizeHigh += (UInt32)(b) << ((i - 4) * 8);
    }

    if (waitEOS)
    {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
      printf("Stream with EOS marker is not supported");
#endif
      return LZMA_RESULT_DATA_ERROR;
    }
    outSizeFull = (SizeT)outSize;
    if (sizeof(SizeT) >= 8)
      outSizeFull |= (((SizeT)outSizeHigh << 16) << 16);
    else if (outSizeHigh != 0 || (UInt32)(SizeT)outSize != outSize)
    {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
      printf("Too big uncompressed stream");
#endif
      return LZMA_RESULT_DATA_ERROR;
    }
  }

  /* Decode LZMA properties and allocate memory */
  if (LzmaDecodeProperties(&state.Properties, properties, LZMA_PROPERTIES_SIZE) != LZMA_RESULT_OK)
  {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
    printf("Incorrect stream properties");
#endif
    return LZMA_RESULT_DATA_ERROR;
  }
  state.Probs = (CProb *)malloc(LzmaGetNumProbs(&state.Properties) * sizeof(CProb));

  if (outSizeFull == 0)
    outStream = 0;
  else
  {
    if (outSizeFull > d_len)
      outStream = 0;
    else
      outStream = dest;
  }

  if (compressedSize == 0)
    inStream = 0;
  else
  {
    if ((compressedSize+rpos) > s_len )
      inStream = 0;
    else
      inStream = source + rpos;
  }

  if (state.Probs == 0
    || (outStream == 0 && outSizeFull != 0)
    || (inStream == 0 && compressedSize != 0)
    )
  {
    free(state.Probs);
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
    printf("%s\n", kCantAllocateMessage);
#endif
    return LZMA_RESULT_DATA_ERROR;
  }

  /* Decompress */
  {
    SizeT inProcessed;
    SizeT outProcessed;
    res = LzmaDecode(&state,
      inStream, compressedSize, &inProcessed,
      outStream, outSizeFull, &outProcessed);
    if (res != 0)
    {
#if defined(DEBUG_ENABLE_BOOTSTRAP_PRINTF) || !defined(CFG_BOOTSTRAP_CODE)
      printf("\nDecoding error = %d\n", res);
#endif
      res = 1;
    }
    else
    {
      *d_len = outProcessed;
    }
  }

  free(state.Probs);
  return res;
}


text:
<?php

/* @var $scenario Codeception\Scenario */

$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that home page redirs to login');
$I->amOnPage(Yii::$app->homeUrl);
$I->see('Login');


text:
redirect_from:
  - "/engine/articles/systemd/"
title: "Limit a container's resources"
description: "Limiting the system resources a container can use"
keywords: "docker, daemon, configuration"
---

By default, a container has no resource constraints and can use as much of a
given resource as the host's kernel scheduler will allow. Docker provides ways
to control how much memory, CPU, or block IO a container can use, setting runtime
configuration flags of the `docker run` command. This section provides details
on when you should set such limits and the possible implications of setting them.

## Memory

Docker can enforce hard memory limits, which allow the container to use no more
than a given amount of user or system memory, or soft limits, which allow the
container to use as much memory as it needs unless certain conditions are met,
such as when the kernel detects low memory or contention on the host machine.
Some of these options have different effects when used alone or when more than
one option is set.

Most of these options take a positive integer, followed by a suffix of `b`, `k`,
`m`, `g`, to indicate bytes, kilobytes, megabytes, or gigabytes.

| Option                | Description                 |
|-----------------------|-----------------------------|
| `-m` or `--memory=` | The maximum amount of memory the container can use. If you set this option, the minimum allowed value is `4m` (4 megabyte). |
| `--memory-swap`*    | The amount of memory this container is allowed to swap to disk. See [`--memory-swap` details](resource_constraints.md#memory-swap-details). |
| `--memory-swappiness` | By default, the host kernel can swap out a percentage of anonymous pages used by a container. You can set `--memory-swappiness` to a value between 0 and 100, to tune this percentage. See [`--memory-swappiness` details](resource_constraints.md#memory-swappiness-details). |
| `--memory-reservation` | Allows you to specify a soft limit smaller than `--memory` which is activated when Docker detects contention or low memory on the host machine. If you use `--memory-reservation`, it must be set lower than `--memory` in order for it to take precedence. Because it is a soft limit, it does not guarantee that the container will not exceed the limit. |
| `--kernel-memory` | The maximum amount of kernel memory the container can use. The minimum allowed value is `4m`. Because kernel memory cannot be swapped out, a container which is starved of kernel memory may block host machine resources, which can have side effects on the host machine and on other containers. See [`--kernel-memory` details](resource_constraints.md#kernel-memory-details). |
| `--oom-kill-disable` | By default, if an out-of-memory (OOM) error occurs, the kernel kills processes in a container. To change this behavior, use the `--oom-kill-disable` option. Only disable the OOM killer on containers where you have also set the `-m/--memory` option. If the `-m` flag is not set, the host can run out of memory and the kernel may need to kill the host system's processes to free memory. |

For more information about cgroups and memory in general, see the documentation
for [Memory Resource Controller](https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt).

### `--memory-swap` details

`--memory-swap` is a modifier flag that only has meaning if `--memory` is also
set. Using swap allows the container to write excess memory requirements to disk
when the container has exhausted all the RAM that is available to it. There is a
performance penalty for applications that swap memory to disk often.

Its setting can have complicated effects:

- If `--memory-swap` is set to a positive integer, then both `--memory` and
  `--memory-swap` must be set. `--memory-swap` represents the total amount of
  memory and swap that can be used, and `--memory` controls the amount used by
  non-swap memory. So if `--memory="300m"` and `--memory-swap="1g"`, the
  container can use 300m of memory and 700m (`1g - 300m`) swap.

- If `--memory-swap` is set to `0`, the setting is ignored, and the value is
  treated as unset.

- If `--memory-swap` is set to the same value as `--memory`, and `--memory` is
  set to a positive integer, the effect is the same as setting `--memory-swap`
  to `0` (the value is treated as unset).

- If `--memory-swap` is unset, and `--memory` is set, the container can use
  twice as much swap as the `--memory` setting, if the host container has swap
  memory configured. For instance, if `--memory="300m"` and `--memory-swap` is
  not set, the container can use 300m of memory and 600m of swap.

- If `--memory-swap` is explicitly set to `-1`, the container is allowed to use
  unlimited swap, up to the amount available on the host system.

### `--memory-swappiness` details

- A value of 0 turns off anonymous page swapping.
- A value of 100 sets all anonymous pages as swappable.
- By default, if you do not set `--memory-swappiness`, the value is
  inherited from the host machine.

### `--kernel-memory` details

Kernel memory limits are expressed in terms of the overall memory allocated to
a container. Consider the following scenarios:

- **Unlimited memory, unlimited kernel memory**: This is the default
  behavior.
- **Unlimited memory, limited kernel memory**: This is appropriate when the
  amount of memory needed by all cgroups is greater than the amount of
  memory that actually exists on the host machine. You can configure the
  kernel memory to never go over what is available on the host machine,
  and containers which need more memory need to wait for it.
- **Limited memory, umlimited kernel memory**: The overall memory is
  limited, but the kernel memory is not.
- **Limited memory, limited kernel memory**: Limiting both user and kernel
  memory can be useful for debugging memory-related problems. If a container
  is using an unexpected amount of either type of memory, it will run out
  of memory without affecting other containers or the host machine. Within
  this setting, if the kernel memory limit is lower than the user memory
  limit, running out of kernel memory will cause the container to experience
  an OOM error. If the kernel memory limit is higher than the user memory
  limit, the kernel limit will not cause the container to experience an OOM.

When you turn on any kernel memory limits, the host machine tracks "high water
mark" statistics on a per-process basis, so you can track which processes (in
this case, containers) are using excess memory. This can be seen per process
by viewing `/proc/<PID>/status` on the host machine.

## CPU

By default, each container's access to the host machine's CPU cycles is unlimited.
You can set various constraints to limit a given container's access to the host
machine's CPU cycles. Most users will use and configure the
[default CFS scheduler](#configure-the-default-cfs-scheduler). In Docker 1.13
and higher, you can also configure the
[realtime scheduler](#configure-the-realtime-scheduler).

### Configure the default CFS scheduler

The CFS is the Linux kernel CPU scheduler for normal Linux processes. Several
runtime flags allow you to configure the amount of access to CPU resources your
container has. When you use these settings, Docker modifies the settings for
the container's cgroup on the host machine.

| Option                | Description                 |
|-----------------------|-----------------------------|
| `--cpus=<value>`      | Specify how much of the available CPU resources a container can use. For instance, if the host machine has two CPUs and you set `--cpus="1.5"`, the container will be guaranteed to be able to access at most one and a half of the CPUs. This is the equivalent of setting `--cpu-period="100000"` and `--cpu-quota="150000"`. Available in Docker 1.13 and higher. |
| `--cpu-period=<value>`| Specify the CPU CFS scheduler period, which is used alongside  `--cpu-quota`. Defaults to 1 second, expressed in micro-seconds. Most users do not change this from the default. If you use Docker 1.13 or higher, use `--cpus` instead. |
| `--cpu-quota=<value>` | Impose a CPU CFS quota on the container. The number of microseconds per `--cpu-period` that the container is guaranteed CPU access. In other words, `cpu-quota / cpu-period`. If you use Docker 1.13 or higher, use `--cpus` instead. |
| `--cpuset-cpus`       | Limit the specific CPUs or cores a container can use. A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU. The first CPU is numbered 0. A valid value might be `0-3` (to use the first, second, third, and fourth CPU) or `1,3` (to use the second and fourth CPU). |
| `--cpu-shares`        | Set this flag to a value greater or less than the default of 1024 to increase or reduce the container's weight, and give it access to a greater or lesser proportion of the host machine's CPU cycles. This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. `--cpu-shares` does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access. |

If you have 1 CPU, each of the following commands will guarantee the container at
most 50% of the CPU every second.

**Docker 1.13 and higher**:

```bash
docker run -it --cpus=".5" ubuntu /bin/bash
```

**Docker 1.12 and lower**:

```bash
$ docker run -it --cpu-period=100000 --cpu-quota=50000 ubuntu /bin/bash
```

### Configure the realtime scheduler

In Docker 1.13 and higher, you can configure your container to use the
realtime scheduler, for tasks which cannot use the CFS scheduler. You need to
[make sure the host machine's kernel is configured correctly](#configure-the-host-machines-kernel)
before you can [configure the Docker daemon](#configure-the-docker-daemon) or
[configure individual containers](#configure-individual-containers).

>**Warning**: CPU scheduling and prioritization are advanced kernel-level
features. Most users do not need to change these values from their defaults.
Setting these values incorrectly can cause your host system to become unstable
or unusable.

#### Configure the host machine's kernel

Verify that `CONFIG_RT_GROUP_SCHED` is enabled in the Linux kernel by running
`zcat /proc/config.gz | grep CONFIG_RT_GROUP_SCHED` or by checking for the
existence of the file `/sys/fs/cgroup/cpu.rt_runtime_us`. For guidance on
configuring the kernel realtime scheduler, consult the documentation for your
operating system.

#### Configure the Docker daemon

To run containers using the realtime scheduler, run the Docker daemon with
the `--cpu-rt-runtime` flag set to the maximum number of microseconds reserved
for realtime tasks per runtime period. For instance, with the default period of
10000 microseconds (1 second), setting `--cpu-rt-runtime=95000` ensures that
containers using the realtime scheduler can run for 95000 microseconds for every
10000-microsecond period, leaving at least 5000 microseconds available for
non-realtime tasks. To make this configuration permanent on systems which use
`systemd`, see [Control and configure Docker with systemd](systemd.md).

#### Configure individual containers

You can pass several flags to control a container's CPU priority when you
start the container using `docker run`. Consult your operating system's
documentation or the `ulimit` command for information on appropriate values.

| Option                    | Description                 |
|---------------------------|-----------------------------|
| `--cap-add=sys_nice`      | Grants the container the `CAP_SYS_NICE` capability, which allows the container to raise process `nice` values, set real-time scheduling policies, set CPU affinity, and other operations. |
| `--cpu-rt-runtime=<value>`| The maximum number of microseconds the container can run at realtime priority within the Docker daemon's realtime scheduler period. You also need the `--cap-add=sys_nice` flag. |
| `--ulimit rtprio=<value>` | The maximum realtime priority allowed for the container. You also need the `--cap-add=sys_nice` flag. |

The following example command sets each of these three flags on a `debian:jessie`
container.

```bash
$ docker run --it --cpu-rt-runtime=95000 \
                  --ulimit rtprio=99 \
                  --cap-add=sys_nice \
                  debian:jessie
```

If the kernel or Docker daemon is not configured correctly, an error will occur.


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="DW Consulting Engineers llp is an independent partnership formed by former principals of larger consultancies to give clients a quality of service that bigger businesses are unable to provide.">
    <meta name="author" content="CWalton">

  <link rel="stylesheet" type="text/css" href="/CSS/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="/CSS/Main.css">

  <title>About | DWllp</title>
  <link rel="icon" href="/Images/DW.png">

    <link rel="apple-touch-icon" type="image/png" href="Images/DW.png">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-1" aria-expanded="false">

                    </button>

DW Consulting Engineers llp

0161 969 4144
office@dwllp.com

About

Services

Sectors

Contact

About

Services

Sectors

Contact

Company Profile

DW Consulting Engineers llp is an independent partnership formed by former principals of larger consultancies to give clients a quality of service that bigger businesses are unable to provide.

We pride ourselves on giving a personal service and enjoy good working relationships throughout our industry.

The partners and all key technical staff have worked together for many years and can offer a wealth of experience in all sectors of construction. Whilst our core skills are in the structural and civil disciplines, we also offer management services to clients where appropriate on projects with significant engineering considerations.

We operate from offices in Harrogate and Sale and aim to provide 'local' service to our clients across the whole of the North of England. Notwithstanding that we also operate throughout the whole of the UK on a regular basis.

Our success is dependant upon a commitment to technical excellence and a focus on identifying, meeting and delivering clients' needs.

We pride ourselves that most of our clients give us repeat business. Our reputation depends upon delivering a good service every time we are entrusted with a project; as a service provider we are only as good as our last job.

Key Persons

Stuart Walton

Northwest office

        Stuart@dwllp.com

        07788 593200

        BSc, CEng, MICE, MIStructE

Chris Corrigan

Northwest office

        Chris@dwllp.com

        07884 003577

        CEng, MIStructE

Alan Wells

Yorkshire office

        Alan@dwllp.com

        07756 335716

        BSc(Hons), CEng, MIStructE

We are all extremely experienced chartered engineers heading teams with the capability to bring elegantly engineered economic design solutions.

As engineers we enjoy striving to achieve commercial design solutions.

We have successfully delivered projects in all sectors ranging from simple residential developments up to commercial schemes in excess of £30M construction value.

North West office

			Name
            Email
            Number
			Certifications

				Stuart Walton
                Stuart@dwllp.com
                07788 593200
				BSc CEng MICE MIStructE

				Chris Corrigan
                Chris@dwllp.com
                07884 003577
				CEng MIStructE

Yorkshire office

			Name
            Email
            Number
			Certifications

				Alan Wells
                Alan@dwllp.com
                07756 335716
                BSc(Hons) CEng MIStructE

© dwllp 2016


text:
/*
 * 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.
 */
package io.trino.plugin.resourcegroups.db;

import org.jdbi.v3.core.Handle;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.OracleContainer;
import org.testng.annotations.Test;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

@Test(singleThreaded = true)
public class TestDbResourceGroupsOracleFlywayMigration
        extends BaseTestDbResourceGroupsFlywayMigration
{
    @Override
    protected final JdbcDatabaseContainer<?> startContainer()
    {
        JdbcDatabaseContainer<?> container = new OracleContainer("gvenzl/oracle-xe:18.4.0-slim")
                .withPassword("trino")
                .withEnv("ORACLE_PASSWORD", "trino");
        container.start();
        return container;
    }

    @Override
    protected void dropAllTables()
    {
        String propertiesTable = "resource_groups_global_properties".toUpperCase(Locale.ENGLISH);
        String resourceGroupsTable = "resource_groups".toUpperCase(Locale.ENGLISH);
        String selectorsTable = "selectors".toUpperCase(Locale.ENGLISH);
        String exactMatchTable = "exact_match_source_selectors".toUpperCase(Locale.ENGLISH);
        String flywayHistoryTable = "flyway_schema_history";
        Handle jdbiHandle = jdbi.open();
        if (tableExists(jdbiHandle, propertiesTable)) {
            jdbiHandle.execute("DROP TABLE " + propertiesTable);
        }
        if (tableExists(jdbiHandle, selectorsTable)) {
            jdbiHandle.execute("DROP TABLE " + selectorsTable);
        }
        if (tableExists(jdbiHandle, resourceGroupsTable)) {
            jdbiHandle.execute("DROP TABLE " + resourceGroupsTable);
        }
        if (tableExists(jdbiHandle, exactMatchTable)) {
            jdbiHandle.execute("DROP TABLE " + exactMatchTable);
        }
        if (tableExists(jdbiHandle, flywayHistoryTable)) {
            jdbiHandle.execute("DROP TABLE \"" + flywayHistoryTable + "\"");
        }
        jdbiHandle.close();
    }

    private boolean tableExists(Handle jdbiHandle, String tableName)
    {
        try {
            DatabaseMetaData metaData = jdbiHandle.getConnection().getMetaData();
            try (ResultSet resultSet = metaData.getTables(null, null, tableName, null)) {
                while (resultSet.next()) {
                    String table = resultSet.getString("TABLE_NAME");
                    if (tableName.equalsIgnoreCase(table)) {
                        return true;
                    }
                }
            }
            return false;
        }
        catch (SQLException e) {
            return false;
        }
    }

    @Test
    public void forceTestNgToRespectSingleThreaded()
    {
        // TODO: Remove after updating TestNG to 7.4.0+ (https://github.com/trinodb/trino/issues/8571)
        // TestNG doesn't enforce @Test(singleThreaded = true) when tests are defined in base class. According to
        // https://github.com/cbeust/testng/issues/2361#issuecomment-688393166 a workaround it to add a dummy test to the leaf test class.
    }
}


text:
package org.apache.servicecomb.demo.edge.service.encrypt;

import java.util.concurrent.CompletableFuture;

import org.apache.servicecomb.demo.edge.authentication.encrypt.Hcr;

public interface Encrypt {
  CompletableFuture<String> queryUserId(String serviceToken);

  CompletableFuture<Hcr> queryHcr(String hcrId);
}


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace WebApi.Migration.Demo.Migrations
{
    public partial class addFk4 : Microsoft.EntityFrameworkCore.Migrations.Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_Lodging_Destination_DestinationDestinationId",
                table: "Lodging");

            migrationBuilder.DropIndex(
                name: "IX_Lodging_DestinationDestinationId",
                table: "Lodging");

            migrationBuilder.RenameColumn(
                name: "DestinationDestinationId",
                table: "Lodging",
                newName: "DestId");

            migrationBuilder.AddColumn<int>(
                name: "TargetDestinationId",
                table: "Lodging",
                nullable: true);

            migrationBuilder.CreateIndex(
                name: "IX_Lodging_TargetDestinationId",
                table: "Lodging",
                column: "TargetDestinationId");

            migrationBuilder.AddForeignKey(
                name: "FK_Lodging_Destination_TargetDestinationId",
                table: "Lodging",
                column: "TargetDestinationId",
                principalTable: "Destination",
                principalColumn: "DestinationId",
                onDelete: ReferentialAction.Restrict);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_Lodging_Destination_TargetDestinationId",
                table: "Lodging");

            migrationBuilder.DropIndex(
                name: "IX_Lodging_TargetDestinationId",
                table: "Lodging");

            migrationBuilder.DropColumn(
                name: "TargetDestinationId",
                table: "Lodging");

            migrationBuilder.RenameColumn(
                name: "DestId",
                table: "Lodging",
                newName: "DestinationDestinationId");

            migrationBuilder.CreateIndex(
                name: "IX_Lodging_DestinationDestinationId",
                table: "Lodging",
                column: "DestinationDestinationId");

            migrationBuilder.AddForeignKey(
                name: "FK_Lodging_Destination_DestinationDestinationId",
                table: "Lodging",
                column: "DestinationDestinationId",
                principalTable: "Destination",
                principalColumn: "DestinationId",
                onDelete: ReferentialAction.Cascade);
        }
    }
}


text:
<ion-view view-title="Estados" hide-back-button="false">
	<ion-content class="has-footer" has-tabs="true" on-scroll="scrollList()">
		<ion-list>
			<ion-item
			href="#/app/estado_restaurante/{{estado.id}}"
			ng-repeat="estado in estados | filter:query | orderBy: 'nombre' "
			ng-click="go('/app/estado_restaurante/{{estado.id}}')">
					{{estado.nombre}}
			</ion-item>
		</ion-list>
	</ion-content>
</ion-view>


text:
import { connect } from 'react-redux';
import { initial } from '../actions/MapActions';
import InitialBtn from '../components/InitialBtn';

const mapStateToProps = state => ({
})

const mapDispatchToProps = dispatch => ({
  onClick: () => dispatch(initial())
})

const InitialBtnContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(InitialBtn)

export default InitialBtnContainer


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using LeapProject;

namespace Pointable
{
    public partial class FormShutdown : Form
    {
        Form1 mainForm;
        bool shuttingDown = false;
        int counter = 10;

        public FormShutdown(Form1 mainForm1, bool isShutdown)
        {
            InitializeComponent();
            mainForm = mainForm1;
            shuttingDown = isShutdown;

            try
            {
                if (isShutdown)
                {
                    this.Text = "System Shutdown";
                    label1.Text = "Shutdown in";
                    buttonNow.Text ="Shutdown now";
                }
                else
                {
                    this.Text = "System Restart";
                    label1.Text = "Restart in";
                    buttonNow.Text = "Restart now";
                }
                counter = 10;
            }
            catch { }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            try
            {
                timer1.Enabled = false;
                this.Close();
            }
            catch { }
        }

        private void buttonNow_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            if (shuttingDown)
            {
                label1.Text = "System shutdown in progress";
                labelCounter.Text = "";
                runShutdown();
            }
            else
            {
                label1.Text = "System restart in progress";
                labelCounter.Text = "";
                runRestart();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                counter--;
                if (counter > 0)
                {
                    labelCounter.Text = counter.ToString() + " seconds";
                }
                else
                {
                    timer1.Enabled = false;
                    if (shuttingDown)
                    {
                        label1.Text = "System shutdown in progress";
                        labelCounter.Text = "";
                        runShutdown();
                    }
                    else
                    {
                        label1.Text = "System restart in progress";
                        labelCounter.Text = "";
                        runRestart();
                    }
                }
            }
            catch { }
        }

        private void runShutdown()
        {
            //MessageBox.Show("ShutDown"); return;
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "shutdown.exe";// triggerFilename;//"C:\\Program Files (x86)\\EventGhost\\EventGhost.exe";
                startInfo.Arguments = "-s -t 00";// "-event NextChannel";
                Process.Start(startInfo);
            }
            catch { };//(Exception error){Debug.WriteLine(error.ToString()); }
        }
        private void runRestart()
        {
            //MessageBox.Show("restart"); return;
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "shutdown.exe";// triggerFilename;//"C:\\Program Files (x86)\\EventGhost\\EventGhost.exe";
                startInfo.Arguments = "-r -t 00";// "-event NextChannel";
                Process.Start(startInfo);
            }
            catch { };//(Exception error){Debug.WriteLine(error.ToString()); }
        }
    }
}