text:
namespace capnp {
namespace rpc {
inline kj::String KJ_STRINGIFY(Message::Which which) {
  return kj::str(static_cast<uint16_t>(which));
}
}  // namespace rpc
}  // namespace capnp

namespace capnp {
namespace _ {  // private
namespace {

class RpcDumper {
  // Class which stringifies RPC messages for debugging purposes, including decoding params and
  // results based on the call's interface and method IDs and extracting cap descriptors.
  //
  // TODO(cleanup):  Clean this code up and move it to someplace reusable, so it can be used as
  //   a packet inspector / debugging tool for Cap'n Proto network traffic.

public:
  void addSchema(InterfaceSchema schema) {
    schemas[schema.getProto().getId()] = schema;
  }

  enum Sender {
    CLIENT,
    SERVER
  };

  kj::String dump(rpc::Message::Reader message, Sender sender) {
    const char* senderName = sender == CLIENT ? "client" : "server";

    switch (message.which()) {
      case rpc::Message::CALL: {
        auto call = message.getCall();
        auto iter = schemas.find(call.getInterfaceId());
        if (iter == schemas.end()) {
          break;
        }
        InterfaceSchema schema = iter->second;
        auto methods = schema.getMethods();
        if (call.getMethodId() >= methods.size()) {
          break;
        }
        InterfaceSchema::Method method = methods[call.getMethodId()];

        auto schemaProto = schema.getProto();
        auto interfaceName =
            schemaProto.getDisplayName().slice(schemaProto.getDisplayNamePrefixLength());

        auto methodProto = method.getProto();
        auto paramType = method.getParamType();
        auto resultType = method.getResultType();

        if (call.getSendResultsTo().isCaller()) {
          returnTypes[std::make_pair(sender, call.getQuestionId())] = resultType;
        }

        auto payload = call.getParams();
        auto params = kj::str(payload.getContent().getAs<DynamicStruct>(paramType));

        auto sendResultsTo = call.getSendResultsTo();

        return kj::str(senderName, "(", call.getQuestionId(), "): call ",
                       call.getTarget(), " <- ", interfaceName, ".",
                       methodProto.getName(), params,
                       " caps:[", kj::strArray(payload.getCapTable(), ", "), "]",
                       sendResultsTo.isCaller() ? kj::str()
                                                : kj::str(" sendResultsTo:", sendResultsTo));
      }

      case rpc::Message::RETURN: {
        auto ret = message.getReturn();

        auto iter = returnTypes.find(
            std::make_pair(sender == CLIENT ? SERVER : CLIENT, ret.getAnswerId()));
        if (iter == returnTypes.end()) {
          break;
        }

        auto schema = iter->second;
        returnTypes.erase(iter);
        if (ret.which() != rpc::Return::RESULTS) {
          // Oops, no results returned.  We don't check this earlier because we want to make sure
          // returnTypes.erase() gets a chance to happen.
          break;
        }

        auto payload = ret.getResults();

        if (schema.getProto().isStruct()) {
          auto results = kj::str(payload.getContent().getAs<DynamicStruct>(schema.asStruct()));

          return kj::str(senderName, "(", ret.getAnswerId(), "): return ", results,
                         " caps:[", kj::strArray(payload.getCapTable(), ", "), "]");
        } else if (schema.getProto().isInterface()) {
          payload.getContent().getAs<DynamicCapability>(schema.asInterface());
          return kj::str(senderName, "(", ret.getAnswerId(), "): return cap ",
                         kj::strArray(payload.getCapTable(), ", "));
        } else {
          break;
        }
      }

      case rpc::Message::BOOTSTRAP: {
        auto restore = message.getBootstrap();

        returnTypes[std::make_pair(sender, restore.getQuestionId())] = InterfaceSchema();

        return kj::str(senderName, "(", restore.getQuestionId(), "): bootstrap ",
                       restore.getDeprecatedObjectId().getAs<test::TestSturdyRefObjectId>());
      }

      default:
        break;
    }

    return kj::str(senderName, ": ", message);
  }

private:
  std::map<uint64_t, InterfaceSchema> schemas;
  std::map<std::pair<Sender, uint32_t>, Schema> returnTypes;
};

// =======================================================================================

class TestNetworkAdapter;

class TestNetwork {
public:
  TestNetwork() {
    dumper.addSchema(Schema::from<test::TestInterface>());
    dumper.addSchema(Schema::from<test::TestExtends>());
    dumper.addSchema(Schema::from<test::TestPipeline>());
    dumper.addSchema(Schema::from<test::TestCallOrder>());
    dumper.addSchema(Schema::from<test::TestTailCallee>());
    dumper.addSchema(Schema::from<test::TestTailCaller>());
    dumper.addSchema(Schema::from<test::TestMoreStuff>());
  }
  ~TestNetwork() noexcept(false);

  TestNetworkAdapter& add(kj::StringPtr name);

  kj::Maybe<TestNetworkAdapter&> find(kj::StringPtr name) {
    auto iter = map.find(name);
    if (iter == map.end()) {
      return nullptr;
    } else {
      return *iter->second;
    }
  }

  RpcDumper dumper;

private:
  std::map<kj::StringPtr, kj::Own<TestNetworkAdapter>> map;
};

typedef VatNetwork<
    test::TestSturdyRefHostId, test::TestProvisionId, test::TestRecipientId,
    test::TestThirdPartyCapId, test::TestJoinResult> TestNetworkAdapterBase;

class TestNetworkAdapter final: public TestNetworkAdapterBase {
public:
  TestNetworkAdapter(TestNetwork& network): network(network) {}

  ~TestNetworkAdapter() {
    kj::Exception exception = KJ_EXCEPTION(FAILED, "Network was destroyed.");
    for (auto& entry: connections) {
      entry.second->disconnect(kj::cp(exception));
    }
  }

  uint getSentCount() { return sent; }
  uint getReceivedCount() { return received; }

  typedef TestNetworkAdapterBase::Connection Connection;

  class ConnectionImpl final
      : public Connection, public kj::Refcounted, public kj::TaskSet::ErrorHandler {
  public:
    ConnectionImpl(TestNetworkAdapter& network, RpcDumper::Sender sender)
        : network(network), sender(sender), tasks(kj::heap<kj::TaskSet>(*this)) {}

    void attach(ConnectionImpl& other) {
      KJ_REQUIRE(partner == nullptr);
      KJ_REQUIRE(other.partner == nullptr);
      partner = other;
      other.partner = *this;
    }

    void disconnect(kj::Exception&& exception) {
      while (!fulfillers.empty()) {
        fulfillers.front()->reject(kj::cp(exception));
        fulfillers.pop();
      }

      networkException = kj::mv(exception);

      tasks = nullptr;
    }

    class IncomingRpcMessageImpl final: public IncomingRpcMessage, public kj::Refcounted {
    public:
      IncomingRpcMessageImpl(kj::Array<word> data)
          : data(kj::mv(data)),
            message(this->data) {}

      AnyPointer::Reader getBody() override {
        return message.getRoot<AnyPointer>();
      }

      void initCapTable(kj::Array<kj::Maybe<kj::Own<ClientHook>>>&& capTable) override {
        message.initCapTable(kj::mv(capTable));
      }

      kj::Array<word> data;
      FlatArrayMessageReader message;
    };

    class OutgoingRpcMessageImpl final: public OutgoingRpcMessage {
    public:
      OutgoingRpcMessageImpl(ConnectionImpl& connection, uint firstSegmentWordSize)
          : connection(connection),
            message(firstSegmentWordSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS
                                              : firstSegmentWordSize) {}

      AnyPointer::Builder getBody() override {
        return message.getRoot<AnyPointer>();
      }

      kj::ArrayPtr<kj::Maybe<kj::Own<ClientHook>>> getCapTable() override {
        return message.getCapTable();
      }

      void send() override {
        if (connection.networkException != nullptr) {
          return;
        }

        ++connection.network.sent;

        // Uncomment to get a debug dump.
//        kj::String msg = connection.network.network.dumper.dump(
//            message.getRoot<rpc::Message>(), connection.sender);
//        KJ_ DBG(msg);

        auto incomingMessage = kj::heap<IncomingRpcMessageImpl>(messageToFlatArray(message));

        auto connectionPtr = &connection;
        connection.tasks->add(kj::evalLater(kj::mvCapture(incomingMessage,
            [connectionPtr](kj::Own<IncomingRpcMessageImpl>&& message) {
          KJ_IF_MAYBE(p, connectionPtr->partner) {
            if (p->fulfillers.empty()) {
              p->messages.push(kj::mv(message));
            } else {
              ++p->network.received;
              p->fulfillers.front()->fulfill(
                  kj::Own<IncomingRpcMessage>(kj::mv(message)));
              p->fulfillers.pop();
            }
          }
        })));
      }

    private:
      ConnectionImpl& connection;
      MallocMessageBuilder message;
    };

    test::TestSturdyRefHostId::Reader getPeerVatId() override {
      // Not actually implemented for the purpose of this test.
      return test::TestSturdyRefHostId::Reader();
    }

    kj::Own<OutgoingRpcMessage> newOutgoingMessage(uint firstSegmentWordSize) override {
      return kj::heap<OutgoingRpcMessageImpl>(*this, firstSegmentWordSize);
    }
    kj::Promise<kj::Maybe<kj::Own<IncomingRpcMessage>>> receiveIncomingMessage() override {
      KJ_IF_MAYBE(e, networkException) {
        return kj::cp(*e);
      }

      if (messages.empty()) {
        KJ_IF_MAYBE(f, fulfillOnEnd) {
          f->get()->fulfill();
          return kj::Maybe<kj::Own<IncomingRpcMessage>>(nullptr);
        } else {
          auto paf = kj::newPromiseAndFulfiller<kj::Maybe<kj::Own<IncomingRpcMessage>>>();
          fulfillers.push(kj::mv(paf.fulfiller));
          return kj::mv(paf.promise);
        }
      } else {
        ++network.received;
        auto result = kj::mv(messages.front());
        messages.pop();
        return kj::Maybe<kj::Own<IncomingRpcMessage>>(kj::mv(result));
      }
    }
    kj::Promise<void> shutdown() override {
      KJ_IF_MAYBE(p, partner) {
        auto paf = kj::newPromiseAndFulfiller<void>();
        p->fulfillOnEnd = kj::mv(paf.fulfiller);
        return kj::mv(paf.promise);
      } else {
        return kj::READY_NOW;
      }
    }

    void taskFailed(kj::Exception&& exception) override {
      ADD_FAILURE() << kj::str(exception).cStr();
    }

  private:
    TestNetworkAdapter& network;
    RpcDumper::Sender sender KJ_UNUSED_MEMBER;
    kj::Maybe<ConnectionImpl&> partner;

    kj::Maybe<kj::Exception> networkException;

    std::queue<kj::Own<kj::PromiseFulfiller<kj::Maybe<kj::Own<IncomingRpcMessage>>>>> fulfillers;
    std::queue<kj::Own<IncomingRpcMessage>> messages;
    kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> fulfillOnEnd;

    kj::Own<kj::TaskSet> tasks;
  };

  kj::Maybe<kj::Own<Connection>> connect(test::TestSturdyRefHostId::Reader hostId) override {
    TestNetworkAdapter& dst = KJ_REQUIRE_NONNULL(network.find(hostId.getHost()));

    auto iter = connections.find(&dst);
    if (iter == connections.end()) {
      auto local = kj::refcounted<ConnectionImpl>(*this, RpcDumper::CLIENT);
      auto remote = kj::refcounted<ConnectionImpl>(dst, RpcDumper::SERVER);
      local->attach(*remote);

      connections[&dst] = kj::addRef(*local);
      dst.connections[this] = kj::addRef(*remote);

      if (dst.fulfillerQueue.empty()) {
        dst.connectionQueue.push(kj::mv(remote));
      } else {
        dst.fulfillerQueue.front()->fulfill(kj::mv(remote));
        dst.fulfillerQueue.pop();
      }

      return kj::Own<Connection>(kj::mv(local));
    } else {
      return kj::Own<Connection>(kj::addRef(*iter->second));
    }
  }

