text:
// Copyright (C) 2013 Vicente Botet
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// B

#include <malloc.h>
#include <boost/thread/thread.hpp>

#include <boost/thread/mutex.hpp>

#include <boost/bind.hpp>

#include <iostream>

       static void
       display_mallinfo()
       {
           struct mallinfo mi;

           mi = mallinfo();

           printf("Total non-mmapped bytes (arena):       %d\n", mi.arena);
           printf("# of free chunks (ordblks):            %d\n", mi.ordblks);
           printf("# of free fastbin blocks (smblks):     %d\n", mi.smblks);
           printf("# of mapped regions (hblks):           %d\n", mi.hblks);
           printf("Bytes in mapped regions (hblkhd):      %d\n", mi.hblkhd);
           printf("Max. total allocated space (usmblks):  %d\n", mi.usmblks);
           printf("Free bytes held in fastbins (fsmblks): %d\n", mi.fsmblks);
           printf("Total allocated space (uordblks):      %d\n", mi.uordblks);
           printf("Total free space (fordblks):           %d\n", mi.fordblks);
           printf("Topmost releasable block (keepcost):   %d\n", mi.keepcost);
       }

boost::mutex io_mutex;

void count() {

    for (int i = 0; i < 10; ++i) {

        boost::mutex::scoped_lock lock(io_mutex);

        //boost::this_thread::sleep( boost::posix_time::milliseconds( 100 ) );

    }

}
void* count2(void*) {

    for (int i = 0; i < 10; ++i) {

        boost::mutex::scoped_lock lock(io_mutex);

        boost::this_thread::sleep( boost::posix_time::milliseconds( 100 ) );

    }
    return 0;
}

int main() {
  printf("\n============== sizeof(boost::thread) ============== %d\n", sizeof(boost::thread));
  printf("\n============== sizeof(boost::detail::thread_data_base) ============== %d\n", sizeof(boost::detail::thread_data_base));
  printf("\n============== sizeof(boost::detail::thread_data<>) ============== %d\n", sizeof(boost::detail::thread_data<void(*)()>));
  printf("\n============== Before thread creation ==============\n");
  display_mallinfo();
  {
    boost::thread thrd1(&count);

    printf("\n============== After thread creation ==============\n");
    display_mallinfo();

    boost::thread thrd2(&count);
    printf("\n============== After thread creation ==============\n");
    display_mallinfo();
    boost::thread thrd3(&count);
    printf("\n============== After thread creation ==============\n");
    display_mallinfo();

    thrd1.join();
    printf("\n============== After thread join ==============\n");
    display_mallinfo();

    thrd2.join();
    printf("\n============== After thread join ==============\n");
    display_mallinfo();
    thrd3.join();
    printf("\n============== After thread join ==============\n");
    display_mallinfo();
  }
  printf("\n============== After thread destruction ==============\n");
  display_mallinfo();

  {
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    pthread_t thrd1;
    pthread_create(&thrd1, &attr, &count2, 0);
    printf("\n============== After thread creation ==============\n");
    display_mallinfo();

    pthread_t thrd2;
    pthread_create(&thrd2, &attr, &count2, 0);
    printf("\n============== After thread creation ==============\n");
    display_mallinfo();

    pthread_t thrd3;
    pthread_create(&thrd3, &attr, &count2, 0);
    printf("\n============== After thread creation ==============\n");
    display_mallinfo();

    pthread_attr_destroy(&attr);
    printf("\n============== After thread attr destroy ==============\n");
    display_mallinfo();

    void* res;
    pthread_join(thrd3, &res);
    printf("\n============== After thread join ==============\n");
    display_mallinfo();

    pthread_join(thrd2, &res);
    printf("\n============== After thread join ==============\n");
    display_mallinfo();
    pthread_join(thrd1, &res);
    printf("\n============== After thread join ==============\n");
    display_mallinfo();

    //pthread_destroy(&thrd1);
    //pthread_destroy(&thrd2);
    //pthread_destroy(&thrd3);
  }
  printf("\n============== After thread destruction ==============\n");
  display_mallinfo();

    return 1;

}


text:
#include <complex>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <fmt/format.h>
//#include <boost/config/warning_disable.hpp>
//#include <boost/spirit/home/x3.hpp>
//#include <range/v3/all.hpp>
#include <cstdint>
// 0 ,1
//1,2
//(i,j)( i+j +1
//i,j+1   (i+j+1,0
int main(int argc, char **argv)
{
  int i = 2978 - 1, j = 3083 - 1;
  int n = (i - 1) + j;
  int total = 0;
  for (int i = 0; i <= n; ++i) {
    total += 1 + i;
  }
  total += j + 1;
  //a[total]-1;
  std::int64_t a = 20151125;
  for (int i = 1; i < total; ++i) {
    a *= 252533;
    a %= 33554393;
    //fmt::print(";i:{},a:{}", i, a);
    //
  }
  fmt::print("{}", a);
}

ext: cpp

max_stars_repo_name: jiayuehua/adventOfCode

max_issues_repo_name: jiayuehua/adventOfCode

max_forks_repo_name: jiayuehua/adventOfCode


text: #include <boost/callable_traits/apply_return.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**

Copyright (c) 2016, Borella Jocelyn, Meißner Pascal
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "Domain.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <chrono>
#include <ctime>

Domain::Domain()
{
    getDomainFromParams();
}

Domain::~Domain()
{
}

void Domain::calcIntermediateObjectsForDomain()
{
    //Calculate intermediate object ranking for each object in each scene
    for (std::vector<SceneSharedPointer>::iterator sceneIterator = SceneList.begin(); sceneIterator != SceneList.end(); ++sceneIterator)
	{
        (*sceneIterator)->getObjectFromDb();
        (*sceneIterator)->calcAveragePositionForEachObject();
        (*sceneIterator)->calcPresenceInSceneForEachObject();
        (*sceneIterator)->getObjectAverageDistance();
        (*sceneIterator)->normalize();
        (*sceneIterator)->rank();
        (*sceneIterator)->displayStats();
	}
    std::list<evalulatorTupleSharedPtr> evaluatorTupleList;
	std::list<std::string> sceneList;
    ROS_DEBUG_STREAM("Domain::calcIntermediateObjectsForDomain begin scene fusion");
    //Creation of an evaluator tuple for all object in all scenes. (1 evaluator tuple per object per scene)
    for (std::vector<SceneSharedPointer>::iterator sceneIterator = SceneList.begin(); sceneIterator != SceneList.end(); ++sceneIterator)
	{
        std::string sceneName = (*sceneIterator)->getSceneName();
		sceneList.push_back(sceneName);
        std::unordered_map<std::string,ObjectSharedPointer> bufferObjectMap = (*sceneIterator)->getObjectMap();
        for (std::unordered_map<std::string,ObjectSharedPointer>::iterator objectMapIterator=bufferObjectMap.begin(); objectMapIterator!=bufferObjectMap.end(); ++objectMapIterator)
		{
            evaluatorTupleList.push_back(evalulatorTupleSharedPtr(new evalulatorTuple(objectMapIterator->second->getRankValue(),sceneName,objectMapIterator->first,
                                           objectMapIterator->second->getObjectName(),objectMapIterator->second->getObservedId())));
		}
	}
    ROS_DEBUG_STREAM("Domain::calcIntermediateObjectsForDomain scene fusion completed");
    ROS_DEBUG_STREAM("Domain::calcIntermediateObjectsForDomain begin from evaluation");
    Evaluator evaluator = Evaluator(evaluatorTupleList,sceneList,GainValueThreshold,NBVPath,Scene_path);
	IntermediateOjects = evaluator.getIntermediateObjects();
    ROS_DEBUG_STREAM("Domain::calcIntermediateObjectsForDomain end from evaluation");
}

void Domain::getDomainFromParams()
{
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/RankingMethod",RankingMethod);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/Alpha",Alpha);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/Beta",Beta);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/Gamma",Gamma);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/GainValueThreshold",GainValueThreshold);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/DomainName",DomainName);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/AutomatPath", AutomatPath);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/LogPath", LogPath);
    LocalHandle.getParam(LocalHandle.getNamespace() + "/asr_intermediate_object_generator/NBVPath", NBVPath);

    LocalHandle.getParam(LocalHandle.getNamespace() +  "/asr_intermediate_object_generator/dbfilename", Scene_path);

    std::vector<std::string> pathSplit;
    boost::split(pathSplit, Scene_path, boost::is_any_of("/"));
    std::string dbName = pathSplit[pathSplit.size()-1];

    const std::string placeholder = "XXX";
    std::string::size_type pos;
    if ((pos = AutomatPath.find(placeholder)) != std::string::npos) {
        AutomatPath.replace(pos, placeholder.length(), dbName);
    }

    if ((pos = NBVPath.find(placeholder)) != std::string::npos) {
        NBVPath.replace(pos, placeholder.length(), dbName);
    }

    ROS_DEBUG_STREAM("Domain::getDomainFromParams BEGIN");
    ROS_DEBUG_STREAM("Domain::getDomainFromParams RankingMethod : " << RankingMethod);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams Alpha : " << Alpha);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams Beta : " << Beta);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams Gamma : " << Gamma);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams GainValueThreshold : " << GainValueThreshold);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams AutomatPath : " << AutomatPath);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams LogPath : " << LogPath);
    ROS_DEBUG_STREAM("Domain::getDomainFromParams NBVPath : " << NBVPath);

    ISM::TableHelper tabelHelper(Scene_path);
    std::vector<std::string> Scene_patterns = tabelHelper.getRecordedPatternNames();
    for(const std::string &name : Scene_patterns)
    {
        SceneList.push_back(SceneSharedPointer(new Scene(Scene_path, name, RankingMethod, Alpha, Beta, Gamma)));
        ROS_DEBUG_STREAM("Domain::getDomainFromParams Adding scene : " << name);
        ROS_DEBUG_STREAM("Domain::getDomainFromParams with path : " << Scene_path);
    }
    ROS_DEBUG_STREAM("Domain::getDomainFromParams END");
}

void Domain::publishLogs()
{
    //Publish logs in the log file folder.
	std::chrono::time_point<std::chrono::system_clock> start;
	start = std::chrono::system_clock::now();
	std::time_t start_time = std::chrono::system_clock::to_time_t(start);
    std::string filePath = this->LogPath + this->DomainName + ".log";
	std::ofstream file(filePath, std::ios::out | std::ios::app);
	if(file)
	{
		file << std::endl <<this->DomainName << " Log file" << std::endl;
		file << "Timestamp for the Log " << std::ctime(&start_time) << std::endl;
		file << std::endl << "Intermediate Objects for The Domain " << std::endl;
        for (const objectTupleSharedPtr &tuple : IntermediateOjects)
		{
            file << std::get<1>(*tuple) << " : " << std::get<0>(*tuple) << std::endl;
		}
		file.close();
	}
    for (std::vector<SceneSharedPointer>::iterator sceneIterator = SceneList.begin(); sceneIterator != SceneList.end(); ++sceneIterator)
	{
        (*sceneIterator)->publishLogs(filePath);
	}
}

void Domain::publishIntermediateObjectToAutomat()
{
    //Publish the XML data containing intermediate object for the direct search.
    std::string output = "<InterObj>";
    for (const objectTupleSharedPtr &tuple : IntermediateOjects)
    {
        output += "<obj type=\"" + std::get<2>(*tuple) + "\" identifier=\""+ std::get<3>(*tuple) + "\"/>";
    }
    output += "</InterObj>";
    std::ofstream file(AutomatPath, std::ios::out | std::ios::trunc);
    if(file)
    {
        file << output;
        file.close();
    }
}


text:
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_MODIFIER_HEADERS_HPP_20100624
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_MODIFIER_HEADERS_HPP_20100624

// Copyright 2010 (C) Dean Michael Berris
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/network/support/is_async.hpp>
#include <boost/thread/future.hpp>
#include <boost/concept/requires.hpp>

