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

#include "corgi/version.h"

namespace corgi {

#define CORGI_VERSION_MAJOR 1
#define CORGI_VERSION_MINOR 0
#define CORGI_VERSION_REVISION 0

// Turn X into a string literal.
#define CORGI_STRING_EXPAND(X) #X
#define CORGI_STRING(X) CORGI_STRING_EXPAND(X)

/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const CorgiVersion kVersion = {
    CORGI_VERSION_MAJOR, CORGI_VERSION_MINOR, CORGI_VERSION_REVISION,
    "Corgi Entity Library " CORGI_STRING(MOTIVE_VERSION_MAJOR) "." CORGI_STRING(
        MOTIVE_VERSION_MINOR) "." CORGI_STRING(MOTIVE_VERSION_REVISION)};

const CorgiVersion& Version() { return kVersion; }

}  // namespace corgi
<commit_msg>Fixed version number string.<commit_after>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "corgi/version.h"

namespace corgi {

#define CORGI_VERSION_MAJOR 1
#define CORGI_VERSION_MINOR 0
#define CORGI_VERSION_REVISION 0

// Turn X into a string literal.
#define CORGI_STRING_EXPAND(X) #X
#define CORGI_STRING(X) CORGI_STRING_EXPAND(X)

/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const CorgiVersion kVersion = {
    CORGI_VERSION_MAJOR, CORGI_VERSION_MINOR, CORGI_VERSION_REVISION,
    "Corgi Entity Library " CORGI_STRING(CORGI_VERSION_MAJOR) "." CORGI_STRING(
        CORGI_VERSION_MINOR) "." CORGI_STRING(CORGI_VERSION_REVISION)};

const CorgiVersion& Version() { return kVersion; }

}  // namespace corgi
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "c6f905e"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>shade, feature staging<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "6cc45d1"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>#include <string>
#include <cstdlib>
#include <sstream>
#include <iostream>

#include "number.hh"
#include "describe.hh"
#include "test_util.hh"

using namespace std;

static bool result;

template<typename T>
void fail_message(Number::Type t, istream& i,
                  const Number& n, T expect){
  result = false;

  string buf;
  std::getline(i, buf);

  cerr << "[failed] input='" << buf << "', expect type='" << stringify(t) << "'"
       << ", expected = '" << expect << "'\n"
       << "\tgotten: " << n << '\n';
}

void check(istream& i){
  static constexpr auto type = Number::Type::uninitialized;

  with_expect_error([&]() -> void {
      const Number n = parse_number(i);
      if(n.type() != type){
        fail_message(type, i, n, "(uninitialized)");
        return;
      }
    });
}

template<typename T>
void check(istream& i, const T& expect){
  static constexpr auto type = to_tag<Number::Type, T>();

  const Number n = parse_number(i);
  if(n.type() != type || n.get<T>() != expect){
    fail_message(type, i, n, expect);
    return;
  }
}

void check(const string& input){
  stringstream ss(input);
  check(ss);
}

template<typename T>
void check(const string& input, T&& t){
  stringstream ss(input);
  check(ss, t);
}

// printing test
void check(const Number& n, int radix, const char* expect){
  stringstream ss;
  print(ss, n, radix);

  auto evaled = ss.str();

  if(evaled != expect){
    cerr << "[failed] printed " << evaled << ", expected " << expect << "\n";
    result = false;
  }
}