  kj::Promise<kj::Own<Connection>> accept() override {
    if (connectionQueue.empty()) {
      auto paf = kj::newPromiseAndFulfiller<kj::Own<Connection>>();
      fulfillerQueue.push(kj::mv(paf.fulfiller));
      return kj::mv(paf.promise);
    } else {
      auto result = kj::mv(connectionQueue.front());
      connectionQueue.pop();
      return kj::mv(result);
    }
  }

private:
  TestNetwork& network;
  uint sent = 0;
  uint received = 0;

  std::map<const TestNetworkAdapter*, kj::Own<ConnectionImpl>> connections;
  std::queue<kj::Own<kj::PromiseFulfiller<kj::Own<Connection>>>> fulfillerQueue;
  std::queue<kj::Own<Connection>> connectionQueue;
};

TestNetwork::~TestNetwork() noexcept(false) {}

TestNetworkAdapter& TestNetwork::add(kj::StringPtr name) {
  return *(map[name] = kj::heap<TestNetworkAdapter>(*this));
}

// =======================================================================================

class TestRestorer final: public SturdyRefRestorer<test::TestSturdyRefObjectId> {
public:
  int callCount = 0;
  int handleCount = 0;

  Capability::Client restore(test::TestSturdyRefObjectId::Reader objectId) override {
    switch (objectId.getTag()) {
      case test::TestSturdyRefObjectId::Tag::TEST_INTERFACE:
        return kj::heap<TestInterfaceImpl>(callCount);
      case test::TestSturdyRefObjectId::Tag::TEST_EXTENDS:
        return Capability::Client(newBrokenCap("No TestExtends implemented."));
      case test::TestSturdyRefObjectId::Tag::TEST_PIPELINE:
        return kj::heap<TestPipelineImpl>(callCount);
      case test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLEE:
        return kj::heap<TestTailCalleeImpl>(callCount);
      case test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLER:
        return kj::heap<TestTailCallerImpl>(callCount);
      case test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF:
        return kj::heap<TestMoreStuffImpl>(callCount, handleCount);
    }
    KJ_UNREACHABLE;
  }
};

struct TestContext {
  kj::EventLoop loop;
  kj::WaitScope waitScope;
  TestNetwork network;
  TestRestorer restorer;
  TestNetworkAdapter& clientNetwork;
  TestNetworkAdapter& serverNetwork;
  RpcSystem<test::TestSturdyRefHostId> rpcClient;
  RpcSystem<test::TestSturdyRefHostId> rpcServer;

  TestContext()
      : waitScope(loop),
        clientNetwork(network.add("client")),
        serverNetwork(network.add("server")),
        rpcClient(makeRpcClient(clientNetwork)),
        rpcServer(makeRpcServer(serverNetwork, restorer)) {}
  TestContext(Capability::Client bootstrap,
              RealmGateway<test::TestSturdyRef, Text>::Client gateway)
      : waitScope(loop),
        clientNetwork(network.add("client")),
        serverNetwork(network.add("server")),
        rpcClient(makeRpcClient(clientNetwork, gateway)),
        rpcServer(makeRpcServer(serverNetwork, bootstrap)) {}
  TestContext(Capability::Client bootstrap,
              RealmGateway<test::TestSturdyRef, Text>::Client gateway,
              bool)
      : waitScope(loop),
        clientNetwork(network.add("client")),
        serverNetwork(network.add("server")),
        rpcClient(makeRpcClient(clientNetwork)),
        rpcServer(makeRpcServer(serverNetwork, bootstrap, gateway)) {}

  Capability::Client connect(test::TestSturdyRefObjectId::Tag tag) {
    MallocMessageBuilder refMessage(128);
    auto ref = refMessage.initRoot<test::TestSturdyRef>();
    auto hostId = ref.initHostId();
    hostId.setHost("server");
    ref.getObjectId().initAs<test::TestSturdyRefObjectId>().setTag(tag);

    return rpcClient.restore(hostId, ref.getObjectId());
  }
};

TEST(Rpc, Basic) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_INTERFACE)
      .castAs<test::TestInterface>();

  auto request1 = client.fooRequest();
  request1.setI(123);
  request1.setJ(true);
  auto promise1 = request1.send();

  // We used to call bar() after baz(), hence the numbering, but this masked the case where the
  // RPC system actually disconnected on bar() (thus returning an exception, which we decided
  // was expected).
  bool barFailed = false;
  auto request3 = client.barRequest();
  auto promise3 = request3.send().then(
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
        barFailed = true;
      });

  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

  EXPECT_EQ(0, context.restorer.callCount);

  auto response1 = promise1.wait(context.waitScope);

  EXPECT_EQ("foo", response1.getX());

  auto response2 = promise2.wait(context.waitScope);

  promise3.wait(context.waitScope);

  EXPECT_EQ(2, context.restorer.callCount);
  EXPECT_TRUE(barFailed);
}

TEST(Rpc, Pipelining) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_PIPELINE)
      .castAs<test::TestPipeline>();

  int chainedCallCount = 0;

  auto request = client.getCapRequest();
  request.setN(234);
  request.setInCap(kj::heap<TestInterfaceImpl>(chainedCallCount));

  auto promise = request.send();

  auto pipelineRequest = promise.getOutBox().getCap().fooRequest();
  pipelineRequest.setI(321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = promise.getOutBox().getCap().castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

  promise = nullptr;  // Just to be annoying, drop the original promise.

  EXPECT_EQ(0, context.restorer.callCount);
  EXPECT_EQ(0, chainedCallCount);

  auto response = pipelinePromise.wait(context.waitScope);
  EXPECT_EQ("bar", response.getX());

  auto response2 = pipelinePromise2.wait(context.waitScope);
  checkTestMessage(response2);

  EXPECT_EQ(3, context.restorer.callCount);
  EXPECT_EQ(1, chainedCallCount);
}

TEST(Rpc, Release) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto handle1 = client.getHandleRequest().send().wait(context.waitScope).getHandle();
  auto promise = client.getHandleRequest().send();
  auto handle2 = promise.wait(context.waitScope).getHandle();

  EXPECT_EQ(2, context.restorer.handleCount);

  handle1 = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(1, context.restorer.handleCount);

  handle2 = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(1, context.restorer.handleCount);

  promise = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(0, context.restorer.handleCount);
}

TEST(Rpc, ReleaseOnCancel) {
  // At one time, there was a bug where if a Return contained capabilities, but the client had
  // canceled the request and already send a Finish (which presumably didn't reach the server before
  // the Return), then we'd leak those caps. Test for that.

  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();
  client.whenResolved().wait(context.waitScope);

  {
    auto promise = client.getHandleRequest().send();

    // If the server receives cancellation too early, it won't even return a capability in the
    // results, it will just return "canceled". We want to emulate the case where the return message
    // and the cancel (finish) message cross paths. It turns out that exactly two evalLater()s get
    // us there.
    //
    // TODO(cleanup): This is fragile, but I'm not sure how else to write it without a ton
    //   of scaffolding.
    kj::evalLater([]() {}).wait(context.waitScope);
    kj::evalLater([]() {}).wait(context.waitScope);
  }

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(0, context.restorer.handleCount);
}

TEST(Rpc, TailCall) {
  TestContext context;

  auto caller = context.connect(test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLER)
      .castAs<test::TestTailCaller>();

  int calleeCallCount = 0;

  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));

  auto request = caller.fooRequest();
  request.setI(456);
  request.setCallee(callee);

  auto promise = request.send();

  auto dependentCall0 = promise.getC().getCallSequenceRequest().send();

  auto response = promise.wait(context.waitScope);
  EXPECT_EQ(456, response.getI());
  EXPECT_EQ("from TestTailCaller", response.getT());

  auto dependentCall1 = promise.getC().getCallSequenceRequest().send();

  auto dependentCall2 = response.getC().getCallSequenceRequest().send();

  EXPECT_EQ(0, dependentCall0.wait(context.waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(context.waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(context.waitScope).getN());

  EXPECT_EQ(1, calleeCallCount);
  EXPECT_EQ(1, context.restorer.callCount);
}

TEST(Rpc, Cancelation) {
  // Tests allowCancellation().

  TestContext context;

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  kj::Promise<void> promise = nullptr;

  bool returned = false;
  {
    auto request = client.expectCancelRequest();
    request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
    promise = request.send().then(
        [&](Response<test::TestMoreStuff::ExpectCancelResults>&& response) {
      returned = true;
    }).eagerlyEvaluate(nullptr);
  }
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);

  // We can detect that the method was canceled because it will drop the cap.
  EXPECT_FALSE(destroyed);
  EXPECT_FALSE(returned);

  promise = nullptr;  // request cancellation
  destructionPromise.wait(context.waitScope);

  EXPECT_TRUE(destroyed);
  EXPECT_FALSE(returned);
}

TEST(Rpc, PromiseResolve) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  int chainedCallCount = 0;

  auto request = client.callFooRequest();
  auto request2 = client.callFooWhenResolvedRequest();

  auto paf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();

  {
    auto fork = paf.promise.fork();
    request.setCap(fork.addBranch());
    request2.setCap(fork.addBranch());
  }

  auto promise = request.send();
  auto promise2 = request2.send();

  // Make sure getCap() has been called on the server side by sending another call and waiting
  // for it.
  EXPECT_EQ(2, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
  EXPECT_EQ(3, context.restorer.callCount);

  // OK, now fulfill the local promise.
  paf.fulfiller->fulfill(kj::heap<TestInterfaceImpl>(chainedCallCount));

  // We should now be able to wait for getCap() to finish.
  EXPECT_EQ("bar", promise.wait(context.waitScope).getS());
  EXPECT_EQ("bar", promise2.wait(context.waitScope).getS());

  EXPECT_EQ(3, context.restorer.callCount);
  EXPECT_EQ(2, chainedCallCount);
}

TEST(Rpc, RetainAndRelease) {
  TestContext context;

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);

  {
    auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
        .castAs<test::TestMoreStuff>();

    {
      auto request = client.holdRequest();
      request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
      request.send().wait(context.waitScope);
    }

    // Do some other call to add a round trip.
    EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());

    // Shouldn't be destroyed because it's being held by the server.
    EXPECT_FALSE(destroyed);

    // We can ask it to call the held capability.
    EXPECT_EQ("bar", client.callHeldRequest().send().wait(context.waitScope).getS());

    {
      // We can get the cap back from it.
      auto capCopy = client.getHeldRequest().send().wait(context.waitScope).getCap();

      {
        // And call it, without any network communications.
        uint oldSentCount = context.clientNetwork.getSentCount();
        auto request = capCopy.fooRequest();
        request.setI(123);
        request.setJ(true);
        EXPECT_EQ("foo", request.send().wait(context.waitScope).getX());
        EXPECT_EQ(oldSentCount, context.clientNetwork.getSentCount());
      }

      {
        // We can send another copy of the same cap to another method, and it works.
        auto request = client.callFooRequest();
        request.setCap(capCopy);
        EXPECT_EQ("bar", request.send().wait(context.waitScope).getS());
      }
    }

    // Give some time to settle.
    EXPECT_EQ(5, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
    EXPECT_EQ(6, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
    EXPECT_EQ(7, client.getCallSequenceRequest().send().wait(context.waitScope).getN());

    // Can't be destroyed, we haven't released it.
    EXPECT_FALSE(destroyed);
  }

  // We released our client, which should cause the server to be released, which in turn will
  // release the cap pointing back to us.
  destructionPromise.wait(context.waitScope);
  EXPECT_TRUE(destroyed);
}