namespace boost {
namespace network {
namespace http {

template <class Tag>
struct basic_response;

template <class Tag>
struct basic_request;

namespace impl {

template <class Tag, class T>
void headers(basic_response<Tag> &response, T const &value,
             mpl::false_ const &) {
  response << headers(value);
}

template <class Tag, class T>
void headers(basic_response<Tag> &response, T const &future,
             mpl::true_ const &) {
  response.headers(future);
}

template <class Tag, class T>
void headers(basic_request<Tag> &request, T const &value,
             tags::server const &) {
  request.headers = value;
}
}

template <class Tag, class T>
inline void headers(basic_response<Tag> &response, T const &value) {
  impl::headers(response, value, is_async<Tag>());
}

template <class Tag, class T>
inline void headers(basic_request<Tag> &request, T const &value) {
  impl::headers(request, value, Tag());
}

}  // namespace http

}  // namespace network

}  // namespace boost

#endif  // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_MODIFIER_HEADERS_HPP_20100624

max_stars_repo_name: ChadSki/Phasor


text:
// Boost.Geometry

// Copyright (c) 2019-2020, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGIES_IO_SERVICES_HPP
#define BOOST_GEOMETRY_STRATEGIES_IO_SERVICES_HPP

#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/static_assert.hpp>

namespace boost { namespace geometry
{

namespace strategies { namespace io
{

namespace services
{

template
<
    typename Geometry,
    typename CSTag = typename geometry::cs_tag<Geometry>::type
>
struct default_strategy
{
    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(
        "Not implemented for this coordinate system.",
        Geometry, CSTag);
};

} // namespace services

}} // namespace strategies::io

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_IO_SERVICES_HPP


text:
{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
{{{precontent}}}
#include <boost/python.hpp>
#include <cmath>

/* postinclude */

void {{enum.mangled_name}}()
{
::boost::python::object parent_object(::boost::python::scope(){{!
    }}{{#enum.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/enum.scope}});
::boost::python::scope parent_scope(parent_object);

::boost::python::enum_<{{{enum.type}}}>("{{enum.name}}"){{#enum.values}}
.value("{{name}}", {{{qualified_name}}}){{/enum.values}}
;
}
{{{postcontent}}}
{{{footer}}}


text:
#include "CorePch.h"
#include <rtp++/rfc2326/RtspServer.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <cpputil/StringTokenizer.h>
#include <rtp++/rfc2326/HeaderFields.h>
#include <rtp++/rfc2326/ResponseCodes.h>
#include <rtp++/rfc2326/RtspUri.h>
#include <rtp++/rfc2326/RtspUtil.h>

using boost::asio::ip::tcp;

namespace rtp_plus_plus
{
namespace rfc2326
{

const unsigned RtspServer::DEFAULT_SESSION_TIMEOUT = 60;

RtspServer::RtspServer( boost::asio::io_service& ioService, const GenericParameters& applicationParameters,
  boost::system::error_code& ec, unsigned short uiPort, unsigned uiSessionTimeout)
  :m_applicationParameters(applicationParameters),
    m_uiPort(uiPort),
    m_uiTimerTimeout(2),
    m_uiSessionTimeout(uiSessionTimeout),
    m_ioService(ioService),
    m_timer(ioService, boost::posix_time::seconds(m_uiTimerTimeout)),
    m_acceptor(ioService),
    //m_portManager(m_ioService),
    m_mediaSessionNetworkManager(ioService),
    m_uiRequestNumber(0),
    m_bShuttingDown(false)
{
  // bind to port
  boost::asio::ip::tcp::endpoint endpoint = tcp::endpoint(tcp::v4(), m_uiPort);
  m_acceptor.open(endpoint.protocol(), ec);
  if (ec) return;
  m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), ec);
  if (ec) return;
  m_acceptor.bind(endpoint, ec);
  if (ec) return;
  m_acceptor.listen();
}

RtspServer::~RtspServer()
{

}

boost::system::error_code RtspServer::doStart()
{
  m_timer.async_wait(boost::bind(&RtspServer::checkConnectionsTask, this, boost::asio::placeholders::error));
  startAccept();
  return boost::system::error_code();
}

boost::system::error_code RtspServer::start()
{
  VLOG(5) << "Starting RTSP server: " << getRtspServerAddress();
  return doStart();
}

boost::system::error_code RtspServer::doShutdown()
{
  m_bShuttingDown = true;
  boost::system::error_code ec;
  VLOG(5) << "Shutting down RTSP server. Closing acceptor";
  m_acceptor.close(ec);
  VLOG(5) << "Shutting down RTSP sessions";
  // teardown RTSP sessions
  teardownAllSessions();
  VLOG(5) << "Calling on shutdown";
  // give subclass opportunity for cleanup
  onShutdown();
  VLOG(5) << "Shutdown complete";
  return ec;
}

boost::system::error_code RtspServer::shutdown()
{
  // close all connections
  for (size_t i = 0; i < m_vConnections.size(); ++i)
  {
    if (!m_vConnections[i]->isClosed())
    {
      VLOG(2) << "Closing connection: " << m_vConnections[i]->getId();
      m_vConnections[i]->close();
    }
    else
    {
      VLOG(2) << "Connection " << m_vConnections[i]->getId() << " closed already";
    }
  }
  return doShutdown();
}

std::string RtspServer::getRtspServerAddress() const
{
  std::ostringstream ostr;
  ostr << "rtsp://";
  std::string sHostName = boost::asio::ip::host_name();
  boost::asio::ip::tcp::resolver resolver(m_ioService);
  boost::asio::ip::tcp::resolver::query query(boost::asio::ip::host_name(), "");
  boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
  boost::asio::ip::tcp::resolver::iterator end;;
  while(iter != end)
  {
    if (iter->endpoint().protocol() == tcp::v4())
    {
      // HACK: temporary fix to get IP: will NOT work if there are multiple IP addresses/NICs
      sHostName = iter->endpoint().address().to_string();
      break;
    }
    ++iter;
  }

  ostr << sHostName << ":" << m_uiPort;
  return ostr.str();
}

void RtspServer::startAccept()
{
  VLOG(10) << "RTSP server listening for connections on port " << m_uiPort;

  RtspServerConnectionPtr pNewConnection = RtspServerConnection::create(m_acceptor.get_io_service());
  pNewConnection->setReadCompletionHandler(boost::bind(&RtspServer::readCompletionHandler, this, boost::asio::placeholders::error, _2, _3) );
  pNewConnection->setWriteCompletionHandler(boost::bind(&RtspServer::writeCompletionHandler, this, boost::asio::placeholders::error, _2, _3, _4) );
  pNewConnection->setCloseHandler(boost::bind(&RtspServer::closeCompletionHandler, this, _1) );

  m_acceptor.async_accept(pNewConnection->socket(),
                          boost::bind(&RtspServer::acceptHandler, this,
                                      boost::asio::placeholders::error, pNewConnection));
}

void RtspServer::acceptHandler( const boost::system::error_code& error, RtspServerConnectionPtr pNewConnection )
{
  if (!error)
  {
    VLOG(2) << "Starting new connection: " << pNewConnection->getId();
    // handle new connection
    pNewConnection->start();
    // store pointer to connection so that we can close them all on shutdown
    m_vConnections.push_back(pNewConnection);

    // listen for new connections
    startAccept();
  }
  else
  {
    // The operation will be aborted on close.
    if (error!= boost::asio::error::operation_aborted)
      LOG(WARNING) << "Error in accept: " << error.message();
  }
}

void RtspServer::closeCompletionHandler( RtspServerConnectionPtr pConnection )
{
  VLOG(10) << "RtspServer::closeCompletionHandler: " << pConnection->getId();
  // TODO: remove all requests related to connection
  //  m_connectionRequestDatabase.removeEntries( pConnection->getId() );

  //  m_connectionManager.removeConnection( pConnection );
}

void RtspServer::readCompletionHandler( const boost::system::error_code& error, const std::string& sRtspMessage, RtspServerConnectionPtr pConnection )
{
  if (!error)
  {
    VLOG(2) << "Read RTSP message (" << sRtspMessage.length() << "):\r\n" << sRtspMessage;
    boost::optional<RtspMessage> pRtspMessage = RtspMessage::parse(sRtspMessage);
    if (!pRtspMessage)
    {
      // Invalid RTSP message received
      // 400 BAD REQUEST
      VLOG(5) << "Bad RTSP request";
      pConnection->write(m_uiRequestNumber++, createErrorResponse(BAD_REQUEST, 0));
      return;
    }
    else
    {
      std::vector<std::string> vSupported = getSupported(*pRtspMessage);
      if (pRtspMessage->isRequest())
      {
        handleRequest(*pRtspMessage, pConnection, vSupported);
      }
      else if (pRtspMessage->isResponse())
      {
        handleResponse(*pRtspMessage, pConnection, vSupported);
      }
      else
      {
        LOG(WARNING) << "Not request or response!!";
        assert(false);
      }
    }
  }
  else
  {
    if ((error != boost::asio::error::eof) &&
      (error != boost::asio::error::connection_aborted)) // is called on windows when closing the socket
    {
      LOG(WARNING) << "Error in read: " << error.message();
    }
    else
    {
      VLOG(5) << "Error in read: " << error.message();
    }
  }
}

void RtspServer::writeCompletionHandler( const boost::system::error_code& error, uint32_t uiMessageId, const std::string& sRtspMessage, RtspServerConnectionPtr pConnection )
{
  if (!error)
  {
    VLOG(2) << "[S->C] Wrote RTSP message (" << sRtspMessage.length() << "):\r\n" << sRtspMessage;
  }
  else
  {
    LOG(WARNING) << "Error in write: " << error.message();
  }
}

bool RtspServer::sessionExists(const std::string& sSession) const
{
  boost::mutex::scoped_lock l(m_sessionLock);
  auto it = m_mRtspSessions.find(sSession);
  return (it != m_mRtspSessions.end());
}

uint32_t RtspServer::activeSessionCount() const
{
  boost::mutex::scoped_lock l(m_sessionLock);
  return m_mRtspSessions.size();
}

std::vector<std::string> RtspServer::getSupported(const RtspMessage& rtspRequest)
{
  std::vector<std::string> vSupportedByServer;
  // default method: nothing is supported
  boost::optional<std::string> supportedByClient = rtspRequest.getHeaderField(SUPPORTED);
  if (supportedByClient)
  {
    std::vector<std::string> vSupportedByClient = StringTokenizer::tokenize(*supportedByClient, ",", true, true);
    for (size_t i = 0; i < vSupportedByClient.size(); ++i)
    {
      if (isOptionSupportedByServer(vSupportedByClient[i]))
        vSupportedByServer.push_back(vSupportedByClient[i]);
    }
  }
  return vSupportedByServer;
}

void RtspServer::handleRequest(const RtspMessage& rtspRequest, RtspServerConnectionPtr pConnection, const std::vector<std::string>& vSupported)
{
  assert(rtspRequest.isRequest());

  // handle unsupported options here by returning the appropriate error code on Require
  std::vector<std::string> vUnsupported = getUnsupported(rtspRequest);
  if (!vUnsupported.empty())
  {
    pConnection->write(m_uiRequestNumber++, createErrorResponse(OPTION_NOT_SUPPORTED, rtspRequest.getCSeq(), vSupported, vUnsupported));
    return;
  }

  std::string sSession = rtspRequest.getSession();

  if (sSession != "")
  {
    // handle request in session if possible
    if (!sessionExists(sSession))
    {
      // NOT FOUND
      pConnection->write(m_uiRequestNumber++, createErrorResponse(SESSION_NOT_FOUND, rtspRequest.getCSeq(), vSupported, vUnsupported));
      return;
    }
    else
    {
      switch(rtspRequest.getMethod())
      {
        // we want to handle teardowns at the server level
        case TEARDOWN:
        {
          IRtspAgent::handleRequest(rtspRequest, pConnection, vSupported);
          break;
        }
        // other requests with sessions are handled at the session level
        default:
        {
          boost::mutex::scoped_lock l(m_sessionLock);
          m_mRtspSessions[sSession]->handleRequest(rtspRequest, pConnection, vSupported);
        }
      }
    }
  }
  else
  {
    IRtspAgent::handleRequest(rtspRequest, pConnection, vSupported);
  }
}

void RtspServer::handleResponse(const RtspMessage& rtspResponse, RtspServerConnectionPtr pConnection, const std::vector<std::string>& vSupported)
{
  // TODO: we are not currently sending requests and therefore do not handle responses
  LOG(WARNING) << "TODO: we are not currently sending requests and therefore do not handle responses";
}

void RtspServer::checkConnectionsTask( const boost::system::error_code& ec)
{
  checkRtspSessions();

  // Check connections every 5 seconds
  if (!m_bShuttingDown)
  {
    m_timer.expires_at(m_timer.expires_at() + boost::posix_time::seconds(m_uiTimerTimeout));
    m_timer.async_wait(boost::bind(&RtspServer::checkConnectionsTask, this, boost::asio::placeholders::error ));
  }
  else
  {
    boost::mutex::scoped_lock l(m_sessionLock);
    // if we're shutting down we have to wait until all sessions have been removed
    if (!m_mRtspSessions.empty())
    {
      VLOG(2) << "Waiting for " << m_mRtspSessions.size() << " RTSP sessions to be removed";
      m_timer.expires_at(m_timer.expires_at() + boost::posix_time::seconds(m_uiTimerTimeout));
      m_timer.async_wait(boost::bind(&RtspServer::checkConnectionsTask, this, boost::asio::placeholders::error ));
    }
    else
    {
      VLOG(5) << "All RTSP sessions removed";
    }
  }
}

void RtspServer::teardownAllSessions()
{
  boost::mutex::scoped_lock l(m_sessionLock);
  VLOG(10) << "teardownAllSessions";
  // Check session to see if they have timed out
  for (auto it = m_mRtspSessions.begin(); it != m_mRtspSessions.end(); ++it)
  {
    it->second->shutdown();
  }
}

void RtspServer::checkRtspSessions()
{
  boost::mutex::scoped_lock l(m_sessionLock);
  // Check session to see if they have timed out
  for (auto it = m_mRtspSessions.begin(); it != m_mRtspSessions.end(); )
  {
    //it->second->updateState();

    if (it->second->isExpired())
    {
      VLOG(2) << "Session " << it->second->getSession() << " expired. Removing.";
      it = m_mRtspSessions.erase(it);
    }
    else
    {
#if 1
      // check session liveness
      if (it->second->livenessCheckFailed())
      {
        VLOG(2) << "Liveness check failed. Shutting down session";
        it->second->shutdown();
      }
#endif
      ++it;
    }
  }
}

std::map<std::string, std::string> RtspServer::parseSetParameterMessageBody( const std::string& sMessageBody )
{
  std::map<std::string, std::string> mParams;
  char szBuffer[256];
  std::istringstream istr(sMessageBody);
  while (!istr.eof())
  {
    istr.getline(szBuffer, 256);
    std::string sLine(szBuffer);
    size_t pos = sLine.find(":");
    if (pos == std::string::npos)
    {
      // Invalid param
      continue;
    }
    std::string sName = sLine.substr(0, pos);
    std::string sValue = sLine.substr(pos + 1);
    boost::trim(sValue);
    mParams[sName] = sValue;
  }
  return mParams;
}

ResponseCode RtspServer::handleDescribe(const RtspMessage& describe, std::string& sSessionDescription, std::string& sContentType, const std::vector<std::string>& vSupported)
{
  boost::optional<std::string> accept = describe.getHeaderField(ACCEPT);
  if (accept)
  {
    // check if SDP is listed
    std::vector<std::string> vAccepted = StringTokenizer::tokenize(*accept, ",", true, true);
    if (!isContentTypeAccepted(vAccepted))
    {
      // we can't satisfy this request
      return NOT_ACCEPTABLE;
    }
  }

  if (getResourceDescription(describe.getRtspUri(), sSessionDescription, sContentType, vSupported))
  {
    return OK;
  }
  else
  {
    return INTERNAL_SERVER_ERROR;
  }
}

ResponseCode RtspServer::handleSetup(const RtspMessage& setup, std::string& sSession,
                                     Transport& transport, const std::vector<std::string>& vSupported)
{
  VLOG(2) << "Request for " << setup.getRtspUri();
  // if the SETUP is handled in the server, we need to create the session
  // Otherwise the request would have been handled in the session
  sSession = m_sessionGenerator.generateSession();

  boost::mutex::scoped_lock l(m_sessionLock);
  assert(m_mRtspSessions.find(sSession) == m_mRtspSessions.end());

  std::string sSessionDescription;
  std::string sContentType;
  if (getResourceDescription(setup.getRtspUri(), sSessionDescription, sContentType, vSupported, transport))
  {
    // create new session
    m_mRtspSessions[sSession] = createServerMediaSession(sSession, sSessionDescription, sContentType);
    // handle setup of first media line
    return m_mRtspSessions[sSession]->handleSetup(setup, sSession, transport, vSupported);
  }
  else
  {
    return INTERNAL_SERVER_ERROR;
  }
}

ResponseCode RtspServer::handleTeardown(const RtspMessage& teardown, const std::vector<std::string>& vSupported)
{
  boost::mutex::scoped_lock l(m_sessionLock);
  auto it = m_mRtspSessions.find(teardown.getSession());
  if (it != m_mRtspSessions.end())
  {
    m_mRtspSessions[teardown.getSession()]->shutdown();
    return OK;
  }
  else
  {
    return NOT_FOUND;
  }
}

std::unique_ptr<ServerMediaSession> RtspServer::createServerMediaSession(const std::string& sSession, const std::string& sSessionDescription, const std::string& sContentType)
{
  return std::unique_ptr<ServerMediaSession>(new ServerMediaSession(*this, sSession, sSessionDescription, sContentType));
}

} // rfc2326
} // rtp_plus_plus


text:
#ifndef BOOST_ASIO_TCP_ECHO_SERVER_RESPONSECOMMAND_HPP_
#define BOOST_ASIO_TCP_ECHO_SERVER_RESPONSECOMMAND_HPP_

#include "server/Settings.hpp"

#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>

#include <functional>
#include <memory>
#include <string>

namespace boost_asio_tcp_echo
{
namespace server
{

class ResponseCommand : public std::enable_shared_from_this<ResponseCommand>
{
public:

    explicit ResponseCommand(
            boost::asio::io_context &ioContext,
            std::shared_ptr<Settings> settings,
            std::shared_ptr<boost::asio::ip::tcp::socket> socket,
            std::string responseBody);

    ~ResponseCommand();

    ResponseCommand(const ResponseCommand&) = delete;

    ResponseCommand(ResponseCommand&&) = delete;

    void run(
            std::function<void(std::shared_ptr<boost::asio::ip::tcp::socket>)> callback);

    ResponseCommand& operator=(const ResponseCommand&) = delete;

    ResponseCommand& operator=(ResponseCommand&&) = delete;

private:

    void handleTimeout(
            const std::shared_ptr<boost::asio::ip::tcp::socket> socket,
            const std::shared_ptr<boost::asio::steady_timer> deadLineTimer,
            const boost::system::error_code &ec);

    void handleWrite(
            std::function<void(std::shared_ptr<boost::asio::ip::tcp::socket>)> callback,
            std::shared_ptr<boost::asio::ip::tcp::socket> socket,
            const std::shared_ptr<boost::asio::steady_timer> deadLineTimer,
            const boost::system::error_code &ec,
            std::size_t bytesTransferred);

    boost::asio::io_context &ioContext_;

    std::shared_ptr<Settings> settings_;

    std::shared_ptr<boost::asio::ip::tcp::socket> socket_;

    std::string responseBody_;

};

} // namespace server
} // namespace boost_asio_tcp_echo

#endif // BOOST_ASIO_TCP_ECHO_SERVER_RESPONSECOMMAND_HPP_


text:
// Copyright (c) 2014-2020 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "hash.h"
#include "gridcoin/contract/contract.h"
#include "gridcoin/project.h"
#include "wallet/wallet.h"

#include <boost/test/unit_test.hpp>
#include <vector>

namespace {
//!
//! \brief A contract payload for testing.
//!
class TestPayload : public GRC::IContractPayload
{
public:
    std::string m_data;

    TestPayload(std::string data) : m_data(std::move(data))
    {
    }

    GRC::ContractType ContractType() const override
    {
        return GRC::ContractType::UNKNOWN;
    }

    bool WellFormed(const GRC::ContractAction action) const override
    {
        return !m_data.empty();
    }

    std::string LegacyKeyString() const override
    {
        return m_data;
    }

    std::string LegacyValueString() const override
    {
        return m_data;
    }

    int64_t RequiredBurnAmount() const override
    {
        return GRC::Contract::STANDARD_BURN_AMOUNT;
    }

    ADD_CONTRACT_PAYLOAD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(
        Stream& s,
        Operation ser_action,
        const GRC::ContractAction contract_action)
    {
        READWRITE(m_data);
    }
}; // TestPayload

//!
//! \brief Provides various signature representations for tests.
//!
//! Valid signatures created by signing the contracts below with the keys above.
//!
struct TestSig
{
    //!
    //! \brief Create a valid signature of a version 1 contract for tests.
    //!
    //! \return Base64-encoded signature. Created by signing the v1 contract
    //! message body in the class below with the private key above.
    //!
    static std::string V1String()
    {
        return "MEQCIHCvttZzIrBqFty9ED/fn5yMSzTzuch4Xf4KxiNJjwvM"
               "AiAp7QvHHhf1+xqEB57/k00jZW5RIITaxI9jXaR51Lmfnw==";
    }

    //!
    //! \brief Create an invalid signature for tests.
    //!
    //! \return Base64-encoded signature. Same invalid signature as the bytes
    //! below.
    //!
    static std::string InvalidString()
    {
        return "MEQCIHCvttZzIrBqFty9ED/fn5yMSzTzuch4Xf4KxiNJjwvM"
               "AiAp7QvHHhf1+xqEB57/k00jZW5RIITaxI9jXaR51LmfDw==";
    }
}; // struct TestSig

//!
//! \brief Provides various contract message representations for tests.
//!
struct TestMessage
{
    //!
    //! \brief Create a complete, signed contract object for the latest contract
    //! version.
    //!
    //! \return Contains the default content used to create the v2 signature
    //! above and includes that signature.
    //!
    static GRC::Contract Current()
    {
        return GRC::Contract(
            GRC::Contract::CURRENT_VERSION,
            GRC::ContractType::PROJECT,
            GRC::ContractAction::ADD,
            GRC::ContractPayload::Make<GRC::Project>("test", "test", 123));
    }

    //!
    //! \brief Create a complete, signed, legacy, version 1 contract object.
    //!
    //! \return Contains the default content used to create the v1 signature
    //! above and includes that signature.
    //!
    static GRC::Contract V1()
    {
        GRC::Contract contract = GRC::MakeLegacyContract(
            GRC::ContractType::PROJECT,
            GRC::ContractAction::ADD,
            "test",
            "test");

        contract.m_version = 1;

        return contract;
    }

    //!
    //! \brief Create a legacy version 1 contract message string for tests.
    //!
    //! \return Signed by the private key above.
    //!
    static std::string V1String()
    {
        // This message was signed by the message private key and contains a valid
        // signature:
        return std::string(
            "<MT>beacon</MT>"
            "<MK>test</MK>"
            "<MV>test</MV>"
            "<MA>A</MA>"
            "<MPK></MPK>"
            "<MS>" + TestSig::V1String() + "</MS>");
    }

    //!
    //! \brief Get a serialized representation of a valid version 2 contract
    //! message.
    //!
    //! \return As bytes. Matches the contract message string above (without
    //! tags) and includes version 2 components.
    //!
    static std::vector<unsigned char> V2Serialized()
    {
        std::vector<unsigned char> serialized {
            0x02, 0x00, 0x00, 0x00, // Version: 32-bit int (little-endian)
            0x05,                   // Type: PROJECT
            0x01,                   // Action: ADD
            0x01, 0x00, 0x00, 0x00, // Project contract version
            0x04,                   // Length of the project name
            0x74, 0x65, 0x73, 0x74, // "test" as bytes
            0x04,                   // Length of the project URL
            0x74, 0x65, 0x73, 0x74, // "test" as bytes
        };

        return serialized;
    }

    //!
    //! \brief Create a legacy, version 1 contract message string for tests.
    //!
    //! \return A contract message with an invalid signature.
    //!
    static std::string InvalidV1String()
    {
        return std::string(
            "<MT>beacon</MT>"
            "<MK>test</MK>"
            "<MV>test</MV>"
            "<MA>A</MA>"
            "<MPK></MPK>"
            "<MS>" + TestSig::InvalidString() + "</MS>");
    }

    //!
    //! \brief Create an invalid, partial, legacy, version 1 contract message
    //! string for tests.
    //!
    //! \return Contains a message type for detection, but missing items that
    //! must fail to validate.
    //!
    static std::string PartialV1String()
    {
        return "<MT>beacon</MT><MK>test</MK><MA>A</MA><MPK></MPK>";
    }
}; // struct TestMessage
} // anonymous namespace

// -----------------------------------------------------------------------------
// Contract::Type
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(Contract__Type)

BOOST_AUTO_TEST_CASE(it_initializes_to_a_provided_type)
{
    GRC::Contract::Type type(GRC::ContractType::BEACON);

    BOOST_CHECK(type == GRC::ContractType::BEACON);
}

BOOST_AUTO_TEST_CASE(it_parses_a_contract_type_from_a_string)
{
    GRC::Contract::Type type = GRC::Contract::Type::Parse("beacon");

    BOOST_CHECK(type == GRC::ContractType::BEACON);
}

BOOST_AUTO_TEST_CASE(it_parses_unknown_contract_types_to_unknown)
{
    GRC::Contract::Type type = GRC::Contract::Type::Parse("something");

    BOOST_CHECK(type == GRC::ContractType::UNKNOWN);
}

BOOST_AUTO_TEST_CASE(it_provides_the_wrapped_contract_type_enum_value)
{
    GRC::Contract::Type type(GRC::ContractType::BEACON);

    BOOST_CHECK(type.Value() == GRC::ContractType::BEACON);
}

BOOST_AUTO_TEST_CASE(it_represents_itself_as_a_string)
{
    GRC::Contract::Type type(GRC::ContractType::BEACON);

    BOOST_CHECK(type.ToString() == "beacon");
}

BOOST_AUTO_TEST_CASE(it_supports_equality_operators_with_contract_type_enums)
{
    GRC::Contract::Type type(GRC::ContractType::BEACON);

    BOOST_CHECK(type == GRC::ContractType::BEACON);
    BOOST_CHECK(type != GRC::ContractType::PROJECT);
}

BOOST_AUTO_TEST_CASE(it_serializes_to_a_stream)
{
    GRC::Contract::Type type(GRC::ContractType::BEACON); // BEACON == 0x01

    BOOST_CHECK(GetSerializeSize(type, SER_NETWORK, 1) == 1);

    CDataStream stream(SER_NETWORK, 1);
    stream << type;
    std::vector<unsigned char> output(stream.begin(), stream.end());

    BOOST_CHECK(output == std::vector<unsigned char> { 0x01 });
}

BOOST_AUTO_TEST_CASE(it_deserializes_from_a_stream)
{
    GRC::Contract::Type type(GRC::ContractType::UNKNOWN);

    std::vector<unsigned char> bytes { 0x01 };
    CDataStream stream(bytes, SER_NETWORK, 1);

    stream >> type;

    BOOST_CHECK(type == GRC::ContractType::BEACON); // BEACON == 0x01
}

BOOST_AUTO_TEST_CASE(it_refuses_to_deserialize_unknown_types)
{
    GRC::Contract::Type type(GRC::ContractType::UNKNOWN);

    std::vector<unsigned char> bytes { 0xFF }; // out-of-range
    CDataStream stream(bytes, SER_NETWORK, 1);

    BOOST_CHECK_THROW(stream >> type, std::ios_base::failure);
}

BOOST_AUTO_TEST_SUITE_END()

// -----------------------------------------------------------------------------
// Contract::Action
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(Contract__Action)

BOOST_AUTO_TEST_CASE(it_initializes_to_a_provided_action)
{
    GRC::Contract::Action action(GRC::ContractAction::ADD);

    BOOST_CHECK(action == GRC::ContractAction::ADD);
}

BOOST_AUTO_TEST_CASE(it_parses_a_contract_action_from_a_string)
{
    GRC::Contract::Action action = GRC::Contract::Action::Parse("A");

    BOOST_CHECK(action == GRC::ContractAction::ADD);
}

BOOST_AUTO_TEST_CASE(it_parses_unknown_contract_actions_to_unknown)
{
    GRC::Contract::Action action = GRC::Contract::Action::Parse("something");

    BOOST_CHECK(action == GRC::ContractAction::UNKNOWN);
}

BOOST_AUTO_TEST_CASE(it_provides_the_wrapped_contract_action_enum_value)
{
    GRC::Contract::Action action(GRC::ContractAction::REMOVE);

    BOOST_CHECK(action.Value() == GRC::ContractAction::REMOVE);
}

BOOST_AUTO_TEST_CASE(it_represents_itself_as_a_string)
{
    GRC::Contract::Action action(GRC::ContractAction::REMOVE);

    BOOST_CHECK(action.ToString() == "D");
}

BOOST_AUTO_TEST_CASE(it_supports_equality_operators_with_contract_action_enums)
{
    GRC::Contract::Action action(GRC::ContractAction::ADD);

    BOOST_CHECK(action == GRC::ContractAction::ADD);
    BOOST_CHECK(action != GRC::ContractAction::REMOVE);
}

BOOST_AUTO_TEST_CASE(it_serializes_to_a_stream)
{
    GRC::Contract::Action action(GRC::ContractAction::ADD); // ADD == 0x01

    BOOST_CHECK(GetSerializeSize(action, SER_NETWORK, 1) == 1);

    CDataStream stream(SER_NETWORK, 1);

    stream << action;
    std::vector<unsigned char> output(stream.begin(), stream.end());

    BOOST_CHECK(output == std::vector<unsigned char> { 0x01 });
}

BOOST_AUTO_TEST_CASE(it_deserializes_from_a_stream)
{
    GRC::Contract::Action action(GRC::ContractAction::UNKNOWN);

    CDataStream stream(std::vector<unsigned char> { 0x02 }, SER_NETWORK, 1);

    stream >> action;

    BOOST_CHECK(action == GRC::ContractAction::REMOVE); // REMOVE == 0x02
}

BOOST_AUTO_TEST_CASE(it_refuses_to_deserialize_unknown_actions)
{
    GRC::Contract::Action action(GRC::ContractAction::UNKNOWN);

    std::vector<unsigned char> bytes { 0xFF }; // out-of-range
    CDataStream stream(bytes, SER_NETWORK, 1);

    BOOST_CHECK_THROW(stream >> action, std::ios_base::failure);
}

BOOST_AUTO_TEST_SUITE_END()

// -----------------------------------------------------------------------------
// Contract::Body
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(Contract__Body)

BOOST_AUTO_TEST_CASE(it_initializes_to_an_empty_payload)
{
    const GRC::Contract::Body body;

    BOOST_CHECK(body.WellFormed(GRC::ContractAction::ADD) == false);
}

BOOST_AUTO_TEST_CASE(it_initializes_to_the_supplied_payload)
{
    const GRC::Contract::Body body(GRC::ContractPayload::Make<TestPayload>("test"));

    BOOST_CHECK(body.WellFormed(GRC::ContractAction::ADD) == true);
}

BOOST_AUTO_TEST_CASE(it_provides_access_to_a_known_legacy_payload)
{
    // The Contract class intentionally abstracts the construction of the body
    // to encapsulate the details for management of the polymorphic object. We
    // need to instantiate a contract object to test the body here:
    //
    const GRC::Contract contract = TestMessage::V1();
    const GRC::ContractPayload payload = contract.m_body.AssumeLegacy();

    BOOST_CHECK(payload->ContractType() == GRC::ContractType::UNKNOWN);
    BOOST_CHECK(payload->WellFormed(contract.m_action.Value()) == true);
    BOOST_CHECK_EQUAL(payload->LegacyKeyString(), "test");
    BOOST_CHECK_EQUAL(payload->LegacyValueString(), "test");
}

BOOST_AUTO_TEST_CASE(it_converts_a_legacy_payload_into_a_specific_contract_type)
{
    // The Contract class intentionally abstracts the construction of the body
    // to encapsulate the details for management of the polymorphic object. We
    // need to instantiate a contract object to test the body here:
    //
    const GRC::Contract contract = GRC::MakeLegacyContract(
        GRC::ContractType::PROJECT,
        GRC::ContractAction::ADD,
        "Project Name",
        "https://example.com/@");

    const GRC::ContractPayload payload = contract.m_body.ConvertFromLegacy(
        GRC::ContractType::PROJECT);

    BOOST_CHECK(payload->ContractType() == GRC::ContractType::PROJECT);
    BOOST_CHECK(payload->WellFormed(contract.m_action.Value()) == true);
    BOOST_CHECK_EQUAL(payload->LegacyKeyString(), "Project Name");
    BOOST_CHECK_EQUAL(payload->LegacyValueString(), "https://example.com/@");

    const GRC::Project& project = payload.As<GRC::Project>();

    BOOST_CHECK_EQUAL(project.m_name, "Project Name");
    BOOST_CHECK_EQUAL(project.m_url, "https://example.com/@");
}

BOOST_AUTO_TEST_CASE(it_serializes_to_a_stream)
{
    const GRC::Contract::Body body(GRC::ContractPayload::Make<TestPayload>("test"));

    const CDataStream expected = CDataStream(SER_NETWORK, PROTOCOL_VERSION)
        << std::string("test");

    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    body.Serialize(stream, GRC::ContractAction::ADD);

    BOOST_CHECK_EQUAL_COLLECTIONS(
        stream.begin(),
        stream.end(),
        expected.begin(),
        expected.end());
}

BOOST_AUTO_TEST_CASE(it_deserializes_from_a_stream)
{
    CDataStream stream = CDataStream(SER_NETWORK, PROTOCOL_VERSION)
        << std::string("test");

    GRC::Contract::Body body(GRC::ContractPayload::Make<TestPayload>(""));
    body.Unserialize(stream, GRC::ContractAction::ADD);

    const GRC::ContractPayload contract_payload = body.AssumeLegacy();
    const TestPayload& payload = contract_payload.As<TestPayload>();

    BOOST_CHECK_EQUAL(payload.m_data, "test");
}

BOOST_AUTO_TEST_SUITE_END()

// -----------------------------------------------------------------------------
// Contract
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(Contract)

BOOST_AUTO_TEST_CASE(it_initializes_to_an_invalid_contract_by_default)
{
    GRC::Contract contract;

    BOOST_CHECK(contract.m_version == GRC::Contract::CURRENT_VERSION);
    BOOST_CHECK(contract.m_type == GRC::ContractType::UNKNOWN);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::UNKNOWN);
    BOOST_CHECK(contract.m_body.WellFormed(contract.m_action.Value()) == false);
}

BOOST_AUTO_TEST_CASE(it_initializes_with_components_for_a_new_contract)
{
    GRC::Contract contract(
        GRC::ContractType::BEACON,
        GRC::ContractAction::ADD,
        GRC::ContractPayload::Make<TestPayload>("test data"));

    BOOST_CHECK(contract.m_version == GRC::Contract::CURRENT_VERSION);
    BOOST_CHECK(contract.m_type == GRC::ContractType::BEACON);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::ADD);
    BOOST_CHECK(contract.m_body.WellFormed(contract.m_action.Value()) == true);
}

BOOST_AUTO_TEST_CASE(it_initializes_with_components_from_a_contract_message)
{
    GRC::Contract contract(
        GRC::Contract::CURRENT_VERSION,
        GRC::ContractType::BEACON,
        GRC::ContractAction::ADD,
        GRC::ContractPayload::Make<TestPayload>("test data"));

    BOOST_CHECK(contract.m_version == GRC::Contract::CURRENT_VERSION);
    BOOST_CHECK(contract.m_type == GRC::ContractType::BEACON);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::ADD);
    BOOST_CHECK(contract.m_body.WellFormed(contract.m_action.Value()) == true);
}

BOOST_AUTO_TEST_CASE(it_detects_a_contract_in_a_transaction_message)
{
    BOOST_CHECK(GRC::Contract::Detect(TestMessage::V1String()) == true);
    BOOST_CHECK(GRC::Contract::Detect("<MESSAGE></MESSAGE>") == false);
    BOOST_CHECK(GRC::Contract::Detect("") == false);
}

BOOST_AUTO_TEST_CASE(it_ignores_superblocks_during_legacy_v1_contract_detection)
{
    std::string message(
        "<MT>superblock</MT>"
        "<MK>test</MK>"
        "<MV>test</MV>"
        "<MA>A</MA>"
        "<MPK></MPK>"
        "<MS>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</MS>");

    BOOST_CHECK(GRC::Contract::Detect(message) == false);
}

BOOST_AUTO_TEST_CASE(it_parses_a_legacy_v1_contract_from_a_transaction_message)
{
    GRC::Contract contract = GRC::Contract::Parse(TestMessage::V1String());
    GRC::ContractPayload payload = contract.m_body.AssumeLegacy();

    BOOST_CHECK(contract.m_version == 1); // Legacy strings always parse to v1
    BOOST_CHECK(contract.m_type == GRC::ContractType::BEACON);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::ADD);
    BOOST_CHECK(payload->LegacyKeyString() == "test");
    BOOST_CHECK(payload->LegacyValueString() == "test");
}

BOOST_AUTO_TEST_CASE(it_gives_an_invalid_contract_when_parsing_an_empty_message)
{
    GRC::Contract contract = GRC::Contract::Parse("");

    BOOST_CHECK(contract.m_version == GRC::Contract::CURRENT_VERSION);
    BOOST_CHECK(contract.m_type == GRC::ContractType::UNKNOWN);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::UNKNOWN);
    BOOST_CHECK(contract.m_body.WellFormed(contract.m_action.Value()) == false);
}

BOOST_AUTO_TEST_CASE(it_gives_an_invalid_contract_when_parsing_a_non_contract)
{
    GRC::Contract contract = GRC::Contract::Parse("<MESSAGE></MESSAGE>");

    BOOST_CHECK(contract.m_version == 1); // Legacy strings always parse to v1
    BOOST_CHECK(contract.m_type == GRC::ContractType::UNKNOWN);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::UNKNOWN);
    BOOST_CHECK(contract.m_body.WellFormed(contract.m_action.Value()) == false);
}

