text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "services/network/public/cpp/server/http_server.h"

#include <algorithm>
#include <memory>
#include <utility>
#include <vector>

#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/cxx17_backports.h"
#include "base/format_macros.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_response_headers.h"
#include "net/log/net_log_source.h"
#include "net/test/gtest_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_test_util.h"
#include "net/websockets/websocket_frame.h"
#include "services/network/public/cpp/server/http_connection.h"
#include "services/network/public/cpp/server/http_server_request_info.h"
#include "services/network/socket_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using net::test::IsOk;

namespace {

class TestHttpClient {
 public:
  TestHttpClient() : factory_(nullptr, &url_request_context_) {}

  int ConnectAndWait(const net::IPEndPoint& address) {
    net::AddressList addresses(address);
    base::RunLoop run_loop;
    int net_error = net::ERR_FAILED;
    factory_.CreateTCPConnectedSocket(
        absl::nullopt /* local address */, addresses,
        nullptr /* tcp_connected_socket_options */,
        TRAFFIC_ANNOTATION_FOR_TESTS, socket_.BindNewPipeAndPassReceiver(),
        mojo::NullRemote() /* observer */,
        base::BindOnce(
            [](base::RunLoop* run_loop, int* result_out,
               mojo::ScopedDataPipeConsumerHandle* receive_pipe_handle_out,
               mojo::ScopedDataPipeProducerHandle* send_pipe_handle_out,
               int result, const absl::optional<net::IPEndPoint>& local_addr,
               const absl::optional<net::IPEndPoint>& peer_addr,
               mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
               mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
              *receive_pipe_handle_out = std::move(receive_pipe_handle);
              *send_pipe_handle_out = std::move(send_pipe_handle);
              *result_out = result;
              run_loop->Quit();
            },
            base::Unretained(&run_loop), base::Unretained(&net_error),
            &receive_pipe_handle_, &send_pipe_handle_));
    run_loop.Run();
    return net_error;
  }

  void Send(const std::string& message) {
    size_t index = 0;
    uint32_t write_size = message.size();
    while (write_size > 0) {
      base::RunLoop().RunUntilIdle();
      MojoResult result = send_pipe_handle_->WriteData(
          message.data() + index, &write_size, MOJO_WRITE_DATA_FLAG_NONE);
      if (result == MOJO_RESULT_SHOULD_WAIT)
        continue;
      if (result != MOJO_RESULT_OK)
        return;
      index += write_size;
      write_size = message.size() - index;
    }
  }

  bool Read(std::string* data, size_t num_bytes) {
    while (data->size() < num_bytes) {
      base::RunLoop().RunUntilIdle();
      std::vector<char> buffer(num_bytes);
      uint32_t read_size = num_bytes;
      MojoResult result = receive_pipe_handle_->ReadData(
          buffer.data(), &read_size, MOJO_READ_DATA_FLAG_NONE);
      if (result == MOJO_RESULT_SHOULD_WAIT)
        continue;
      if (result != MOJO_RESULT_OK)
        return false;
      data->append(buffer.data(), read_size);
    }
    return true;
  }

  bool ReadResponse(std::string* message) {
    if (!Read(message, 1))
      return false;
    while (!IsCompleteResponse(*message)) {
      std::string chunk;
      if (!Read(&chunk, 1))
        return false;
      message->append(chunk);
    }
    return true;
  }

  void ExpectUsedThenDisconnectedWithNoData() {
    // Check that the socket was closed when the server disconnected. Verify
    // that the socket was closed by checking that a Read() fails.
    std::string response;
    ASSERT_FALSE(Read(&response, 1u));
    ASSERT_TRUE(response.empty());
  }

  void Close() { socket_.reset(); }

 private:
  bool IsCompleteResponse(const std::string& response) {
    // Check end of headers first.
    size_t end_of_headers =
        net::HttpUtil::LocateEndOfHeaders(response.data(), response.size());
    if (end_of_headers == std::string::npos)
      return false;

    // Return true if response has data equal to or more than content length.
    int64_t body_size = static_cast<int64_t>(response.size()) - end_of_headers;
    DCHECK_LE(0, body_size);
    auto headers = base::MakeRefCounted<net::HttpResponseHeaders>(
        net::HttpUtil::AssembleRawHeaders(
            base::StringPiece(response.data(), end_of_headers)));
    return body_size >= headers->GetContentLength();
  }

  net::TestURLRequestContext url_request_context_;
  network::SocketFactory factory_;
  scoped_refptr<net::IOBufferWithSize> read_buffer_;
  scoped_refptr<net::DrainableIOBuffer> write_buffer_;

  mojo::ScopedDataPipeConsumerHandle receive_pipe_handle_;
  mojo::ScopedDataPipeProducerHandle send_pipe_handle_;

  mojo::Remote<network::mojom::TCPConnectedSocket> socket_;
};

}  // namespace

namespace network {

namespace server {

class HttpServerTest : public testing::Test, public HttpServer::Delegate {
 public:
  HttpServerTest()
      : task_environment_(base::test::TaskEnvironment::MainThreadType::IO),
        quit_after_request_count_(0),
        quit_on_close_connection_(-1),
        factory_(nullptr, &url_request_context_) {}

  void SetUp() override {
    int net_error = net::ERR_FAILED;
    base::RunLoop run_loop;
    factory_.CreateTCPServerSocket(
        net::IPEndPoint(net::IPAddress::IPv6Localhost(), 0), 1 /* backlog */,
        TRAFFIC_ANNOTATION_FOR_TESTS,
        server_socket_.InitWithNewPipeAndPassReceiver(),
        base::BindOnce(
            [](base::RunLoop* run_loop, int* result_out,
               net::IPEndPoint* local_addr_out, int result,
               const absl::optional<net::IPEndPoint>& local_addr) {
              *result_out = result;
              if (local_addr)
                *local_addr_out = local_addr.value();
              run_loop->Quit();
            },
            base::Unretained(&run_loop), base::Unretained(&net_error),
            base::Unretained(&server_address_)));
    run_loop.Run();
    EXPECT_EQ(net::OK, net_error);

    server_ = std::make_unique<HttpServer>(std::move(server_socket_), this);
  }

  void OnConnect(int connection_id) override {
    DCHECK(connection_map_.find(connection_id) == connection_map_.end());
    connection_map_[connection_id] = true;
    // This is set in CreateConnection(), which must be invoked once for every
    // expected connection.
    quit_on_create_loop_->Quit();
  }

  void OnHttpRequest(int connection_id,
                     const HttpServerRequestInfo& info) override {
    requests_.push_back(std::make_pair(info, connection_id));
    if (requests_.size() == quit_after_request_count_) {
      run_loop_quit_func_.Run();
    }
  }

  void OnWebSocketRequest(int connection_id,
                          const HttpServerRequestInfo& info) override {
    NOTREACHED();
  }

  void OnWebSocketMessage(int connection_id, std::string data) override {
    NOTREACHED();
  }

  void OnClose(int connection_id) override {
    DCHECK(connection_map_.find(connection_id) != connection_map_.end());
    connection_map_[connection_id] = false;
    if (connection_id == quit_on_close_connection_)
      run_loop_quit_func_.Run();
  }

  // This waits until the _total_ requests received is equal to |count|.  This
  // means that, after waiting for one request, in order to wait for a single
  // additional request, |count| must be 2, not 1.
  void RunUntilRequestsReceived(size_t count) {
    quit_after_request_count_ = count;
    if (requests_.size() == count)
      return;

    base::RunLoop run_loop;
    base::AutoReset<base::RepeatingClosure> run_loop_quit_func(
        &run_loop_quit_func_, run_loop.QuitClosure());
    run_loop.Run();

    ASSERT_EQ(requests_.size(), count);
  }

  // Connections should only be created using this method, which waits until
  // both the server and the client have received the connected socket over
  // Mojo.
  void CreateConnection(TestHttpClient* client) {
    ASSERT_FALSE(quit_on_create_loop_);
    quit_on_create_loop_ = std::make_unique<base::RunLoop>();
    EXPECT_THAT(client->ConnectAndWait(server_address_), IsOk());
    quit_on_create_loop_->Run();
    quit_on_create_loop_.reset();
  }

  void RunUntilConnectionIdClosed(int connection_id) {
    quit_on_close_connection_ = connection_id;
    auto iter = connection_map_.find(connection_id);
    if (iter != connection_map_.end() && !iter->second) {
      // Already disconnected.
      return;
    }

    base::RunLoop run_loop;
    base::AutoReset<base::RepeatingClosure> run_loop_quit_func(
        &run_loop_quit_func_, run_loop.QuitClosure());
    run_loop.Run();

    iter = connection_map_.find(connection_id);
    ASSERT_TRUE(iter != connection_map_.end());
    ASSERT_FALSE(iter->second);
  }

  HttpServerRequestInfo GetRequest(size_t request_index) {
    return requests_[request_index].first;
  }

  size_t num_requests() const { return requests_.size(); }

  int GetConnectionId(size_t request_index) {
    return requests_[request_index].second;
  }

  HttpConnection* FindConnection(int connection_id) {
    return server_->FindConnection(connection_id);
  }

  std::unordered_map<int, bool>& connection_map() { return connection_map_; }

 protected:
  std::unique_ptr<HttpServer> server_;
  net::IPEndPoint server_address_;
  base::RepeatingClosure run_loop_quit_func_;
  std::vector<std::pair<HttpServerRequestInfo, int>> requests_;
  std::unordered_map<int /* connection_id */, bool /* connected */>
      connection_map_;

 private:
  base::test::TaskEnvironment task_environment_;
  size_t quit_after_request_count_;
  std::unique_ptr<base::RunLoop> quit_on_create_loop_;
  int quit_on_close_connection_;

  net::TestURLRequestContext url_request_context_;
  SocketFactory factory_;
  mojo::PendingRemote<mojom::TCPServerSocket> server_socket_;
};

class WebSocketTest : public HttpServerTest {
  void OnHttpRequest(int connection_id,
                     const HttpServerRequestInfo& info) override {
    NOTREACHED();
  }

  void OnWebSocketRequest(
      int connection_id,
      const network::server::HttpServerRequestInfo& info) override {
    HttpServerTest::OnHttpRequest(connection_id, info);
  }

  void OnWebSocketMessage(int connection_id, std::string data) override {}
};

class WebSocketAcceptingTest : public WebSocketTest {
 public:
  void OnWebSocketRequest(int connection_id,
                          const HttpServerRequestInfo& info) override {
    HttpServerTest::OnHttpRequest(connection_id, info);
    server_->AcceptWebSocket(connection_id, info, TRAFFIC_ANNOTATION_FOR_TESTS);
  }