TEST(Rpc, Cancel) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);

  {
    auto request = client.neverReturnRequest();
    request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));

    {
      auto responsePromise = request.send();

      // Allow some time to settle.
      EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
      EXPECT_EQ(2, client.getCallSequenceRequest().send().wait(context.waitScope).getN());

      // The cap shouldn't have been destroyed yet because the call never returned.
      EXPECT_FALSE(destroyed);
    }
  }

  // Now the cap should be released.
  destructionPromise.wait(context.waitScope);
  EXPECT_TRUE(destroyed);
}

TEST(Rpc, SendTwice) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);

  auto cap = test::TestInterface::Client(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));

  {
    auto request = client.callFooRequest();
    request.setCap(cap);

    EXPECT_EQ("bar", request.send().wait(context.waitScope).getS());
  }

  // Allow some time for the server to release `cap`.
  EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());

  {
    // More requests with the same cap.
    auto request = client.callFooRequest();
    auto request2 = client.callFooRequest();
    request.setCap(cap);
    request2.setCap(kj::mv(cap));

    auto promise = request.send();
    auto promise2 = request2.send();

    EXPECT_EQ("bar", promise.wait(context.waitScope).getS());
    EXPECT_EQ("bar", promise2.wait(context.waitScope).getS());
  }

  // Now the cap should be released.
  destructionPromise.wait(context.waitScope);
  EXPECT_TRUE(destroyed);
}

RemotePromise<test::TestCallOrder::GetCallSequenceResults> getCallSequence(
    test::TestCallOrder::Client& client, uint expected) {
  auto req = client.getCallSequenceRequest();
  req.setExpected(expected);
  return req.send();
}

TEST(Rpc, Embargo) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto cap = test::TestCallOrder::Client(kj::heap<TestCallOrderImpl>());

  auto earlyCall = client.getCallSequenceRequest().send();

  auto echoRequest = client.echoRequest();
  echoRequest.setCap(cap);
  auto echo = echoRequest.send();

  auto pipeline = echo.getCap();

  auto call0 = getCallSequence(pipeline, 0);
  auto call1 = getCallSequence(pipeline, 1);

  earlyCall.wait(context.waitScope);

  auto call2 = getCallSequence(pipeline, 2);

  auto resolved = echo.wait(context.waitScope).getCap();

  auto call3 = getCallSequence(pipeline, 3);
  auto call4 = getCallSequence(pipeline, 4);
  auto call5 = getCallSequence(pipeline, 5);

  EXPECT_EQ(0, call0.wait(context.waitScope).getN());
  EXPECT_EQ(1, call1.wait(context.waitScope).getN());
  EXPECT_EQ(2, call2.wait(context.waitScope).getN());
  EXPECT_EQ(3, call3.wait(context.waitScope).getN());
  EXPECT_EQ(4, call4.wait(context.waitScope).getN());
  EXPECT_EQ(5, call5.wait(context.waitScope).getN());
}

template <typename T>
void expectPromiseThrows(kj::Promise<T>&& promise, kj::WaitScope& waitScope) {
  EXPECT_TRUE(promise.then([](T&&) { return false; }, [](kj::Exception&&) { return true; })
      .wait(waitScope));
}

template <>
void expectPromiseThrows(kj::Promise<void>&& promise, kj::WaitScope& waitScope) {
  EXPECT_TRUE(promise.then([]() { return false; }, [](kj::Exception&&) { return true; })
      .wait(waitScope));
}

TEST(Rpc, EmbargoError) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<test::TestCallOrder::Client>();

  auto cap = test::TestCallOrder::Client(kj::mv(paf.promise));

  auto earlyCall = client.getCallSequenceRequest().send();

  auto echoRequest = client.echoRequest();
  echoRequest.setCap(cap);
  auto echo = echoRequest.send();

  auto pipeline = echo.getCap();

  auto call0 = getCallSequence(pipeline, 0);
  auto call1 = getCallSequence(pipeline, 1);

  earlyCall.wait(context.waitScope);

  auto call2 = getCallSequence(pipeline, 2);

  auto resolved = echo.wait(context.waitScope).getCap();

  auto call3 = getCallSequence(pipeline, 3);
  auto call4 = getCallSequence(pipeline, 4);
  auto call5 = getCallSequence(pipeline, 5);

  paf.fulfiller->rejectIfThrows([]() { KJ_FAIL_ASSERT("foo") { break; } });

  expectPromiseThrows(kj::mv(call0), context.waitScope);
  expectPromiseThrows(kj::mv(call1), context.waitScope);
  expectPromiseThrows(kj::mv(call2), context.waitScope);
  expectPromiseThrows(kj::mv(call3), context.waitScope);
  expectPromiseThrows(kj::mv(call4), context.waitScope);
  expectPromiseThrows(kj::mv(call5), context.waitScope);

  // Verify that we're still connected (there were no protocol errors).
  getCallSequence(client, 1).wait(context.waitScope);
}

TEST(Rpc, CallBrokenPromise) {
  // Tell the server to call back to a promise client, then resolve the promise to an error.

  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();
  auto paf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();

  {
    auto req = client.holdRequest();
    req.setCap(kj::mv(paf.promise));
    req.send().wait(context.waitScope);
  }

  bool returned = false;
  auto req = client.callHeldRequest().send()
      .then([&](capnp::Response<test::TestMoreStuff::CallHeldResults>&&) {
    returned = true;
  }, [&](kj::Exception&& e) {
    returned = true;
    kj::throwRecoverableException(kj::mv(e));
  }).eagerlyEvaluate(nullptr);

  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);

  EXPECT_FALSE(returned);

  paf.fulfiller->rejectIfThrows([]() { KJ_FAIL_ASSERT("foo") { break; } });

  expectPromiseThrows(kj::mv(req), context.waitScope);
  EXPECT_TRUE(returned);

  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);

  // Verify that we're still connected (there were no protocol errors).
  getCallSequence(client, 1).wait(context.waitScope);
}

TEST(Rpc, Abort) {
  // Verify that aborts are received.

  TestContext context;

  MallocMessageBuilder refMessage(128);
  auto hostId = refMessage.initRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  auto conn = KJ_ASSERT_NONNULL(context.clientNetwork.connect(hostId));

  {
    // Send an invalid message (Return to non-existent question).
    auto msg = conn->newOutgoingMessage(128);
    auto body = msg->getBody().initAs<rpc::Message>().initReturn();
    body.setAnswerId(1234);
    body.setCanceled();
    msg->send();
  }

  auto reply = KJ_ASSERT_NONNULL(conn->receiveIncomingMessage().wait(context.waitScope));
  EXPECT_EQ(rpc::Message::ABORT, reply->getBody().getAs<rpc::Message>().which());

  EXPECT_TRUE(conn->receiveIncomingMessage().wait(context.waitScope) == nullptr);
}

// =======================================================================================

typedef RealmGateway<test::TestSturdyRef, Text> TestRealmGateway;

class TestGateway final: public TestRealmGateway::Server {
public:
  kj::Promise<void> import(ImportContext context) override {
    auto cap = context.getParams().getCap();
    context.releaseParams();
    return cap.saveRequest().send()
        .then([context](Response<Persistent<Text>::SaveResults> response) mutable {
      context.getResults().initSturdyRef().getObjectId().setAs<Text>(
          kj::str("imported-", response.getSturdyRef()));
    });
  }

  kj::Promise<void> export_(ExportContext context) override {
    auto cap = context.getParams().getCap();
    context.releaseParams();
    return cap.saveRequest().send()
        .then([context](Response<Persistent<test::TestSturdyRef>::SaveResults> response) mutable {
      context.getResults().setSturdyRef(kj::str("exported-",
          response.getSturdyRef().getObjectId().getAs<Text>()));
    });
  }
};

class TestPersistent final: public Persistent<test::TestSturdyRef>::Server {
public:
  TestPersistent(kj::StringPtr name): name(name) {}

  kj::Promise<void> save(SaveContext context) override {
    context.initResults().initSturdyRef().getObjectId().setAs<Text>(name);
    return kj::READY_NOW;
  }

private:
  kj::StringPtr name;
};

class TestPersistentText final: public Persistent<Text>::Server {
public:
  TestPersistentText(kj::StringPtr name): name(name) {}

  kj::Promise<void> save(SaveContext context) override {
    context.initResults().setSturdyRef(name);
    return kj::READY_NOW;
  }

private:
  kj::StringPtr name;
};

TEST(Rpc, RealmGatewayImport) {
  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<Text>::Client bootstrap = kj::heap<TestPersistentText>("foo");

  MallocMessageBuilder hostIdBuilder;
  auto hostId = hostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  TestContext context(bootstrap, gateway);
  auto client = context.rpcClient.bootstrap(hostId).castAs<Persistent<test::TestSturdyRef>>();

  auto response = client.saveRequest().send().wait(context.waitScope);

  EXPECT_EQ("imported-foo", response.getSturdyRef().getObjectId().getAs<Text>());
}

TEST(Rpc, RealmGatewayExport) {
  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<test::TestSturdyRef>::Client bootstrap = kj::heap<TestPersistent>("foo");

  MallocMessageBuilder hostIdBuilder;
  auto hostId = hostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  TestContext context(bootstrap, gateway, true);
  auto client = context.rpcClient.bootstrap(hostId).castAs<Persistent<Text>>();

  auto response = client.saveRequest().send().wait(context.waitScope);

  EXPECT_EQ("exported-foo", response.getSturdyRef());
}

}  // namespace
}  // namespace _ (private)
}  // namespace capnp


text:
@interface RKAccuAngleDriveAddon : NSObject <RKDriveVectorAddon>

@property ( readwrite ) BOOL enabled;
@property ( readwrite ) int32_t rotationRateThreshold;
@property ( readwrite ) float_t outputRatio;
@end

redpajama_set_name: RedPajamaGithub


text:
@implementation UITextView (EmojiKit)

- (UIImage *)screenshot {
    UIImage *image = nil;

    UIGraphicsBeginImageContextWithOptions(self.contentSize, NO, UIScreen.mainScreen.scale);

    CGPoint offset = self.contentOffset;
    CGRect frame = self.frame;

    self.contentOffset = CGPointZero;
    self.frame = CGRectMake(0, 0, self.contentSize.width, self.contentSize.height);

    [self.layer renderInContext: UIGraphicsGetCurrentContext()];
    image = UIGraphicsGetImageFromCurrentImageContext();

    self.contentOffset = offset;
    self.frame = frame;

    UIGraphicsEndImageContext();

    return image;
}

@end


text:
/*
 * This interface is used for compatibility with old U-boots *ONLY*.
 * Please do not imitate or extend this.
 */

/*
 * (C) Copyright 2000, 2001
 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

#ifndef __PPCBOOT_H__
#define __PPCBOOT_H__

/*
 * Board information passed to kernel from PPCBoot
 *
 * include/asm-ppc/ppcboot.h
 */

#include "types.h"