BOOST_AUTO_TEST_CASE(it_determines_whether_a_contract_is_complete)
{
    GRC::Contract contract = TestMessage::Current();
    BOOST_CHECK(contract.WellFormed() == true);
}

BOOST_AUTO_TEST_CASE(it_determines_whether_a_legacy_v1_contract_is_complete)
{
    GRC::Contract contract = GRC::Contract::Parse(TestMessage::V1String());
    BOOST_CHECK(contract.WellFormed() == true);

    // WellFormed() does NOT verify the signature:
    contract = GRC::Contract::Parse(TestMessage::InvalidV1String());
    BOOST_CHECK(contract.WellFormed() == true);

    contract = GRC::Contract::Parse(TestMessage::PartialV1String());
    BOOST_CHECK(contract.WellFormed() == false);

    contract = GRC::Contract::Parse("");
    BOOST_CHECK(contract.WellFormed() == false);

    contract = GRC::Contract::Parse("<MESSAGE></MESSAGE>");
    BOOST_CHECK(contract.WellFormed() == false);
}

BOOST_AUTO_TEST_CASE(it_determines_the_requred_burn_fee)
{
    const GRC::Contract contract = TestMessage::Current();

    BOOST_CHECK(contract.RequiredBurnAmount() > 0);
}

BOOST_AUTO_TEST_CASE(it_provides_access_to_the_contract_payload)
{
    const GRC::Contract contract = TestMessage::Current();
    const GRC::ContractPayload payload = contract.SharePayload();

    BOOST_CHECK(payload->ContractType() == GRC::ContractType::PROJECT);
    BOOST_CHECK_EQUAL(payload->LegacyKeyString(), "test");
    BOOST_CHECK_EQUAL(payload->LegacyValueString(), "test");
}