int main(){
  result = true;

  // invalids
  check("hogehoge");
  check(".");

  // int
  check("100", 100l);
  check("-100", -100l);
  check("1##", 100l);

  check("#b10", 2l);
  check("#b-10", -2l);
  check("#o10", 8l);
  check("#o-10", -8l);
  check("#x10", 16l);
  check("#x-10", -16l);
  check("#x9abcdef", 0x9abcdefl);

  // float
  check("-1.1", -1.1);
  check("1.", 1.0);
  check(".1", 0.1);
  check("3.14159265358979e0", 3.14159265358979e0);
  check("0.6s0", 0.6e0);
  check(".1f10", 0.1e10);
  check("3.d2", 3e2);
  check("3#.l-3", 30e-3);

  check("#b1.0");
  check("#o1.0");
  check("#x1.0");
  check("#d1.0", 1.0);

  // complex
  check("1.0+1i", Number::complex_type(1, 1));
  check("-2.5+0.0i", Number::complex_type(-2.5, 0));
  check("1.0@3", polar(1.0, 3.0));
  check("1.0i");
  check("+1.0i", Number::complex_type(0, 1.0));

  // prefix
  check("#e1", 1l);
  check("#i1", 1.0);
  check("#e1.0", 1l);
  check("#i1.0", 1.0);
  check("#e1.0i");
  check("#i-1.0i", Number::complex_type(0, -1.0));

  check("#o#e10", 8l);
  check("#i#x10", 16.0);

  check("#x#x10");
  check("#i#e1");

  // printing test
  check(Number(100l), 10, "100");
  check(Number(100l), 8, "#o144");
  check(Number(100l), 16, "#x64");
  check(Number(100l), 2, "#b1100100");

  check(Number(-100l), 10, "-100");
  check(Number(-100l), 8, "#o-144");
  check(Number(-100l), 16, "#x-64");
  check(Number(-100l), 2, "#b-1100100");

  return (result) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>added test<commit_after>#include <string>
#include <cstdlib>
#include <sstream>
#include <iostream>

#include "number.hh"
#include "describe.hh"
#include "test_util.hh"

using namespace std;

static bool result;

template<typename T>
void fail_message(Number::Type t, istream& i,
                  const Number& n, T expect){
  result = false;

  string buf;
  std::getline(i, buf);

  cerr << "[failed] input='" << buf << "', expect type='" << stringify(t) << "'"
       << ", expected = '" << expect << "'\n"
       << "\tgotten: " << n << '\n';
}

void check(istream& i){
  static constexpr auto type = Number::Type::uninitialized;

  with_expect_error([&]() -> void {
      const Number n = parse_number(i);
      if(n.type() != type){
        fail_message(type, i, n, "(uninitialized)");
        return;
      }
    });
}

template<typename T>
void check(istream& i, const T& expect){
  static constexpr auto type = to_tag<Number::Type, T>();

  const Number n = parse_number(i);
  if(n.type() != type || n.get<T>() != expect){
    fail_message(type, i, n, expect);
    return;
  }
}

void check(const string& input){
  stringstream ss(input);
  check(ss);
}

template<typename T>
void check(const string& input, T&& t){
  stringstream ss(input);
  check(ss, t);
}

// printing test
void check(const Number& n, int radix, const char* expect){
  stringstream ss;
  print(ss, n, radix);

  auto evaled = ss.str();

  if(evaled != expect){
    cerr << "[failed] printed " << evaled << ", expected " << expect << "\n";
    result = false;
  }
}

int main(){
  result = true;

  // invalids
  check("hogehoge");
  check(".");

  // int
  check("100", 100l);
  check("-100", -100l);
  check("1##", 100l);

  check("#b10", 2l);
  check("#b-10", -2l);
  check("#o10", 8l);
  check("#o-10", -8l);
  check("#x10", 16l);
  check("#x-10", -16l);
  check("#x9abcdef", 0x9abcdefl);

  // float
  check("-1.1", -1.1);
  check("1.", 1.0);
  check(".1", 0.1);
  check("3.14159265358979e0", 3.14159265358979e0);
  check("0.6s0", 0.6e0);
  check(".1f10", 0.1e10);
  check("3.d2", 3e2);
  check("3#.l-3", 30e-3);

  check("#b1.0");
  check("#o1.0");
  check("#x1.0");
  check("#d1.0", 1.0);

  // complex
  check("1.0+1i", Number::complex_type(1, 1));
  check("-2.5+0.0i", Number::complex_type(-2.5, 0));
  check("1.0@3", polar(1.0, 3.0));
  check("1.0i");
  check("+1.0i", Number::complex_type(0, 1.0));
  check("+1i", Number::complex_type(0, 1));
  check("+i", Number::complex_type(0, 1));

  // prefix
  check("#e1", 1l);
  check("#i1", 1.0);
  check("#e1.0", 1l);
  check("#i1.0", 1.0);
  check("#e1.0i");
  check("#i-1.0i", Number::complex_type(0, -1.0));

  check("#o#e10", 8l);
  check("#i#x10", 16.0);

  check("#x#x10");
  check("#i#e1");

  // printing test
  check(Number(100l), 10, "100");
  check(Number(100l), 8, "#o144");
  check(Number(100l), 16, "#x64");
  check(Number(100l), 2, "#b1100100");

  check(Number(-100l), 10, "-100");
  check(Number(-100l), 8, "#o-144");
  check(Number(-100l), 16, "#x-64");
  check(Number(-100l), 2, "#b-1100100");

  return (result) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <string>

#include <cpr/cpr.h>

// TODO: This uses private proxy servers and public servers for endpoints. This should be replaced with a source
// code implementation inside server.cpp

#define HTTP_PROXY "192.168.0.180:3128"
#define HTTPS_PROXY "192.168.0.180:3128"
#define PROXY_USER "u$er"
#define PROXY_PASS "p@ss"

using namespace cpr;

// TODO: These should be fixed after a source code implementation of a proxy
#if defined(false)
TEST(ProxyAuthTests, SingleProxyTest) {
    Url url{"https://www.httpbin.org/get"};
    Response response = cpr::Get(url, Proxies{{"https", HTTP_PROXY}}, ProxyAuthentication{{"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, MultipleProxyHttpTest) {
    Url url{"http://www.httpbin.org/get"};
    Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}, {"https", HTTPS_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}, {"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, ProxyHttpsTest) {
    Url url{"https://www.httpbin.org/get"};
    Response response = cpr::Get(url, Proxies{{"https", HTTPS_PROXY}}, ProxyAuthentication{{"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, MultipleProxyHttpsTest) {
    Url url{"https://www.httpbin.org/get"};
    Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}, {"https", HTTPS_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}, {"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, CopyProxyTest) {
    Url url{"http://www.httpbin.org/get"};
    Proxies proxies{{"http", HTTP_PROXY}};
    ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}};
    Response response = cpr::Get(url, proxies, proxy_auth);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, ProxySessionTest) {
    Url url{"http://www.httpbin.org/get"};
    Session session;
    session.SetUrl(url);
    session.SetProxies(Proxies{{"http", HTTP_PROXY}});
    session.SetProxyAuth(ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    Response response = session.Get();
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, ReferenceProxySessionTest) {
    Url url{"http://www.httpbin.org/get"};
    Proxies proxies{{"http", HTTP_PROXY}};
    ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}};
    Session session;
    session.SetUrl(url);
    session.SetProxies(proxies);
    session.SetProxyAuth(proxy_auth);
    Response response = session.Get();
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}
#endif

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>Change to use the library http server for tests<commit_after>#include <gtest/gtest.h>

#include <string>

#include "cpr/cpr.h"
#include "httpServer.hpp"

// TODO: This requires a local proxy server (squid). This should be replaced with a source
// code implementation.

#define HTTP_PROXY "127.0.0.1:3128"
#define HTTPS_PROXY "127.0.0.1:3128"
#define PROXY_USER "u$er"
#define PROXY_PASS "p@ss"

using namespace cpr;

static HttpServer* server = new HttpServer();

// TODO: These should be fixed after a source code implementation of a proxy
#if defined(false)
TEST(ProxyAuthTests, SingleProxyTest) {
    Url url{server->GetBaseUrl() + "/hello.html"};
    Response response = cpr::Get(url, Proxies{{"http", HTTP_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    std::string expected_text{"Hello world!"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, MultipleProxyHttpTest) {
    Url url{server->GetBaseUrl() + "/hello.html"};
    Response response = cpr::Get(url, Proxies{{"https", HTTPS_PROXY}, {"http", HTTP_PROXY}}, ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}, {"https", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    std::string expected_text{"Hello world!"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, CopyProxyTest) {
    Url url{server->GetBaseUrl() + "/hello.html"};
    Proxies proxies{{"http", HTTP_PROXY}};
    ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}};
    Response response = cpr::Get(url, proxies, proxy_auth);
    std::string expected_text{"Hello world!"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, ProxySessionTest) {
    Url url{server->GetBaseUrl() + "/hello.html"};
    Session session;
    session.SetUrl(url);
    session.SetProxies(Proxies{{"http", HTTP_PROXY}});
    session.SetProxyAuth(ProxyAuthentication{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}});
    Response response = session.Get();
    std::string expected_text{"Hello world!"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}

TEST(ProxyAuthTests, ReferenceProxySessionTest) {
    Url url{server->GetBaseUrl() + "/hello.html"};
    Proxies proxies{{"http", HTTP_PROXY}};
    ProxyAuthentication proxy_auth{{"http", EncodedAuthentication{PROXY_USER, PROXY_PASS}}};
    Session session;
    session.SetUrl(url);
    session.SetProxies(proxies);
    session.SetProxyAuth(proxy_auth);
    Response response = session.Get();
    std::string expected_text{"Hello world!"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}
#endif

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(server);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include <yal/yal.hpp>

#include <boost/filesystem.hpp>

#include <cstdio>
#include <cctype>
#include <cerrno>

#include <unordered_map>
#include <algorithm>

namespace yal {

/***************************************************************************/

logger::logger_session_manager_ptr logger::object;
std::once_flag logger::flag;

/***************************************************************************/

namespace detail {

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

struct session::impl {
	impl(const std::string &path, const std::string &name, std::size_t volume_size, std::size_t shift_after)
		:path(path)
		,name(name)
		,volume_size(volume_size)
		,shift_after(shift_after)
		,file(0)
		,toterm(false)
		,prefix()
		,level(yal::info)
		,writen_bytes(0)
		,volume_number(0)
	{
		std::string logpath, logfname;
		auto pos = name.find_last_of('/');
		if ( pos != std::string::npos ) {
			logpath = path + "/" + name.substr(0, pos);
			logfname= name.substr(pos+1);
		} else {
			logpath = path;
			logfname= name;
		}

		if ( (pos=logfname.find('.')) != std::string::npos ) {
			logfname = logfname.substr(0, pos);
		}

		boost::filesystem::directory_iterator fs_beg(logpath), fs_end;
		for ( ; fs_beg != fs_end; ++fs_beg ) {
			auto filename = fs_beg->path().filename().string();
			if ( filename == "." || filename == ".." || boost::filesystem::is_directory(*fs_beg) )
				continue;

			if ( filename.find(logfname+"-") == std::string::npos )
				continue;

			auto beg = std::find(filename.begin(), filename.end(), '-');
			if ( beg == filename.end() || beg+1 == filename.end() )
				continue;

			std::advance(beg, 1);

			if ( !std::isdigit(*beg) )
				continue;

			auto end = beg;
			for ( ; std::isdigit(*end); ++end)
				;

			const std::size_t num = std::stoul(std::string(beg, end)) + 1;
			if ( num > volume_number )
				volume_number = num;
		}

		create_volume();
	}

	~impl() {
		std::fclose(file);
	}

	enum resolution { sec_res, usec_res };

	static std::string datetime(const resolution res) {
		struct timespec ts;
		char buf[128] = "\0";

		clock_gettime(CLOCK_REALTIME, &ts);
		const std::tm *tm = std::localtime(&ts.tv_sec);
		if ( res == usec_res ) {
			std::snprintf(
				 buf, sizeof(buf)
				,"%02d.%02d.%04d-%02d.%02d.%02d-%6ld"
				,tm->tm_mday, tm->tm_mon, tm->tm_year
				,tm->tm_hour, tm->tm_min, tm->tm_sec
				,ts.tv_nsec/1000
			);
		} else {
			std::snprintf(
				 buf, sizeof(buf)
				,"%02d.%02d.%04d-%02d.%02d.%02d"
				,tm->tm_mday, tm->tm_mon, tm->tm_year
				,tm->tm_hour, tm->tm_min, tm->tm_sec
			);
		}

		return std::string(buf);
	}

	std::string volume_fname() {
		std::string result;

		if ( volume_number > shift_after ) {
			shift_after = shift_after * 10 + 9;
		}

		char fmt[64] = {0};
		const int digits = std::log10(shift_after)+1;
		std::snprintf(fmt, sizeof(fmt), "%s%d%s", "%s/%s-%0", digits, "d-%s");

		std::string::const_iterator it = std::find(name.begin(), name.end(), '.');
		if ( it == name.end() ) {
			result = (
				boost::format(fmt)
					% path
					% name
					% volume_number
					% datetime(sec_res)
			).str();
		} else {
			std::strcat(fmt, "%s");
			result = (
				boost::format(fmt)
					% path
					% std::string(name.begin(), it)
					% volume_number
					% datetime(sec_res)
					% std::string(it, name.end())
			).str();
		}

		//std::cout << "shift_after:" << shift_after << ", digits:" << digits << ", fmt:" << fmt << ", name:" << result << std::endl;

		return result;
	}

	void create_volume() {
		const std::string &fname = volume_fname();
		file = std::fopen(fname.c_str(), "wb");
		if ( !file ) {
			int error = errno;
			throw std::runtime_error("yal: cannot create logfile \"" + fname + "\" with errno="+std::to_string(error));
		}
	}

	void set_buffer(std::size_t size) {
		std::setvbuf(file, 0, (size == 0 ? _IONBF : _IOFBF), size);
	}

	void to_term(bool ok, const std::string &pref) {
		toterm = ok;
		prefix = pref;
	}

	void set_level(const yal::level lvl) {
		level = lvl;
	}

	void write(const char *fileline, const char *func, const std::string &data, const yal::level lvl) {
		const char *levelstr = (
			lvl == yal::debug ? "debug  "
				:lvl == yal::error ? "error  "
					:lvl == yal::info ? "info   "
						:lvl == yal::warning ? "warning"
							: 0
		);
		if ( toterm ) {
			auto termlog = ((lvl == yal::info || lvl == yal::debug) ? stdout : stderr);
			if ( prefix.empty() ) {
				std::fprintf(termlog, "[%s][%s][%s][%s]: %s\n", datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());
			} else {
				std::fprintf(termlog, "<%s>[%s][%s][%s][%s]: %s\n", prefix.c_str(), datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());
			}
			std::fflush(termlog);
		}

		const int writen = std::fprintf(file, "[%s][%s][%s][%s]: %s\n", datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());

		if ( writen < 0 ) {
			int error = errno;
			throw std::runtime_error("yal: cannot write to logfile with errno="+std::to_string(error));
		}

		writen_bytes += writen;
		if ( writen_bytes >= volume_size ) {
			writen_bytes = 0;

			std::fclose(file);

			volume_number += 1;
			create_volume();
		}
	}

	void flush() {
		if ( file )
			std::fflush(file);
	}

	const std::string			path;
	const std::string			name;
	const std::size_t			volume_size;
	std::size_t					shift_after;
	FILE							*file;
	bool							toterm;
	std::string					prefix;
	yal::level					level;
	std::size_t					writen_bytes;
	std::size_t					volume_number;
};

/***************************************************************************/

session::session(const std::string &path, const std::string &name, std::size_t volume_size, std::size_t shift_after)
	:pimpl(new impl(path, name, volume_size, shift_after))
{}

session::~session()
{ delete pimpl; }

const std::string &session::name() const { return pimpl->name; }

std::string session::sec_date_str() { return impl::datetime(impl::sec_res).c_str(); }
std::string session::usec_date_str() { return impl::datetime(impl::usec_res).c_str(); }

/***************************************************************************/

void session::set_buffer(const std::size_t size) {
	pimpl->set_buffer(size);
}

void session::to_term(const bool ok, const std::string &pref) {
	pimpl->to_term(ok, pref);
}

void session::set_level(const level lvl) {
	pimpl->set_level(lvl);
}

level session::get_level() const { return pimpl->level; }

void session::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	if ( data.empty() ) return;
	pimpl->write(fileline, func, data, lvl);
}

void session::flush() {
	pimpl->flush();
}

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

struct session_manager::impl {
	using session_weak_ptr = std::weak_ptr<session>;
	using sessions_map = std::unordered_map<std::string, session_weak_ptr>;

	impl()
		:mutex()
		,root_path(".")
		,sessions()
	{}

	template<typename Cont, typename F>
	static void iterate(Cont &cont, F func) {
		for ( auto it = cont.begin(), end = cont.end(); it != end; ) {
			if ( auto session = it->second.lock() ) {
				func(session);
				++it;
			} else {
				it = cont.erase(it);
			}
		}
	}

	std::mutex mutex;
	std::string root_path;
	sessions_map sessions;
}; // struct impl

/***************************************************************************/

session_manager::session_manager()
	:pimpl(new impl)
{}

session_manager::~session_manager() {
	flush();
	delete pimpl;
}

/***************************************************************************/

const std::string &session_manager::root_path() const {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	return pimpl->root_path;
}

void session_manager::root_path(const std::string &path) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	if ( !boost::filesystem::exists(path) )
		boost::filesystem::create_directories(path);

	pimpl->root_path = path;
}

std::shared_ptr<session>
session_manager::create(const std::string &name, std::size_t volume_size, std::size_t shift_after) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	if ( !name.empty() && name[0] == '/' )
		throw std::runtime_error("yal: session name cannot be a full path name");
	if ( !shift_after )
		throw std::runtime_error("yal: shift_after can be 1 or greater");

	impl::iterate(
		 pimpl->sessions
		,[&name](yal::session s) {
			if ( s->name() == name )
				throw std::runtime_error("yal: session \""+name+"\" already exists");
		}
	);

	const auto pos = name.find_last_of('/');
	if ( pos != std::string::npos ) {
		const std::string &path = pimpl->root_path+"/"+name.substr(0, pos);
		//std::cout << "path:" << path << std::endl;
		if ( !boost::filesystem::exists(path) )
			boost::filesystem::create_directories(path);
	}

	yal::session session = std::make_shared<detail::session>(pimpl->root_path, name, volume_size, shift_after);
	pimpl->sessions.insert({name, session});

	return session;
}

/***************************************************************************/

void session_manager::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	impl::iterate(
		 pimpl->sessions
		,[fileline, func, &data, lvl](yal::session s) { s->write(fileline, func, data, lvl); }
	);
}

std::shared_ptr<session>
session_manager::get(const std::string &name) const {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	auto it = pimpl->sessions.find(name);
	if ( it == pimpl->sessions.end() )
		return std::shared_ptr<session>();

	if ( auto s = it->second.lock() ) {
		return s;
	} else {
		pimpl->sessions.erase(it);
		return std::shared_ptr<session>();
	}
}

/***************************************************************************/

void session_manager::flush() {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	impl::iterate(
		 pimpl->sessions
		,[](yal::session s) { s->flush(); }
	);
}

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

} // ns detail

logger::logger_session_manager_ptr logger::instance() {
	std::call_once(flag, &init);
	return object;
}

const std::string &logger::root_path() { return instance()->root_path(); }

session logger::create(const std::string &name, std::size_t volume_size, std::size_t shift_after) {
	return instance()->create(name, volume_size, shift_after);
}

yal::session logger::get(const std::string &name) {
	return instance()->get(name);
}

void logger::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	instance()->write(fileline, func, data, lvl);
}

void logger::flush() { instance()->flush(); }

void logger::init() { object = std::make_shared<logger_session_manager_ptr::element_type>(); }

void logger::root_path(const std::string &path) { instance()->root_path(path); }

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

} // ns yal
<commit_msg>Update yal.cpp<commit_after>#include <yal/yal.hpp>

#include <boost/filesystem.hpp>

#include <cstdio>
#include <cctype>
#include <cerrno>

#include <unordered_map>
#include <algorithm>

namespace yal {

/***************************************************************************/

logger::logger_session_manager_ptr logger::object;
std::once_flag logger::flag;

/***************************************************************************/

namespace detail {

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

struct session::impl {
	impl(const std::string &path, const std::string &name, std::size_t volume_size, std::size_t shift_after)
		:path(path)
		,name(name)
		,volume_size(volume_size)
		,shift_after(shift_after)
		,file(0)
		,toterm(false)
		,prefix()
		,level(yal::info)
		,writen_bytes(0)
		,volume_number(0)
	{
		std::string logpath, logfname;
		auto pos = name.find_last_of('/');
		if ( pos != std::string::npos ) {
			logpath = path + "/" + name.substr(0, pos);
			logfname= name.substr(pos+1);
		} else {
			logpath = path;
			logfname= name;
		}

		if ( (pos=logfname.find('.')) != std::string::npos ) {
			logfname = logfname.substr(0, pos);
		}

		boost::filesystem::directory_iterator fs_beg(logpath), fs_end;
		for ( ; fs_beg != fs_end; ++fs_beg ) {
			auto filename = fs_beg->path().filename().string();
			if ( filename == "." || filename == ".." || boost::filesystem::is_directory(*fs_beg) )
				continue;

			if ( filename.find(logfname+"-") == std::string::npos )
				continue;

			auto beg = std::find(filename.begin(), filename.end(), '-');
			if ( beg == filename.end() || beg+1 == filename.end() )
				continue;

			std::advance(beg, 1);

			if ( !std::isdigit(*beg) )
				continue;

			auto end = beg;
			for ( ; std::isdigit(*end); ++end)
				;

			const std::size_t num = std::stoul(std::string(beg, end)) + 1;
			if ( num > volume_number )
				volume_number = num;
		}

		create_volume();
	}

	~impl() {
		std::fclose(file);
	}

	enum resolution { sec_res, usec_res };

	static std::string datetime(const resolution res) {
		struct timespec ts;
		char buf[128] = "\0";

		clock_gettime(CLOCK_REALTIME, &ts);
		const std::tm *tm = std::localtime(&ts.tv_sec);
		if ( res == usec_res ) {
			std::snprintf(
				 buf, sizeof(buf)
				,"%02d.%02d.%04d-%02d.%02d.%02d-%6ld"
				,tm->tm_mday, tm->tm_mon, tm->tm_year
				,tm->tm_hour, tm->tm_min, tm->tm_sec
				,ts.tv_nsec/1000
			);
		} else {
			std::snprintf(
				 buf, sizeof(buf)
				,"%02d.%02d.%04d-%02d.%02d.%02d"
				,tm->tm_mday, tm->tm_mon, tm->tm_year
				,tm->tm_hour, tm->tm_min, tm->tm_sec
			);
		}

		return std::string(buf);
	}

	std::string volume_fname() {
		std::string result;

		if ( volume_number > shift_after ) {
			shift_after = shift_after * 10 + 9;
		}

		char fmt[64] = {0};
		const int digits = std::log10(shift_after)+1;
		std::snprintf(fmt, sizeof(fmt), "%s%d%s", "%s/%s-%0", digits, "d-%s");

		std::string::const_iterator it = std::find(name.begin(), name.end(), '.');
		if ( it == name.end() ) {
			result = (
				boost::format(fmt)
					% path
					% name
					% volume_number
					% datetime(sec_res)
			).str();
		} else {
			std::strcat(fmt, "%s");
			result = (
				boost::format(fmt)
					% path
					% std::string(name.begin(), it)
					% volume_number
					% datetime(sec_res)
					% std::string(it, name.end())
			).str();
		}

		//std::cout << "shift_after:" << shift_after << ", digits:" << digits << ", fmt:" << fmt << ", name:" << result << std::endl;

		return result;
	}

	void create_volume() {
		const std::string &fname = volume_fname();
		file = std::fopen(fname.c_str(), "wb");
		if ( !file ) {
			int error = errno;
			throw std::runtime_error("yal: cannot create logfile \"" + fname + "\" with errno="+std::to_string(error));
		}
	}

	void set_buffer(std::size_t size) {
		std::setvbuf(file, 0, (size == 0 ? _IONBF : _IOFBF), size);
	}

	void to_term(bool ok, const std::string &pref) {
		toterm = ok;
		prefix = pref;
	}

	void set_level(const yal::level lvl) {
		level = lvl;
	}

	void write(const char *fileline, const char *func, const std::string &data, const yal::level lvl) {
		const char *levelstr = (
			lvl == yal::debug ? "debug  "
				:lvl == yal::error ? "error  "
					:lvl == yal::info ? "info   "
						:lvl == yal::warning ? "warning"
							: 0
		);
		if ( toterm ) {
			auto termlog = ((lvl == yal::info || lvl == yal::debug) ? stdout : stderr);
			if ( prefix.empty() ) {
				std::fprintf(termlog, "[%s][%s][%s][%s]: %s\n", datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());
			} else {
				std::fprintf(termlog, "<%s>[%s][%s][%s][%s]: %s\n", prefix.c_str(), datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());
			}
			std::fflush(termlog);
		}

		const int writen = std::fprintf(file, "[%s][%s][%s][%s]: %s\n", datetime(usec_res).c_str(), levelstr, fileline, func, data.c_str());

		if ( writen < 0 ) {
			int error = errno;
			throw std::runtime_error("yal: cannot write to logfile with errno="+std::to_string(error));
		}

		writen_bytes += writen;
		if ( writen_bytes >= volume_size ) {
			writen_bytes = 0;

			if ( std::fclose(file) != 0 ) {
				int error = errno;
				throw std::runtime_error("yal: cannot close logfile with errno="+std::to_string(error));
			}

			volume_number += 1;
			create_volume();
		}
	}

	void flush() {
		if ( file )
			std::fflush(file);
	}

	const std::string			path;
	const std::string			name;
	const std::size_t			volume_size;
	std::size_t					shift_after;
	FILE							*file;
	bool							toterm;
	std::string					prefix;
	yal::level					level;
	std::size_t					writen_bytes;
	std::size_t					volume_number;
};

/***************************************************************************/

session::session(const std::string &path, const std::string &name, std::size_t volume_size, std::size_t shift_after)
	:pimpl(new impl(path, name, volume_size, shift_after))
{}

session::~session()
{ delete pimpl; }

const std::string &session::name() const { return pimpl->name; }

std::string session::sec_date_str() { return impl::datetime(impl::sec_res).c_str(); }
std::string session::usec_date_str() { return impl::datetime(impl::usec_res).c_str(); }

/***************************************************************************/

void session::set_buffer(const std::size_t size) {
	pimpl->set_buffer(size);
}

void session::to_term(const bool ok, const std::string &pref) {
	pimpl->to_term(ok, pref);
}

void session::set_level(const level lvl) {
	pimpl->set_level(lvl);
}

level session::get_level() const { return pimpl->level; }

void session::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	if ( data.empty() ) return;
	pimpl->write(fileline, func, data, lvl);
}

void session::flush() {
	pimpl->flush();
}

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

struct session_manager::impl {
	using session_weak_ptr = std::weak_ptr<session>;
	using sessions_map = std::unordered_map<std::string, session_weak_ptr>;

	impl()
		:mutex()
		,root_path(".")
		,sessions()
	{}

	template<typename Cont, typename F>
	static void iterate(Cont &cont, F func) {
		for ( auto it = cont.begin(), end = cont.end(); it != end; ) {
			if ( auto session = it->second.lock() ) {
				func(session);
				++it;
			} else {
				it = cont.erase(it);
			}
		}
	}

	std::mutex mutex;
	std::string root_path;
	sessions_map sessions;
}; // struct impl

/***************************************************************************/

session_manager::session_manager()
	:pimpl(new impl)
{}

session_manager::~session_manager() {
	flush();
	delete pimpl;
}

/***************************************************************************/

const std::string &session_manager::root_path() const {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	return pimpl->root_path;
}

void session_manager::root_path(const std::string &path) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	if ( !boost::filesystem::exists(path) )
		boost::filesystem::create_directories(path);

	pimpl->root_path = path;
}

std::shared_ptr<session>
session_manager::create(const std::string &name, std::size_t volume_size, std::size_t shift_after) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	if ( !name.empty() && name[0] == '/' )
		throw std::runtime_error("yal: session name cannot be a full path name");
	if ( !shift_after )
		throw std::runtime_error("yal: shift_after can be 1 or greater");

	impl::iterate(
		 pimpl->sessions
		,[&name](yal::session s) {
			if ( s->name() == name )
				throw std::runtime_error("yal: session \""+name+"\" already exists");
		}
	);

	const auto pos = name.find_last_of('/');
	if ( pos != std::string::npos ) {
		const std::string &path = pimpl->root_path+"/"+name.substr(0, pos);
		//std::cout << "path:" << path << std::endl;
		if ( !boost::filesystem::exists(path) )
			boost::filesystem::create_directories(path);
	}

	yal::session session = std::make_shared<detail::session>(pimpl->root_path, name, volume_size, shift_after);
	pimpl->sessions.insert({name, session});

	return session;
}

/***************************************************************************/

void session_manager::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	impl::iterate(
		 pimpl->sessions
		,[fileline, func, &data, lvl](yal::session s) { s->write(fileline, func, data, lvl); }
	);
}

std::shared_ptr<session>
session_manager::get(const std::string &name) const {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	auto it = pimpl->sessions.find(name);
	if ( it == pimpl->sessions.end() )
		return std::shared_ptr<session>();

	if ( auto s = it->second.lock() ) {
		return s;
	} else {
		pimpl->sessions.erase(it);
		return std::shared_ptr<session>();
	}
}

/***************************************************************************/

void session_manager::flush() {
	std::lock_guard<std::mutex> lock(pimpl->mutex);

	impl::iterate(
		 pimpl->sessions
		,[](yal::session s) { s->flush(); }
	);
}

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

} // ns detail

logger::logger_session_manager_ptr logger::instance() {
	std::call_once(flag, &init);
	return object;
}

const std::string &logger::root_path() { return instance()->root_path(); }

session logger::create(const std::string &name, std::size_t volume_size, std::size_t shift_after) {
	return instance()->create(name, volume_size, shift_after);
}

yal::session logger::get(const std::string &name) {
	return instance()->get(name);
}

void logger::write(const char *fileline, const char *func, const std::string &data, level lvl) {
	instance()->write(fileline, func, data, lvl);
}

void logger::flush() { instance()->flush(); }

void logger::init() { object = std::make_shared<logger_session_manager_ptr::element_type>(); }

void logger::root_path(const std::string &path) { instance()->root_path(path); }

/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

} // ns yal
<|endoftext|>


<commit_before>#ifndef NANOBLAS_TEST_TEST_KERNEL_PACK_HPP
#define NANOBLAS_TEST_TEST_KERNEL_PACK_HPP

#include <iostream>
#include <random>
#include <vector>
#include "nanoblas_kernel.hpp"
#include "lib/util.hpp"
#include "lib/reference_kernel.hpp"

using namespace nanoblas;

template<typename FTYPE>
bool run_pack_test(std::mt19937 gen, const kernel_t<FTYPE> &kernel,
		int len, int packing_slice_len, int packing_slice_real_len,
		ptrdiff_t interval_mn, ptrdiff_t interval_k) {
	std::uniform_real_distribution<FTYPE> dist(0, 1);

	std::vector<FTYPE> mtx(std::max(packing_slice_len * interval_mn, len * interval_k));
	std::vector<FTYPE> ans_pack(packing_slice_len * (len + 8) + 32/sizeof(FTYPE));
	std::vector<FTYPE> tst_pack(packing_slice_len * (len + 8) + 32/sizeof(FTYPE));

	for (auto &&v: mtx) v = dist(gen);
	std::mt19937 gen2 = gen;
	for (auto &&v: ans_pack) v = dist(gen);
	for (auto &&v: tst_pack) v = dist(gen2);

	FTYPE *ans_pack_aligned = reinterpret_cast<FTYPE*>(
			reinterpret_cast<uintptr_t>(ans_pack.data()) + (-reinterpret_cast<uintptr_t>(ans_pack.data()) & 31));
	FTYPE *tst_pack_aligned = reinterpret_cast<FTYPE*>(
			reinterpret_cast<uintptr_t>(tst_pack.data()) + (-reinterpret_cast<uintptr_t>(tst_pack.data()) & 31));

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
	prepack_state_t<FTYPE> st = {
		mtx.data(),
		ans_pack_aligned,
		interval_mn * static_cast<int>(sizeof(FTYPE)),
		interval_k * static_cast<int>(sizeof(FTYPE)),
		packing_slice_len,
		len,
		packing_slice_real_len,
	};
#pragma GCC diagnostic pop

	reference_kernel_pack<FTYPE>(&st);

	st.next_cur = mtx.data();
	st.next_pack_cur = tst_pack_aligned;
	st.remained_len = len;

	kernel.pack(&st);

	bool s = false;
	if (st.next_cur != mtx.data() + interval_k * len) {
		std::cerr << "next_cur is incremented by "<<st.next_cur - mtx.data()<<", not "<<interval_k * len << std::endl;
		s = true;
	}
	for (int i = 0; i < len; i++) {
		for (int j = 0; j < packing_slice_len; j++) {
			FTYPE x = ans_pack_aligned[packing_slice_len*i+j];
			FTYPE y = tst_pack_aligned[packing_slice_len*i+j];
			if (!mostly_equal(x, y)) {
				std::cerr <<
					"ans_pack["<<i<<"]["<<j<<"] = "<<x<<"; " <<
					"tst_pack["<<i<<"]["<<j<<"] = "<<y<<";" << std::endl;
				s = true;
			}
		}
	}
	return s;
}

template<typename FTYPE>
bool run_pack_test(std::mt19937 gen, const kernel_t<FTYPE> &kernel,
		int len, int packing_slice_len,
		ptrdiff_t interval_mn, ptrdiff_t interval_k) {
	return run_pack_test<FTYPE>(gen, kernel, len, packing_slice_len, packing_slice_len, interval_mn, interval_k);
}

#endif
<commit_msg>fix test<commit_after>#ifndef NANOBLAS_TEST_TEST_KERNEL_PACK_HPP
#define NANOBLAS_TEST_TEST_KERNEL_PACK_HPP

#include <iostream>
#include <random>
#include <vector>
#include "nanoblas_kernel.hpp"
#include "lib/util.hpp"
#include "lib/reference_kernel.hpp"

using namespace nanoblas;

template<typename FTYPE>
bool run_pack_test(std::mt19937 gen, const kernel_t<FTYPE> &kernel,
		int len, int packing_slice_len, int packing_slice_real_len,
		ptrdiff_t interval_mn, ptrdiff_t interval_k) {
	std::uniform_real_distribution<FTYPE> dist(0, 1);

	std::vector<FTYPE> mtx(std::max(packing_slice_len * interval_mn, len * interval_k));
	std::vector<FTYPE> ans_pack(packing_slice_len * (len + 8) + 32/sizeof(FTYPE));
	std::vector<FTYPE> tst_pack(packing_slice_len * (len + 8) + 32/sizeof(FTYPE));

	for (auto &&v: mtx) v = dist(gen);
	std::mt19937 gen2 = gen;
	for (auto &&v: ans_pack) v = dist(gen);
	for (auto &&v: tst_pack) v = dist(gen2);

	FTYPE *ans_pack_aligned = reinterpret_cast<FTYPE*>(
			reinterpret_cast<uintptr_t>(ans_pack.data()) + (-reinterpret_cast<uintptr_t>(ans_pack.data()) & 31));
	FTYPE *tst_pack_aligned = reinterpret_cast<FTYPE*>(
			reinterpret_cast<uintptr_t>(tst_pack.data()) + (-reinterpret_cast<uintptr_t>(tst_pack.data()) & 31));

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
	prepack_state_t<FTYPE> st = {
		mtx.data(),
		ans_pack_aligned,
		interval_mn * static_cast<int>(sizeof(FTYPE)),
		interval_k * static_cast<int>(sizeof(FTYPE)),
		packing_slice_len,
		len,
		packing_slice_real_len,
	};
#pragma GCC diagnostic pop

	reference_kernel_pack<FTYPE>(&st);

	st.next_cur = mtx.data();
	st.next_pack_cur = tst_pack_aligned;
	st.remained_len = len;

	kernel.pack(&st);

	bool s = false;
	if (st.next_pack_cur != tst_pack_aligned + packing_slice_len * len) {
		std::cerr << "next_pack_cur is incremented by "<<st.next_pack_cur - tst_pack_aligned<<", not "<<packing_slice_len * len << std::endl;
		s = true;
	}
	for (int i = 0; i < len; i++) {
		for (int j = 0; j < packing_slice_len; j++) {
			FTYPE x = ans_pack_aligned[packing_slice_len*i+j];
			FTYPE y = tst_pack_aligned[packing_slice_len*i+j];
			if (!mostly_equal(x, y)) {
				std::cerr <<
					"ans_pack["<<i<<"]["<<j<<"] = "<<x<<"; " <<
					"tst_pack["<<i<<"]["<<j<<"] = "<<y<<";" << std::endl;
				s = true;
			}
		}
	}
	return s;
}

template<typename FTYPE>
bool run_pack_test(std::mt19937 gen, const kernel_t<FTYPE> &kernel,
		int len, int packing_slice_len,
		ptrdiff_t interval_mn, ptrdiff_t interval_k) {
	return run_pack_test<FTYPE>(gen, kernel, len, packing_slice_len, packing_slice_len, interval_mn, interval_k);
}

#endif
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE MyFirstTest
#define BOOST_TEST_MAIN
#include <cap/utils.h>
#ifdef WITH_DEAL_II
  #include <deal.II/base/types.h>
  #include <deal.II/base/exceptions.h>
#endif
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( test_parse_params )
{
   // create a database
   boost::property_tree::ptree params;

#ifdef WITH_DEAL_II
   // ensure material_ids and boundary_ids are parsed correctly
   params.put("some_material_id", 3);
   params.put("some_boundary_id", 1);
   BOOST_CHECK_EQUAL( params.get<dealii::types::material_id>("some_material_id"), dealii::types::material_id(3) );
   BOOST_CHECK_EQUAL( params.get<dealii::types::material_id>("some_boundary_id"), dealii::types::boundary_id(1) );

   params.put("material_ids", "0,1,2,3");
   std::vector<dealii::types::material_id> material_ids = cap::to_vector<dealii::types::material_id>(params.get<std::string>(("material_ids")));
   BOOST_CHECK_EQUAL( material_ids[0], dealii::types::material_id(0) );
   BOOST_CHECK_EQUAL( material_ids[1], dealii::types::material_id(1) );
   BOOST_CHECK_EQUAL( material_ids[2], dealii::types::material_id(2) );
   BOOST_CHECK_EQUAL( material_ids[3], dealii::types::material_id(3) );
#endif

   // ensure property tree will throw
   params.put("is_a_string", "hello cruel world");
   BOOST_CHECK_THROW( params.get<double>("invalid_key"), boost::property_tree::ptree_bad_path );
   BOOST_CHECK_THROW( params.get<double>("is_a_string"), boost::property_tree::ptree_bad_data );

   // ensure to_string and to_vector are working properly
   params.put("ones",  cap::to_string(std::vector<double>     (10, 1.0)  ));
   params.put("yes",   cap::to_string(std::vector<std::string>(10, "yes")));
   params.put("empty", cap::to_string(std::vector<int>        ()         ));
   std::vector<double>      ones  = cap::to_vector<double>     (params.get<std::string>("ones") );
   std::vector<std::string> yes   = cap::to_vector<std::string>(params.get<std::string>("yes")  );
   std::vector<int>         empty = cap::to_vector<int>        (params.get<std::string>("empty"));
   BOOST_FOREACH(double const & val, ones)
       BOOST_CHECK_EQUAL( val, 1.0 );
   BOOST_FOREACH(std::string const & val, yes)
       BOOST_CHECK_EQUAL( val, "yes" );
   BOOST_CHECK( empty.empty() );

   // ensure entry is overwritten
   std::string const default_value("default");
   std::string const path("some.path");
   params.put(path, default_value);
   BOOST_CHECK_EQUAL(default_value.compare(params.get<std::string>(path)), 0);
   std::string const new_value("new");
   params.put(path, new_value);
   BOOST_CHECK_EQUAL(new_value.compare(params.get<std::string>(path)), 0);
   BOOST_CHECK_THROW(params.get<double>(path), boost::property_tree::ptree_bad_data);
   double const pi = 3.14159265359;
   params.put(path, pi);
   BOOST_CHECK_EQUAL(params.get<double>(path), pi);
   std::string const pi_to_string = std::to_string(pi);
   std::size_t const precision = 6;
   BOOST_CHECK_EQUAL(pi_to_string.compare(0, precision+1, params.get<std::string>(path), 0, precision+1), 0);

}
<commit_msg>no space allowed when parsing vector (fixme?)<commit_after>#define BOOST_TEST_MODULE MyFirstTest
#define BOOST_TEST_MAIN
#include <cap/utils.h>
#ifdef WITH_DEAL_II
  #include <deal.II/base/types.h>
  #include <deal.II/base/exceptions.h>
#endif
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( test_parse_params )
{
   // create a database
   boost::property_tree::ptree params;

#ifdef WITH_DEAL_II
   // ensure material_ids and boundary_ids are parsed correctly
   params.put("some_material_id", 3);
   params.put("some_boundary_id", 1);
   BOOST_CHECK_EQUAL( params.get<dealii::types::material_id>("some_material_id"), dealii::types::material_id(3) );
   BOOST_CHECK_EQUAL( params.get<dealii::types::material_id>("some_boundary_id"), dealii::types::boundary_id(1) );

   params.put("material_ids", "0,1,2,3");
   std::vector<dealii::types::material_id> material_ids = cap::to_vector<dealii::types::material_id>(params.get<std::string>(("material_ids")));
   BOOST_CHECK_EQUAL( material_ids[0], dealii::types::material_id(0) );
   BOOST_CHECK_EQUAL( material_ids[1], dealii::types::material_id(1) );
   BOOST_CHECK_EQUAL( material_ids[2], dealii::types::material_id(2) );
   BOOST_CHECK_EQUAL( material_ids[3], dealii::types::material_id(3) );
#endif

   // ensure property tree will throw
   params.put("is_a_string", "hello cruel world");
   BOOST_CHECK_THROW( params.get<double>("invalid_key"), boost::property_tree::ptree_bad_path );
   BOOST_CHECK_THROW( params.get<double>("is_a_string"), boost::property_tree::ptree_bad_data );

   // ensure to_string and to_vector are working properly
   params.put("ones",  cap::to_string(std::vector<double>     (10, 1.0)  ));
   params.put("yes",   cap::to_string(std::vector<std::string>(10, "yes")));
   params.put("empty", cap::to_string(std::vector<int>        ()         ));
   std::vector<double>      ones  = cap::to_vector<double>     (params.get<std::string>("ones") );
   std::vector<std::string> yes   = cap::to_vector<std::string>(params.get<std::string>("yes")  );
   std::vector<int>         empty = cap::to_vector<int>        (params.get<std::string>("empty"));
   BOOST_FOREACH(double const & val, ones)
       BOOST_CHECK_EQUAL( val, 1.0 );
   BOOST_FOREACH(std::string const & val, yes)
       BOOST_CHECK_EQUAL( val, "yes" );
   BOOST_CHECK( empty.empty() );
   // no space allowed
   std::vector<double> bugfixme = { 1.234, 5.678 };
   params.put("bugfixme", "1.234,5.678");
   std::vector<double> fixed =
       cap::to_vector<double>(params.get<std::string>("bugfixme"));
   BOOST_TEST(bugfixme == fixed);

   // ensure entry is overwritten
   std::string const default_value("default");
   std::string const path("some.path");
   params.put(path, default_value);
   BOOST_CHECK_EQUAL(default_value.compare(params.get<std::string>(path)), 0);
   std::string const new_value("new");
   params.put(path, new_value);
   BOOST_CHECK_EQUAL(new_value.compare(params.get<std::string>(path)), 0);
   BOOST_CHECK_THROW(params.get<double>(path), boost::property_tree::ptree_bad_data);
   double const pi = 3.14159265359;
   params.put(path, pi);
   BOOST_CHECK_EQUAL(params.get<double>(path), pi);
   std::string const pi_to_string = std::to_string(pi);
   std::size_t const precision = 6;
   BOOST_CHECK_EQUAL(pi_to_string.compare(0, precision+1, params.get<std::string>(path), 0, precision+1), 0);

}
<|endoftext|>


<commit_before>// Filename: httpCookie.cxx
// Created by:  drose (26Aug04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////

#include "httpCookie.h"

#ifdef HAVE_OPENSSL

#include "ctype.h"
#include "httpChannel.h"

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::operator <
//       Access: Published
//  Description: The sorting operator allows the cookies to be stored
//               in a single dictionary; it returns nonequal only if
//               the cookies are different in name, path, or domain.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
operator < (const HTTPCookie &other) const {
  if (_domain != other._domain) {
    return _domain < other._domain;
  }

  if (_path != other._path) {
    // We use reverse sorting on the path, so that cookies with longer
    // paths will be sent to the server before cookies with shorter
    // paths.
    return _path > other._path;
  }

  if (_name != other._name) {
    return _name < other._name;
  }

  return false;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::update_from
//       Access: Published
//  Description: Assuming the operator < method, above, has already
//               evaluated these two cookies as equal, then assign the
//               remaining values (value, expiration date, secure
//               flag) from the indicated cookie.  This is guaranteed
//               not to change the ordering of the cookie in a set,
//               and so can be used to update an existing cookie
//               within a set with new values.
////////////////////////////////////////////////////////////////////
void HTTPCookie::
update_from(const HTTPCookie &other) {
  nassertv(!(other < *this) && !(*this < other));

  _value = other._value;
  _expires = other._expires;
  _secure = other._secure;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::parse_set_cookie
//       Access: Published
//  Description: Separates out the parameter/value pairs of the
//               Set-Cookie header and assigns the values of the
//               cookie appropriate.  Returns true if the header is
//               parsed correctly, false if something is not
//               understood.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
parse_set_cookie(const string &format, const URLSpec &url) {
  _name = string();
  _value = string();
  _domain = url.get_server();
  _path = url.get_path();
  _expires = HTTPDate();
  _secure = false;

  bool okflag = true;
  bool first_param = true;

  size_t start = 0;
  while (start < format.length() && isspace(format[start])) {
    start++;
  }
  size_t semicolon = format.find(';', start);

  while (semicolon != string::npos) {
    if (!parse_cookie_param(format.substr(start, semicolon - start),
                            first_param)) {
      okflag = false;
    }
    first_param = false;
    start = semicolon + 1;
    while (start < format.length() && isspace(format[start])) {
      start++;
    }
    semicolon = format.find(';', start);
  }

  if (!parse_cookie_param(format.substr(start), first_param)) {
    okflag = false;
  }

  return okflag;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::matches_url
//       Access: Published
//  Description: Returns true if the cookie is appropriate to send
//               with the indicated URL request, false otherwise.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
matches_url(const URLSpec &url) const {
  if (_domain.empty()) {
    return false;
  }
  string server = url.get_server();
  if (server == _domain ||
      (server.length() > _domain.length() &&
       server.substr(server.length() - _domain.length()) == _domain &&
       (_domain[0] == '.' || server[server.length() - _domain.length() - 1] == '.'))) {
    // The domain matches.

    string path = url.get_path();
    if (path.length() >= _path.length() &&
        path.substr(0, _path.length()) == _path) {

      // The path matches too.
      if (_secure && !url.is_ssl()) {
        // Oops, can't send a secure cookie over a non-secure connection.
        return false;
      }

      return true;
    }
  }

  return false;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::output
//       Access: Published
//  Description:
////////////////////////////////////////////////////////////////////
void HTTPCookie::
output(ostream &out) const {
  out << _name << "=" << _value
      << "; path=" << _path << "; domain=" << _domain;

  if (has_expires()) {
    out << "; expires=" << _expires;
  }

  if (_secure) {
    out << "; secure";
  }
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::parse_cookie_param
//       Access: Private
//  Description: Called internally by parse_set_cookie() with each
//               parameter=value pair split out from the header
//               string.  first_param will be true for the first
//               parameter (which has special meaning).  This should
//               return true on success, false on failure.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
parse_cookie_param(const string &param, bool first_param) {
  size_t equals = param.find('=');

  string key, value;
  if (equals == string::npos) {
    key = param;
  } else {
    key = param.substr(0, equals);
    value = param.substr(equals + 1);
  }

  if (first_param) {
    _name = key;
    _value = value;

  } else {
    key = HTTPChannel::downcase(key);
    if (key == "expires") {
      _expires = HTTPDate(value);
      if (!_expires.is_valid()) {
        return false;
      }

    } else if (key == "path") {
      _path = value;

    } else if (key == "domain") {
      _domain = HTTPChannel::downcase(value);

    } else if (key == "secure") {
      _secure = true;

    } else {
      return false;
    }
  }

  return true;
}

#endif  // HAVE_OPENSSL
<commit_msg>minor cookie domain issue<commit_after>// Filename: httpCookie.cxx
// Created by:  drose (26Aug04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////

#include "httpCookie.h"

#ifdef HAVE_OPENSSL

#include "ctype.h"
#include "httpChannel.h"

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::operator <
//       Access: Published
//  Description: The sorting operator allows the cookies to be stored
//               in a single dictionary; it returns nonequal only if
//               the cookies are different in name, path, or domain.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
operator < (const HTTPCookie &other) const {
  if (_domain != other._domain) {
    return _domain < other._domain;
  }

  if (_path != other._path) {
    // We use reverse sorting on the path, so that cookies with longer
    // paths will be sent to the server before cookies with shorter
    // paths.
    return _path > other._path;
  }

  if (_name != other._name) {
    return _name < other._name;
  }

  return false;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::update_from
//       Access: Published
//  Description: Assuming the operator < method, above, has already
//               evaluated these two cookies as equal, then assign the
//               remaining values (value, expiration date, secure
//               flag) from the indicated cookie.  This is guaranteed
//               not to change the ordering of the cookie in a set,
//               and so can be used to update an existing cookie
//               within a set with new values.
////////////////////////////////////////////////////////////////////
void HTTPCookie::
update_from(const HTTPCookie &other) {
  nassertv(!(other < *this) && !(*this < other));

  _value = other._value;
  _expires = other._expires;
  _secure = other._secure;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::parse_set_cookie
//       Access: Published
//  Description: Separates out the parameter/value pairs of the
//               Set-Cookie header and assigns the values of the
//               cookie appropriate.  Returns true if the header is
//               parsed correctly, false if something is not
//               understood.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
parse_set_cookie(const string &format, const URLSpec &url) {
  _name = string();
  _value = string();
  _domain = url.get_server();
  _path = url.get_path();
  _expires = HTTPDate();
  _secure = false;

  bool okflag = true;
  bool first_param = true;

  size_t start = 0;
  while (start < format.length() && isspace(format[start])) {
    start++;
  }
  size_t semicolon = format.find(';', start);

  while (semicolon != string::npos) {
    if (!parse_cookie_param(format.substr(start, semicolon - start),
                            first_param)) {
      okflag = false;
    }
    first_param = false;
    start = semicolon + 1;
    while (start < format.length() && isspace(format[start])) {
      start++;
    }
    semicolon = format.find(';', start);
  }

  if (!parse_cookie_param(format.substr(start), first_param)) {
    okflag = false;
  }

  return okflag;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::matches_url
//       Access: Published
//  Description: Returns true if the cookie is appropriate to send
//               with the indicated URL request, false otherwise.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
matches_url(const URLSpec &url) const {
  if (_domain.empty()) {
    return false;
  }
  string server = url.get_server();
  if (server == _domain ||
      (server.length() > _domain.length() &&
       server.substr(server.length() - _domain.length()) == _domain &&
       (_domain[0] == '.' || server[server.length() - _domain.length() - 1] == '.'))) {
    // The domain matches.

    string path = url.get_path();
    if (path.length() >= _path.length() &&
        path.substr(0, _path.length()) == _path) {

      // The path matches too.
      if (_secure && !url.is_ssl()) {
        // Oops, can't send a secure cookie over a non-secure connection.
        return false;
      }

      return true;
    }
  }

  return false;
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::output
//       Access: Published
//  Description:
////////////////////////////////////////////////////////////////////
void HTTPCookie::
output(ostream &out) const {
  out << _name << "=" << _value
      << "; path=" << _path << "; domain=" << _domain;

  if (has_expires()) {
    out << "; expires=" << _expires;
  }

  if (_secure) {
    out << "; secure";
  }
}

////////////////////////////////////////////////////////////////////
//     Function: HTTPCookie::parse_cookie_param
//       Access: Private
//  Description: Called internally by parse_set_cookie() with each
//               parameter=value pair split out from the header
//               string.  first_param will be true for the first
//               parameter (which has special meaning).  This should
//               return true on success, false on failure.
////////////////////////////////////////////////////////////////////
bool HTTPCookie::
parse_cookie_param(const string &param, bool first_param) {
  size_t equals = param.find('=');

  string key, value;
  if (equals == string::npos) {
    key = param;
  } else {
    key = param.substr(0, equals);
    value = param.substr(equals + 1);
  }

  if (first_param) {
    _name = key;
    _value = value;

  } else {
    key = HTTPChannel::downcase(key);
    if (key == "expires") {
      _expires = HTTPDate(value);
      if (!_expires.is_valid()) {
        return false;
      }

    } else if (key == "path") {
      _path = value;

    } else if (key == "domain") {
      _domain = HTTPChannel::downcase(value);

      // From RFC 2965: If an explicitly specified value does not
      // start with a dot, the user agent supplies a leading dot.
      if (!_domain.empty() && _domain[0] != '.') {
        _domain = string(".") + _domain;
      }

    } else if (key == "secure") {
      _secure = true;

    } else {
      return false;
    }
  }

  return true;
}

#endif  // HAVE_OPENSSL
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cassert>
#include "zmqpp/zmqpp.hpp"

int main()
{
  zmqpp::context ctx;
  zmqpp::socket req(ctx, zmqpp::socket_type::request);
  zmqpp::socket rep(ctx, zmqpp::socket_type::reply);

  rep.bind("inproc://test.sock");
  req.connect("inproc://test.sock");

  zmqpp::message reqMsg;
  reqMsg << "hello";
  req.send(reqMsg);

  zmqpp::message receivedReqMsg;
  rep.receive(receivedReqMsg);
  assert(receivedReqMsg.get(0) == reqMsg.get(0));

  zmqpp::message repMsg;
  repMsg << "world";
  rep.send(repMsg);

  zmqpp::message receivedRepMsg;
  req.receive(receivedRepMsg);
  assert(receivedRepMsg.get(0) == repMsg.get(0));

  return 0;
}
<commit_msg>do not compare with message already sent out.<commit_after>#include <iostream>
#include <string>
#include <cassert>
#include "zmqpp/zmqpp.hpp"

int main()
{
  zmqpp::context ctx;
  zmqpp::socket req(ctx, zmqpp::socket_type::request);
  zmqpp::socket rep(ctx, zmqpp::socket_type::reply);

  rep.bind("inproc://test.sock");
  req.connect("inproc://test.sock");

  zmqpp::message reqMsg;
  reqMsg << "hello";
  req.send(reqMsg);

  zmqpp::message receivedMsg;
  rep.receive(receivedMsg);
  assert(receivedMsg.get(0) == "hello");

  zmqpp::message repMsg;
  repMsg << "world";
  rep.send(repMsg);

  req.receive(receivedMsg);
  assert(receivedMsg.get(0) == "world");

  return 0;
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkColor.h"
#include "SkColorFilter.h"
#include "SkRandom.h"
#include "SkXfermode.h"

static SkFlattenable* reincarnate_flattenable(SkFlattenable* obj) {
    SkFlattenable::Factory fact = obj->getFactory();
    if (NULL == fact) {
        return NULL;
    }

    SkFlattenableWriteBuffer wb(1024);
    obj->flatten(wb);

    size_t size = wb.size();
    SkAutoSMalloc<1024> storage(size);
    // make a copy into storage
    wb.flatten(storage.get());

    SkFlattenableReadBuffer rb(storage.get(), size);
    return fact(rb);
}

template <typename T> T* reincarnate(T* obj) {
    return (T*)reincarnate_flattenable(obj);
}

///////////////////////////////////////////////////////////////////////////////

#define ILLEGAL_MODE    ((SkXfermode::Mode)-1)

static void test_asColorMode(skiatest::Reporter* reporter) {
    SkRandom rand;

    for (int mode = 0; mode <= SkXfermode::kLastMode; mode++) {
        SkColor color = rand.nextU();

        // ensure we always get a filter, by avoiding the possibility of a
        // special case that would return NULL (if color's alpha is 0 or 0xFF)
        color = SkColorSetA(color, 0x7F);

        SkColorFilter* cf = SkColorFilter::CreateModeFilter(color,
                                                        (SkXfermode::Mode)mode);

        // allow for no filter if we're in Dst mode (its a no op)
        if (SkXfermode::kDst_Mode == mode && NULL == cf) {
            continue;
        }

        SkAutoUnref aur(cf);
        REPORTER_ASSERT(reporter, cf);

        SkColor c = ~color;
        SkXfermode::Mode m = ILLEGAL_MODE;

        SkColor expectedColor = color;
        SkXfermode::Mode expectedMode = (SkXfermode::Mode)mode;

//        SkDebugf("--- mc [%d %x] ", mode, color);

        REPORTER_ASSERT(reporter, cf->asColorMode(&c, &m));
        // handle special-case folding by the factory
        if (SkXfermode::kClear_Mode == mode) {
            if (c != expectedColor) {
                expectedColor = 0;
            }
            if (m != expectedMode) {
                expectedMode = SkXfermode::kSrc_Mode;
            }
        }

//        SkDebugf("--- got [%d %x] expected [%d %x]\n", m, c, expectedMode, expectedColor);

        REPORTER_ASSERT(reporter, c == expectedColor);
        REPORTER_ASSERT(reporter, m == expectedMode);

        {
            SkColorFilter* cf2 = reincarnate(cf);
            SkAutoUnref aur2(cf2);
            REPORTER_ASSERT(reporter, cf2);

            SkColor c2 = ~color;
            SkXfermode::Mode m2 = ILLEGAL_MODE;
            REPORTER_ASSERT(reporter, cf2->asColorMode(&c2, &m2));
            REPORTER_ASSERT(reporter, c2 == expectedColor);
            REPORTER_ASSERT(reporter, m2 == expectedMode);
        }
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("ColorFilter", ColorFilterTestClass, test_asColorMode)
<commit_msg>Fix test to use the flattenable writer class instead of flattening the object directly. Review URL: https://codereview.appspot.com/5901059<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkColor.h"
#include "SkColorFilter.h"
#include "SkRandom.h"
#include "SkXfermode.h"

static SkFlattenable* reincarnate_flattenable(SkFlattenable* obj) {
    SkFlattenableWriteBuffer wb(1024);
    wb.writeFlattenable(obj);

    size_t size = wb.size();
    SkAutoSMalloc<1024> storage(size);
    // make a copy into storage
    wb.flatten(storage.get());

    SkFlattenableReadBuffer rb(storage.get(), size);
    return rb.readFlattenable();
}

template <typename T> T* reincarnate(T* obj) {
    return (T*)reincarnate_flattenable(obj);
}

///////////////////////////////////////////////////////////////////////////////

#define ILLEGAL_MODE    ((SkXfermode::Mode)-1)

static void test_asColorMode(skiatest::Reporter* reporter) {
    SkRandom rand;

    for (int mode = 0; mode <= SkXfermode::kLastMode; mode++) {
        SkColor color = rand.nextU();

        // ensure we always get a filter, by avoiding the possibility of a
        // special case that would return NULL (if color's alpha is 0 or 0xFF)
        color = SkColorSetA(color, 0x7F);

        SkColorFilter* cf = SkColorFilter::CreateModeFilter(color,
                                                        (SkXfermode::Mode)mode);

        // allow for no filter if we're in Dst mode (its a no op)
        if (SkXfermode::kDst_Mode == mode && NULL == cf) {
            continue;
        }

        SkAutoUnref aur(cf);
        REPORTER_ASSERT(reporter, cf);

        SkColor c = ~color;
        SkXfermode::Mode m = ILLEGAL_MODE;

        SkColor expectedColor = color;
        SkXfermode::Mode expectedMode = (SkXfermode::Mode)mode;

//        SkDebugf("--- mc [%d %x] ", mode, color);

        REPORTER_ASSERT(reporter, cf->asColorMode(&c, &m));
        // handle special-case folding by the factory
        if (SkXfermode::kClear_Mode == mode) {
            if (c != expectedColor) {
                expectedColor = 0;
            }
            if (m != expectedMode) {
                expectedMode = SkXfermode::kSrc_Mode;
            }
        }

//        SkDebugf("--- got [%d %x] expected [%d %x]\n", m, c, expectedMode, expectedColor);

        REPORTER_ASSERT(reporter, c == expectedColor);
        REPORTER_ASSERT(reporter, m == expectedMode);

        {
            SkColorFilter* cf2 = reincarnate(cf);
            SkAutoUnref aur2(cf2);
            REPORTER_ASSERT(reporter, cf2);

            SkColor c2 = ~color;
            SkXfermode::Mode m2 = ILLEGAL_MODE;
            REPORTER_ASSERT(reporter, cf2->asColorMode(&c2, &m2));
            REPORTER_ASSERT(reporter, c2 == expectedColor);
            REPORTER_ASSERT(reporter, m2 == expectedMode);
        }
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("ColorFilter", ColorFilterTestClass, test_asColorMode)
<|endoftext|>


<commit_before>// Copyright 2012-2017 CNRS-UM LIRMM, CNRS-AIST JRL
//
// This file is part of SpaceVecAlg.
//
// SpaceVecAlg is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SpaceVecAlg is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with SpaceVecAlg.  If not, see <http://www.gnu.org/licenses/>.

// check memory allocation in some method
#define EIGEN_RUNTIME_NO_MALLOC

// includes
// std
#include <iostream>

// boost
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE PTransformd test
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>

// SpaceVecAlg
#include <SpaceVecAlg/SpaceVecAlg>
#include <SpaceVecAlg/Conversions.h>

BOOST_AUTO_TEST_CASE(ConversionsHomogeneous)
{
    using namespace Eigen;
    using namespace sva;

    Matrix4d hom = Matrix4d::Zero();
    hom(0,1) = -1;
    hom(1,0) = +1;
    hom(2,2) = +1;
    hom(3,3) = +1;
    PTransformd pt = conversions::fromHomogeneous(hom, conversions::RightHanded);

    const Vector4d vec(4,3,2,1);
    Matrix4d homVec = Matrix4d::Identity();
    homVec.block<4,1>(0,3) = vec;
    PTransformd ptVec = conversions::fromHomogeneous(homVec, conversions::RightHanded);

    Matrix4d hom2 = conversions::toHomogeneous(pt, conversions::RightHanded);

    const PTransformd rotatedPT= ptVec*pt;
    const Vector4d rotated = hom*vec;
    const Vector4d rotated2 = hom2*vec;

    BOOST_CHECK_EQUAL(rotated, rotated2);
    BOOST_CHECK_EQUAL((rotated.block<3,1>(0,0)), rotatedPT.translation());
}

BOOST_AUTO_TEST_CASE(ConversionsEigenTransform)
{
    using namespace Eigen;
    using namespace sva;

    PTransformd pt(sva::RotX(M_PI/2)*sva::RotZ(M_PI/4), Eigen::Vector3d(1., 2., 3.));
    conversions::affine3_t<double> et = conversions::toAffine(pt, conversions::RightHanded);
    PTransformd pt2 = conversions::fromAffine(et, conversions::RightHanded);

    BOOST_CHECK_SMALL(sva::transformError(pt, pt2).vector().norm(), 1e-12);

    conversions::affine3_t<double> etL = conversions::toAffine(pt, conversions::LeftHanded);
    PTransformd pt3 = conversions::fromAffine(etL, conversions::LeftHanded);

    BOOST_CHECK_SMALL(sva::transformError(pt, pt3).vector().norm(), 1e-12);

    Eigen::Vector3d vec(5, 7, 12);

    sva::PTransformd transformed = sva::PTransformd(vec)*pt;
    Eigen::Vector3d affineTransformed = et*vec;

    std::cout << transformed.translation().transpose() << std::endl;
    std::cout << affineTransformed.transpose() << std::endl;

    BOOST_CHECK_EQUAL(transformed.translation(), affineTransformed);
}
<commit_msg>Use boost::math::constants::pi<double> instead of M_PI<commit_after>// Copyright 2012-2017 CNRS-UM LIRMM, CNRS-AIST JRL
//
// This file is part of SpaceVecAlg.
//
// SpaceVecAlg is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SpaceVecAlg is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with SpaceVecAlg.  If not, see <http://www.gnu.org/licenses/>.

// check memory allocation in some method
#define EIGEN_RUNTIME_NO_MALLOC

// includes
// std
#include <iostream>

// boost
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE PTransformd test
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>

// SpaceVecAlg
#include <SpaceVecAlg/SpaceVecAlg>
#include <SpaceVecAlg/Conversions.h>

namespace sva
{
  static constexpr double PI = boost::math::constants::pi<double>();
}

BOOST_AUTO_TEST_CASE(ConversionsHomogeneous)
{
    using namespace Eigen;
    using namespace sva;

    Matrix4d hom = Matrix4d::Zero();
    hom(0,1) = -1;
    hom(1,0) = +1;
    hom(2,2) = +1;
    hom(3,3) = +1;
    PTransformd pt = conversions::fromHomogeneous(hom, conversions::RightHanded);

    const Vector4d vec(4,3,2,1);
    Matrix4d homVec = Matrix4d::Identity();
    homVec.block<4,1>(0,3) = vec;
    PTransformd ptVec = conversions::fromHomogeneous(homVec, conversions::RightHanded);

    Matrix4d hom2 = conversions::toHomogeneous(pt, conversions::RightHanded);

    const PTransformd rotatedPT= ptVec*pt;
    const Vector4d rotated = hom*vec;
    const Vector4d rotated2 = hom2*vec;

    BOOST_CHECK_EQUAL(rotated, rotated2);
    BOOST_CHECK_EQUAL((rotated.block<3,1>(0,0)), rotatedPT.translation());
}

BOOST_AUTO_TEST_CASE(ConversionsEigenTransform)
{
    using namespace Eigen;
    using namespace sva;

    PTransformd pt(sva::RotX(sva::PI/2)*sva::RotZ(sva::PI/4), Eigen::Vector3d(1., 2., 3.));
    conversions::affine3_t<double> et = conversions::toAffine(pt, conversions::RightHanded);
    PTransformd pt2 = conversions::fromAffine(et, conversions::RightHanded);

    BOOST_CHECK_SMALL(sva::transformError(pt, pt2).vector().norm(), 1e-12);

    conversions::affine3_t<double> etL = conversions::toAffine(pt, conversions::LeftHanded);
    PTransformd pt3 = conversions::fromAffine(etL, conversions::LeftHanded);

    BOOST_CHECK_SMALL(sva::transformError(pt, pt3).vector().norm(), 1e-12);

    Eigen::Vector3d vec(5, 7, 12);

    sva::PTransformd transformed = sva::PTransformd(vec)*pt;
    Eigen::Vector3d affineTransformed = et*vec;

    std::cout << transformed.translation().transpose() << std::endl;
    std::cout << affineTransformed.transpose() << std::endl;

    BOOST_CHECK_EQUAL(transformed.translation(), affineTransformed);
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Foobar is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * State test functions.
 */

#include <secp256k1.h>
#include <BlockChain.h>
#include <State.h>
using namespace std;
using namespace eth;

int stateTest()
{
	KeyPair me = sha3("Gav Wood");
	KeyPair myMiner = sha3("Gav's Miner");
//	KeyPair you = sha3("123");

	Defaults::setDBPath("/tmp");

	Overlay stateDB = State::openDB();
	BlockChain bc;
	State s(myMiner.address(), stateDB);

	cout << bc;

	// Sync up - this won't do much until we use the last state.
	s.sync(bc);

	cout << s;

	// Mine to get some ether!
	s.commitToMine(bc);
	while (s.mine(100).completed) {}
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	// Inject a transaction to transfer funds from miner to me.
	bytes tx;
	{
		Transaction t;
		t.nonce = s.transactionsFrom(myMiner.address());
		t.fee = 0;
		t.value = 1000;			// 1e3 wei.
		t.receiveAddress = me.address();
		t.sign(myMiner.secret());
		assert(t.sender() == myMiner.address());
		tx = t.rlp();
	}
	s.execute(tx);

	cout << s;

	// Mine to get some ether and set in stone.
	s.commitToMine(bc);
	while (s.mine(100).completed) {}
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	return 0;
}

<commit_msg>Repot defaults.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Foobar is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * State test functions.
 */

#include <secp256k1.h>
#include <BlockChain.h>
#include <State.h>
#include <Defaults.h>
using namespace std;
using namespace eth;

int stateTest()
{
	KeyPair me = sha3("Gav Wood");
	KeyPair myMiner = sha3("Gav's Miner");
//	KeyPair you = sha3("123");

	Defaults::setDBPath("/tmp");

	Overlay stateDB = State::openDB();
	BlockChain bc;
	State s(myMiner.address(), stateDB);

	cout << bc;

	// Sync up - this won't do much until we use the last state.
	s.sync(bc);

	cout << s;

	// Mine to get some ether!
	s.commitToMine(bc);
	while (s.mine(100).completed) {}
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	// Inject a transaction to transfer funds from miner to me.
	bytes tx;
	{
		Transaction t;
		t.nonce = s.transactionsFrom(myMiner.address());
		t.fee = 0;
		t.value = 1000;			// 1e3 wei.
		t.receiveAddress = me.address();
		t.sign(myMiner.secret());
		assert(t.sender() == myMiner.address());
		tx = t.rlp();
	}
	s.execute(tx);

	cout << s;

	// Mine to get some ether and set in stone.
	s.commitToMine(bc);
	while (s.mine(100).completed) {}
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	return 0;
}

<|endoftext|>