typedef struct bd_info {
	unsigned long	bi_memstart;	/* start of DRAM memory */
	unsigned long	bi_memsize;	/* size	 of DRAM memory in bytes */
	unsigned long	bi_flashstart;	/* start of FLASH memory */
	unsigned long	bi_flashsize;	/* size	 of FLASH memory */
	unsigned long	bi_flashoffset; /* reserved area for startup monitor */
	unsigned long	bi_sramstart;	/* start of SRAM memory */
	unsigned long	bi_sramsize;	/* size	 of SRAM memory */
#if defined(TARGET_8xx) || defined(TARGET_CPM2) || defined(TARGET_85xx) ||\
	defined(TARGET_83xx)
	unsigned long	bi_immr_base;	/* base of IMMR register */
#endif
#if defined(TARGET_PPC_MPC52xx)
	unsigned long   bi_mbar_base;   /* base of internal registers */
#endif
	unsigned long	bi_bootflags;	/* boot / reboot flag (for LynxOS) */
	unsigned long	bi_ip_addr;	/* IP Address */
	unsigned char	bi_enetaddr[6];	/* Ethernet address */
	unsigned short	bi_ethspeed;	/* Ethernet speed in Mbps */
	unsigned long	bi_intfreq;	/* Internal Freq, in MHz */
	unsigned long	bi_busfreq;	/* Bus Freq, in MHz */
#if defined(TARGET_CPM2)
	unsigned long	bi_cpmfreq;	/* CPM_CLK Freq, in MHz */
	unsigned long	bi_brgfreq;	/* BRG_CLK Freq, in MHz */
	unsigned long	bi_sccfreq;	/* SCC_CLK Freq, in MHz */
	unsigned long	bi_vco;		/* VCO Out from PLL, in MHz */
#endif
#if defined(TARGET_PPC_MPC52xx)
	unsigned long   bi_ipbfreq;     /* IPB Bus Freq, in MHz */
	unsigned long   bi_pcifreq;     /* PCI Bus Freq, in MHz */
#endif
	unsigned long	bi_baudrate;	/* Console Baudrate */
#if defined(TARGET_4xx)
	unsigned char	bi_s_version[4];	/* Version of this structure */
	unsigned char	bi_r_version[32];	/* Version of the ROM (IBM) */
	unsigned int	bi_procfreq;	/* CPU (Internal) Freq, in Hz */
	unsigned int	bi_plb_busfreq;	/* PLB Bus speed, in Hz */
	unsigned int	bi_pci_busfreq;	/* PCI Bus speed, in Hz */
	unsigned char	bi_pci_enetaddr[6];	/* PCI Ethernet MAC address */
#endif
#if defined(TARGET_HYMOD)
	hymod_conf_t	bi_hymod_conf;	/* hymod configuration information */
#endif
#if defined(TARGET_EVB64260) || defined(TARGET_405EP) || defined(TARGET_44x) || \
	defined(TARGET_85xx) ||	defined(TARGET_83xx) || defined(TARGET_HAS_ETH1)
	/* second onboard ethernet port */
	unsigned char	bi_enet1addr[6];
#define HAVE_ENET1ADDR
#endif
#if defined(TARGET_EVB64260) || defined(TARGET_440GX) || \
    defined(TARGET_85xx) || defined(TARGET_HAS_ETH2)
	/* third onboard ethernet ports */
	unsigned char	bi_enet2addr[6];
#define HAVE_ENET2ADDR
#endif
#if defined(TARGET_440GX) || defined(TARGET_HAS_ETH3)
	/* fourth onboard ethernet ports */
	unsigned char	bi_enet3addr[6];
#define HAVE_ENET3ADDR
#endif
#if defined(TARGET_4xx)
	unsigned int	bi_opbfreq;		/* OB clock in Hz */
	int		bi_iic_fast[2];		/* Use fast i2c mode */
#endif
#if defined(TARGET_440GX)
	int		bi_phynum[4];		/* phy mapping */
	int		bi_phymode[4];		/* phy mode */
#endif
} bd_t;

#define bi_tbfreq	bi_intfreq

#endif	/* __PPCBOOT_H__ */


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="gittern.data_collector.transport.class">Ebutik\GitternBundle\Profiler\TransportDataCollector</parameter>
        <parameter key="gittern.repository.class">Gittern\Repository</parameter>
        <parameter key="gittern.repository.configurator.class">Gittern\Configurator</parameter>
        <parameter key="gittern.repository.transport.logger.class">Ebutik\GitternBundle\Profiler\TransportLogger</parameter>
        <parameter key="gittern.repository.transport.profiler.class">Ebutik\GitternBundle\Profiler\ProfilingTransportDecorator</parameter>
        <parameter key="gittern.repository.transport.cache.class">Ebutik\GitternBundle\Cache\CachingTransportDecorator</parameter>
        <parameter key="gittern.repository.transport.real.class">Gittern\Transport\NativeTransport</parameter>
    </parameters>

    <services>
        <service id="gittern.data_collector.transport" class="%gittern.data_collector.transport.class%">
            <argument type="service" id="gittern.repository.transport.logger" />

            <tag name="data_collector" template="EbutikGitternBundle::profiler.html.twig" id="gittern_transport" />
        </service>

        <service id="gittern.repository" class="%gittern.repository.class%">
            <call method="setTransport">
                <argument type="service" id="gittern.repository.transport" />
            </call>

            <configurator service="gittern.repository.configurator" method="defaultConfigure" />
        </service>

        <service id="gittern.repository.configurator" class="%gittern.repository.configurator.class%" />

        <service id="gittern.repository.transport.logger" class="%gittern.repository.transport.logger.class%" public="false" />

        <service id="gittern.repository.transport.profiler" class="%gittern.repository.transport.profiler.class%" public="false">
            <argument />
            <argument type="service" id="debug.stopwatch" on-invalid="null" />

            <call method="setTransportLogger">
                <argument type="service" id="gittern.repository.transport.logger" />
            </call>
        </service>

        <service id="gittern.repository.transport.cache" class="%gittern.repository.transport.cache.class%" public="false">
            <argument />
            <argument />
            <argument />
        </service>

        <service id="gittern.repository.transport.real" class="%gittern.repository.transport.real.class%" public="false">
            <argument>%gittern.repository.transport.real.path%</argument>
        </service>
    </services>
</container>


text:
__author__ = 'PARKJINSANG'

import math

def cosine_similarity(vector_a, vector_b, cmp_len):

    dot_product = 0
    for i in range(0, cmp_len):
        dot_product += vector_a[i] * vector_b[i]

    a_vector_magnitude = 0
    for elem in vector_a:
        a_vector_magnitude += math.pow(elem, 2)
    b_vector_magnitude = 0
    for elem in vector_b:
        b_vector_magnitude += math.pow(elem, 2)

    magnitude = math.sqrt(a_vector_magnitude) * math.sqrt(b_vector_magnitude)

    return dot_product / magnitude


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tbl_post".
 *
 * @property integer $id
 * @property string $title
 * @property string $content
 * @property string $tags
 * @property integer $status
 * @property integer $create_time
 * @property integer $update_time
 * @property integer $user_id
 *
 * @property TblComment[] $tblComments
 * @property TblUser $user
 */
class Post extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_post';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'content', 'status', 'user_id'], 'required'],
            [['content', 'tags'], 'string'],
            [['status', 'create_time', 'update_time', 'user_id'], 'integer'],
            [['title'], 'string', 'max' => 128]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Title'),
            'content' => Yii::t('app', 'Content'),
            'tags' => Yii::t('app', 'Tags'),
            'status' => Yii::t('app', 'Status'),
            'create_time' => Yii::t('app', 'Create Time'),
            'update_time' => Yii::t('app', 'Update Time'),
            'user_id' => Yii::t('app', 'User ID'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTblComments()
    {
        return $this->hasMany(TblComment::className(), ['post_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(TblUser::className(), ['id' => 'user_id']);
    }
}


text:
<ion-header>
  <ion-navbar>
    <ion-title>Settings</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list radio-group [(ngModel)]="scanMode" no-margin-bottom>
    <ion-list-header color="light">Mode</ion-list-header>
    <ion-item>
      <ion-label>IBAN</ion-label>
      <ion-radio value="iban"></ion-radio>
    </ion-item>
    <ion-item>
      <ion-label>GS1 AI</ion-label>
      <ion-radio value="gs1"></ion-radio>
    </ion-item>
    <ion-item>
      <ion-label>Scan a price</ion-label>
      <ion-radio value="price"></ion-radio>
    </ion-item>
  </ion-list>

  <ion-list radio-group [(ngModel)]="scanPosition">
    <ion-list-header color="light">Scan Position</ion-list-header>
    <ion-item>
      <ion-label>Top</ion-label>
      <ion-radio value="top"></ion-radio>
    </ion-item>
    <ion-item>
      <ion-label>Center</ion-label>
      <ion-radio value="center"></ion-radio>
    </ion-item>
    <ion-item>
      <ion-label>Bottom</ion-label>
      <ion-radio value="bottom"></ion-radio>
    </ion-item>
  </ion-list>
</ion-content>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width" />

{{title}}

{{subTitle}}

{{body}}


text:
#ifndef EventSource_h
#define EventSource_h

#include "ActiveDOMObject.h"
#include "EventTarget.h"
#include "KURL.h"
#include "ThreadableLoaderClient.h"
#include "Timer.h"
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>

namespace WebCore {

class Dictionary;
class MessageEvent;
class ResourceResponse;
class TextResourceDecoder;
class ThreadableLoader;

class EventSource : public RefCounted<EventSource>, public EventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
    WTF_MAKE_FAST_ALLOCATED;
public:
    static PassRefPtr<EventSource> create(ScriptExecutionContext*, const String& url, const Dictionary&, ExceptionCode&);
    virtual ~EventSource();

    static const unsigned long long defaultReconnectDelay;

    String url() const;
    bool withCredentials() const;

    typedef short State;
    static const State CONNECTING = 0;
    static const State OPEN = 1;
    static const State CLOSED = 2;

    State readyState() const;

    DEFINE_ATTRIBUTE_EVENT_LISTENER(open);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);

    void close();

    using RefCounted<EventSource>::ref;
    using RefCounted<EventSource>::deref;

    virtual const AtomicString& interfaceName() const;
    virtual ScriptExecutionContext* scriptExecutionContext() const;

    virtual void stop();

private:
    EventSource(ScriptExecutionContext*, const KURL&, const Dictionary&);

    virtual void refEventTarget() { ref(); }
    virtual void derefEventTarget() { deref(); }
    virtual EventTargetData* eventTargetData();
    virtual EventTargetData* ensureEventTargetData();

    virtual void didReceiveResponse(unsigned long, const ResourceResponse&);
    virtual void didReceiveData(const char*, int);
    virtual void didFinishLoading(unsigned long, double);
    virtual void didFail(const ResourceError&);
    virtual void didFailAccessControlCheck(const ResourceError&);
    virtual void didFailRedirectCheck();

    void connect();
    void networkRequestEnded();
    void scheduleInitialConnect();
    void scheduleReconnect();
    void connectTimerFired(Timer<EventSource>*);
    void abortConnectionAttempt();
    void parseEventStream();
    void parseEventStreamLine(unsigned pos, int fieldLength, int lineLength);
    PassRefPtr<MessageEvent> createMessageEvent();

    KURL m_url;
    bool m_withCredentials;
    State m_state;

    RefPtr<TextResourceDecoder> m_decoder;
    RefPtr<ThreadableLoader> m_loader;
    Timer<EventSource> m_connectTimer;
    Vector<UChar> m_receiveBuf;
    bool m_discardTrailingNewline;
    bool m_requestInFlight;

    String m_eventName;
    Vector<UChar> m_data;
    String m_currentlyParsedEventId;
    String m_lastEventId;
    unsigned long long m_reconnectDelay;
    String m_eventStreamOrigin;

    EventTargetData m_eventTargetData;
};

} // namespace WebCore

#endif // EventSource_h


text:
..
      Copyright 2013 New Dream Network, LLC (DreamHost)

      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.

====================================
 Installing the API Behind mod_wsgi
====================================