BOOST_AUTO_TEST_CASE(it_casts_known_contract_payloads)
{
    const GRC::Contract contract = TestMessage::Current();
    const auto payload = contract.SharePayloadAs<GRC::Project>();

    BOOST_CHECK_EQUAL(payload->m_name, "test");
    BOOST_CHECK_EQUAL(payload->m_url, "test");
}

BOOST_AUTO_TEST_CASE(it_converts_known_legacy_contract_payloads)
{
    const GRC::Contract contract = TestMessage::V1();
    const auto payload = contract.SharePayloadAs<GRC::Project>();

    BOOST_CHECK_EQUAL(payload->m_name, "test");
    BOOST_CHECK_EQUAL(payload->m_url, "test");
}

BOOST_AUTO_TEST_CASE(it_copies_a_cast_or_converted_payload)
{
    const GRC::Contract contract = TestMessage::Current();
    const GRC::Project project = contract.CopyPayloadAs<GRC::Project>();

    BOOST_CHECK_EQUAL(project.m_name, "test");
    BOOST_CHECK_EQUAL(project.m_url, "test");

    // Copying the payload leaves the contract in a valid state:
    BOOST_CHECK(contract.WellFormed() == true);
}

BOOST_AUTO_TEST_CASE(it_moves_a_cast_or_converted_payload)
{
    GRC::Contract contract = TestMessage::Current();
    const GRC::Project project = contract.PullPayloadAs<GRC::Project>();

    BOOST_CHECK_EQUAL(project.m_name, "test");
    BOOST_CHECK_EQUAL(project.m_url, "test");

    // Moving the payload invalidates the contract:
    BOOST_CHECK(contract.WellFormed() == false);
}