  void OnWebSocketMessage(int connection_id, std::string data) override {
    message_ = data;
    if (run_loop_) {
      run_loop_->Quit();
    }
  }

  const std::string& GetMessage() {
    run_loop_ = std::make_unique<base::RunLoop>();
    run_loop_->Run();
    run_loop_.reset();
    return message_;
  }

 private:
  std::string message_;
  std::unique_ptr<base::RunLoop> run_loop_;
};

std::string EncodeFrame(std::string message,
                        net::WebSocketFrameHeader::OpCodeEnum op_code,
                        bool mask,
                        bool finish) {
  net::WebSocketFrameHeader header(op_code);
  header.final = finish;
  header.masked = mask;
  header.payload_length = message.size();
  const int header_size = GetWebSocketFrameHeaderSize(header);
  std::string frame_header;
  frame_header.resize(header_size);
  if (mask) {
    net::WebSocketMaskingKey masking_key = net::GenerateWebSocketMaskingKey();
    WriteWebSocketFrameHeader(header, &masking_key, &frame_header[0],
                              header_size);
    MaskWebSocketFramePayload(masking_key, 0, &message[0], message.size());
  } else {
    WriteWebSocketFrameHeader(header, nullptr, &frame_header[0], header_size);
  }
  return frame_header + message;
}

TEST_F(HttpServerTest, SetNonexistingConnectionBuffer) {
  EXPECT_FALSE(server_->SetReceiveBufferSize(1, 1000));
  EXPECT_FALSE(server_->SetSendBufferSize(1, 1000));
}

TEST_F(HttpServerTest, Request) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send("GET /test HTTP/1.1\r\n\r\n");

  int connection_id = connection_map_.begin()->first;
  HttpConnection* conn = FindConnection(connection_id);
  EXPECT_TRUE(server_->SetReceiveBufferSize(connection_id, 5u * 1024 * 1024));
  EXPECT_TRUE(server_->SetSendBufferSize(connection_id, 5u * 1024 * 1024));
  EXPECT_EQ(conn->ReadBufferSize(), 5u * 1024u * 1024u);
  EXPECT_EQ(conn->WriteBufferSize(), 5u * 1024u * 1024u);

  RunUntilRequestsReceived(1);
  ASSERT_EQ("GET", GetRequest(0).method);
  ASSERT_EQ("/test", GetRequest(0).path);
  ASSERT_EQ("", GetRequest(0).data);
  ASSERT_EQ(0u, GetRequest(0).headers.size());
  ASSERT_EQ(GetRequest(0).peer.address(), net::IPAddress::IPv6Localhost());
}

TEST_F(HttpServerTest, RequestBrokenTermination) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send("GET /test HTTP/1.1\r\n\r)");
  RunUntilConnectionIdClosed(1);
  EXPECT_EQ(0u, num_requests());
  client.ExpectUsedThenDisconnectedWithNoData();
}

TEST_F(HttpServerTest, RequestWithHeaders) {
  TestHttpClient client;
  CreateConnection(&client);
  const char* const kHeaders[][3] = {
      {"Header", ": ", "1"},
      {"HeaderWithNoWhitespace", ":", "1"},
      {"HeaderWithWhitespace", "   :  \t   ", "1 1 1 \t  "},
      {"HeaderWithColon", ": ", "1:1"},
      {"EmptyHeader", ":", ""},
      {"EmptyHeaderWithWhitespace", ":  \t  ", ""},
      {"HeaderWithNonASCII", ":  ", "\xf7"},
  };
  std::string headers;
  for (size_t i = 0; i < base::size(kHeaders); ++i) {
    headers +=
        std::string(kHeaders[i][0]) + kHeaders[i][1] + kHeaders[i][2] + "\r\n";
  }

  client.Send("GET /test HTTP/1.1\r\n" + headers + "\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_EQ("", GetRequest(0).data);

  for (size_t i = 0; i < base::size(kHeaders); ++i) {
    std::string field = base::ToLowerASCII(std::string(kHeaders[i][0]));
    std::string value = kHeaders[i][2];
    ASSERT_EQ(1u, GetRequest(0).headers.count(field)) << field;
    ASSERT_EQ(value, GetRequest(0).headers[field]) << kHeaders[i][0];
  }
}

TEST_F(HttpServerTest, RequestWithDuplicateHeaders) {
  TestHttpClient client;
  CreateConnection(&client);
  const char* const kHeaders[][3] = {
      {"FirstHeader", ": ", "1"},  {"DuplicateHeader", ": ", "2"},
      {"MiddleHeader", ": ", "3"}, {"DuplicateHeader", ": ", "4"},
      {"LastHeader", ": ", "5"},
  };
  std::string headers;
  for (size_t i = 0; i < base::size(kHeaders); ++i) {
    headers +=
        std::string(kHeaders[i][0]) + kHeaders[i][1] + kHeaders[i][2] + "\r\n";
  }

  client.Send("GET /test HTTP/1.1\r\n" + headers + "\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_EQ("", GetRequest(0).data);

  for (size_t i = 0; i < base::size(kHeaders); ++i) {
    std::string field = base::ToLowerASCII(std::string(kHeaders[i][0]));
    std::string value = (field == "duplicateheader") ? "2,4" : kHeaders[i][2];
    ASSERT_EQ(1u, GetRequest(0).headers.count(field)) << field;
    ASSERT_EQ(value, GetRequest(0).headers[field]) << kHeaders[i][0];
  }
}

TEST_F(HttpServerTest, HasHeaderValueTest) {
  TestHttpClient client;
  CreateConnection(&client);
  const char* const kHeaders[] = {
      "Header: Abcd",
      "HeaderWithNoWhitespace:E",
      "HeaderWithWhitespace   :  \t   f \t  ",
      "DuplicateHeader: g",
      "HeaderWithComma: h, i ,j",
      "DuplicateHeader: k",
      "EmptyHeader:",
      "EmptyHeaderWithWhitespace:  \t  ",
      "HeaderWithNonASCII:  \xf7",
  };
  std::string headers;
  for (size_t i = 0; i < base::size(kHeaders); ++i) {
    headers += std::string(kHeaders[i]) + "\r\n";
  }

  client.Send("GET /test HTTP/1.1\r\n" + headers + "\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_EQ("", GetRequest(0).data);

  ASSERT_TRUE(GetRequest(0).HasHeaderValue("header", "abcd"));
  ASSERT_FALSE(GetRequest(0).HasHeaderValue("header", "bc"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithnowhitespace", "e"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithwhitespace", "f"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("duplicateheader", "g"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithcomma", "h"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithcomma", "i"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithcomma", "j"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("duplicateheader", "k"));
  ASSERT_FALSE(GetRequest(0).HasHeaderValue("emptyheader", "x"));
  ASSERT_FALSE(GetRequest(0).HasHeaderValue("emptyheaderwithwhitespace", "x"));
  ASSERT_TRUE(GetRequest(0).HasHeaderValue("headerwithnonascii", "\xf7"));
}

TEST_F(HttpServerTest, RequestWithBody) {
  TestHttpClient client;
  CreateConnection(&client);
  std::string body = "a" + std::string(1 << 10, 'b') + "c";
  client.Send(
      base::StringPrintf("GET /test HTTP/1.1\r\n"
                         "SomeHeader: 1\r\n"
                         "Content-Length: %" PRIuS "\r\n\r\n%s",
                         body.length(), body.c_str()));
  RunUntilRequestsReceived(1);
  ASSERT_EQ(2u, GetRequest(0).headers.size());
  ASSERT_EQ(body.length(), GetRequest(0).data.length());
  ASSERT_EQ('a', body[0]);
  ASSERT_EQ('c', *body.rbegin());
}

// Tests that |HttpServer::HandleReadResult| will ignore Upgrade header if value
// is not WebSocket.
TEST_F(HttpServerTest, UpgradeIgnored) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: h2c\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "\r\n");
  RunUntilRequestsReceived(1);
}

// Tests that |HttpServer:OnReadable()| will notice the closure of the connected
// socket and not try to read from an invalid pipe.
TEST_F(WebSocketTest, PipeClosed) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n"
      "\r\n");
  RunUntilRequestsReceived(1);
  client.Close();
  RunUntilConnectionIdClosed(1);
}

TEST_F(WebSocketTest, RequestWebSocket) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n"
      "\r\n");
  RunUntilRequestsReceived(1);
}

TEST_F(WebSocketTest, RequestWebSocketTrailingJunk) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n"
      "\r\nHello? Anyone");
  RunUntilConnectionIdClosed(1);
  client.ExpectUsedThenDisconnectedWithNoData();
}

TEST_F(WebSocketAcceptingTest, SendPingFrameWithNoMessage) {
  TestHttpClient client;
  CreateConnection(&client);
  std::string response;
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_TRUE(client.ReadResponse(&response));
  const std::string message = "";
  const std::string ping_frame =
      EncodeFrame(message, net::WebSocketFrameHeader::OpCodeEnum::kOpCodePing,
                  /* mask= */ true, /* finish= */ true);
  const std::string pong_frame =
      EncodeFrame(message, net::WebSocketFrameHeader::OpCodeEnum::kOpCodePong,
                  /* mask= */ false, /* finish= */ true);
  client.Send(ping_frame);
  response.clear();
  ASSERT_TRUE(client.Read(&response, pong_frame.length()));
  EXPECT_EQ(response, pong_frame);
}

TEST_F(WebSocketAcceptingTest, SendPingFrameWithMessage) {
  TestHttpClient client;
  CreateConnection(&client);
  std::string response;
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_TRUE(client.ReadResponse(&response));
  const std::string message = "hello";
  const std::string ping_frame =
      EncodeFrame(message, net::WebSocketFrameHeader::OpCodeEnum::kOpCodePing,
                  /* mask= */ true, /* finish= */ true);
  const std::string pong_frame =
      EncodeFrame(message, net::WebSocketFrameHeader::OpCodeEnum::kOpCodePong,
                  /* mask= */ false, /* finish= */ true);
  client.Send(ping_frame);
  response.clear();
  ASSERT_TRUE(client.Read(&response, pong_frame.length()));
  EXPECT_EQ(response, pong_frame);
}