Ceilometer comes with a few example files for configuring the API
service to run behind Apache with ``mod_wsgi``.

app.wsgi
========

The file ``ceilometer/api/app.wsgi`` sets up the V2 API WSGI
application. The file is installed with the rest of the ceilometer
application code, and should not need to be modified.

etc/apache2/ceilometer
======================

The ``etc/apache2/ceilometer`` file contains example settings that
work with a copy of ceilometer installed via devstack.

.. literalinclude:: ../../../etc/apache2/ceilometer

1. Copy or symlink the file to ``/etc/apache2/sites-avilable``.

2. Modify the ``VirtualHost`` directive, setting a hostname or IP for
   the service. The default settings assume that the ceilometer API is
   the only service running on the local Apache instance, which
   conflicts with Horizon's default configuration.

3. Modify the ``WSGIDaemonProcess`` directive to set the
   ``user`` and ``group`` values to a user available on your server.

4. Modify the ``APACHE_RUN_USER`` and ``APACHE_RUN_GROUP`` values to
   the name of a user and group available on your server.

5. Enable the ceilometer site.

   ::

      $ a2ensite ceilometer
      $ service apache2 reload

Limitation
==========

As Ceilometer is using Pecan and Pecan's DebugMiddleware doesn't support
multiple processes, there is no way to set debug mode in the multiprocessing
case. To allow multiple processes the DebugMiddleware may be turned off by
setting ``pecan_debug`` to ``False`` in the ``api`` section of
``ceilometer.conf``.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>de.uni_potsdam.hpi.bpt.bp2014.rest</title>
<meta name="date" content="2015-04-21">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package de.uni_potsdam.hpi.bpt.bp2014.rest

Class Summary

Class
Description

JsonUtil

This class provides the helper methods/classes used for the JSON representation for the REST connections.

JsonUtil.JsonHashMapIntegerString

This class is a JSON HashMap containing a List of ID's and a HashMap consisting of the given ID's and labels as Strings.

JsonUtil.JsonHashMapMultipleIntegerString

JsonUtil.JsonInteger

This class is the representation of an Integer as JSON.

JsonUtil.JsonIntegerList

This class handles the JSON representation of a list filled with database ID's.

JsonUtil.JsonStringHashMap

This class is the representation of a HashMap that maps a String to a String.

RestInterface

RestInterface.DataObjectJaxBean

A JAX bean which is used for dataobject data.

RestInterface.NamedJaxBean

A JAX bean which is used for a naming an entity.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
using System;

namespace Atata
{
    /// <summary>
    /// Represents the log consumer that writes log to NLog using default NLog configuration.
    /// </summary>
    public class NLogConsumer : LazyInitializableLogConsumer, INamedLogConsumer
    {
        public NLogConsumer()
            : this(null)
        {
        }

        public NLogConsumer(string loggerName) =>
            LoggerName = loggerName;

        /// <inheritdoc/>
        public string LoggerName { get; set; }

        /// <inheritdoc/>
        protected override dynamic GetLogger()
        {
            var logger = LoggerName != null
                ? NLogAdapter.GetLogger(LoggerName)
                : NLogAdapter.GetCurrentClassLogger();

            return logger ?? throw new InvalidOperationException("Failed to create NLog logger.");
        }

        /// <inheritdoc/>
        protected override void OnLog(LogEventInfo eventInfo)
        {
            dynamic otherEventInfo = NLogAdapter.CreateLogEventInfo(eventInfo);
            Logger.Log(otherEventInfo);
        }
    }
}


text:
import pytest
import os

import CHIP_IO.GPIO as GPIO

def teardown_module(module):
    GPIO.cleanup()