BOOST_AUTO_TEST_CASE(it_serializes_to_a_stream)
{
    GRC::Contract contract = TestMessage::Current();

    // 20 bytes = 4 bytes for the serialization protocol version
    //  + 1 byte each for the type and action
    //  + 14 bytes for the project payload
    //  + 1 byte for the empty public key size
    //
    BOOST_CHECK(GetSerializeSize(contract, SER_NETWORK, 1) == 20);

    CDataStream stream(SER_NETWORK, 1);

    stream << contract;
    std::vector<unsigned char> output(stream.begin(), stream.end());

    BOOST_CHECK(output == TestMessage::V2Serialized());
}

BOOST_AUTO_TEST_CASE(it_deserializes_from_a_stream)
{
    GRC::Contract contract;

    CDataStream stream(TestMessage::V2Serialized(), SER_NETWORK, 1);

    stream >> contract;

    GRC::ContractPayload payload = contract.SharePayload();

    BOOST_CHECK(contract.WellFormed() == true);
    BOOST_CHECK(contract.m_version == GRC::Contract::CURRENT_VERSION);
    BOOST_CHECK(contract.m_type == GRC::ContractType::PROJECT);
    BOOST_CHECK(contract.m_action == GRC::ContractAction::ADD);
    BOOST_CHECK(payload->LegacyKeyString() == "test");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: sweede-se/Gridcoin-Research

max_issues_repo_name: sweede-se/Gridcoin-Research

max_forks_repo_name: sweede-se/Gridcoin-Research


text:
//Link to Boost
 #define BOOST_TEST_DYN_LINK

//VERY IMPORTANT - include this last
#include <boost/test/unit_test.hpp>

#include <cmath>
#include "test.h"
#include "../common.h"
#include "../gegenbauer_polynomial.hpp"

BOOST_DATA_TEST_CASE(GegenbauerDAlphaAt0_test, bdata::xrange(0, 20) ^ bdata::random(-10.0, 10.0), n, x)
{
    float_type actual = GegenbauerDAlphaAt0(n, x);

    float_type arr[1] = {x};
    float_type *v1 = gegenbauer_polynomial_value(n, 1, -inc, arr);
    float_type *v2 = gegenbauer_polynomial_value(n, 1, inc, arr);
    float_type ret1 = v1[n + 0 * (n + 1)];
    float_type ret2 = v2[n + 0 * (n + 1)];
    delete v1;
    delete v2;

    float_type expect = (ret2 - ret1) / (2 * inc);
    MY_FLOAT_EQUAL(actual, expect, tol);
}

max_stars_repo_name: gaolichen/cftbtsp

max_issues_repo_name: gaolichen/cftbtsp

max_forks_repo_name: gaolichen/cftbtsp


text:
#define BOOST_TEST_MODULE math_test_module
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(metr_number_test_suite)

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gwlsrm/Units

max_issues_repo_name: gwlsrm/Units

max_forks_repo_name: gwlsrm/Units


text:
//=======================================================================
// Copyright (c) 2013 Piotr Wygocki
//               2014 Piotr Godlewski
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/**
 * @file steiner_network_example.cpp
 * @brief
 * @author Piotr Wygocki, Piotr Godlewski
 * @version 1.0
 * @date 2013-06-24
 */

//! [Steiner Network Example]
#include "paal/iterative_rounding/steiner_network/steiner_network.hpp"

#include <boost/graph/adjacency_list.hpp>

#include <iostream>
#include <vector>

int main() {
    using Graph = boost::adjacency_list<boost::vecS, boost::vecS,
        boost::undirectedS, boost::no_property,
        boost::property<boost::edge_weight_t, int>>;
    using Edge = boost::graph_traits<Graph>::edge_descriptor;

    // sample problem
    std::vector<std::pair<int, int>> edges {{0,1},{0,1},{1,2},{1,2},{2,0}};
    std::vector<int> costs {1,1,1,1,7};
    auto restrictions = [](int i, int j) {return 2;};

    Graph g(edges.begin(), edges.end(), costs.begin(), 3);

    std::vector<Edge> result_network;

    // optional input validity checking
    auto steiner_network = paal::ir::make_steiner_network(
        g, restrictions, std::back_inserter(result_network));
    auto error = steiner_network.check_input_validity();
    if (error) {
        std::cerr << "The input is not valid!" << std::endl;
        std::cerr << *error << std::endl;
        return -1;
    }

    // solve it
    auto result = paal::ir::steiner_network_iterative_rounding(
        g, restrictions, std::back_inserter(result_network));

    // print result
    if (result.first == paal::lp::OPTIMAL) {
        std::cout << "Edges in steiner network" << std::endl;
        for (auto e : result_network) {
            std::cout << "Edge " << e << std::endl;
        }
        std::cout << "Cost of the solution: " << *(result.second) << std::endl;
    } else {
        std::cout << "The instance is infeasible" << std::endl;
    }
    paal::lp::glp::free_env();
    return 0;
}
    //! [Steiner Network Example]

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

/*
  root_behavior_manager_test.cc
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <stdio.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/vfs.h>

#include <boost/test/unit_test.hpp>

#include "mldb/arch/timers.h"
#include "mldb/base/scope.h"
#include "mldb/vfs/fs_utils.h"
#include "mldb/vfs/filter_streams.h"
#include "mldb/utils/runner.h"
#include "mldb/utils/testing/print_utils.h"
#include "mldb/plugins/behavior/behavior_manager.h"

using namespace std;
using namespace MLDB;

namespace {

uint64_t freeDiskSpace(const string & directory)
{
    struct statfs fsstats;
    int res = ::statfs(directory.c_str(), &fsstats);
    if (res == -1) {
        throw MLDB::Exception(errno, "statfs");
    }

    return fsstats.f_bavail * fsstats.f_bsize;
}

/****************************************************************************/
/* TEMPORARY MOUNT                                                          */
/****************************************************************************/

/* TemporaryMount is a class that performs the creation and mounting of
 * temporary filesystem volumes. The programs instantiating it must be run as
 * root. */

struct TemporaryMount
{
    TemporaryMount(size_t volSize);
    ~TemporaryMount() noexcept;

    const std::string & mountPoint() const
    {
        return mountPoint_;
    }

private:
    void createVolume();
    void mountVolume();

    void attachVolume();

    void cleanup() noexcept;
    void detachVolume() noexcept;
    void unmountVolume() noexcept;

    size_t volSize_;
    std::string volume_;
    bool volumeExists_;

    std::string loopDevice_;
    bool attached_;

    std::string mountPoint_;
    bool mountPointExists_;
    bool mounted_;
};

const string FSTYPE("ext2");
const string MKFS("/sbin/mkfs." + FSTYPE);
const string LOSETUP("/sbin/losetup");

TemporaryMount::
TemporaryMount(size_t volSize)
    : volSize_(volSize),
      volumeExists_(false), attached_(false),
      mountPointExists_(false), mounted_(false)
{
    // if (getuid() != 0) {
    //     throw MLDB::Exception("You are not root");
    // }

    bool ok(false);

    Scope_Exit(
        if (!ok) {
            cleanup();
        }
    );

    /* we create a sparse file of size "volSize" */
    createVolume();

    /* initialise the filesystem with blocks of 1024 KBytes */
    auto runRes = execute({MKFS,
                           "-b", "1024",
                           "-i", "1024",
                           "-m", "0",
                           volume_});
    if (runRes.processStatus() != 0) {
        throw MLDB::Exception("failure initialising filesystem");
    }

    /* attach the volume file to the loop device */
    attachVolume();

    /* create the mount directory */
    mountPoint_ = "/tmp/" + randomString(16);
    int res = ::mkdir(mountPoint_.c_str(), 0700);
    if (res == -1) {
        throw MLDB::Exception(errno, "mkdir");
    }
    mountPointExists_ = true;

    /* mount the filesystem */
    mountVolume();

    ok = true;
}

void
TemporaryMount::
cleanup()
    noexcept
{
    if (mounted_) {
        unmountVolume();
    }
    if (mountPointExists_) {
        int res = ::rmdir(mountPoint_.c_str());
        if (res == -1) {
            perror("TemporaryMount::cleanup rmdir");
        }
        mountPointExists_ = false;
    }
    if (attached_) {
        detachVolume();
    }
    if (volumeExists_) {
        int res = ::unlink(volume_.c_str());
        if (res == -1) {
            perror("TemporaryMount::cleanup unlink");
        }
        volumeExists_ = false;
    }
}

void
TemporaryMount::
createVolume()
{
    volume_ = "/tmp/" + randomString(16);

    FILE * f = ::fopen(volume_.c_str(), "w+");
    if (!f) {
        throw MLDB::Exception(errno, "fopen");
    }
    volumeExists_ = true;
    Scope_Exit(::fclose(f));
    int res = ::fseek(f, volSize_ - 1, SEEK_SET);
    if (res == -1) {
        throw MLDB::Exception(errno, "fseek");
    }
    res = ::fwrite("a", 1, 1, f);
    if (res == -1) {
        throw MLDB::Exception(errno, "fwrite");
    }
}

void
TemporaryMount::
mountVolume()
{
    ExcAssert(!mounted_);
    ExcAssert(attached_);
    ExcAssert(!loopDevice_.empty());
    ExcAssert(!mountPoint_.empty());
    int res = ::mount(loopDevice_.c_str(), mountPoint_.c_str(),
                      FSTYPE.c_str(), 0, 0);
    if (res == -1) {
        throw MLDB::Exception(errno, "mount");
    }
    mounted_ = true;
}

void
TemporaryMount::
unmountVolume()
    noexcept
{
    try {
        ExcAssert(mounted_);
        ExcAssert(!volume_.empty());
        ExcAssert(!mountPoint_.empty());
    } catch (...) {
        std::terminate();
    }
    int res = umount(mountPoint_.c_str());
    if (res == -1) {
        perror("TemporaryMount::unmountVolume");
    }
    mounted_ = false;
}

void
TemporaryMount::
attachVolume()
{
    auto onStdout = [&] (std::string && data) {
        loopDevice_ += data;
    };
    auto sink = make_shared<CallbackInputSink>(onStdout);
    auto runRes = execute({LOSETUP, "--find", "--show", volume_},
                          sink, nullptr);
    if (runRes.processStatus() != 0) {
        throw MLDB::Exception("failure attaching loop device");
    }
    attached_ = true;
    ExcAssert(!loopDevice_.empty());
    loopDevice_.resize(loopDevice_.size() - 1);
    cerr << "loop device: " + loopDevice_ + "\n";
}

void
TemporaryMount::
detachVolume()
    noexcept
{
    try {
        ExcAssert(attached_);
        ExcAssert(!loopDevice_.empty());
    } catch (...) {
        std::terminate();
    }
    auto runRes = execute({LOSETUP, "--detach", loopDevice_});
    if (runRes.processStatus() != 0) {
        perror("detaching loop device");
    }
    attached_ = false;
    loopDevice_.clear();
}

TemporaryMount::
~TemporaryMount()
    noexcept
{
    cleanup();
}

void populateCache(const string & directory, uint64_t space)
{
    uint64_t used(0);
    size_t nFiles(0);

    /* compute the new atime */
    struct timeval newATime;
    int res = ::gettimeofday(&newATime, nullptr);
    if (res == -1) {
        throw MLDB::Exception("gettimeofday");
    }

    while (true) {
        uint64_t fileSize = nFiles * 6543;
        if (used + fileSize > space) {
            break;
        }
        string filename = directory + "/file" + to_string(nFiles);
        filter_ostream stream(filename);
        stream << randomString(fileSize);
        stream.close();

        /* apply the new atime */
        newATime.tv_sec -= 60;
        struct timeval times[] = {newATime, newATime};
        res = ::utimes(filename.c_str(), times);
        if (res == -1) {
            throw MLDB::Exception("utimes");
        }

        used += fileSize;
        nFiles++;
    }
    cerr << ("populated cache with " + to_string(nFiles)
             + " files of " + to_string(used) + " bytes in total"
             + " on " + to_string(space)
             + "\n");
}

}