TEST_F(WebSocketAcceptingTest, SendPongFrame) {
  TestHttpClient client;
  CreateConnection(&client);
  std::string response;
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_TRUE(client.ReadResponse(&response));
  const std::string ping_frame = EncodeFrame(
      /* message= */ "", net::WebSocketFrameHeader::OpCodeEnum::kOpCodePing,
      /* mask= */ true, /* finish= */ true);
  const std::string pong_frame_send = EncodeFrame(
      /* message= */ "", net::WebSocketFrameHeader::OpCodeEnum::kOpCodePong,
      /* mask= */ true, /* finish= */ true);
  const std::string pong_frame_receive = EncodeFrame(
      /* message= */ "", net::WebSocketFrameHeader::OpCodeEnum::kOpCodePong,
      /* mask= */ false, /* finish= */ true);
  client.Send(pong_frame_send);
  client.Send(ping_frame);
  response.clear();
  ASSERT_TRUE(client.Read(&response, pong_frame_receive.length()));
  EXPECT_EQ(response, pong_frame_receive);
}

TEST_F(WebSocketAcceptingTest, SendLongTextFrame) {
  TestHttpClient client;
  CreateConnection(&client);
  std::string response;
  client.Send(
      "GET /test HTTP/1.1\r\n"
      "Upgrade: WebSocket\r\n"
      "Connection: SomethingElse, Upgrade\r\n"
      "Sec-WebSocket-Version: 8\r\n"
      "Sec-WebSocket-Key: key\r\n\r\n");
  RunUntilRequestsReceived(1);
  ASSERT_TRUE(client.ReadResponse(&response));
  constexpr int kFrameSize = 100000;
  const std::string text_frame(kFrameSize, 'a');
  const std::string continuation_frame(kFrameSize, 'b');
  const std::string text_encoded_frame = EncodeFrame(
      text_frame, net::WebSocketFrameHeader::OpCodeEnum::kOpCodeText,
      /* mask= */ true,
      /* finish= */ false);
  const std::string continuation_encoded_frame =
      EncodeFrame(continuation_frame,
                  net::WebSocketFrameHeader::OpCodeEnum::kOpCodeContinuation,
                  /* mask= */ true, /* finish= */ true);
  client.Send(text_encoded_frame);
  client.Send(continuation_encoded_frame);
  std::string received_message = GetMessage();
  EXPECT_EQ(received_message, text_frame + continuation_frame);
}

TEST_F(HttpServerTest, Send200) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send("GET /test HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(1);
  server_->Send200(GetConnectionId(0), "Response!", "text/plain",
                   TRAFFIC_ANNOTATION_FOR_TESTS);

  std::string response;
  ASSERT_TRUE(client.ReadResponse(&response));
  ASSERT_TRUE(base::StartsWith(response, "HTTP/1.1 200 OK",
                               base::CompareCase::SENSITIVE));
  ASSERT_TRUE(
      base::EndsWith(response, "Response!", base::CompareCase::SENSITIVE));
}