class TestSetup:
    def test_setup_output_key(self):
        GPIO.setup("U14_37", GPIO.OUT)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'out\n'
        GPIO.cleanup()

    def test_setup_output_name(self):
        GPIO.setup("CSID6", GPIO.OUT)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'out\n'
        GPIO.cleanup()

    def test_setup_input_key(self):
        GPIO.setup("U14_37", GPIO.IN)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'in\n'
        GPIO.cleanup()

    def test_setup_input_name(self):
        GPIO.setup("CSID6", GPIO.IN)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'in\n'
        GPIO.cleanup()

    def test_setup_input_pull_up(self):
        GPIO.setup("U14_37", GPIO.IN, pull_up_down=GPIO.PUD_UP)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'in\n'
        GPIO.cleanup()

    def test_setup_input_pull_down(self):
        GPIO.setup("U14_37", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        assert os.path.exists('/sys/class/gpio/gpio138')
        direction = open('/sys/class/gpio/gpio138/direction').read()
        assert direction == 'in\n'
        GPIO.cleanup()

    def test_setup_cleanup(self):
        GPIO.setup("U14_37", GPIO.OUT)
        assert os.path.exists('/sys/class/gpio/gpio138')
        GPIO.cleanup()
        assert not os.path.exists('/sys/class/gpio/gpio138')

    def test_setup_failed_type_error(self):
        with pytest.raises(TypeError):
            GPIO.setup("U14_37", "WEIRD")
            GPIO.cleanup()

    def test_setup_failed_value_error(self):
        with pytest.raises(ValueError):
            GPIO.setup("U14_37", 3)
            GPIO.cleanup()

    def test_setup_expanded_gpio(self):
        GPIO.setup("XIO-P1", GPIO.OUT)
        base = GPIO.get_gpio_base() + 1
        gfile = '/sys/class/gpio/gpio%d' % base
        assert os.path.exists(gfile)
        GPIO.cleanup()
        assert not os.path.exists(gfile)


text:
class Libtensorflow < Formula
  include Language::Python::Virtualenv

  desc "C interface for Google's OS library for Machine Intelligence"
  homepage "https://www.tensorflow.org/"
  url "https://github.com/tensorflow/tensorflow/archive/v2.1.0.tar.gz"
  sha256 "638e541a4981f52c69da4a311815f1e7989bf1d67a41d204511966e1daed14f7"
  revision 1

  bottle do
    cellar :any
    sha256 "ae426ef446f51bec0ab875e326b5c3e8bf77383a00a37c3770a49c2a5da93b00" => :catalina
    sha256 "e5acab2f4eb720903e3887e0067b63bd25da25ccc76b6134ca9d52d88d20040f" => :mojave
    sha256 "f34c781a2ba4cf4fce53edc41e71eed861630562207ee4e7d418f2c84bc5a22c" => :high_sierra
  end

  depends_on "bazel" => :build
  depends_on :java => ["1.8", :build]
  depends_on "python@3.8" => :build

  resource "numpy" do
    url "https://files.pythonhosted.org/packages/40/de/0ea5092b8bfd2e3aa6fdbb2e499a9f9adf810992884d414defc1573dca3f/numpy-1.18.1.zip"
    sha256 "b6ff59cee96b454516e47e7721098e6ceebef435e3e21ac2d6c3b8b02628eb77"
  end

  resource "six" do
    url "https://files.pythonhosted.org/packages/94/3e/edcf6fef41d89187df7e38e868b2dd2182677922b600e880baad7749c865/six-1.13.0.tar.gz"
    sha256 "30f610279e8b2578cab6db20741130331735c781b56053c59c4076da27f06b66"
  end

  resource "test-model" do
    url "https://github.com/tensorflow/models/raw/v1.13.0/samples/languages/java/training/model/graph.pb"
    sha256 "147fab50ddc945972818516418942157de5e7053d4b67e7fca0b0ada16733ecb"
  end

  def install
    # Bazel fails if version from .bazelversion doesn't match bazel version, so just to use the latest one
    rm_f ".bazelversion"

    cmd = Language::Java.java_home_cmd("1.8")
    ENV["JAVA_HOME"] = Utils.popen_read(cmd).chomp

    venv = virtualenv_create("#{buildpath}/venv", "python3")
    (resources.map(&:name).to_set - ["test-model"]).each do |r|
      venv.pip_install resource(r)
    end
    ENV["PYTHON_BIN_PATH"] = "#{buildpath}/venv/bin/python"

    ENV["CC_OPT_FLAGS"] = "-march=native"
    ENV["TF_IGNORE_MAX_BAZEL_VERSION"] = "1"
    ENV["TF_NEED_JEMALLOC"] = "1"
    ENV["TF_NEED_GCP"] = "0"
    ENV["TF_NEED_HDFS"] = "0"
    ENV["TF_ENABLE_XLA"] = "0"
    ENV["USE_DEFAULT_PYTHON_LIB_PATH"] = "1"
    ENV["TF_NEED_OPENCL"] = "0"
    ENV["TF_NEED_CUDA"] = "0"
    ENV["TF_NEED_MKL"] = "0"
    ENV["TF_NEED_VERBS"] = "0"
    ENV["TF_NEED_MPI"] = "0"
    ENV["TF_NEED_S3"] = "1"
    ENV["TF_NEED_GDR"] = "0"
    ENV["TF_NEED_KAFKA"] = "0"
    ENV["TF_NEED_OPENCL_SYCL"] = "0"
    ENV["TF_NEED_ROCM"] = "0"
    ENV["TF_DOWNLOAD_CLANG"] = "0"
    ENV["TF_SET_ANDROID_WORKSPACE"] = "0"
    ENV["TF_CONFIGURE_IOS"] = "0"
    system "./configure"

    bazel_args =%W[
      --jobs=#{ENV.make_jobs}
      --compilation_mode=opt
      --copt=-march=native
    ]
    targets = %w[
      tensorflow:libtensorflow.so
      tensorflow/tools/benchmark:benchmark_model
      tensorflow/tools/graph_transforms:summarize_graph
      tensorflow/tools/graph_transforms:transform_graph
    ]
    system "bazel", "build", *bazel_args, *targets

    lib.install Dir["bazel-bin/tensorflow/*.so*", "bazel-bin/tensorflow/*.dylib*"]
    (include/"tensorflow/c").install %w[
      tensorflow/c/c_api.h
      tensorflow/c/c_api_experimental.h
      tensorflow/c/tf_attrtype.h
      tensorflow/c/tf_datatype.h
      tensorflow/c/tf_status.h
      tensorflow/c/tf_tensor.h
    ]
    bin.install %w[
      bazel-bin/tensorflow/tools/benchmark/benchmark_model
      bazel-bin/tensorflow/tools/graph_transforms/summarize_graph
      bazel-bin/tensorflow/tools/graph_transforms/transform_graph
    ]

    (lib/"pkgconfig/tensorflow.pc").write <<~EOS
      Name: tensorflow
      Description: Tensorflow library
      Version: #{version}
      Libs: -L#{lib} -ltensorflow
      Cflags: -I#{include}
    EOS
  end

  test do
    (testpath/"test.c").write <<~EOS
      #include <stdio.h>
      #include <tensorflow/c/c_api.h>
      int main() {
        printf("%s", TF_Version());
      }
    EOS
    system ENV.cc, "-L#{lib}", "-ltensorflow", "-o", "test_tf", "test.c"
    assert_equal version, shell_output("./test_tf")

    resource("test-model").stage(testpath)

    summarize_graph_output = shell_output("#{bin}/summarize_graph --in_graph=#{testpath}/graph.pb 2>&1")
    variables_match = /Found \d+ variables:.+$/.match(summarize_graph_output)
    assert_not_nil variables_match, "Unexpected stdout from summarize_graph for graph.pb (no found variables)"
    variables_names = variables_match[0].scan(/name=([^,]+)/).flatten.sort

    transform_command = %W[
      #{bin}/transform_graph
      --in_graph=#{testpath}/graph.pb
      --out_graph=#{testpath}/graph-new.pb
      --inputs=n/a
      --outputs=n/a
      --transforms="obfuscate_names"
      2>&1
    ].join(" ")
    shell_output(transform_command)

    assert_predicate testpath/"graph-new.pb", :exist?, "transform_graph did not create an output graph"

    new_summarize_graph_output = shell_output("#{bin}/summarize_graph --in_graph=#{testpath}/graph-new.pb 2>&1")
    new_variables_match = /Found \d+ variables:.+$/.match(new_summarize_graph_output)
    assert_not_nil new_variables_match, "Unexpected summarize_graph output for graph-new.pb (no found variables)"
    new_variables_names = new_variables_match[0].scan(/name=([^,]+)/).flatten.sort

    assert_not_equal variables_names, new_variables_names, "transform_graph didn't obfuscate variable names"

    benchmark_model_match = /benchmark_model -- (.+)$/.match(new_summarize_graph_output)
    assert_not_nil benchmark_model_match, "Unexpected summarize_graph output for graph-new.pb (no benchmark_model example)"

    benchmark_model_args = benchmark_model_match[1].split(" ")
    benchmark_model_args.delete("--show_flops")

    benchmark_model_command = [
      "#{bin}/benchmark_model",
      "--time_limit=10",
      "--num_threads=1",
      *benchmark_model_args,
      "2>&1",
    ].join(" ")

    benchmark_model_output = shell_output(benchmark_model_command)
    assert_includes benchmark_model_output, "Timings (microseconds):", "Unexpected benchmark_model output (no timings)"
  end
end


text:
import { ReflectiveInjector } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { CurrentNode, NavigationService, NavigationViews, NavigationNode, VersionInfo } from 'app/navigation/navigation.service';
import { LocationService } from 'app/shared/location.service';
import { MockLocationService } from 'testing/location.service';
import { Logger } from 'app/shared/logger.service';

describe('NavigationService', () => {

  let injector: ReflectiveInjector;
  let backend: MockBackend;
  let navService: NavigationService;

  function createResponse(body: any) {
    return new Response(new ResponseOptions({ body: JSON.stringify(body) }));
  }

  beforeEach(() => {
    injector = ReflectiveInjector.resolveAndCreate([
        NavigationService,
        { provide: LocationService, useFactory: () => new MockLocationService('a') },
        { provide: ConnectionBackend, useClass: MockBackend },
        { provide: RequestOptions, useClass: BaseRequestOptions },
        Http,
        Logger
    ]);
  });

  beforeEach(() => {
    backend = injector.get(ConnectionBackend);
    navService = injector.get(NavigationService);
  });

  it('should be creatable', () => {
    expect(navService).toBeTruthy();
  });

  describe('navigationViews', () => {

    it('should make a single connection to the server', () => {
      expect(backend.connectionsArray.length).toEqual(1);
      expect(backend.connectionsArray[0].request.url).toEqual('generated/navigation.json');
    });

    it('should expose the server response', () => {
      const viewsEvents: NavigationViews[] = [];
      navService.navigationViews.subscribe(views => viewsEvents.push(views));

      expect(viewsEvents).toEqual([]);
      backend.connectionsArray[0].mockRespond(createResponse({ TopBar: [ { url: 'a' }] }));
      expect(viewsEvents).toEqual([{ TopBar: [ { url: 'a' }] }]);
    });

    it('navigationViews observable should complete', () => {
      let completed = false;
      navService.navigationViews.subscribe(null, null, () => completed = true);
      expect(true).toBe(true, 'observable completed');
    });

    it('should return the same object to all subscribers', () => {
      let views1: NavigationViews;
      navService.navigationViews.subscribe(views => views1 = views);

      let views2: NavigationViews;
      navService.navigationViews.subscribe(views => views2 = views);

      backend.connectionsArray[0].mockRespond(createResponse({ TopBar: [{ url: 'a' }] }));

      // modify the response so we can check that future subscriptions do not trigger another request
      backend.connectionsArray[0].response.next(createResponse({ TopBar: [{ url: 'error 1' }] }));

      let views3: NavigationViews;
      navService.navigationViews.subscribe(views => views3 = views);

      expect(views2).toBe(views1);
      expect(views3).toBe(views1);
    });

    it('should do WHAT(?) if the request fails');
  });

  describe('node.tooltip', () => {
    let view: NavigationNode[];

    const sideNav: NavigationNode[] = [
      { title: 'a', tooltip: 'a tip' },
      { title: 'b' },
      { title: 'c!'},
      { url: 'foo' }
    ];

    beforeEach(() => {
      navService.navigationViews.subscribe(views => view = views['sideNav']);
      backend.connectionsArray[0].mockRespond(createResponse({sideNav}));
    });

    it('should have the supplied tooltip', () => {
      expect(view[0].tooltip).toEqual('a tip');
    });

    it('should create a tooltip from title + period', () => {
      expect(view[1].tooltip).toEqual('b.');
    });

    it('should create a tooltip from title, keeping its trailing punctuation', () => {
      expect(view[2].tooltip).toEqual('c!');
    });

    it('should not create a tooltip if there is no title', () => {
      expect(view[3].tooltip).toBeUndefined();
    });
  });

  describe('currentNode', () => {
    let currentNode: CurrentNode;
    let locationService: MockLocationService;

    const topBarNodes: NavigationNode[] = [
      { url: 'features', title: 'Features', tooltip: 'tip' }
    ];
    const sideNavNodes: NavigationNode[] = [
        { title: 'a', tooltip: 'tip', children: [
          { url: 'b', title: 'b', tooltip: 'tip', children: [
            { url: 'c', title: 'c', tooltip: 'tip' },
            { url: 'd', title: 'd', tooltip: 'tip' }
          ] },
          { url: 'e', title: 'e', tooltip: 'tip' }
        ] },
        { url: 'f', title: 'f', tooltip: 'tip' }
      ];

    const navJson = {
      TopBar: topBarNodes,
      SideNav: sideNavNodes,
      __versionInfo: {}
    };

    beforeEach(() => {
      locationService = injector.get(LocationService);
      navService.currentNode.subscribe(selected => currentNode = selected);
      backend.connectionsArray[0].mockRespond(createResponse(navJson));
    });

    it('should list the side navigation node that matches the current location, and all its ancestors', () => {
      locationService.go('b');
      expect(currentNode).toEqual({
        url: 'b',
        view: 'SideNav',
        nodes: [
          sideNavNodes[0].children[0],
          sideNavNodes[0]
        ]
      });

      locationService.go('d');
      expect(currentNode).toEqual({
        url: 'd',
        view: 'SideNav',
        nodes: [
          sideNavNodes[0].children[0].children[1],
          sideNavNodes[0].children[0],
          sideNavNodes[0]
        ]
      });

      locationService.go('f');
      expect(currentNode).toEqual({
        url: 'f',
        view: 'SideNav',
        nodes: [ sideNavNodes[1] ]
      });
    });

    it('should be a TopBar selected node if the current location is a top menu node', () => {
      locationService.go('features');
      expect(currentNode).toEqual({
        url: 'features',
        view: 'TopBar',
        nodes: [ topBarNodes[0] ]
      });
    });

    it('should be a plain object if no side navigation node matches the current location', () => {
      locationService.go('g?search=moo#anchor-1');
      expect(currentNode).toEqual({
        url: 'g',
        view: '',
        nodes: []
      });
    });

    it('should ignore trailing slashes, hashes, and search params on URLs in the navmap', () => {
      const cnode: CurrentNode = {
        url: 'c',
        view: 'SideNav',
        nodes: [
          sideNavNodes[0].children[0].children[0],
          sideNavNodes[0].children[0],
          sideNavNodes[0]
        ]
      };

      locationService.go('c');
      expect(currentNode).toEqual(cnode, 'location: c');

      locationService.go('c#foo');
      expect(currentNode).toEqual(cnode, 'location: c#foo');

      locationService.go('c?foo=1');
      expect(currentNode).toEqual(cnode, 'location: c?foo=1');

      locationService.go('c#foo?bar=1&baz=2');
      expect(currentNode).toEqual(cnode, 'location: c#foo?bar=1&baz=2');
    });
  });

  describe('versionInfo', () => {
    const expectedVersionInfo = { raw: '4.0.0' } as VersionInfo;
    let versionInfo: VersionInfo;

    beforeEach(() => {
      navService.versionInfo.subscribe(info => versionInfo = info);
      backend.connectionsArray[0].mockRespond(createResponse({
        __versionInfo: expectedVersionInfo
      }));
    });

    it('should extract the version info', () => {
      expect(versionInfo).toEqual(expectedVersionInfo);
    });
  });

  describe('docVersions', () => {
    let actualDocVersions: NavigationNode[];
    let docVersions: NavigationNode[];
    let expectedDocVersions: NavigationNode[];

    beforeEach(() => {
      actualDocVersions = [];
      docVersions = [
        { title: 'v4.0.0' },
        { title: 'v2', url: 'https://v2.angular.io' }
      ];

      expectedDocVersions = docVersions.map(v => (
        {...v, ...{ tooltip: v.title + '.'}})
      );

      navService.navigationViews.subscribe(views => actualDocVersions = views['docVersions']);
    });

    it('should extract the docVersions', () => {
      backend.connectionsArray[0].mockRespond(createResponse({ docVersions }));
      expect(actualDocVersions).toEqual(expectedDocVersions);
    });
  });
});


text:
<!DOCTYPE html>

<TITLE>Manpage of certmonger_selinux</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

certmonger_selinux

Section: certmonger SELinux Policy documentation (8)
Updated: certmonger
Index
Return to Main Contents

NAME

certmonger_selinux - Security Enhanced Linux Policy for the certmonger processes

DESCRIPTION

SELinux Linux secures
certmonger

(Certificate status monitor and PKI enrollment client)
processes via flexible mandatory access
control.

FILE CONTEXTS

SELinux requires files to have an extended attribute to define the file type.

You can see the context of a file using the -Z option to lsP
Policy governs the access confined processes have to these files.
SELinux certmonger policy is very flexible allowing users to setup their certmonger processes in as secure a method as possible.

The following file types are defined for certmonger:

certmonger_exec_t

- Set files with the certmonger_exec_t type, if you want to transition an executable to the certmonger_t domain.

certmonger_initrc_exec_t

- Set files with the certmonger_initrc_exec_t type, if you want to transition an executable to the certmonger_initrc_t domain.

certmonger_var_lib_t

- Set files with the certmonger_var_lib_t type, if you want to store the certmonger files under the /var/lib directory.

certmonger_var_run_t

- Set files with the certmonger_var_run_t type, if you want to store the certmonger files under the /run directory.

Note: File context can be temporarily modified with the chcon command.  If you want to permanently change the file context you need to use the
semanage fcontext

command.  This will modify the SELinux labeling database.  You will need to use
restorecon

to apply the labels.

PROCESS TYPES

SELinux defines process types (domains) for each process running on the system

You can see the context of a process using the -Z option to psP
Policy governs the access confined processes have to files.
SELinux certmonger policy is very flexible allowing users to setup their certmonger processes in as secure a method as possible.

The following process types are defined for certmonger:

certmonger_t

Note:
semanage permissive -a PROCESS_TYPE

can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated.

COMMANDS

semanage fcontext

can also be used to manipulate default file context mappings.

semanage permissive

can also be used to manipulate whether or not a process type is permissive.

semanage module

can also be used to enable/disable/install/remove policy modules.

system-config-selinux

is a GUI tool available to customize SELinux policy settings.

AUTHOR<TT>  </TT>

This manual page was autogenerated by genman.py.

SEE ALSO

selinux(8), certmonger(8), semanage(8), restorecon(8), chcon(1)

Index

NAME

DESCRIPTION

FILE CONTEXTS

PROCESS TYPES

COMMANDS

AUTHOR<TT>  </TT>

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:24 GMT, December 24, 2015


text:
describe Colossus::Engine::MemoryMonitor do
  let(:subject) { described_class.new(4) }

  describe '#gc_ttl' do
    before(:each) do
      allow(Time).to receive(:now) { Time.local('1975', 'may') }
    end

    it 'keeps unexpired session' do
      subject.set('user_id', 'client_id', 'active')

      subject.gc_ttl
      expect(subject.client_sessions.length).to eq(1)
    end

    it 'removes expired session' do
      subject.set('user_id', 'client_id', 'active')
      allow(Time).to receive(:now) { Time.local('1975', 'jun') }

      subject.gc_ttl
      expect(subject.client_sessions.length).to eq(0)
    end

    it 'removes expired session even on multiple sessions' do
      subject.set('user_id', 'client_id', 'active')
      subject.set('user_id', 'client_id_bis', 'active')
      allow(Time).to receive(:now) { Time.local('1975', 'jun') }

      subject.gc_ttl
      expect(subject.client_sessions.length).to eq(0)
    end

    it 'removes expired session even on multiple users' do
      subject.set('user_id', 'client_id', 'active')
      subject.set('user_id_bis', 'client_id', 'active')
      allow(Time).to receive(:now) { Time.local('1975', 'jun') }

      subject.gc_ttl
      expect(subject.client_sessions.length).to eq(0)
    end

    it 'removes expired session in sessions stores' do
      subject.set('user_id', 'client_id', 'active')
      allow(Time).to receive(:now) { Time.local('1975', 'jun') }
      subject.set('user_id', 'client_id_bis', 'active')

      subject.gc_ttl
      expect(subject.client_sessions.values.first.sessions.length).to eq(1)
    end
  end

  describe '#set' do
    it 'sets the status' do
      subject.set('user_id', 'client_id', 'active')
      expect(subject.client_sessions.values.first.sessions.values.first.status).to eq('active')
    end

    it 'works with get' do
      subject.set('user_id', 'client_id', 'active')
      expect(subject.get('user_id')).to eq('user_id' => 'active')
    end

    it 'deletes the user if the only given status is disconnected' do
      subject.set('user_id', 'client_id', 'active')
      subject.set('user_id', 'client_id', 'disconnected')
      expect(subject.client_sessions.length).to eq(0)
    end

    it 'calls user_changed when a user get active' do
      obs = SpecObserver.new do |user_id, status|
        expect([user_id, status]).to eq(['user_id', 'active'])
      end
      subject.add_observer(obs)
      subject.set('user_id', 'client_id', 'active')
    end

    it 'calls user_changed when a user get disconnected' do
      subject.set('user_id', 'client_id', 'active')
      obs = SpecObserver.new do |user_id, status|
        expect([user_id, status]).to eq(['user_id', 'disconnected'])
      end
      subject.set('user_id', 'client_id', 'disconnected')
      subject.add_observer(obs)
    end

    it 'calls user_changed when a user get disconnected' do
      subject.set('user_id', 'client_id', 'active')
      obs = SpecObserver.new do |user_id, status|
        expect([user_id, status]).to eq(['user_id', 'disconnected'])
      end
      subject.set('user_id', 'client_id', 'disconnected')
      subject.add_observer(obs)
    end
  end
end


text:
require 'helper'
require 'support/navigable_collection_example'
require 'support/renderable_example'
require 'cloudapp/tui/drops'

describe CloudApp::TUI::Drops do
  let(:drops) { DropsDouble.new count: 0 }
  subject { CloudApp::TUI::Drops.new drops }

  it_behaves_like 'a navigable collection'
  it_behaves_like 'a renderable'

  describe '#each' do
    subject { CloudApp::TUI::Drops.new(drops) }

    it 'delegates to drops' do
      drops.should_receive(:each).with(no_args).and_return(:response)
      subject.each.should eq(:response)
    end
  end

  describe '#first_page' do
    let(:drops) { DropsDouble.new follow: first_page, has_link?: true }
    let(:first_page) { DropsDouble.new }
    subject { CloudApp::TUI::Drops.new(drops) }

    it 'follows the first link' do
      drops.should_receive(:follow).with('first').and_return(first_page)

      subject = CloudApp::TUI::Drops.new drops
      subject.first_page
    end

    it 'returns the first page of drops' do
      subject.first_page.should be_a(CloudApp::TUI::Drops)
    end

    context 'with no first page' do
      let(:drops) { DropsDouble.new count: 42, follow: nil, has_link?: false }

      it 'returns itself' do
        subject.first_page.should eq(subject)
      end

      it 'follows no links' do
        drops.should_not_receive(:follow)
        subject.first_page.should eq(subject)
      end
    end
  end

  describe '#previous_page' do
    let(:drops) { DropsDouble.new follow: previous_page, has_link?: true }
    let(:previous_page) { DropsDouble.new }
    subject { CloudApp::TUI::Drops.new(drops) }

    it 'follows the previous link' do
      drops.should_receive(:follow).with('previous').and_return(previous_page)

      subject = CloudApp::TUI::Drops.new drops
      subject.previous_page
    end

    it 'returns the previous page of drops' do
      subject.previous_page.should be_a(CloudApp::TUI::Drops)
    end

    context 'with no previous page' do
      let(:drops) { DropsDouble.new count: 42, follow: nil, has_link?: false }

      it 'returns itself' do
        subject.previous_page.should eq(subject)
      end

      it 'follows no links' do
        drops.should_not_receive(:follow)
        subject.previous_page.should eq(subject)
      end
    end
  end

  describe '#next_page' do
    let(:drops) { DropsDouble.new follow: next_page, has_link?: true }
    let(:next_page) { DropsDouble.new }
    subject { CloudApp::TUI::Drops.new(drops) }

    it 'follows the next link' do
      drops.should_receive(:follow).with('next').and_return(next_page)

      subject = CloudApp::TUI::Drops.new drops
      subject.next_page
    end

    it 'returns the next page of drops' do
      subject.next_page.should be_a(CloudApp::TUI::Drops)
    end

    context 'with no next page' do
      let(:drops) { DropsDouble.new has_link?: false }

      it 'returns itself' do
        subject.next_page.should eq(subject)
      end

      it 'follows no links' do
        drops.should_not_receive(:follow)
        subject.next_page.should eq(subject)
      end
    end
  end

  describe '#selection_index' do
    let(:drops) { DropsDouble.new count: 2 }

    it 'defaults to 0' do
      subject.selection_index.should eq(0)
    end

    it 'returns the given selection index' do
      subject = CloudApp::TUI::Drops.new drops, selection_index: 1
      subject.selection_index.should eq(1)
    end

    it 'maxes out at the number of drops' do
      subject = CloudApp::TUI::Drops.new drops, selection_index: 42
      subject.selection_index.should eq(1)
    end

    it 'mins out at 0' do
      subject = CloudApp::TUI::Drops.new drops, selection_index: -42
      subject.selection_index.should eq(0)
    end
  end

  describe '#selection' do
    let(:drops) { DropsDouble.new count: 42 }
    subject { CloudApp::TUI::Drops.new drops, selection_index: 2 }

    it 'returns the selection' do
      selection = :selection
      drops.should_receive(:[]).with(2).and_return(selection)
      subject.selection.should eq(selection)
    end
  end

  describe '#previous_selection' do
    let(:drops) { DropsDouble.new count: 2 }
    subject {
      CloudApp::TUI::Drops.new(drops, selection_index: 1).previous_selection
    }

    it { should be_a(CloudApp::TUI::Drops) }
    its(:selection_index) { should eq(0) }
  end

  describe '#next_selection' do
    let(:drops) { DropsDouble.new count: 2 }
    subject { CloudApp::TUI::Drops.new(drops).next_selection }

    it { should be_a(CloudApp::TUI::Drops) }
    its(:selection_index) { should eq(1) }
  end

  describe '#trash_selection' do
    let(:drops) { DropsDouble.new count: 3, selection: selection, follow: self_page }
    let(:selection) { DropDouble.new }
    let(:self_page) { DropsDouble.new count: 3 }
    subject { CloudApp::TUI::Drops.new(drops, selection_index: 1).trash_selection }

    it { should be_a(CloudApp::TUI::Drops) }
    its(:selection_index) { should eq(1) }

    it 'trashes the drop' do
      selection.should_receive(:trash).once
      subject
    end

    it 'refreshes the same page of drops' do
      drops.should_receive(:follow).with('self').once.and_return(self_page)
      subject
    end
  end

  describe '#recover_selection' do
    let(:drops) { DropsDouble.new count: 3, selection: selection, follow: self_page }
    let(:selection) { DropDouble.new }
    let(:self_page) { DropsDouble.new count: 3 }
    subject { CloudApp::TUI::Drops.new(drops, selection_index: 1).recover_selection }

    it { should be_a(CloudApp::TUI::Drops) }
    its(:selection_index) { should eq(1) }

    it 'recovers the drop' do
      selection.should_receive(:recover).once
      subject
    end

    it 'refreshes the same page of drops' do
      drops.should_receive(:follow).with('self').once.and_return(self_page)
      subject
    end
  end

  describe '#toggle_selection_privacy' do
    let(:drops) { DropsDouble.new count: 3, selection: selection, follow: self_page }
    let(:selection) { DropDouble.new }
    let(:self_page) { DropsDouble.new count: 3 }
    subject {
      CloudApp::TUI::Drops.new(drops, selection_index: 1).
        toggle_selection_privacy
    }

    it { should be_a(CloudApp::TUI::Drops) }
    its(:selection_index) { should eq(1) }

    it "togglees the drop's privacy" do
      selection.should_receive(:toggle_privacy).once
      subject
    end

    it 'refreshes the same page of drops' do
      drops.should_receive(:follow).with('self').once.and_return(self_page)
      subject
    end
  end
end

class DropsDouble
  attr_reader :count
  def has_link?(link) @has_link  end
  def follow(link)    @follow    end
  def [](index)       @selection end

  def initialize(options = {})
    @count     = options.fetch :count,     0
    @follow    = options.fetch :follow,    nil
    @has_link  = options.fetch :has_link?, nil
    @selection = options.fetch :selection, nil
  end
end

class DropDouble
  def trash() end
  def recover() end
  def toggle_privacy() end
end

# I like the idea of asserting that my double adheres to the defined interface,
# but I'm not too thrilled that this particular interface is outside of my
# control. It's the response from CloudApp::Service#drops.
describe DropsDouble do
  it { should respond_to(:count) }

  it 'responds to #follow' do
    subject.should respond_to(:follow)
    -> { subject.follow('link') }.should_not raise_error(ArgumentError)
  end

  it 'responds to #has_link?' do
    subject.should respond_to(:has_link?)
    -> { subject.has_link?('link') }.should_not raise_error(ArgumentError)
  end

  it 'responds to #[]' do
    subject.should respond_to(:[])
  end
end

describe DropDouble do
  it { should respond_to(:trash) }
  it { should respond_to(:recover) }
  it { should respond_to(:toggle_privacy) }
end


text:
BMI Calculator Application
==========================

Author : Ahmed Mohamed

# To run the application

	ring BMI_Calculator.ring

# Screen Shot

![bmicalculator](https://raw.githubusercontent.com/ring-lang/ring/master/applications/bmicalculator/BMI.png)


text:
package org.apache.logging.log4j.core.config;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAliases;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.status.StatusLogger;

/**
 * An Appender reference.
 */
@Plugin(name = "AppenderRef", category = Node.CATEGORY, printObject = true)
@PluginAliases("appender-ref")
public final class AppenderRef {
    private static final Logger LOGGER = StatusLogger.getLogger();

    private final String ref;
    private final Level level;
    private final Filter filter;

    private AppenderRef(final String ref, final Level level, final Filter filter) {
        this.ref = ref;
        this.level = level;
        this.filter = filter;
    }

    public String getRef() {
        return ref;
    }

    public Level getLevel() {
        return level;
    }

    public Filter getFilter() {
        return filter;
    }

    @Override
    public String toString() {
        return ref;
    }

    /**
     * Create an Appender reference.
     * @param ref The name of the Appender.
     * @param level The Level to filter against.
     * @param filter The filter(s) to use.
     * @return The name of the Appender.
     */
    @PluginFactory
    public static AppenderRef createAppenderRef(
            @PluginAttribute("ref") final String ref,
            @PluginAttribute("level") final Level level,
            @PluginElement("Filter") final Filter filter) {

        if (ref == null) {
            LOGGER.error("Appender references must contain a reference");
            return null;
        }
        return new AppenderRef(ref, level, filter);
    }
}


text:
n, d = map(
    int,
    input().split()
)

numbers = list(
    map(
        int,
        input().split()
    )
)

numbers_map = {
    number: True
    for number
    in numbers
}

total_triplets = 0

for number in numbers:
    if number + d in numbers_map and number + 2 * d in numbers_map:
        total_triplets += 1

print(total_triplets)


text:
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#ifndef SELECTEV_H
#define SELECTEV_H 1

int SProcXSelectExtensionEvent(ClientPtr	/* client */
    );

int ProcXSelectExtensionEvent(ClientPtr	/* client */
    );

#endif /* SELECTEV_H */


text:
title: Mémoires et soutenances
---

## Présentation du mémoire et soutenance – Consignes générales.

1.  Après deux années de formation, et si vous avez obtenu au moins 14/20 à l'examen de second niveau, vous aurez accès à la rédaction du mémoire qui seul vous donnera droit à un diplôme de fin d'études [(cf. Conception du diplôme)](/le-cetl/le-diplome).
    Si vous ne souhaitez pas faire le mémoire, à défaut du diplôme vous recevrez une attestation mentionnant vos résultats pour les deux niveaux accomplis et réussis.

2.  Pour la rédaction du mémoire vous disposez de trois années. Au-delà de ce délai, un supplément de 500 euros sera exigé par année de dépassement.

3.  Vous devrez impérativement travailler sous la houlette d'un directeur de mémoire, qui sera un traducteur littéraire professionnel reconnu, de préférence enseignant au CETL. Vous pourrez choisir vous-même votre patron de mémoire, mais ce choix devra être avalisé par la direction du CETL.

4.  Pour réussir le mémoire, il faut obtenir au moins 14/20. Pour que le travail soit publiable, il faut obtenir au moins 17/20. Si vous n'avez pas 17 : vous pourrez revoir et améliorer votre traduction en suivant les consignes du jury.
    Dans ce cas, l'alternative est donc :

- Soit vous réclamez votre diplôme juste après la soutenance, avec la note de 14 au moins qui y sera mentionnée.

- Soit vous décidez d'améliorer la première version et d'attendre d'avoir au moins 17 pour obtenir le diplôme.

5.  Si vous n'avez pas obtenu 14/20 au terme de la soutenance, vous avez droit à une "seconde chance". Vous devrez alors corriger le mémoire dans le sens indiqué par le jury et en tenant compte très précisément de ses remarques et commentaires (souvent notés dans le travail). Le travail revu et remanié sera envoyé sous forme électronique aux membres du jury. Il n'y aura pas de seconde soutenance.
    Il n'y aura pas de troisième chance…

6.  Le mémoire doit être remis en 5 exemplaires. Sa structure doit répondre à des normes précises et doit comprendre impérativement les parties mentionnées dans le règlement. Je vous rappelle que le mémoire est conçu comme un dossier destiné à convaincre un éditeur potentiel du bien-fondé de la publication de la traduction.

7.  La soutenance se fait devant un jury composé du directeur de mémoire, d'un autre traducteur spécialiste de la même langue de départ, de la directrice du CETL et d'un critique littéraire, représentant de maisons d'édition. Cette soutenance se déroule généralement à Paris, au Centre National du Livre (CNL), ou à la Sorbonne nouvelle, ou dans une autre ville selon le cas (dans un collège de traducteur ou dans une université). Les frais de déplacement ou de séjour de l'étudiant sont à la charge du candidat. Le CETL prend en charge les honoraires du jury, et leurs frais de déplacement et/ou de séjour. Les modalités de déroulement de la soutenance vous seront communiquées en temps utiles.

## Structure du mémoire

1.  Table des matières

2.  Introduction :
    Présentation de l'auteur, évocation de son (éventuel) succès, dans son pays et/ou à l'étranger (joindre de préférence des articles de presse dans les annexes).
    Résumé de l'ouvrage : le situer dans son contexte propre et ses éventuelles filiations, en faire une brève analyse et évoquer les raisons d'un accueil favorable dans la culture de la langue cible.

3.  Traduction : le texte original doit figurer sur la page de gauche et la traduction (correspondant exactement) sur la page de droite, une soixantaine de pages au moins de 1500 signes.

4.  Commentaires de traduction : le chapitre sans doute le plus important, après la traduction elle-même. Il doit faire état de vos réflexions pour ainsi dire « traductologiques » sur les difficultés générales et ponctuelles rencontrées lors de votre travail. Il proposera donc une analyse globale des difficultés inhérentes au texte lui-même (par exemple au contexte d'écriture, au registre, au style, au lexique etc.) et passera en revue les difficultés ponctuelles et vos choix justifiés.
    Attention : cette partie ne doit nullement parler des difficultés de linguistique contrastive générale (passage d'une langue à l'autre hors contexte), mais des difficultés spécifiques du texte et de l'auteur.

5.  Bibliographie : elle mentionnera tous les ouvrages du même auteur, y compris leurs traductions existantes, ainsi que tous les manuels ou sites Internet consultés pour le travail.

6.  Annexes (articles de presse etc.), facultatif.

## Quelques exemples de mémoires et de soutenances parmi une centaine

### ANGLAIS au français

**Carine Bratzlawsky**

Traduction de trente-quatre lettres (1907-1927) de Virginia Woolf à sa sœur Vanessa Bell Selected diaries, Vintage Classics, tiré de la correspondance en six volumes, The Hogarth Press/Chatto & Windus, 1975-1980 ).

Directrice de mémoire : Anne-Marie Smith di Biasio

Soutenance au Centre National du Livre (CNL) Paris.

Note obtenue : **87/100**

---

**Elisabeth Lowys**

Traduction de quatre nouvelles tirées du recueil intitulé Other People We Married, de Emma Straub
(Five Chapters Books, 2011, New York)

Directeur de mémoire : Daniel Lemoine

Soutenance au Centre National du Livre (CNL) Paris

Note obtenue : **98/100 (exceptionnel !)**

---

**Yveline Pailhoux**

Traduction de Sept nouvelles de Sara Baume, parues dans divers journaux et magazines entre 2011 et 2016

Directrice du mémoire : Christine Raguet

Soutenance au Collège des traducteurs de Seneffe, Belgique

Note obtenue : **86/100**

### ESPAGNOL au français

**Annie Vignal**
Traduction des chapitres I, II et X du roman d'Oscar Collazos « Rancoeurs » (« Rancor », Seix Barral Biblioteca Breve, Tercera Edicion, 2006)

Directeur de mémoire : Albert Bensoussan

Soutenance à l'Institut anglophone, Université Sorbonne nouvelle, Paris

Note obtenue : **85/100**

---

**Cristina Lopez Devaux**

Montaner 18 (Chapitres I, II et III), José Antonio Garriga Vela.

Directeur de mémoire : Georges Tyras

Soutenance à l'Institut anglophone, Université Sorbonne nouvelle, Paris

Note obtenue : **90/100**

### ALLEMAND au français

**Delphine Bouillard**

Anmut und Gnade (p. 10 à 72) Wolfgang Schlüter

Directeur de mémoire : Marc de Launay

Soutenance à l'Institut anglophone, Université Sorbonne nouvelle, Paris

Note obtenue : **90/100**

---

**Isabelle Raison**

Fremde Signale, de Katarina FAber (Bilgerverlag, 2008)

Directrice de mémoire : Marie-Claude Auger

Soutenance au Centre national du livre (CNL) Paris

Note obtenue : **82/100**

### SUEDOIS au français

**Amanda Belassami-Sideris**

Min Mormor Hälsar och Säger Förlat, traduction des chapitres 1 à 6, Fredrik Backman –Ed. Forum 2013

Directrice de mémoire : Anna Gibson

Soutenance au Centre national du livre (CNL) Paris

Note obtenue : **70/100**

### ITALIEN au français

**Marylène di Stefano**

L'Abusivo, Antonio Franchini, Marsilio 2001, traduction des pages 7 à 70

Directeur de mémoire : Vincent Raynaud

Soutenance au Centre National du Livre( CNL) Paris

Note obtenue : **75/100**

### RUSSE au français

**Fanchon Deligne**

Présentation et traduction de deux textes autobiographiques de Vladislav Khodassevtich : Prime Enfance (1933) et Le Couloir blanc (1925)

Directeur de mémoire : Anne-Marie Tatsis-Botton

Soutenance au Collège des traducteurs d'Arles (CITL)

Note obtenue : **94/100**

### FRANÇAIS au bosnien

**Almira Drino**

Sélection de quatorze contes de Maurice Carême

Directeur de mémoire : Radivoje Konstantinovic

Soutenance à l'Université de Belgrade, Faculté des lettres romanes.

Note obtenue : **95/100**

---

**Bisera Cero**

Les Cavaliers, Joseph Kessel (pages 13 à 88)

Directrice de mémoire : Tijana Popovic

Soutenance à l'ISTI, Bruxelles

Note obtenue : **95/100**

---

**Azra Pita Parente**

Oscar et la dame rose – Monsieur Ibrahim et les fleurs du Coran (Eric Emmanuel Shmitt)

Directeurs de mémoire : Aleksander Grujicic et Radivoje Konstantinovic

Soutenance par visioconférence : janvier 2019

Note obtenue : **95/100** avec les félicitations du jury

---

[Voir la liste des soutenances à venir](/events)


text:
require 'active_admin'
require 'omniauth-facebook'
require 'omniauth-twitter'
require 'koala'
require 'twitter'

module RailsBootstrap
  #include ActiveAdmin::Admin
  class Engine < Rails::Engine
    isolate_namespace RailsBootstrap
  #  paths["app/views"] << "/app/views/active_admin"
  end
end


text:
<!DOCTYPE html>
<html>
<!-- Hiya! Nice to see you here! -->

<head>
    <title>NitroGuy</title>

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

    <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
    <link rel="manifest" href="favicon/site.webmanifest">

    <style>
        button {
            font-size: 1vw;
            padding: 1vw;
        }
    </style>
    <script src="../js/FileSaver.js"></script>
    <script src="../js/song_data.js"></script>
    <script>
        const content = ["Collection"]
        const fileName = "the_sass_song_data.csv"

        for (let field in fieldNames)
        {
            content.push(",")
            content.push(fieldNames[field])
        }

        for (let i = 0; i < songData.length; i++)
        {
            for (let song of songData[i])
            {
                content.push("\n")
                content.push(collectionNames[i])
                for (let field in fieldNames)
                {
                    content.push(",")
                    content.push(song[field])
                }
            }
        }

        const blob = new Blob([content.join("")], {
            type: "text/csv;charset=utf-8"
        })

        saveAs(blob, fileName)
    </script>
</head>

<body>
    <button onclick="saveAs(blob, fileName)">Click here if download does not automatically start</button>
</body>

</html>