BOOST_AUTO_TEST_CASE( test_beh_manager_parse_specs )
{
    /* setup and mount a temporary volume */
    size_t volumeSize(20*1024*1024);
    TemporaryMount volume(volumeSize);
    const string & mountPoint = volume.mountPoint();

    BehaviorManager behMgr;
    behMgr.setRemoteCacheDir(mountPoint);

    uint64_t initialSpace = freeDiskSpace(mountPoint);
    populateCache(mountPoint, initialSpace - 10000);

    uint64_t freeSpace(0), newFreeSpace(0);

    /* populating the cache created a file named "file73" that is going to be
     * deleted later */
    auto info = tryGetUriObjectInfo(mountPoint + "/file73");
    BOOST_CHECK_EQUAL(bool(info), true);

    /* test with a file larger than volume size: cleanup refused */
    bool res = behMgr.prepareRemoteCache(volumeSize + 100);
    BOOST_CHECK_EQUAL(res, false);

    /* test with a file smaller then free size: no cleanup required */
    freeSpace = freeDiskSpace(mountPoint);
    res = behMgr.prepareRemoteCache(100);
    BOOST_CHECK_EQUAL(res, true);
    newFreeSpace = freeDiskSpace(mountPoint);
    BOOST_CHECK_EQUAL(newFreeSpace, freeSpace);

    /* test with a file smaller than the sum of the sizes of the cleanable
       files: the cleanup must have succeeded and file73 must have been
       deleted */
    res = behMgr.prepareRemoteCache(freeSpace + 10);
    BOOST_CHECK_EQUAL(res, true);
    newFreeSpace = freeDiskSpace(mountPoint);
    BOOST_CHECK_GT(newFreeSpace, freeSpace);
    freeSpace = newFreeSpace;
    info = tryGetUriObjectInfo(mountPoint + "/file73");
    BOOST_CHECK_EQUAL(bool(info), false);

    /* Our algorithm for dealing with race conditions requires us to be able
     * to remove all the files that takes up to the required disk space,
     * notwithstanding the initial free space. Thus, requesting a file smaller
     * than the disk space but larger than the used space must fail and all
     * the files present on disk must stay untouched. */
    res = behMgr.prepareRemoteCache(initialSpace - 10000);
    BOOST_CHECK_EQUAL(res, false);
    newFreeSpace = freeDiskSpace(mountPoint);
    BOOST_CHECK_EQUAL(newFreeSpace, freeSpace);
}

ext: cc

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


text:
#include <boost/units/cmath.hpp>
#include <boost/units/io.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
#include <iostream>
#include <tuple>

using Length_unit = boost::units::si::length;
using Length = boost::units::quantity<Length_unit>;
using Time_unit = boost::units::si::time;
using Time = boost::units::quantity<Time_unit>;
using Velocity_unit = boost::units::si::velocity;
using Velocity = boost::units::quantity<Velocity_unit>;

Velocity compute_velocity(const Length dx, const Time dt) {
    return dx/dt;
}

using Point = std::tuple<Length, Length>;

Length distance(const Point& p1, const Point& p2) {
    Length x1 {std::get<0>(p1)};
    Length x2 {std::get<0>(p2)};
    Length y1 {std::get<1>(p1)};
    Length y2 {std::get<1>(p2)};
    return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}

int main() {
    // define units to make formulas easier to read
    Length_unit m {boost::units::si::meter};
    Time_unit s {boost::units::si::seconds};

    Length dx {3.5*m};
    Time dt {2.0*s};
    Velocity velocity = compute_velocity(dx, dt);
    std::cout << velocity << std::endl;
    std::cout << velocity.value() << std::endl;

    Point p1 {std::make_tuple(3.0*m, 4.0*m)};
    Point p2 {std::make_tuple(5.0*m, 2.0*m)};
    std::cout << distance(p1, p2) << std::endl;

    return 0;
}

max_stars_repo_name: gjbex/Scientific-C-

max_issues_repo_name: gjbex/Scientific-C-

max_forks_repo_name: gjbex/Scientific-C-


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <vector>
#include <tbb/spin_rw_mutex.h>

#include <boost/bind.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/type_traits.hpp>

#include "base/compiler.h"
#include "base/logging.h"
#include "base/task_annotations.h"
#include "db/db.h"
#include "db/db_partition.h"
#include "db/db_table.h"
#include "db/db_table_partition.h"
#include "db/db_table_walker.h"

class DBEntry;
class DBEntryBase;

using namespace std;

DBRequest::DBRequest() : oper(static_cast<DBOperation>(0)) {
}

DBRequest::~DBRequest() {
#if defined(__GNUC__) && (__GNUC_PREREQ(4, 2) > 0)
    boost::has_virtual_destructor<DBRequestKey>::type key_has_destructor;
    boost::has_virtual_destructor<DBRequestData>::type data_has_destructor;
    assert(key_has_destructor && data_has_destructor);
#endif
}

void DBRequest::Swap(DBRequest *rhs) {
    swap(oper, rhs->oper);
    swap(key, rhs->key);
    swap(data, rhs->data);
}

class DBTableBase::ListenerInfo {
public:
    typedef vector<ChangeCallback> CallbackList;

    DBTableBase::ListenerId Register(ChangeCallback callback) {
        tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
        size_t i = bmap_.find_first();
        if (i == bmap_.npos) {
            i = callbacks_.size();
            callbacks_.push_back(callback);
        } else {
            bmap_.reset(i);
            if (bmap_.none()) {
                bmap_.clear();
            }
            callbacks_[i] = callback;
        }
        return i;
    }

    void Unregister(ListenerId listener) {
        tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
        callbacks_[listener] = NULL;
        if ((size_t) listener == callbacks_.size() - 1) {
            while (!callbacks_.empty() && callbacks_.back() == NULL) {
                callbacks_.pop_back();
            }
            if (bmap_.size() > callbacks_.size()) {
                bmap_.resize(callbacks_.size());
            }
        } else {
            if ((size_t) listener >= bmap_.size()) {
                bmap_.resize(listener + 1);
            }
            bmap_.set(listener);
        }
    }

    // concurrency: called from DBPartition task.
    void RunNotify(DBTablePartBase *tpart, DBEntryBase *entry) {
        tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
        for (CallbackList::iterator iter = callbacks_.begin();
             iter != callbacks_.end(); ++iter) {
            if (*iter != NULL) {
                ChangeCallback cb = *iter;
                (cb)(tpart, entry);
            }
        }
    }