TEST_F(HttpServerTest, SendRaw) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send("GET /test HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(1);
  server_->SendRaw(GetConnectionId(0), "Raw Data ",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  server_->SendRaw(GetConnectionId(0), "More Data",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  server_->SendRaw(GetConnectionId(0), "Third Piece of Data",
                   TRAFFIC_ANNOTATION_FOR_TESTS);

  const std::string expected_response("Raw Data More DataThird Piece of Data");
  std::string response;
  ASSERT_TRUE(client.Read(&response, expected_response.length()));
  ASSERT_EQ(expected_response, response);
}

TEST_F(HttpServerTest, SendRawOverTwoConnections) {
  TestHttpClient client1;
  TestHttpClient client2;

  // Requests are staggered so that their order is deterministic - otherwise the
  // test has no way of associating the response with the client object.
  CreateConnection(&client1);
  client1.Send("GET /test1 HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(1);

  CreateConnection(&client2);
  client2.Send("GET /test2 HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(2);

  server_->SendRaw(GetConnectionId(0), "Raw Data ",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  server_->SendRaw(GetConnectionId(1), "More Data",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  server_->SendRaw(GetConnectionId(0), "Third Piece of Data",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  server_->SendRaw(GetConnectionId(1), "And #4", TRAFFIC_ANNOTATION_FOR_TESTS);

  const std::string expected_response1("Raw Data Third Piece of Data");
  const std::string expected_response2("More DataAnd #4");
  std::string response1, response2;

  ASSERT_TRUE(client1.Read(&response1, expected_response1.length()));
  ASSERT_TRUE(client2.Read(&response2, expected_response2.length()));
  ASSERT_EQ(expected_response1, response1);
  ASSERT_EQ(expected_response2, response2);
}

TEST_F(HttpServerTest, WrongProtocolRequest) {
  const char* const kBadProtocolRequests[] = {
      "GET /test HTTP/1.0\r\n\r\n", "GET /test foo\r\n\r\n",
      "GET /test \r\n\r\n",
  };

  for (size_t i = 0; i < base::size(kBadProtocolRequests); ++i) {
    TestHttpClient client;
    CreateConnection(&client);

    client.Send(kBadProtocolRequests[i]);
    client.ExpectUsedThenDisconnectedWithNoData();

    // Assert that the delegate was updated properly.
    ASSERT_EQ(1u, connection_map().size());
    ASSERT_FALSE(connection_map().begin()->second);
    EXPECT_EQ(0ul, requests_.size());

    // Reset the state of the connection map.
    connection_map().clear();
  }
}

TEST_F(HttpServerTest, RequestWithBodySplitAcrossPackets) {
  TestHttpClient client;
  CreateConnection(&client);

  std::string body("body");
  std::string request_text = base::StringPrintf(
      "GET /test HTTP/1.1\r\n"
      "SomeHeader: 1\r\n"
      "Content-Length: %" PRIuS "\r\n\r\n%s",
      body.length(), body.c_str());

  std::string packet1(request_text.c_str(), request_text.length() - 2);
  std::string packet2(request_text, request_text.length() - 2);

  client.Send(packet1);
  base::RunLoop().RunUntilIdle();
  client.Send(packet2);
  RunUntilRequestsReceived(1);

  ASSERT_EQ(1u, requests_.size());
  ASSERT_EQ(body, GetRequest(0).data);
}

TEST_F(HttpServerTest, MultipleRequestsOnSameConnection) {
  // The idea behind this test is that requests with or without bodies should
  // not break parsing of the next request.
  TestHttpClient client;
  CreateConnection(&client);
  std::string body = "body";
  client.Send(
      base::StringPrintf("GET /test HTTP/1.1\r\n"
                         "Content-Length: %" PRIuS "\r\n\r\n%s",
                         body.length(), body.c_str()));
  RunUntilRequestsReceived(1);
  ASSERT_EQ(body, GetRequest(0).data);

  int client_connection_id = GetConnectionId(0);
  server_->Send200(client_connection_id, "Content for /test", "text/plain",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  std::string response1;
  ASSERT_TRUE(client.ReadResponse(&response1));
  ASSERT_TRUE(base::StartsWith(response1, "HTTP/1.1 200 OK",
                               base::CompareCase::SENSITIVE));
  ASSERT_TRUE(base::EndsWith(response1, "Content for /test",
                             base::CompareCase::SENSITIVE));

  client.Send("GET /test2 HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(2);
  ASSERT_EQ("/test2", GetRequest(1).path);

  ASSERT_EQ(client_connection_id, GetConnectionId(1));
  server_->Send404(client_connection_id, TRAFFIC_ANNOTATION_FOR_TESTS);
  std::string response2;
  ASSERT_TRUE(client.ReadResponse(&response2));
  ASSERT_TRUE(base::StartsWith(response2, "HTTP/1.1 404 Not Found",
                               base::CompareCase::SENSITIVE));

  client.Send("GET /test3 HTTP/1.1\r\n\r\n");
  RunUntilRequestsReceived(3);
  ASSERT_EQ("/test3", GetRequest(2).path);

  ASSERT_EQ(client_connection_id, GetConnectionId(2));
  server_->Send200(client_connection_id, "Content for /test3", "text/plain",
                   TRAFFIC_ANNOTATION_FOR_TESTS);
  std::string response3;
  ASSERT_TRUE(client.ReadResponse(&response3));
  ASSERT_TRUE(base::StartsWith(response3, "HTTP/1.1 200 OK",
                               base::CompareCase::SENSITIVE));
  ASSERT_TRUE(base::EndsWith(response3, "Content for /test3",
                             base::CompareCase::SENSITIVE));
}

class CloseOnConnectHttpServerTest : public HttpServerTest {
 public:
  void OnConnect(int connection_id) override {
    HttpServerTest::OnConnect(connection_id);
    connection_ids_.push_back(connection_id);
    server_->Close(connection_id);
  }

 protected:
  std::vector<int> connection_ids_;
};

TEST_F(CloseOnConnectHttpServerTest, ServerImmediatelyClosesConnection) {
  TestHttpClient client;
  CreateConnection(&client);
  client.Send("GET / HTTP/1.1\r\n\r\n");

  // The server should close the socket without responding.
  client.ExpectUsedThenDisconnectedWithNoData();

  // Run any tasks the TestServer posted.
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(1ul, connection_ids_.size());
  // OnHttpRequest() should never have been called, since the connection was
  // closed without reading from it.
  EXPECT_EQ(0ul, requests_.size());
}

}  // namespace server

}  // namespace network


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

==========================================
Bare Metal Trust Using Intel TXT
==========================================
https://blueprints.launchpad.net/ironic/+spec/bare-metal-trust-using-intel-txt
This spec was proposed in the Liberty cycle.

See :doc:`../approved/bare-metal-trust-using-intel-txt`.

redpajama_set_name: RedPajamaGithub


text:
import random

import numpy as np

def create_data_point(number_of_futures):
    """
    Number of features defines the dimension od a single datapoint
    """
    help_list = []
    for i in range(0, number_of_futures):
        help_list.append(random.uniform(0, 100))
    # Returns A vector of simple data point
    return help_list

def create_dataset(number_of_data_points, number_of_features):
    """
    Returns a matrix of data points in given numbers

    """
    data_matrix = []
    for i in range(0, number_of_data_points):
        data_matrix.append(create_data_point(number_of_features))
    return np.array(data_matrix)

def choose_random_centroid_list_from_given_dataset(number_of_centroid, data_matrix):
    """
    Returns a set of points for initial centroids

    """
    number_of_data_point = data_matrix.shape[0]
    random_number_list = []

    while len(random_number_list) != number_of_centroid:
        random_number = random.randint(0, number_of_data_point - 1)
        if random_number in random_number_list:
            pass
        else:
            random_number_list.append(random_number)

    return data_matrix[random_number_list]

def find_minimum_distanced_centroid(data_point, centroid_list):
    """

    """
    distance_list = []

    for centroid in centroid_list:
            distance_list.append(float(np.linalg.norm(data_point - centroid)))

    centroid_index = distance_list.index(min(distance_list))
    return tuple(centroid_list[centroid_index])

def assign_point_to_centroid(dataset, centroid_list):
    """
    Returns a dictionary in which every key represents a centroid and each key has a point list containing closest
    distances

    """
    result_dict = {}
    for centroid in centroid_list:
        result_dict[tuple(centroid)] = []

    for point in dataset:
        min_centroid = find_minimum_distanced_centroid(point, centroid_list)
        result_dict[min_centroid].append(point)
    return result_dict

def find_average_point_from_point_list(point_list):
    """

    """
    result_point = []
    dimension = len(point_list[0])
    for i in range(0, dimension):
        sum_of_coordinate = 0
        for point in point_list:
            sum_of_coordinate += point[i]
        result_point.append(sum_of_coordinate / len(point_list))

    return result_point

def find_new_centroid_from_centroid_point_dictionary(centroid_point_dictionary):
    """
    Returns a new centroid_list
    """
    new_centroid_list =[]

    for key in centroid_point_dictionary.keys():
        new_centroid_list.append(find_average_point_from_point_list(centroid_point_dictionary[key]))

    return np.array(new_centroid_list)

if __name__  == '__main__':

    # feature_numbers = raw_input('Please enter number of features: ')
    # number_of_data_points = raw_input('Please enter number of data points: ')
    number_of_clusters = 4
    number_of_data_points = 1000
    feature_numbers = 2

    # dataset = create_dataset(number_of_data_points, feature_numbers)

    dataset = np.genfromtxt('datafile.txt', delimiter=' ')
    random_centroid_list = choose_random_centroid_list_from_given_dataset(number_of_clusters, dataset)
    result_dict = assign_point_to_centroid(dataset, random_centroid_list)
    new_centroid_list = find_new_centroid_from_centroid_point_dictionary(result_dict)
    for i in range(0,100):
        result_dict = assign_point_to_centroid(dataset, new_centroid_list)
        new_centroid_list = find_new_centroid_from_centroid_point_dictionary(result_dict)
    print(new_centroid_list)

# TODO implement it in more efficient way
# TODO Implement object oriented version of it


text:
import spotipy_twisted
from  spotipy_twisted import util
from twisted.internet import defer
from twisted.trial import unittest
import pprint
import sys

'''
    Since these tests require authentication they are maintained
    separately from the other tests.

    These tests try to be benign and leave your collection and
    playlists in a relatively stable state.
'''

class AuthTestSpotipy(unittest.TestCase):
    '''
        These tests require user authentication
    '''

    playlist = "spotify:user:plamere:playlist:2oCEWyyAPbZp9xhVSxZavx"
    four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
                "spotify:track:7IHOIqZUUInxjVkko181PB",
                "4VrWlk8IQxevMvERoX08iC",
                "http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"]

    two_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
                "spotify:track:7IHOIqZUUInxjVkko181PB"]

    other_tracks=["spotify:track:2wySlB6vMzCbQrRnNGOYKa",
            "spotify:track:29xKs5BAHlmlX1u4gzQAbJ",
            "spotify:track:1PB7gRWcvefzu7t3LJLUlf"]

    bad_id = 'BAD_ID'

    @defer.inlineCallbacks
    def test_track_bad_id(self):
        try:
            track = yield spotify.track(self.bad_id)
            self.assertTrue(False)
        except spotipy_twisted.SpotifyException:
            self.assertTrue(True)

    @defer.inlineCallbacks
    def test_basic_user_profile(self):
        user = yield spotify.user(username)
        self.assertTrue(user['id'] == username)

    @defer.inlineCallbacks
    def test_current_user(self):
        user = yield spotify.current_user()
        self.assertTrue(user['id'] == username)

    @defer.inlineCallbacks
    def test_me(self):
        user = yield spotify.me()
        self.assertTrue(user['id'] == username)

    @defer.inlineCallbacks
    def test_user_playlists(self):
        playlists = yield spotify.user_playlists(username, limit=5)
        self.assertTrue('items' in playlists)

        # known API issue currently causes this test to fail
        # the issue is that the API doesn't currently respect the
        # limit paramter

        self.assertTrue(len(playlists['items']) == 5)

    @defer.inlineCallbacks
    def test_user_playlist_tracks(self):
        playlists = yield spotify.user_playlists(username, limit=5)
        self.assertTrue('items' in playlists)
        for playlist in playlists['items']:
            user = playlist['owner']['id']
            pid = playlist['id']
            results = yield spotify.user_playlist_tracks(user, pid)
            self.assertTrue(len(results['items']) > 0)

    def user_playlist_tracks(self, user, playlist_id = None, fields=None,
        limit=100, offset=0):

        # known API issue currently causes this test to fail
        # the issue is that the API doesn't currently respect the
        # limit paramter

        self.assertTrue(len(playlists['items']) == 5)

    @defer.inlineCallbacks
    def test_current_user_saved_tracks(self):
        tracks = yield spotify.current_user_saved_tracks()
        self.assertTrue(len(tracks['items']) > 0)

    @defer.inlineCallbacks
    def test_current_user_save_and_unsave_tracks(self):
        tracks = yield spotify.current_user_saved_tracks()
        total = tracks['total']

        yield spotify.current_user_saved_tracks_add(self.four_tracks)

        tracks = yield spotify.current_user_saved_tracks()
        new_total = tracks['total']
        self.assertTrue(new_total - total == len(self.four_tracks))

        tracks = yield spotify.current_user_saved_tracks_delete(self.four_tracks)
        tracks = yield spotify.current_user_saved_tracks()
        new_total = tracks['total']
        self.assertTrue(new_total == total)

    @defer.inlineCallbacks
    def test_new_releases(self):
        response = yield spotify.new_releases()
        self.assertTrue(len(response['albums']) > 0)

    @defer.inlineCallbacks
    def test_featured_releases(self):
        response = yield spotify.featured_playlists()
        self.assertTrue(len(response['playlists']) > 0)

    @defer.inlineCallbacks
    def get_or_create_spotify_playlist(self, username, playlist_name):
        playlists = yield spotify.user_playlists(username)
        while playlists:
            for item in playlists['items']:
                if item['name'] == playlist_name:
                    defer.returnValue(item['id'])
            playlists = yield spotify.next(playlists)
        playlist = yield spotify.user_playlist_create(username, playlist_name)
        playlist_id = playlist['uri']
        defer.returnValue(playlist_id)

    @defer.inlineCallbacks
    def test_user_playlist_ops(self):
        # create empty playlist
        playlist_id = yield self.get_or_create_spotify_playlist(username,
                'spotipy-testing-playlist-1')

        # remove all tracks from it

        yield spotify.user_playlist_replace_tracks(username, playlist_id,[])

        playlist = yield spotify.user_playlist(username, playlist_id)
        self.assertTrue(playlist['tracks']['total'] == 0)
        self.assertTrue(len(playlist['tracks']['items']) == 0)

        # add tracks to it

        yield spotify.user_playlist_add_tracks(username, playlist_id, self.four_tracks)
        playlist = yield spotify.user_playlist(username, playlist_id)
        self.assertTrue(playlist['tracks']['total'] == 4)
        self.assertTrue(len(playlist['tracks']['items']) == 4)

        # remove two tracks from it

        yield spotify.user_playlist_remove_all_occurrences_of_tracks (username,
                    playlist_id, self.two_tracks)

        playlist = yield spotify.user_playlist(username, playlist_id)
        self.assertTrue(playlist['tracks']['total'] == 2)
        self.assertTrue(len(playlist['tracks']['items']) == 2)

        # replace with 3 other tracks
        yield spotify.user_playlist_replace_tracks(username,
            playlist_id, self.other_tracks)

        playlist = yield spotify.user_playlist(username, playlist_id)
        self.assertTrue(playlist['tracks']['total'] == 3)
        self.assertTrue(len(playlist['tracks']['items']) == 3)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        username = sys.argv[1]
        del sys.argv[1]

        scope = 'playlist-modify-public '
        scope += 'user-library-read '
        scope += 'user-library-modify '
        scope += 'user-read-private'

        token = util.prompt_for_user_token(username, scope)
        spotify = spotipy_twisted.Spotify(auth=token)
        spotify.trace = False

        import sys
        from twisted.scripts import trial

        sys.argv.extend([__name__])
        trial.run()
    else:
        print "Usage: %s username" % (sys.argv[0],)


text:
import { FunctionComponent } from 'react';

import { Section } from '@waldur/marketplace/types';

import { AttributeRow } from './AttributeRow';

interface AttributeSectionProps {
  section: Section;
  attributes: any;
  hideHeader: boolean;
}

export const AttributeSection: FunctionComponent<AttributeSectionProps> = (
  props,
) => (
  <>
    {!props.hideHeader && (

        {props.section.title}

    )}
    {props.section.attributes
      .filter((attr) => props.attributes.hasOwnProperty(attr.key))
      .map((attr, index) => (
        <AttributeRow
          key={index}
          value={props.attributes[attr.key]}
          attribute={attr}
        />
      ))}
  </>
);


text:
package org.openalto.alto.client.wrapper;

import javax.ws.rs.core.Response;

import org.openalto.alto.client.ALTOResponse;
import org.openalto.alto.client.ALTOResponseParser;

import org.openalto.alto.common.type.ALTOData;
import org.openalto.alto.common.type.MetaData;

public class RawParser extends ALTOResponseParser {

    @Override
    public ALTOResponse parse(Response response) {
        String msg = response.readEntity(String.class);
        ALTOData<?, String> data = new ALTOData<MetaData, String>(null, msg);
        return new ALTOResponseBase(false, response, data);
    }
}


text:
<?php

namespace app\models\api\v1;

use Yii;
use yii\base\Model;
use app\components\helpers\Color;

class TeamColorForm extends Model
{
    public $hue;
    public $rgb;

    public function rules()
    {
        return [
            [['hue'], 'number', 'min' => 0, 'max' => 360],
            [['rgb'], 'validateRgb'],
            [['rgb'], 'makeHue'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }

    public function validateRgb($attribute, $params)
    {
        if ($this->hasErrors($attribute)) {
            return;
        }
        $value = $this->$attribute;
        if (!is_array($value)) {
            $this->addError($attribute, "{$attribute} must be an array.");
            return;
        }
        if (count($value) !== 3) {
            $this->addError($attribute, "{$attribute} must have 3 values.");
            return;
        }

        $numberValidator = new \yii\validators\NumberValidator();
        $numberValidator->integerOnly = true;
        $numberValidator->min = 0;
        $numberValidator->max = 255;
        foreach ($value as $v) {
            $error = null;
            if (!$numberValidator->validate($v, $error)) {
                $this->addError($attribute, $error);
                return;
            }
        }
    }

    public function makeHue()
    {
        if ($this->hasErrors() || (string)$this->hue != '') {
            return;
        }
        if (!is_array($this->rgb) || count($this->rgb) !== 3) {
            return;
        }
        list($r, $g, $b) = $this->rgb;
        $this->hue = (int)Color::getHueFromRGB($r, $g, $b);
    }
}


text:
@interface SampleForFullScreen : UIViewController
{
 @private
  BOOL fullScreen_;
}
@end


text:
package org.apereo.cas.util.serialization;

import org.apereo.cas.CipherExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/**
 * This is {@link SerializationUtils}
 * that encapsulates common serialization operations
 * in one spot.
 *
 * @author Timur Duehr timur.duehr@nccgroup.trust
 * @since 5.0.0
 */
public final class SerializationUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(SerializationUtils.class);

    private SerializationUtils() {
    }

    /**
     * Serialize an object.
     *
     * @param object The object to be serialized
     * @return the +byte[]+ containing the object
     * @since 5.0.0
     */
    public static byte[] serialize(final Serializable object) {
        final ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        serialize(object, outBytes);
        return outBytes.toByteArray();
    }

    /**
     * Serialize an object.
     *
     * @param object       The object to be serialized
     * @param outputStream The stream to receive the object
     * @since 5.0.0
     */
    public static void serialize(final Serializable object, final OutputStream outputStream) {
        try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
            out.writeObject(object);
        } catch (final IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * Deserialize an object.
     *
     * @param <T>     the type parameter
     * @param inBytes The bytes to be deserialized
     * @return the object
     * @since 5.0.0
     */
    public static <T> T deserialize(final byte[] inBytes) {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(inBytes);
        return deserialize(inputStream);
    }

    /**
     * Deserialize an object.
     *
     * @param <T>         the type parameter
     * @param inputStream The stream to be deserialized
     * @return the object
     * @since 5.0.0
     */
    public static <T> T deserialize(final InputStream inputStream) {
        ObjectInputStream in = null;
        try {
            in = new ObjectInputStream(inputStream);
            final T obj = (T) in.readObject();
            return obj;
        } catch (final ClassNotFoundException | IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (final IOException e) {
                    LOGGER.error("Unable to serialize", e);
                }
            }
        }
    }

    /**
     * Serialize and encode object.
     *
     * @param cipher the cipher
     * @param object the object
     * @return the byte []
     * @since 4.2
     */
    public static byte[] serializeAndEncodeObject(final CipherExecutor cipher,
                                                  final Serializable object) {
        final byte[] outBytes = serialize(object);
        return (byte[]) cipher.encode(outBytes);
    }

    /**
     * Decode and serialize object.
     *
     * @param <T>    the type parameter
     * @param object the object
     * @param cipher the cipher
     * @param type   the type
     * @return the t
     * @since 4.2
     */
    public static <T> T decodeAndDeserializeObject(final byte[] object,
                                                   final CipherExecutor cipher,
                                                   final Class<? extends Serializable> type) {
        try {
            final byte[] decoded = (byte[]) cipher.decode(object);
            return deserializeAndCheckObject(decoded, type);
        } catch (final Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * Decode and serialize object.
     *
     * @param <T>    the type parameter
     * @param object the object
     * @param type   the type
     * @return the t
     * @since 4.2
     */
    public static <T> T deserializeAndCheckObject(final byte[] object, final Class<? extends Serializable> type) {
        final Object result = deserialize(object);
        if (!type.isAssignableFrom(result.getClass())) {
            throw new ClassCastException("Decoded object is of type " + result.getClass()
                    + " when we were expecting " + type);
        }
        return (T) result;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="shortcut icon" href="{{asset('favicon.ico')}}">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="renderer" content="webkit" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="SmartWiki" />
    <title>编辑文档 - {{wiki_config('SITE_NAME','SmartWiki')}}</title>
    <link href="{{asset('static/bootstrap/css/bootstrap.min.css')}}" rel="stylesheet">
    <link href="{{asset('static/editormd/css/editormd.min.css')}}" rel="stylesheet">
    <link href="{{asset('static/jstree/themes/default/style.css')}}" rel="stylesheet">

    <link href="{{asset('static/styles/wiki.css')}}" rel="stylesheet">
    <link href="{{asset('static/styles/wikiedit.css')}}" rel="stylesheet">
    <link href="{{asset('static/styles/markdown.css')}}" rel="stylesheet">

             目录

            <button data-target="#create-new" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="create-document" title="创建文档">

            </button>

    <form method="post" action="{{route('document.save')}}" id="form-editormd">

                <input type="hidden" name="doc_id" id="documentId">
                <textarea style="display:none;">### Hello Editor.md !</textarea>

    </form>

            <form class="form-horizontal" role="form" method="post" action="{{route('document.save')}}" id="form-document">
                <input type="hidden" name="project_id" value="{{$project_id or ''}}">
                <input type="hidden" name="id" value="{{$doc_id or ''}}">
                <input type="hidden" name="parentId" value="{{$parent_id or 0}}">

添加文档

                        名称

                            <input type="text" name="documentName" class="form-control" id="documentName" placeholder="文档名称" autocomplete="off">

                    <button type="submit" class="btn btn-primary" id="btn-action" data-loading-text="提交中...">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>

            </form>

请选择模板类型

普通文档

默认类型

简单的文本文档

API文档

用于API文档速写

支持代码高亮

数据字典

用于数据字典显示

表格支持

                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>


text:
from flask_restful import Resource, abort
from flask_restful_swagger import swagger

from hpcpm.api import log
from hpcpm.api.helpers.database import database
from hpcpm.api.helpers.utils import abort_when_node_not_found, abort_when_device_not_found
from hpcpm.api.helpers.constants import COMPUTATION_NODE_PARAM_NAME, DEVICE_IDENTIFIER_PARAM, \
    DEVICE_NOT_FOUND_AND_COMPUTATION_NODE_FETCHED_RESPONSES

class LastPowerUsage(Resource):
    @swagger.operation(
        notes='This endpoint is used for getting last power usage of given device from database',
        nickname='/nodes/computation_node/<string:name>/<string:device_id>/last_power_usage',
        parameters=[
            COMPUTATION_NODE_PARAM_NAME,
            DEVICE_IDENTIFIER_PARAM,
        ],
        responseMessages=DEVICE_NOT_FOUND_AND_COMPUTATION_NODE_FETCHED_RESPONSES
    )
    def get(self, name, device_id):
        computation_node = abort_when_node_not_found(name)

        abort_when_device_not_found(device_id, computation_node)

        db_records = database.get_last_power_usage(name, device_id)
        if not db_records or len(db_records) <= 0:
            log.info('No last power usage for device %s:%s', name, device_id)
            abort(404)

        sorted_result = sorted(zip(db_records.keys(), db_records.values()), key=lambda usage: usage[0], reverse=True)
        sorted_result = [u[1] for u in sorted_result if isinstance(u[1], int)]

        result = {'last_power_usage': sorted_result[0]}

        log.info('Successfully get device %s:%s last power usage info: %s', name, device_id, result)
        return result, 200


text:
package org.modelmapper;

import static org.testng.Assert.assertEquals;

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

import org.modelmapper.config.Configuration.AccessLevel;
import org.modelmapper.spi.MappingContext;

public class ComplexConversion {
  public static class PaymentInfo {
    int id;
    String type;

    PaymentInfo(int id, String type) {
      this.id = id;
      this.type = type;
    }
  }

  public static class Customer {
    List<PaymentInfo> info;

    List<PaymentInfo> getInfo() {
      return info;
    }
  }

  public static class BillingInfoDTO {
    int id;
  }

  public static class ShippingInfoDTO {
    int id;
  }

  public static class CustomerDTO {
    List<BillingInfoDTO> billingInfo;
    List<ShippingInfoDTO> shippingInfo;

    void setBillingInfo(List<BillingInfoDTO> billingInfo) {
      this.billingInfo = billingInfo;
    }

    void setShippingInfo(List<ShippingInfoDTO> shippingInfo) {
      this.shippingInfo = shippingInfo;
    }
  }

  static class PaymentInfoConverter implements Converter<List<PaymentInfo>, List<Object>> {
    private boolean billing;

    PaymentInfoConverter(boolean billing) {
      this.billing = billing;
    }

    public List<Object> convert(MappingContext<List<PaymentInfo>, List<Object>> context) {
      List<PaymentInfo> payments = new ArrayList<PaymentInfo>();
      for (PaymentInfo p : context.getSource())
        if (!billing ^ "Billing".equals(p.type))
          payments.add(p);
      return context.getMappingEngine().map(context.create(payments, context.getDestinationType()));
    }
  }

  public static void main(String... args) throws Exception {
    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration()
        .setFieldMatchingEnabled(true)
        .setFieldAccessLevel(AccessLevel.PACKAGE_PRIVATE);

    modelMapper.addMappings(new PropertyMap<Customer, CustomerDTO>() {
      @Override
      protected void configure() {
        using(new PaymentInfoConverter(true)).map(source.getInfo()).setBillingInfo(null);
        using(new PaymentInfoConverter(false)).map(source.getInfo()).setShippingInfo(null);
      }
    });

    PaymentInfo info1 = new PaymentInfo(1, "Billing");
    PaymentInfo info2 = new PaymentInfo(2, "Shipping");
    PaymentInfo info3 = new PaymentInfo(3, "Billing");
    PaymentInfo info4 = new PaymentInfo(4, "Shipping");
    Customer customer = new Customer();
    customer.info = Arrays.asList(info1, info2, info3, info4);
    CustomerDTO dto = modelMapper.map(customer, CustomerDTO.class);

    assertEquals(dto.billingInfo.get(0).id, 1);
    assertEquals(dto.billingInfo.get(1).id, 3);
    assertEquals(dto.shippingInfo.get(0).id, 2);
    assertEquals(dto.shippingInfo.get(1).id, 4);
  }
}


text:
use utf8;
package Schema::Result::Job;

# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE

=head1 NAME

Schema::Result::Job

=cut

use strict;
use warnings;

use base 'DBIx::Class::Core';

=head1 TABLE: C<job>

=cut

__PACKAGE__->table("job");

=head1 ACCESSORS

=head2 id

  data_type: 'integer'
  is_auto_increment: 1
  is_nullable: 0

=head2 agent

  data_type: 'integer'
  is_foreign_key: 1
  is_nullable: 1

=head2 object_type

  data_type: 'varchar'
  is_nullable: 1
  size: 48

=head2 object_name

  data_type: 'varchar'
  is_nullable: 1
  size: 256

=head2 keyword

  data_type: 'varchar'
  is_nullable: 0
  size: 48

=head2 parameters

  data_type: 'varchar'
  is_nullable: 1
  size: 256

=head2 asset_url

  data_type: 'varchar'
  is_nullable: 0
  size: 512

=head2 asset_type

  data_type: 'varchar'
  is_nullable: 0
  size: 48

=head2 status

  data_type: 'integer'
  is_foreign_key: 1
  is_nullable: 0

=head2 start_time

  data_type: 'datetime'
  datetime_undef_if_invalid: 1
  is_nullable: 0

=head2 entered_time

  data_type: 'datetime'
  datetime_undef_if_invalid: 1
  is_nullable: 0

=head2 job_user

  data_type: 'integer'
  is_foreign_key: 1
  is_nullable: 0

=head2 last_updated

  data_type: 'timestamp'
  datetime_undef_if_invalid: 1
  default_value: current_timestamp
  is_nullable: 1

=head2 job_deliveryservice

  data_type: 'integer'
  is_foreign_key: 1
  is_nullable: 1

=cut

__PACKAGE__->add_columns(
  "id",
  { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
  "agent",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 1 },
  "object_type",
  { data_type => "varchar", is_nullable => 1, size => 48 },
  "object_name",
  { data_type => "varchar", is_nullable => 1, size => 256 },
  "keyword",
  { data_type => "varchar", is_nullable => 0, size => 48 },
  "parameters",
  { data_type => "varchar", is_nullable => 1, size => 256 },
  "asset_url",
  { data_type => "varchar", is_nullable => 0, size => 512 },
  "asset_type",
  { data_type => "varchar", is_nullable => 0, size => 48 },
  "status",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 0 },
  "start_time",
  {
    data_type => "datetime",
    datetime_undef_if_invalid => 1,
    is_nullable => 0,
  },
  "entered_time",
  {
    data_type => "datetime",
    datetime_undef_if_invalid => 1,
    is_nullable => 0,
  },
  "job_user",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 0 },
  "last_updated",
  {
    data_type => "timestamp",
    datetime_undef_if_invalid => 1,
    default_value => \"current_timestamp",
    is_nullable => 1,
  },
  "job_deliveryservice",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 1 },
);

=head1 PRIMARY KEY

=over 4

=item * L</id>

=back

=cut

__PACKAGE__->set_primary_key("id");

=head1 RELATIONS

=head2 agent

Type: belongs_to

Related object: L<Schema::Result::JobAgent>

=cut

__PACKAGE__->belongs_to(
  "agent",
  "Schema::Result::JobAgent",
  { id => "agent" },
  {
    is_deferrable => 1,
    join_type     => "LEFT",
    on_delete     => "CASCADE",
    on_update     => "NO ACTION",
  },
);

=head2 job_deliveryservice

Type: belongs_to

Related object: L<Schema::Result::Deliveryservice>

=cut

__PACKAGE__->belongs_to(
  "job_deliveryservice",
  "Schema::Result::Deliveryservice",
  { id => "job_deliveryservice" },
  {
    is_deferrable => 1,
    join_type     => "LEFT",
    on_delete     => "NO ACTION",
    on_update     => "NO ACTION",
  },
);

=head2 job_results

Type: has_many

Related object: L<Schema::Result::JobResult>

=cut

__PACKAGE__->has_many(
  "job_results",
  "Schema::Result::JobResult",
  { "foreign.job" => "self.id" },
  { cascade_copy => 0, cascade_delete => 0 },
);

=head2 job_user

Type: belongs_to

Related object: L<Schema::Result::TmUser>

=cut

__PACKAGE__->belongs_to(
  "job_user",
  "Schema::Result::TmUser",
  { id => "job_user" },
  { is_deferrable => 1, on_delete => "NO ACTION", on_update => "NO ACTION" },
);

=head2 status

Type: belongs_to

Related object: L<Schema::Result::JobStatus>

=cut

__PACKAGE__->belongs_to(
  "status",
  "Schema::Result::JobStatus",
  { id => "status" },
  { is_deferrable => 1, on_delete => "NO ACTION", on_update => "NO ACTION" },
);

# Created by DBIx::Class::Schema::Loader v0.07043 @ 2015-05-21 13:27:11
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:AOQJIKcfi/ADgnVuB7U+rg

# You can replace this text with custom code or comments, and it will be preserved on regeneration
#
# Copyright 2015 Comcast Cable Communications Management, LLC
#
# 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.
#
#
1;


text:
namespace zombye {
    class asset;
}

namespace zombye {
    class config_system {
    public:
        config_system();

        Json::Value get(std::string, std::string) const;
        void set(std::string, std::string, Json::Value);
        bool has(std::string) const;
        bool has_identifier(std::string, std::string) const;

        void commit();
        void commit(std::string);
    private:
        std::unordered_map<std::string, Json::Value> configs_;
        std::unordered_map<std::string, std::string> paths_;

        void register_config(std::string, zombye::asset*);
    };
}

#endif


text:
Path Bundle list ({{ policy.data['path-bundle'].data.length || 0 }})

        <md-button class="md-icon-button" ng-click="showForm('displayPathBundleForm')">
            add
        </md-button>

    <md-list>
        <md-list-item class="md-2-line" layout="row" ng-repeat="pb in policy.data['path-bundle'].data track by $index"
                      ng-click="fillPathBundleForm(pb, $index)">

{{pb.data['bundle-id']}}

Role: {{ pb.data.role}}

                <md-icon aria-label="Delete path bundle"
                         ng-click="deletePathBundleFromList($index)">
                    clear
                </md-icon>

        </md-list-item>
    </md-list>

        <md-button ng-click="stepBack()">
            Back
        </md-button>
        <md-button ng-disabled="!policy.data['path-bundle'].data.length" ng-click="stepForward()">
            Next
        </md-button>

<form name="pathBundleForm" ng-submit="addPathBundleToList(pathBundleForm)" novalidate ng-if="displayPathBundleForm" flex layout="column">

        <md-input-container flex="50">
            Bundle Id
            <input name="bundleId" ng-model="pathBundle.data['bundle-id']"
                   ng-required="!policy.data['path-bundle'].data.length">

Required field

        </md-input-container>

        <md-input-container flex>
            Direction
            <md-select name="direction" ng-model="pathBundle.data.direction"
                       aria-label="Path bundle, property direction"
                       ng-change="clearEmptyValues(pathBundle.data, 'direction')">
                <md-option value="{{undefined}}"></md-option>
                <md-option ng-repeat="direction in ['forward', 'reverse']" value="{{direction}}">
                    {{direction}}
                </md-option>
            </md-select>

Required field

        </md-input-container>

        <md-input-container flex="50">
            Role
            <md-select name="role" ng-model="pathBundle.data.role"
                       aria-label="Path bundle, property role"
                       >
                <md-option ng-repeat="role in ['active', 'backup']" value="{{role}}">
                    {{role}}
                </md-option>
            </md-select>

Required field

        </md-input-container>

        <md-input-container flex>
            Active Path Bundle Id
            <input name="activePathBundleId" ng-model="pathBundle.data['active-bundle-id']"
                   ng-required="pathBundle.data.role === 'backup'">

Required field

        </md-input-container>

        <md-input-container flex="50">
            Default Use
            <md-select name="defaultUse" ng-model="pathBundle.data['constraints']['default-use']"
                       aria-label="Path bundle, property default-use"
                       ng-required="!policy.data['path-bundle'].data.length">
                <md-option ng-repeat="defaultuse in ['must-not-use', 'may-use']" value="{{defaultuse}}">
                    {{defaultuse}}
                </md-option>
            </md-select>

Required field

        </md-input-container>

        <md-input-container flex>
            Max Path Cost
            <input name="maxPathCost" ng-model="pathBundle.data['constraints']['max-path-cost']">
        </md-input-container>

            <md-button ng-click="hideForm('displayPathBundleForm')">
                Back
            </md-button>
            <md-button  type="submit" ng-disabled="pathBundleForm.$invalid">
                Add to List
            </md-button>

</form>


text:
description: How to keep containers running when the daemon isn't available.
keywords: docker, upgrade, daemon, dockerd, live-restore, daemonless container
title: Keep containers alive during daemon downtime
redirect_from:
- /engine/admin/live-restore/
---

By default, when the Docker daemon terminates, it shuts down running containers.
Starting with Docker Engine 1.12, you can configure the daemon so that
containers remain running if the daemon becomes unavailable. This functionality
is called _live restore_. The live restore option helps reduce container
downtime due to daemon crashes, planned outages, or upgrades.

> **Note**: Live restore is not supported on Windows containers, but it does work
for Linux containers running on Docker for Windows.

## Enable live restore

There are two ways to enable the live restore setting to keep containers alive
when the daemon becomes unavailable. **Only do one of the following**.

* Add the configuration to the daemon configuration file. On Linux, this
  defaults to `/etc/docker/daemon.json`. On Docker for Mac or Docker for Windows,
  select the Docker icon from the task bar, then click
  **Preferences** -> **Daemon** -> **Advanced**.

  - Use the following JSON to enable `live-restore`.

    ```json
    {
      "live-restore": true
    }
    ```

  - Restart the Docker daemon. On Linux, you can avoid a restart (and avoid any
    downtime for your containers) by reload the Docker daemon. If you use
    `systemd`, then use the command `systemctl reload docker`. Otherwise, send a
    `SIGHUP` signal to the `dockerd` process.

* If you prefer, you can start the `dockerd` process manually with the
  `--live-restore` flag. This approach is not recommended because it does not
  set up the environment that `systemd` or another process manager would use
  when starting the Docker process. This can cause unexpected behavior.

## Live restore during upgrades

The live restore feature supports restoring containers to the daemon for
upgrades from one minor release to the next, such as when upgrading from Docker
1.12.1 to 1.12.2.

If you skip releases during an upgrade, the daemon may not restore its
connection to the containers. If the daemon can't restore the connection, it
cannot manage the running containers and you must stop them manually.

## Live restore upon restart

The live restore option only works to restore containers if the daemon options,
such as bridge IP addresses and graph driver, did not change. If any of these
daemon-level configuration options have changed, the live restore may not work
and you may need to manually stop the containers.

## Impact of live restore on running containers

If the daemon is down for a long time, running containers may fill up the FIFO
log the daemon normally reads. A full log blocks containers from logging more
data. The default buffer size is 64K. If the buffers fill, you must restart
the Docker daemon to flush them.

On Linux, you can modify the kernel's buffer size by changing
`/proc/sys/fs/pipe-max-size`. You cannot modify the buffer size on Docker for
Mac or Docker for Windows.

## Live restore and swarm mode

The live restore option only pertains to standalone containers, and not to swarm
services. Swarm services are managed by swarm managers. If swarm managers are
not available, swarm services continue to run on worker nodes but cannot be
managed until enough swarm managers are available to maintain a quorum.


text:
/**
 * Made-Module
 * @author: SimonHao
 * @date:   2015-11-13 11:27:55
 */

'use strict';

var EventEmitter = require('events').EventEmitter;

function MadeModule(){
  EventEmitter.call(this);
}

MadeModule.prototype = new EventEmitter();
MadeModule.prototype.constructor = MadeModule;

MadeModule.prototype._made_module = true;

MadeModule.prototype.destructor = function(){
};

exports._default = MadeModule;


text:
package com.shang.cloud.microservice_consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Think on 2017/5/31.
 */
@RestController
public class UserContoller {

//    @Autowired
//    private RestTemplate restTemplate;
//
//
//    //从配置文件获取连接
//    @Value("${user.userServicePath}")
//    private String userServicePath;
//
//    @GetMapping("/movie/{id}")
//    public User getUserById(@PathVariable Long id){
//        return this.restTemplate.getForObject(userServicePath + id,User.class);
//    }

    @GetMapping("/test")
    public String test(){
        return "test";
    }
}


text:
module.exports = function(logger, utils) {

  // Active Endpoint
  this.endPoint = '/active';

  var hostMachine = process.env.HOST_MACHINE;

  this.active = function(req, res) {
      var method = 'active';

      var response = {
          worker: utils.worker,
          host: utils.host,
          hostMachine: hostMachine,
          active: utils.host === utils.activeHost
      };

      if (req.query && req.query.active) {
          var query = req.query.active.toLowerCase();

          if (query !== 'true' && query !== 'false') {
              response.error = "Invalid query string";
              res.send(response);
              return;
          }

          var redundantHost = utils.host === `${utils.hostPrefix}0` ? `${utils.hostPrefix}1` : `${utils.hostPrefix}0`;
          var activeHost = query === 'true' ? utils.host : redundantHost;
          if (utils.activeHost !== activeHost) {
              if (utils.redisClient) {
                  utils.redisClient.hsetAsync(utils.redisKey, utils.redisField, activeHost)
                  .then(() => {
                      response.active = 'swapping';
                      utils.redisClient.publish(utils.redisKey, activeHost);
                      logger.info(method, 'Active host swap in progress');
                      res.send(response);
                  })
                  .catch(err => {
                      response.error = err;
                      res.send(response);
                  });
              }
              else {
                  response.active = utils.host === activeHost;
                  utils.activeHost = activeHost;
                  var message = 'The active state has changed';
                  logger.info(method, message, 'to', activeHost);
                  response.message = message;
                  res.send(response);
              }
          }
          else {
              res.send(response);
          }
      }
      else {
          res.send(response);
      }
  };

};


text:
#pragma once
#include <aws/location/LocationService_EXPORTS.h>
#include <aws/location/model/Circle.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace LocationService
{
namespace Model
{

  /**
   *
Contains the geofence geometry details.

A geofence geometry is made up
   * of either a polygon or a circle. Can be either a polygon or a circle. Including
   * both will return a validation error.

Amazon Location doesn't
   * currently support polygons with holes, multipolygons, polygons that are wound
   * clockwise, or that cross the antimeridian.

See Also:

   * AWS
   * API Reference

   */
  class AWS_LOCATIONSERVICE_API GeofenceGeometry
  {
  public:
    GeofenceGeometry();
    GeofenceGeometry(Aws::Utils::Json::JsonView jsonValue);
    GeofenceGeometry& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline const Circle& GetCircle() const{ return m_circle; }

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline bool CircleHasBeenSet() const { return m_circleHasBeenSet; }

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline void SetCircle(const Circle& value) { m_circleHasBeenSet = true; m_circle = value; }

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline void SetCircle(Circle&& value) { m_circleHasBeenSet = true; m_circle = std::move(value); }

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline GeofenceGeometry& WithCircle(const Circle& value) { SetCircle(value); return *this;}

    /**
     *
A circle on the earth, as defined by a center point and a radius.

     */
    inline GeofenceGeometry& WithCircle(Circle&& value) { SetCircle(std::move(value)); return *this;}

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline const Aws::Vector<Aws::Vector<Aws::Vector<double>>>& GetPolygon() const{ return m_polygon; }

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline bool PolygonHasBeenSet() const { return m_polygonHasBeenSet; }

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline void SetPolygon(const Aws::Vector<Aws::Vector<Aws::Vector<double>>>& value) { m_polygonHasBeenSet = true; m_polygon = value; }

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline void SetPolygon(Aws::Vector<Aws::Vector<Aws::Vector<double>>>&& value) { m_polygonHasBeenSet = true; m_polygon = std::move(value); }

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline GeofenceGeometry& WithPolygon(const Aws::Vector<Aws::Vector<Aws::Vector<double>>>& value) { SetPolygon(value); return *this;}

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline GeofenceGeometry& WithPolygon(Aws::Vector<Aws::Vector<Aws::Vector<double>>>&& value) { SetPolygon(std::move(value)); return *this;}

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline GeofenceGeometry& AddPolygon(const Aws::Vector<Aws::Vector<double>>& value) { m_polygonHasBeenSet = true; m_polygon.push_back(value); return *this; }

    /**
     *
A polygon is a list of linear rings which are each made up of a list of
     * vertices.

Each vertex is a 2-dimensional point of the form:
     * [longitude, latitude]. This is represented as an array of doubles
     * of length 2 (so [double, double]).

An array of 4 or more
     * vertices, where the first and last vertex are the same (to form a closed
     * boundary), is called a linear ring. The linear ring vertices must be listed in
     * counter-clockwise order around the ring's interior. The linear ring is
     * represented as an array of vertices, or an array of arrays of doubles
     * ([[double, double], ...]).

A geofence consists of a single
     * linear ring. To allow for future expansion, the Polygon parameter takes an array
     * of linear rings, which is represented as an array of arrays of arrays of doubles
     * ([[[double, double], ...], ...]).

A linear ring for use in
     * geofences can consist of between 4 and 1,000 vertices.

     */
    inline GeofenceGeometry& AddPolygon(Aws::Vector<Aws::Vector<double>>&& value) { m_polygonHasBeenSet = true; m_polygon.push_back(std::move(value)); return *this; }

  private:

    Circle m_circle;
    bool m_circleHasBeenSet = false;

    Aws::Vector<Aws::Vector<Aws::Vector<double>>> m_polygon;
    bool m_polygonHasBeenSet = false;
  };

} // namespace Model
} // namespace LocationService
} // namespace Aws


text:
> The more information you provide, the faster we can help you.

⚠ Select what you want - **a feature request** or **report a bug**. Please remove the section you aren't interested in.

# A feature request

##  What do you want to add?

> Please describe what you want to add to the component.

## How should it look like?

> Please add images.

# Report a bug

##  What did you do?

> Please replace this with what you did.

## What did you expect to happen?

> Please replace this with what you expected to happen.

## What happened instead?

> Please replace this with what happened instead.

## Your Environment

- Version of the component: _insert here_
- iOS version: _insert here_
- Device: _insert here_
- Xcode version: _insert here_
- If you use Cocoapods: _run `pod env | pbcopy` and insert here_
- If you use Carthage: _run `carthage version | pbcopy` and insert here_

## Project that demonstrates the bug

> Please add a link to a project we can download that reproduces the bug.


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Cursor</title>
    <meta name="description" content="Cursor - A-Frame">
    <script src="../../../dist/aframe-master.js"></script>
    <script src="https://unpkg.com/aframe-event-set-component@4.1.2/dist/aframe-event-set-component.min.js"></script>
  </head>
  <body>
    <a-scene background="color: #FBE0D8">
      <a-assets>
        <audio id="blip1" src="../../showcase/anime-UI/audio/321103__nsstudios__blip1.wav"></audio>
        <audio id="blip2" src="../../showcase/anime-UI/audio/321104__nsstudios__blip2.wav"></audio>
        <audio id="shot" src="shot.ogg"></audio>
        <a-mixin id="cube" geometry="primitive: box"></a-mixin>
        <a-mixin id="hoverColor" event-set__mouseenter="material.color: #CC435F"></a-mixin>
        <a-mixin id="selectColor" event-set__click="material.color: #876A96"></a-mixin>
        <a-mixin id="leaveColor" event-set__mouseleave="material.color: #9DE0AD"></a-mixin>
        <a-mixin id="red" material="color: #F35F5F"></a-mixin>
        <a-mixin id="green" material="color: #9DE0AD"></a-mixin>
        <a-mixin id="blue" material="color: #36A3EB"></a-mixin>
        <a-mixin id="yellow" material="color: #F1EA65"></a-mixin>
        <a-mixin id="sphere" geometry="primitive: sphere"></a-mixin>
      </a-assets>

      <a-entity id="mouseCursor" cursor="rayOrigin: mouse" raycaster="objects: .intersectable"></a-entity>

      <a-entity position="0 .6 4">
        <a-camera>
          <a-entity raycaster="far: 30; objects: .intersectable"
                    cursor
                    geometry="primitive: ring; radiusOuter: 0.015;
                              radiusInner: 0.01; segmentsTheta: 32"
                    material="color: #283644; shader: flat"
                    position="0 0 -0.75"></a-entity>
        </a-camera>
      </a-entity>

      <a-entity position="-3.5 1 0">
        <a-entity mixin="red cube"
                  class="intersectable"
                  animation="startEvents: click; property: position; from: 0 0 0; to: 0 0 -10; dur: 2000">
        </a-entity>
      </a-entity>

      <a-entity position="0 1 1">
        <a-entity id="invisibleCube"
                  mixin="cube"
                  material="color: grey; opacity: 0.3; transparent: true"
                  scale="1 1 0.1"
                  animation="startEvents: click; property: rotation; to: 0 360 0; easing: linear; dur: 2000">
        </a-entity>
      </a-entity>

      <a-entity position="0 1 0">
        <a-entity id="foregroundCube"
                  class="intersectable"
                  mixin="green cube hoverColor selectColor leaveColor"
                  sound__1="on: click; src: #blip1"
                  sound__2="on: mouseenter; src: #blip2"
                  animation="startEvents: click; property: rotation; to: 0 360 0; easing: linear; dur: 2000">
        </a-entity>
      </a-entity>

      <a-entity position="1 1 0">
        <a-entity mixin="yellow cube"
                  sound__1="on: click; src: #shot; poolSize: 6"
                  sound__2="src: #blip2; autoplay: true"
                  animation="startEvents: click; property: scale; to: 1.2 1.2 1.2; easing: linear; dur: 200">
        </a-entity>
      </a-entity>

      <a-entity position="0 1 -3">
        <a-entity id="backgroundCube"
                  class="intersectable"
                  mixin="green cube"
                  animation="startEvents: click; property: rotation; to: 0 360 0; easing: linear; dur: 2000">
        </a-entity>
      </a-entity>

      <a-entity position="3.5 1 0" rotation="0 45 0">
        <a-entity mixin="blue cube"
                  class="intersectable"
                  animation="startEvents: click; loop: 1; dir: alternate; property: position; from: 0 0 0; to: 15 0 0; dur: 2000">
        </a-entity>
      </a-entity>

      <a-entity mixin="yellow cube" position="0 3 -3" class="intersectable clickable" rotation="0 45 0" scale=".5 .5 .5"></a-entity>
    </a-scene>
  </body>
</html>


text:
import * as React from "react";
import { Link } from "react-router";
import { BackArrow } from "./back_arrow";
import { CropLiveSearchResult } from "./interfaces";
import { Everything } from "../interfaces";
import { openFarmSearchQuery } from "./actions";

interface SpeciesCatalogTileProps {
  result: CropLiveSearchResult;
  dispatch: Function;
}

export function SpeciesCatalogTile({result}: SpeciesCatalogTileProps) {
  let query = { p1: "SpeciesInfo", id: result.crop.slug };
  let pathname = "/app/designer";
  return (

        {result.crop.name}

          <Link to={{ pathname, query }}>

          </Link>

  );
};

export class SpeciesCatalog extends React.Component<Everything, any> {
  render() {
    let species = this.props.designer.cropSearchResults.map(
      (result, k) => <SpeciesCatalogTile result={result}
        key={k}
        dispatch={this.props.dispatch} />
    );
    return

          <BackArrow /> Choose a Species

        <SearchBox query={this.props.designer.cropSearchQuery}
          dispatch={this.props.dispatch} />

          {species}

;
  }
}

interface SearchBoxParams {
  query: string;
  dispatch: Function;
}

function SearchBox({query, dispatch}: SearchBoxParams) {
  return <input value={query}
    onChange={(e) => doSearch(e, dispatch)}
    className="search"
    placeholder="Search OpenFarm for crops" />;
}

function doSearch(e: React.FormEvent<HTMLInputElement>,
  dispatch: Function) {
  dispatch(openFarmSearchQuery(e.currentTarget.value));
}


text:
ThrowingStream
==============
[![Maven Central][mvn-img]][mvn-link]

This project is an alternative API to `java.util.stream` and its various supporting interfaces that allows for checked exceptions to be thrown.

Example usage:

````
Stream<String> names = Stream.of("java.lang.Object", "java.util.stream.Stream");
ThrowingStream<String, ClassNotFoundException> s = ThrowingStream.of(names,
    ClassNotFoundException.class);
s.map(ClassLoader.getSystemClassLoader()::loadClass).forEach(System.out::println);
````

Output:

````
class java.lang.Object
interface java.util.stream.Stream
````

### How can I use this library in my project?
 - [Clone the repository](http://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository#Cloning-an-Existing-Repository) and use maven to generate a .jar file:
````
git clone https://github.com/JeffreyFalgout/ThrowingStream
cd ThrowingStream/
mvn package
````
 - Download a .jar from the [releases](https://github.com/JeffreyFalgout/ThrowingStream/releases) page
 - [Maven central][mvn-link]:
````
<dependency>
    <groupId>name.falgout.jeffrey</groupId>
    <artifactId>throwing-streams</artifactId>
    <version>X.Y.Z</version>
</dependency>
````

### How does it work?
Check out the [wiki](https://github.com/JeffreyFalgout/ThrowingStream/wiki/How-it-works).

[mvn-img]: https://maven-badges.herokuapp.com/maven-central/name.falgout.jeffrey/throwing-streams/badge.svg
[mvn-link]: https://maven-badges.herokuapp.com/maven-central/name.falgout.jeffrey/throwing-streams


text:
import java.lang.reflect.Modifier

class Car
final class Volvo extends Car

object Car {
  val car = new Car {}
}

object Test {
  def main(args: Array[String]) = {
    List(new Car, new Volvo, Car, Car.car)
      .map(_.getClass.getModifiers)
      .foreach { m =>
        println(Modifier.isPrivate(m))
        println(Modifier.isFinal(m))
      }
  }
}


text:
package com.dove.reader.ui.controller;

import android.database.DataSetObservable;

public interface DrawerController {
    /**
     * Get the Drawer's {@link DataSetObservable}.
     * <em>
     * For a fragment, a drawer {@link android.database.DataSetObserver} maybe need to be registered
     * when the fragment is created successfully, and to be unregistered when the fragment is to be destroyed.
     * </em>
     * When the drawer's state changed, like opened or closed, the relative fragment should be notified to do data change.
     */
    DataSetObservable getDrawerObservable();
}


text:
[cmdletbinding()]
param()

# Arrange.
. $PSScriptRoot\..\..\lib\Initialize-Test.ps1 -Legacy
$now = Get-Date
$env:Build_BuildUri = 'Some build URI'
$env:Build_BuildNumber = 'Some build number'
$env:Build_Repository_Name = 'Some build repository name'
$env:Build_Repository_Uri = 'Some build repository URI'
$env:System_TeamProject = 'Some team project'
$env:System_TeamFoundationCollectionUri = 'Some team foundation collection URI'
Register-Mock Get-Date { $now }
Register-Mock Find-Files { 'Some PDB file 1', 'Some PDB file 2' }
Register-Mock Invoke-IndexSources
Register-Mock Invoke-PublishSymbols
foreach ($treatNotIndexedAsWarning in @($true, $false)) {
    # Act.
    $splat = @{
        SymbolsPath = 'Some input symbols path'
        SearchPattern = 'Some input search pattern'
        SourceFolder = '' # Support for sourceFolder has been Deprecated.
        SymbolsProduct = 'Some input symbols product'
        SymbolsVersion = 'Some input symbols version'
        SymbolsMaximumWaitTime = '123'
        SymbolsFolder = 'Some input symbols folder'
        SymbolsArtifactName = 'Some symbols artifact name'
        SkipIndexing = 'false'
        TreatNotIndexedAsWarning = $treatNotIndexedAsWarning.ToString()
    }
    & $PSScriptRoot\..\..\..\Tasks\PublishSymbols\LegacyPublishSymbols.ps1 @splat -NoSuchParam ParamValue -NoSuchSwitch

    # Assert.
    Assert-WasCalled Find-Files -- -SearchPattern 'Some input search pattern' -RootFolder 'Some input symbols folder'
    Assert-WasCalled Invoke-IndexSources -- -SymbolsFilePaths ('Some PDB file 1', 'Some PDB file 2') -TreatNotIndexedAsWarning: $treatNotIndexedAsWarning
    $semaphoreMessage = "Machine: $env:ComputerName, BuildUri: Some build URI, BuildNumber: Some build number, RepositoryName: Some build repository name, RepositoryUri: Some build repository URI, Team Project: Some team project, CollectionUri: Some team foundation collection URI at $($now.ToUniversalTime()) UTC"
    Assert-WasCalled Invoke-PublishSymbols -- -PdbFiles ('Some PDB file 1', 'Some PDB file 2') -Share 'Some input symbols path' -Product 'Some input symbols product' -Version 'Some input symbols version' -MaximumWaitTime (123 * 60 * 1000).ToString() -MaximumSemaphoreAge (24 * 60).ToString() -ArtifactName 'Some symbols artifact name' -SemaphoreMessage $semaphoreMessage
}


text:
var koa         = require("koa");
var serve       = require("koa-static");
var path        = require('path');
var fs          = require("fs");
var config      = require("./config");

var server = koa();
server.use(serve(path.join(__dirname, 'dist')));

var readFileThunk = function(src) {
    return new Promise(function (resolve, reject) {
        fs.readFile(src, 'utf8', function (err, data) {
            if(err) return reject(err);
            resolve(data);
        });
    });
}

server.use(function*(next) {
    try {
        this.body = yield readFileThunk(__dirname + '/dist/index.html');;
    } catch (err){
        console.log('from serverjs',err);
        this.status = err.status || 500;
        if(typeof(err.errors) === 'string' || typeof(err.errors) === 'undefined')
            this.body = [
                {
                    "type" : "custom",
                    "message" : err.errors ? err.errors : err.message,
                    "rule" : "custom"
                }
            ];
        else {
            let errorBody = [];
            for (var error of err.errors) {

                let errorField = Object.keys(error)[0];
                errorBody.push({
                    "type" : error[errorField]["type"],
                    "field" : errorField,
                    "message" : errorConf[error[errorField]["message"]],
                    "rule" : error[errorField]["rule"],
                    "code" : parseInt(error[errorField]["message"],10)
                });
            }
            this.body = errorBody;
        }
    }
});

server.listen(config.serverPort, (err) => {
    if(err) {
        console.error("Server Error: " + err);
    }
    console.info('==> ✅ Server is running on port: ' + config.serverPort);
});


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

		[page:Geometry] →

[name]

A class for generating plane geometries

Example

		var geometry = new THREE.PlaneGeometry( 5, 20, 32 );
		var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
		var plane = new THREE.Mesh( geometry, material );
		scene.add( plane );

Constructor

[name]([param:Float width], [param:Float height], [param:Integer widthSegments], [param:Integer heightSegments])

		width — Width along the X axis. Default is 1.

		height — Height along the Y axis. Default is 1.

		widthSegments — Optional. Default is 1.

		heightSegments — Optional. Default is 1.

Properties

		Each of the contructor parameters is accessible in the parameters property of the object. Any modification of these properties after instantiation does not change the geometry.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]