    bool empty() {
        tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
        return callbacks_.empty();
    }

private:
    CallbackList callbacks_;
    tbb::spin_rw_mutex rw_mutex_;
    boost::dynamic_bitset<> bmap_;      // free list.
};

DBTableBase::DBTableBase(DB *db, const string &name)
        : db_(db), name_(name), info_(new ListenerInfo()) {
}

DBTableBase::~DBTableBase() {
}

DBTableBase::ListenerId DBTableBase::Register(ChangeCallback callback) {
    return info_->Register(callback);
}

void DBTableBase::Unregister(ListenerId listener) {
    info_->Unregister(listener);
}

bool DBTableBase::Enqueue(DBRequest *req) {
    DBTablePartBase *tpart = GetTablePartition(req->key.get());
    DBPartition *partition = db_->GetPartition(tpart->index());
    return partition->EnqueueRequest(tpart, NULL, req);
}

void DBTableBase::EnqueueRemove(DBEntryBase *db_entry) {
    DBTablePartBase *tpart = GetTablePartition(db_entry);
    DBPartition *partition = db_->GetPartition(tpart->index());
    partition->EnqueueRemove(tpart, db_entry);
}

void DBTableBase::RunNotify(DBTablePartBase *tpart, DBEntryBase *entry) {
    info_->RunNotify(tpart, entry);
}

bool DBTableBase::HasListeners() const {
    return !info_->empty();
}

///////////////////////////////////////////////////////////
// Implementation of DBTable methods
///////////////////////////////////////////////////////////
DBTable::DBTable(DB *db, const string &name)
    : DBTableBase(db, name),
      walk_id_(DBTableWalker::kInvalidWalkerId) {
}

DBTable::~DBTable() {
    STLDeleteValues(&partitions_);
}

void DBTable::Init() {
    for (int i = 0; i < PartitionCount(); i++) {
        partitions_.push_back(AllocPartition(i));
    }
}

DBTablePartition *DBTable::AllocPartition(int index) {
    return new DBTablePartition(this, index);
}

DBEntry *DBTable::Add(const DBRequest *req) {
    return AllocEntry(req->key.get()).release();
}

void DBTable::Change(DBEntryBase *entry) {
    DBTablePartBase *tpart = GetTablePartition(entry);
    tpart->Notify(entry);
}

bool DBTable::OnChange(DBEntry *entry, const DBRequest *req) {
    return true;
}

bool DBTable::Delete(DBEntry *entry, const DBRequest *req) {
    return true;
}

int DBTable::PartitionCount() const {
    return DB::PartitionCount();
}

static size_t HashToPartition(size_t hash) {
    return hash % DB::PartitionCount();
}

DBTablePartBase *DBTable::GetTablePartition(const int index) {
    return partitions_[index];
}

DBTablePartBase *DBTable::GetTablePartition(const DBRequestKey *key) {
    int id = HashToPartition(Hash(key));
    return GetTablePartition(id);
}

DBTablePartBase *DBTable::GetTablePartition(const DBEntryBase *entry) {
    const DBEntry *gentry = static_cast<const DBEntry *>(entry);
    size_t id = HashToPartition(Hash(gentry));
    return GetTablePartition(id);
}

DBEntry *DBTable::Find(const DBEntry *entry) {
    size_t id = HashToPartition(Hash(entry));
    DBTablePartition *tbl_partition =
        static_cast<DBTablePartition *>(GetTablePartition(id));
    return tbl_partition->Find(entry);
}

DBEntry *DBTable::Find(const DBRequestKey *key) {
    int id = HashToPartition(Hash(key));
    DBTablePartition *tbl_partition =
    static_cast<DBTablePartition *>(GetTablePartition(id));
    return tbl_partition->Find(key);
}

size_t DBTable::Size() const {
    size_t total = 0;
    for (vector<DBTablePartition *>::const_iterator iter = partitions_.begin();
         iter != partitions_.end(); iter++) {
        total += (*iter)->size();
    }
    return total;
}

void DBTable::Input(DBTablePartition *tbl_partition, DBClient *client,
                    DBRequest *req) {
    DBRequestKey *key =
        static_cast<DBRequestKey *>(req->key.get());
    DBEntry *entry = NULL;

    entry = tbl_partition->Find(key);
    if (req->oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
        if (entry) {
            if (OnChange(entry, req) || entry->IsDeleted()) {
                // The entry may currently be marked as deleted.
                entry->ClearDelete();
                tbl_partition->Change(entry);
            }
        } else {
            if ((entry = Add(req)) != NULL) {
                tbl_partition->Add(entry);
            }
        }
    } else {
        if (entry) {
            if (Delete(entry, req)) {
                tbl_partition->Delete(entry);
            }
        }
    }
}

void DBTable::DBStateClear(DBTable *table, ListenerId id) {
    DBEntryBase *next = NULL;

    for (int i = 0; i < table->PartitionCount(); ++i) {
        DBTablePartition *partition = static_cast<DBTablePartition *>(
            table->GetTablePartition(i));

        for (DBEntryBase *entry = partition->GetFirst(); entry; entry = next) {
            next = partition->GetNext(entry);
            DBState *state = entry->GetState(table, id);
            if (state) {
                entry->ClearState(table, id);
                delete state;
            }
        }
    }
}

//
// Callback for table walk triggered by NotifyAllEntries.
//
bool DBTable::WalkCallback(DBTablePartBase *tpart, DBEntryBase *entry) {
    tpart->Notify(entry);
    return true;
}

//
// Callback for completion of table walk triggered by NotifyAllEntries.
//
void DBTable::WalkCompleteCallback(DBTableBase *tbl_base) {
    walk_id_ = DBTableWalker::kInvalidWalkerId;
}

//
// Concurrency: called from task that's mutually exclusive with db::DBTable.
//
// Trigger notification of all entries to all listeners.
// Should be used sparingly e.g. to handle significant configuration change.
//
// Cancel any outstanding walk and start a new one.  The walk callback just
// turns around and puts the DBentryBase on the change list.
//
void DBTable::NotifyAllEntries() {
    CHECK_CONCURRENCY("bgp::Config");

    DBTableWalker *walker = database()->GetWalker();
    if (walk_id_ != DBTableWalker::kInvalidWalkerId)
        walker->WalkCancel(walk_id_);
    walk_id_= walker->WalkTable(this, NULL, DBTable::WalkCallback,
        boost::bind(&DBTable::WalkCompleteCallback, this, _1));
}


text:
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// 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.
//

#pragma once

#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#if _MSC_VER > 1500
#include <cstdint>
#else
#endif
#ifndef UINT64_MAX
#define UINT64_MAX 0xFFFFFFFFFFFFFFFFull
#endif
#ifndef NOMINMAX
#define NOMINMAX 1
#endif

#include <chrono>
#include <ctime>
#include <date/date.h>
#include <fstream>
#include <iomanip>
#include <limits>
#include <list>
#include <map>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <time.h>
#include <unordered_map>
#include <variant>

#if defined(_WIN32) || defined(_WIN64)
#ifndef _WINDOWS
#define _WINDOWS 1
#endif
#define ISNAN(x) _isnan(x)
#if _MSC_VER < 1800
#define NAN numeric_limits<double>::quiet_NaN()
#endif
#if _MSC_VER >= 1900
#define gets gets_s
#define timezone _timezone
#endif
typedef unsigned __int64 uint64_t;
#else
#define O_BINARY 0
#define ISNAN(x) std::isnan(x)
#include <cstdint>
#include <memory>
#include <sys/resource.h>
#include <unistd.h>
#endif

#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/regex.hpp>

//####### CONSTANTS #######

// Port number to put server on
const unsigned int SERVER_PORT = 8080;

// Size of sliding buffer
const unsigned int DEFAULT_SLIDING_BUFFER_SIZE = 131072;

// Size of buffer exponent: 2^SLIDING_BUFFER_EXP
const unsigned int DEFAULT_SLIDING_BUFFER_EXP = 17;
const unsigned int DEFAULT_MAX_ASSETS = 1024;

namespace mtconnect {
  // Message for when enumerations do not exist in an array/enumeration
  const int ENUM_MISS = -1;

  // Time format
  enum TimeFormat
  {
    HUM_READ,
    GMT,
    GMT_UV_SEC,
    LOCAL
  };

  //####### METHODS #######
  inline double stringToFloat(const std::string &text)
  {
    double value = 0.0;
    try
    {
      value = stof(text);
    }
    catch (const std::out_of_range &)
    {
      value = 0.0;
    }
    catch (const std::invalid_argument &)
    {
      value = 0.0;
    }
    return value;
  }

  inline int stringToInt(const std::string &text, int outOfRangeDefault)
  {
    int value = 0;
    try
    {
      value = stoi(text);
    }
    catch (const std::out_of_range &)
    {
      value = outOfRangeDefault;
    }
    catch (const std::invalid_argument &)
    {
      value = 0;
    }
    return value;
  }

  // Convert a float to string
  inline std::string format(double value)
  {
    std::stringstream s;
    constexpr int precision = std::numeric_limits<double>::digits10;
    s << std::setprecision(precision) << value;
    return s.str();
  }

  class format_double_stream
  {
  protected:
    double val;

  public:
    format_double_stream(double v) { val = v; }

    template <class _CharT, class _Traits>
    inline friend std::basic_ostream<_CharT, _Traits> &operator<<(
        std::basic_ostream<_CharT, _Traits> &os, const format_double_stream &fmter)
    {
      constexpr int precision = std::numeric_limits<double>::digits10;
      os << std::setprecision(precision) << fmter.val;
      return os;
    }
  };

  inline format_double_stream formatted(double v) { return format_double_stream(v); }

  // Convert a string to the same string with all upper case letters
  inline std::string toUpperCase(std::string &text)
  {
    std::transform(text.begin(), text.end(), text.begin(),
                   [](unsigned char c) { return std::toupper(c); });

    return text;
  }

  // Check if each char in a string is a positive integer
  inline bool isNonNegativeInteger(const std::string &s)
  {
    for (const char c : s)
    {
      if (!isdigit(c))
        return false;
    }

    return true;
  }

  inline bool isInteger(const std::string &s)
  {
    auto iter = s.cbegin();
    if (*iter == '-' || *iter == '+')
      ++iter;

    for (; iter != s.end(); iter++)
    {
      if (!isdigit(*iter))
        return false;
    }

    return true;
  }

  void mt_localtime(const time_t *time, struct tm *buf);

  // Get a specified time formatted
  inline std::string getCurrentTime(std::chrono::time_point<std::chrono::system_clock> timePoint,
                                    TimeFormat format)
  {
    using namespace std;
    using namespace std::chrono;
    constexpr char ISO_8601_FMT[] = "%Y-%m-%dT%H:%M:%SZ";

    switch (format)
    {
      case HUM_READ:
        return date::format("%a, %d %b %Y %H:%M:%S GMT", date::floor<seconds>(timePoint));
      case GMT:
        return date::format(ISO_8601_FMT, date::floor<seconds>(timePoint));
      case GMT_UV_SEC:
        return date::format(ISO_8601_FMT, date::floor<microseconds>(timePoint));
      case LOCAL:
        auto time = system_clock::to_time_t(timePoint);
        struct tm timeinfo = {0};
        mt_localtime(&time, &timeinfo);
        char timestamp[64] = {0};
        strftime(timestamp, 50u, "%Y-%m-%dT%H:%M:%S%z", &timeinfo);
        return timestamp;
    }

    return "";
  }

  // Get the current time formatted
  inline std::string getCurrentTime(TimeFormat format)
  {
    return getCurrentTime(std::chrono::system_clock::now(), format);
  }

  template <class timePeriod>
  inline uint64_t getCurrentTimeIn()
  {
    return std::chrono::duration_cast<timePeriod>(
               std::chrono::system_clock::now().time_since_epoch())
        .count();
  }

  // time_t to the ms
  inline uint64_t getCurrentTimeInMicros() { return getCurrentTimeIn<std::chrono::microseconds>(); }

  inline uint64_t getCurrentTimeInSec() { return getCurrentTimeIn<std::chrono::seconds>(); }

  // Get the current time in number of seconds as an integer
  uint64_t getCurrentTimeInSec();

  uint64_t parseTimeMicro(const std::string &aTime);

  // Replace illegal XML characters with the correct corresponding characters
  inline void replaceIllegalCharacters(std::string &data)
  {
    for (auto i = 0u; i < data.length(); i++)
    {
      char c = data[i];

      switch (c)
      {
        case '&':
          data.replace(i, 1, "&");
          break;

        case '<':
          data.replace(i, 1, "<");
          break;

        case '>':
          data.replace(i, 1, ">");
          break;
      }
    }
  }

  std::string addNamespace(const std::string aPath, const std::string aPrefix);

  // Ends with
  inline bool ends_with(const std::string &value, const std::string_view &ending)
  {
    if (ending.size() > value.size())
      return false;
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
  }

  inline std::string ltrim(std::string s)
  {
    boost::algorithm::trim_left(s);
    return s;
  }

  // trim from end (in place)
  static inline std::string rtrim(std::string s)
  {
    boost::algorithm::trim_right(s);
    return s;
  }

  // trim from both ends (in place)
  inline std::string trim(std::string s)
  {
    boost::algorithm::trim(s);
    return s;
  }

  inline bool starts_with(const std::string &value, const std::string_view &beginning)
  {
    if (beginning.size() > value.size())
      return false;
    return std::equal(beginning.begin(), beginning.end(), value.begin());
  }

  inline bool iequals(const std::string &a, const std::string_view &b)
  {
    if (a.size() != b.size())
      return false;

    return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin(), [](char a, char b) {
             return tolower(a) == tolower(b);
           });
  }

  using Attributes = std::map<std::string, std::string>;

  template <class... Ts>
  struct overloaded : Ts...
  {
    using Ts::operator()...;
  };
  template <class... Ts>
  overloaded(Ts...) -> overloaded<Ts...>;

  template <typename T>
  class reverse
  {
  private:
    T &m_iterable;

  public:
    explicit reverse(T &iterable) : m_iterable(iterable) {}
    auto begin() const { return std::rbegin(m_iterable); }
    auto end() const { return std::rend(m_iterable); }
  };

  using SequenceNumber_t = uint64_t;
  using FilterSet = std::set<std::string>;
  using FilterSetOpt = std::optional<FilterSet>;
  using Milliseconds = std::chrono::milliseconds;
  using Microseconds = std::chrono::microseconds;
  using Seconds = std::chrono::seconds;
  using Timestamp = std::chrono::time_point<std::chrono::system_clock>;
  using StringList = std::list<std::string>;
  using ConfigOption = std::variant<std::monostate, bool, int, std::string, double, Seconds,
                                    Milliseconds, StringList>;
  using ConfigOptions = std::map<std::string, ConfigOption>;
  template <typename T>
  inline const std::optional<T> GetOption(const ConfigOptions &options, const std::string &name)
  {
    auto v = options.find(name);
    if (v != options.end())
      return std::get<T>(v->second);
    else
      return std::nullopt;
  }

  inline bool IsOptionSet(const ConfigOptions &options, const std::string &name)
  {
    auto v = options.find(name);
    if (v != options.end())
      return std::get<bool>(v->second);
    else
      return false;
  }

  inline bool HasOption(const ConfigOptions &options, const std::string &name)
  {
    auto v = options.find(name);
    return v != options.end();
  }

  inline auto ConvertOption(const std::string &s, const ConfigOption &def)
  {
    ConfigOption option;
    visit(overloaded {[&option, &s](const std::string &) {
                        if (s.empty())
                          option = std::monostate();
                        else
                          option = s;
                      },
                      [&option, &s](const int &) { option = stoi(s); },
                      [&option, &s](const Milliseconds &) { option = Milliseconds {stoi(s)}; },
                      [&option, &s](const Seconds &) { option = Seconds {stoi(s)}; },
                      [&option, &s](const double &) { option = stod(s); },
                      [&option, &s](const bool &) { option = s == "yes" || s == "true"; },
                      [](const auto &) {}},
          def);
    return option;
  }

  inline int64_t ConvertFileSize(const ConfigOptions &options, const std::string &name,
                                 int64_t size = 0)
  {
    using namespace std;
    using boost::regex;
    using boost::smatch;

    auto value = GetOption<string>(options, name);
    if (value)
    {
      static const regex pat("([0-9]+)([GgMmKkBb]*)");
      smatch match;
      string v = *value;
      if (regex_match(v, match, pat))
      {
        size = boost::lexical_cast<int64_t>(match[1]);
        if (match[2].matched)
        {
          switch (match[2].str()[0])
          {
            case 'G':
            case 'g':
              size *= 1024;

            case 'M':
            case 'm':
              size *= 1024;

            case 'K':
            case 'k':
              size *= 1024;
          }
        }
      }
      else
      {
        std::stringstream msg;
        msg << "Invalid value for " << name << ": " << *value << endl;
        throw std::runtime_error(msg.str());
      }
    }

    return size;
  }

  inline void AddOptions(const boost::property_tree::ptree &tree, ConfigOptions &options,
                         const ConfigOptions &entries)
  {
    for (auto &e : entries)
    {
      auto val = tree.get_optional<std::string>(e.first);
      if (val)
      {
        auto v = ConvertOption(*val, e.second);
        if (v.index() != 0)
          options.insert_or_assign(e.first, v);
      }
    }
  }

  inline void AddDefaultedOptions(const boost::property_tree::ptree &tree, ConfigOptions &options,
                                  const ConfigOptions &entries)
  {
    for (auto &e : entries)
    {
      auto val = tree.get_optional<std::string>(e.first);
      if (val)
      {
        auto v = ConvertOption(*val, e.second);
        if (v.index() != 0)
          options.insert_or_assign(e.first, v);
      }
      else if (options.find(e.first) == options.end())
        options.insert_or_assign(e.first, e.second);
    }
  }

  inline void GetOptions(const boost::property_tree::ptree &tree, ConfigOptions &options,
                         const ConfigOptions &entries)
  {
    for (auto &e : entries)
    {
      if (!std::holds_alternative<std::string>(e.second) ||
          !std::get<std::string>(e.second).empty())
      {
        options.emplace(e.first, e.second);
      }
    }
    AddOptions(tree, options, entries);
  }

  inline std::string format(const Timestamp &ts)
  {
    using namespace std;
    string time = date::format("%FT%T", date::floor<Microseconds>(ts));
    auto pos = time.find_last_not_of("0");
    if (pos != string::npos)
    {
      if (time[pos] != '.')
        pos++;
      time.erase(pos);
    }
    time.append("Z");
    return time;
  }

  inline void capitalize(std::string::iterator start, std::string::iterator end)
  {
    using namespace std;

    // Exceptions to the rule
    const static std::unordered_map<std::string, std::string> exceptions = {
        {"AC", "AC"}, {"DC", "DC"},   {"PH", "PH"},
        {"IP", "IP"}, {"URI", "URI"}, {"MTCONNECT", "MTConnect"}};

    const auto &w = exceptions.find(std::string(start, end));
    if (w != exceptions.end())
    {
      copy(w->second.begin(), w->second.end(), start);
    }
    else
    {
      *start = ::toupper(*start);
      start++;
      transform(start, end, start, ::tolower);
    }
  }

  inline std::string pascalize(const std::string &type, std::optional<std::string> &prefix)
  {
    using namespace std;
    if (type.empty())
      return "";

    string camel;
    auto colon = type.find(':');

    if (colon != string::npos)
    {
      prefix = type.substr(0ul, colon);
      camel = type.substr(colon + 1ul);
    }
    else
      camel = type;

    auto start = camel.begin();
    decltype(start) end;

    bool done;
    do
    {
      end = find(start, camel.end(), '_');
      capitalize(start, end);
      done = end == camel.end();
      if (!done)
      {
        camel.erase(end);
        start = end;
      }
    } while (!done);

    return camel;
  }

#ifdef _WINDOWS
#include <io.h>
  typedef long volatile AtomicInt;
#else
#ifdef MACOSX
#include <libkern/OSAtomic.h>
  typedef volatile long AtomicInt;
#else
  using AtomicInt = int;
#endif
#endif
}  // namespace mtconnect

max_stars_repo_name: bburns/cppagent

max_issues_repo_name: bburns/cppagent

max_forks_repo_name: bburns/cppagent


text:
#pragma once

#include <boost/asio/io_context_strand.hpp>
#include <chrono>
#include <pqxx/pqxx>

#include "core/web/web_types.hpp"

class TournamentId;

struct TournamentListing {
    std::string webName;
    std::string name;
    std::string location;
    std::string date;
};

class Database {
public:
    Database(boost::asio::io_context &context, const std::string &config);

    typedef std::function<void(UserRegistrationResponse, const std::optional<WebToken>&, std::optional<int>)> UserRegistrationCallback;
    void asyncRegisterUser(const std::string &email, const std::string &password, UserRegistrationCallback callback);

    typedef std::function<void(WebTokenRequestResponse, const std::optional<WebToken>&, std::optional<int>)> WebTokenRequestCallback;
    void asyncRequestWebToken(const std::string &email, const std::string &password, WebTokenRequestCallback callback);

    typedef std::function<void(WebTokenValidationResponse, std::optional<int>)> WebTokenValidationCallback;
    void asyncValidateWebToken(const std::string &email, const WebToken& token, WebTokenValidationCallback callback);

    typedef std::function<void(WebNameCheckResponse)> WebNameCheckCallback;
    void asyncCheckWebName(int userId, const TournamentId &id, const std::string &webName, WebNameCheckCallback callback);

    typedef std::function<void(WebNameRegistrationResponse)> WebNameRegistrationCallback;
    void asyncRegisterWebName(int userId, const TournamentId &id, const std::string &webName, WebNameRegistrationCallback callback);

    typedef std::function<void(bool)> SyncedSetCallback;
    void asyncSetSynced(const std::string &webName, SyncedSetCallback callback);

    typedef std::function<void(bool)> SaveTimeSetCallback;
    void asyncSetSaveTime(const std::string &webName, std::chrono::system_clock::time_point time, SaveTimeSetCallback callback);

    typedef std::function<void(bool)> SaveStatusGetCallback;
    void asyncGetSaveStatus(const std::string &webName, SaveStatusGetCallback callback);

    typedef std::function<void(bool)> UpdateTournamentCallback;
    void asyncUpdateTournament(const std::string &webName, const std::string &name, const std::string &location, const std::string &date, UpdateTournamentCallback callback);

    typedef std::function<void(bool, std::vector<TournamentListing>, std::vector<TournamentListing>)> ListTournamentsCallback;
    void asyncListTournaments(ListTournamentsCallback callback);

private:
    void registerUser(const std::string &email, const std::string &password, UserRegistrationCallback callback);

    void requestWebToken(const std::string &email, const std::string &password, WebTokenRequestCallback callback);
    void validateWebToken(const std::string &email, const WebToken &token, WebTokenValidationCallback callback);

    void checkWebName(int userId, const TournamentId &id, const std::string &webName, WebNameCheckCallback callback);
    void registerWebName(int userId, const TournamentId &id, const std::string &webName, WebNameRegistrationCallback callback);

    void setSynced(const std::string &webName, SyncedSetCallback callback);
    void setSaveTime(const std::string &webName, std::chrono::system_clock::time_point time, SaveTimeSetCallback callback);

    void getSaveStatus(const std::string &webName, SaveStatusGetCallback callback);

    void updateTournament(const std::string &webName, const std::string &name, const std::string &location, const std::string &date, UpdateTournamentCallback callback);

    void listTournaments(ListTournamentsCallback callback);

    bool hasUser(const std::string &email);
    bool checkPassword(const std::string &email, const std::string &password);
    WebToken generateWebToken();

    std::string generateWebTokenExpiration();
    bool validateWebTokenExpiration(const std::string &expiration);

private:
    boost::asio::io_context &mContext;
    boost::asio::io_context::strand mStrand;
    pqxx::connection mConnection;
};

max_stars_repo_name: svendcsvendsen/judoassistant

max_issues_repo_name: svendcsvendsen/judoassistant

max_forks_repo_name: judoassistant/judoassistant