text:
#include <boost/program_options.hpp>
#include <filesystem>
#include <iostream>
#include <vips/vips.h>

namespace fs = std::filesystem;
namespace po = boost::program_options;

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////
class VipsExit
{
public:
  VipsExit() { ; }
  ~VipsExit()
  {
    printf("vips_shutdown\n");
    vips_shutdown();
  }
};

////////////////////////////////////////////////////////////////////////////////////////
/// This is needed for calling unref when a VipsImage goes out of scope.
class OnExit
{
public:
  OnExit(VipsImage* image_)
    : image(image_)
  {
    if (image)
      printf("[%d] Tracking image: %p\n", __LINE__, image);
  }
  ~OnExit()
  {
    if (image)
      printf("[%d] About to unref image: %p\n", __LINE__, image);

    if (image)
      g_object_unref(image);
  }

  VipsImage* image;
};

////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
  auto appStart = std::chrono::high_resolution_clock::now();

  // Expects parameter passed in is the image to apply the gaussian blur to
  // Expects second parameter to be the output path to where you want to save the blurred image.
  // Setup program options
  auto desc = po::options_description("Options");
  // clang-format off
  desc.add_options()
  ("help,h", "Show help message")
  ("source,s", po::value< string >(), "The full file path to the source image to blur")
  ("destination,d", po::value< string >(), "The full file path to where to save the blurred image")
  ("blur,b", po::value< int >(), "The blur intensity to use");
  // clang-format on

  // Parse the passed in options
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  // Now act on what we have
  if (vm.count("help"))
  {
    cout << desc << "\n";
    return 1;
  }

  string sourcePath;
  string destPath;
  int blur = -1;

  if (vm.count("source"))
  {
    sourcePath = vm["source"].as<string>();
  }
  else
  {
    printf("Source path parameter missing\n");
    return -1;
  }
  if (vm.count("destination"))
  {
    destPath = vm["destination"].as<string>();
  }
  else
  {
    printf("Destination path parameter missing\n");
    return -1;
  }
  if (vm.count("blur"))
  {
    blur = vm["blur"].as<int>();
  }
  else
  {
    printf("Blur parameter missing\n");
    return -1;
  }

  printf("Init the VIPS library\n");
  string nameOfApp = "gaussian_libvips";
  if (VIPS_INIT(nameOfApp.c_str()))
  {
    printf("Error detected; underlying image processing library did not start up properly");
    return false;
  }

  VipsExit vipsCleanup;

  // Load up the image
  auto sourceImage = vips_image_new_from_file(sourcePath.c_str(), nullptr);
  if (!sourceImage)
  {
    printf("[%d] #### Error detected with vips_image_new_from_file operation", __LINE__);
    return -1;
  }
  OnExit a(sourceImage);

  // Perform blur filter (note blur value is sigma of Gaussian blur)
  // Note, if you wanted to convert box filter kernel size to sigma, use...
  // auto sigma = sqrt (((kernelSize * kernelSize) - 1)/12);
  //
  if (vips_gaussblur(sourceImage, &sourceImage, blur, nullptr) != 0)
  {
    printf("Error detected with vips_gaussblur operation\n");
    return -1;
  }

  if (vips_image_write_to_file(sourceImage, destPath.c_str(), nullptr, nullptr) != 0)
  {
    printf("[%d] #### Error detected with vips_image_write_to_file operation", __LINE__);
    return -1;
  }

  auto appStop = std::chrono::high_resolution_clock::now();
  auto appDuration = std::chrono::duration_cast<std::chrono::microseconds>(appStop - appStart).count();
  printf("App time: %lu\n", appDuration);

  printf("All done\n");
  return 0;
}


text:
/*-----------------------------------------------------------------------------+
Copyright (c) 2010-2010: Joachim Faulhaber
+------------------------------------------------------------------------------+
   Distributed under the Boost Software License, Version 1.0.
      (See accompanying file LICENCE.txt or copy at
           http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_DISCRETE_INTERVAL_HPP_JOFA_100403
#define BOOST_ICL_DISCRETE_INTERVAL_HPP_JOFA_100403

// File differs from Boost distribution by providing define_type functions to
// allow data structures defined here to be marshaled.

#include <functional>
#include <boost/static_assert.hpp>
#include <boost/concept/assert.hpp>
#include <boost/icl/detail/concept_check.hpp>
#include <boost/icl/type_traits/succ_pred.hpp>
#include <boost/icl/concept/interval.hpp>
#include <boost/icl/type_traits/value_size.hpp>
#include <boost/icl/type_traits/type_to_string.hpp>
#include <boost/icl/type_traits/is_continuous.hpp>
#include <boost/icl/type_traits/is_discrete_interval.hpp>
#include <boost/icl/interval_bounds.hpp>

#ifdef _STAPL
# include <stapl/runtime/serialization_fwd.hpp>
#endif

namespace boost{namespace icl
{

template <class DomainT,
          ICL_COMPARE Compare = ICL_COMPARE_INSTANCE(ICL_COMPARE_DEFAULT, DomainT)>
class discrete_interval
{
public:
    typedef discrete_interval<DomainT,Compare> type;
    typedef DomainT domain_type;
    typedef ICL_COMPARE_DOMAIN(Compare,DomainT) domain_compare;
    typedef typename bounded_value<DomainT>::type bounded_domain_type;

public:
    //==========================================================================
    //= Construct, copy, destruct
    //==========================================================================
    /** Default constructor; yields an empty interval <tt>[0,0)</tt>. */
    discrete_interval()
        : _lwb(identity_element<DomainT>::value()), _upb(identity_element<DomainT>::value())
        , _bounds(interval_bounds::right_open())
    {
        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
        BOOST_STATIC_ASSERT((icl::is_discrete<DomainT>::value));
    }

    //NOTE: Compiler generated copy constructor is used

    /** Constructor for a closed singleton interval <tt>[val,val]</tt> */
    explicit discrete_interval(const DomainT& val)
        : _lwb(val), _upb(val), _bounds(interval_bounds::closed())
    {
        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
        BOOST_STATIC_ASSERT((icl::is_discrete<DomainT>::value));
    }

    /** Interval from <tt>low</tt> to <tt>up</tt> with bounds <tt>bounds</tt> */
    discrete_interval(const DomainT& low, const DomainT& up,
                      interval_bounds bounds = interval_bounds::right_open(),
                      discrete_interval* = 0)
        : _lwb(low), _upb(up), _bounds(bounds)
    {
        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
        BOOST_STATIC_ASSERT((icl::is_discrete<DomainT>::value));
    }

    domain_type     lower()const { return _lwb; }
    domain_type     upper()const { return _upb; }
    interval_bounds bounds()const{ return _bounds; }

    static discrete_interval open      (const DomainT& lo, const DomainT& up){ return discrete_interval(lo, up, interval_bounds::open());      }
    static discrete_interval right_open(const DomainT& lo, const DomainT& up){ return discrete_interval(lo, up, interval_bounds::right_open());}
    static discrete_interval left_open (const DomainT& lo, const DomainT& up){ return discrete_interval(lo, up, interval_bounds::left_open()); }
    static discrete_interval closed    (const DomainT& lo, const DomainT& up){ return discrete_interval(lo, up, interval_bounds::closed());    }

#ifdef _STAPL
  void define_type(stapl::typer& t)
  {
    t.member(_lwb);
    t.member(_upb);
    t.member(_bounds);
  }
#endif

private:
    domain_type     _lwb;
    domain_type     _upb;
    interval_bounds _bounds;
};

//==============================================================================
//=T discrete_interval -> concept intervals
//==============================================================================
template<class DomainT, ICL_COMPARE Compare>
struct interval_traits< icl::discrete_interval<DomainT, Compare> >
{
    typedef interval_traits type;
    typedef DomainT domain_type;
    typedef ICL_COMPARE_DOMAIN(Compare,DomainT) domain_compare;
    typedef icl::discrete_interval<DomainT, Compare> interval_type;

    static interval_type construct(const domain_type& lo, const domain_type& up)
    {
        return interval_type(lo, up);
    }

    static domain_type lower(const interval_type& inter_val){ return inter_val.lower(); };
    static domain_type upper(const interval_type& inter_val){ return inter_val.upper(); };
};

//==============================================================================
//=T discrete_interval -> concept dynamic_interval_traits
//==============================================================================
template<class DomainT, ICL_COMPARE Compare>
struct dynamic_interval_traits<boost::icl::discrete_interval<DomainT,Compare> >
{
    typedef dynamic_interval_traits type;
    typedef boost::icl::discrete_interval<DomainT,Compare> interval_type;
    typedef DomainT domain_type;
    typedef ICL_COMPARE_DOMAIN(Compare,DomainT) domain_compare;

    static interval_type construct(const domain_type& lo, const domain_type& up, interval_bounds bounds)
    {
        return interval_type(lo, up, bounds, static_cast<interval_type*>(0) );
    }

    static interval_type construct_bounded(const bounded_value<DomainT>& lo,
                                           const bounded_value<DomainT>& up)
    {
        return  interval_type
                (
                    lo.value(), up.value(),
                    lo.bound().left() | up.bound().right(),
                    static_cast<interval_type* >(0)
                );
    }
};

//==============================================================================
//= Type traits
//==============================================================================
template <class DomainT, ICL_COMPARE Compare>
struct interval_bound_type< discrete_interval<DomainT,Compare> >
{
    typedef interval_bound_type type;
    BOOST_STATIC_CONSTANT(bound_type, value = interval_bounds::dynamic);
};

template <class DomainT, ICL_COMPARE Compare>
struct is_discrete_interval<discrete_interval<DomainT,Compare> >
{
    typedef is_discrete_interval<discrete_interval<DomainT,Compare> > type;
    BOOST_STATIC_CONSTANT(bool, value = is_discrete<DomainT>::value);
};

template <class DomainT, ICL_COMPARE Compare>
struct type_to_string<icl::discrete_interval<DomainT,Compare> >
{
    static std::string apply()
    { return "dI<"+ type_to_string<DomainT>::apply() +">"; }
};

template<class DomainT>
struct value_size<icl::discrete_interval<DomainT> >
{
    static std::size_t apply(const icl::discrete_interval<DomainT>&)
    { return 2; }
};

}} // namespace icl boost

#endif

ext: hpp


text:
#include <sstream>
#include "key-message-handler.h"
#include "stream-util.h"

#define BOOST_TEST_MODULE
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "common/test-init.h"
using namespace std;

BOOST_AUTO_TEST_CASE(KeyHandlerWorks) {

  // Mimics the SUT client's stdin
  stringstream* client_stdin_pipe = new stringstream();
  // Mimics the SUT client's stdout
  stringstream* client_stdout_pipe = new stringstream();
  // Mimics the SUT server's stdin
  stringstream* server_stdin_pipe = new stringstream();
  // Mimics the SUT server's stdout
  stringstream* server_stdout_pipe = new stringstream();

  unique_ptr<stringstream> client_stdin_ptr(client_stdin_pipe);
  unique_ptr<stringstream> client_stdout_ptr(client_stdout_pipe);
  unique_ptr<stringstream> server_stdin_ptr(server_stdin_pipe);
  unique_ptr<stringstream> server_stdout_ptr(server_stdout_pipe);
  unique_ptr<stringstream> results(new stringstream());

  TestHarnessIStream client_stdout(move(client_stdout_ptr));
  TestHarnessOStream client_stdin(move(client_stdin_ptr));
  TestHarnessIStream server_stdout(move(server_stdout_ptr));
  TestHarnessOStream server_stdin(move(server_stdin_ptr));

  auto k = KeyMessageHandler(results.get());
  k.set_client_stdin(&client_stdin);
  k.set_client_stdout(&client_stdout);
  k.set_server_stdin(&server_stdin);
  k.set_server_stdout(&server_stdout);

  // Write the expected client response. This is done before the client actually
  // gets the securit parameter but for testing that's okay. Ideally, the
  // client's response is run in a separate thread.
  *client_stdout_pipe << "KEY\npublic_key\nENDKEY" << endl;

  stringstream file;
  file << "security parameters";
  k.Send(&file);

  BOOST_CHECK_EQUAL(
      client_stdin_pipe->str(), "KEY\nsecurity parameters\nENDKEY\n");
  BOOST_CHECK_EQUAL(
      client_stdout_pipe->str(), "KEY\npublic_key\nENDKEY\n");
  BOOST_CHECK_EQUAL(
      server_stdin_pipe->str(), "KEY\npublic_key\nENDKEY\n");
  BOOST_CHECK(results->str().find("KEYGEN") != string::npos);
}

ext: cc

max_stars_repo_name: nathanawmk/SPARTA

max_issues_repo_name: CianLevy/Modified-HEtest

max_forks_repo_name: CianLevy/Modified-HEtest


text:
#include "SimWindow.h"
#include "RecordWindow.h"
#include "SeqRecordWindow.h"
#include "SplineWindow.h"
#include "RegressionWindow.h"
#include <vector>
#include <string>
#include <GL/glut.h>
#include <boost/program_options.hpp>
#include <experimental/filesystem>
#include <algorithm>
#include <regex>
bool compare_string_with_number(const std::string& s1, const std::string& s2) {
	int length = std::min(s1.length(), s2.length());
	for(int i = 0; i < length; i++) {
		if(s1.at(i) >= 48 && s1.at(i) <= 57 && s2.at(i) >= 48 && s2.at(i) <= 57) {
			int n1 = 0, n2 = 0;
			n1 = (int)s1.at(i) - 48;
			n2 = (int)s2.at(i) - 48;

			int l1 = 1, l2 = 1;
			while(s1.length() > i + l1 && s1.at(i + l1) >= 48 && s1.at(i + l1) <= 57 ) {
				n1 *= 10;
				n1 += (int)s1.at(i + l1) - 48;
				l1 += 1;
			}

			while(s2.length() > i + l2 &&  s2.at(i + l2) >= 48 && s2.at(i + l2) <= 57 ) {
				n2 *= 10;
				n2 += (int)s2.at(i + l2) - 48;
				l2 += 1;
			}

			if(n1 < n2) {
				return true;
			} else if(n1 > n2) {
				return false;
			}

			i += (l1 - 1);
		}
		else {
			if(s1.at(i) < s2.at(i)) {
				return true;
			} else if (s1.at(i) > s2.at(i)) {
				return true;
			}
		}
	}
	return false;
}
int main(int argc,char** argv)
{
	std::cout<<"[ : Frame --"<<std::endl;
	std::cout<<"] : Frame ++"<<std::endl;
	std::cout<<"r : Frame = 0"<<std::endl;
	std::cout<<"C : Capture"<<std::endl;
	std::cout<<"SPACE : Play"<<std::endl;
	std::cout<<"ESC : exit"<<std::endl;

	boost::program_options::options_description desc("allowed options");
	desc.add_options()
	("type,t",boost::program_options::value<std::string>())
	("file,f",boost::program_options::value<std::string>())
	("ref,r",boost::program_options::value<std::string>())
	("network,n",boost::program_options::value<std::string>())
	("save,s",boost::program_options::value<std::string>())
	;

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
	std::string type, file="", network="", save="", ref="";

	if(vm.count("type")) {
		type = vm["type"].as<std::string>();
	}
	if(vm.count("file")) {
		file = vm["file"].as<std::string>();
	}
	if(vm.count("network")) {
		network = vm["network"].as<std::string>();
	}
	if(vm.count("save")) {
		save = vm["save"].as<std::string>();
	}
	if(vm.count("ref")) {
		ref = vm["ref"].as<std::string>();
	}

	if(type.compare("sim")==0) {
		SimWindow* simwindow = new SimWindow(ref, network, save);
		glutInit(&argc, argv);
		simwindow->InitWindow(1600,900,"Render");
		glutMainLoop();
	} else if(type.compare("spl_to_pos")==0) {
		SplineWindow* swindow = new SplineWindow(ref, std::string(CAR_DIR) + std::string("/") + file, "spline");
		glutInit(&argc, argv);
		swindow->InitWindow(1600,900,"Render");
		glutMainLoop();
	} else if(type.compare("pos_to_spl")==0) {
		SplineWindow* swindow = new SplineWindow(ref, std::string(CAR_DIR) + std::string("/") + file, "position");
		glutInit(&argc, argv);
		swindow->InitWindow(1600,900,"Render");
		glutMainLoop();
	} else if(type.compare("rec")==0 || type.compare("srec")==0){
		std::vector<std::string> raw = DPhy::split(file, ',');
		std::vector<std::string> motion;

		for(int i = 0; i < raw.size(); i++) {
			std::vector<std::string> path;
			path.push_back(std::string(CAR_DIR));
			std::vector<std::string> dir = DPhy::split(raw[i], '/');
			for(int j = 0 ; j < dir.size(); j++) {
				std::regex re(dir[j]);
				std::vector<std::string> path_new;

				for(int k = 0; k < path.size(); k++) {
					std::vector<std::string> path_temp;

					for(auto &p: std::experimental::filesystem::directory_iterator(path[k])) {
						if(std::regex_match(p.path().filename().string(), re)) {
							path_temp.push_back(p.path().filename().string());

						}
					}
					std::sort(path_temp.begin(), path_temp.end(), compare_string_with_number);
					for(int l = 0; l < path_temp.size(); l++) {
						path_temp[l] = path[k] + std::string("/") + path_temp[l];
						path_new.push_back(path_temp[l]);
					}
				}
				path = path_new;
			}
			for(int j = 0; j < path.size(); j++) {
				motion.push_back(path[j]);
				std::cout << path[j] << std::endl;
			}
		}
		if(type.compare("rec")==0) {
			RecordWindow* rwindow = new RecordWindow(motion);
			glutInit(&argc, argv);
			rwindow->InitWindow(1600,900,"Render");
			glutMainLoop();
		} else {
			SeqRecordWindow* rwindow = new SeqRecordWindow(motion);
			glutInit(&argc, argv);
			rwindow->InitWindow(1600,900,"Render");
			glutMainLoop();
		}
	} if(type.compare("reg")==0) {
		RegressionWindow* rgwindow = new RegressionWindow(ref, network);
		glutInit(&argc, argv);
		rgwindow->InitWindow(1600,900,"Render");
		glutMainLoop();
	}

	return 0;
}

ext: cpp

max_stars_repo_name: snumrl/CAR

max_issues_repo_name: snumrl/CAR

max_forks_repo_name: snumrl/CAR


text:
/* openrtb_exchange_connector.cc
   Eric Robert, 7 May 2013

   Implementation of the OpenRTB exchange connector.
*/

#include "openrtb_exchange_connector.h"
#include "rtbkit/common/testing/exchange_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/plugins/exchange/http_auction_handler.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "openrtb/openrtb_parsing.h"
#include "soa/types/json_printing.h"
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include "jml/utils/file_functions.h"
#include "jml/arch/info.h"
#include "jml/utils/rng.h"

using namespace Datacratic;

namespace Datacratic {

template<typename T, int I, typename S>
Json::Value jsonEncode(const ML::compact_vector<T, I, S> & vec)
{
    Json::Value result(Json::arrayValue);
    for (unsigned i = 0;  i < vec.size();  ++i)
        result[i] = jsonEncode(vec[i]);
    return result;
}

template<typename T, int I, typename S>
ML::compact_vector<T, I, S>
jsonDecode(const Json::Value & val, ML::compact_vector<T, I, S> *)
{
    ExcAssert(val.isArray());
    ML::compact_vector<T, I, S> res;
    res.reserve(val.size());
    for (unsigned i = 0;  i < val.size();  ++i)
        res.push_back(jsonDecode(val[i], (T*)0));
    return res;
}

} // namespace Datacratic

namespace OpenRTB {

template<typename T>
Json::Value jsonEncode(const OpenRTB::List<T> & vec)
{
    using Datacratic::jsonEncode;
    Json::Value result(Json::arrayValue);
    for (unsigned i = 0;  i < vec.size();  ++i)
        result[i] = jsonEncode(vec[i]);
    return result;
}

template<typename T>
OpenRTB::List<T>
jsonDecode(const Json::Value & val, OpenRTB::List<T> *)
{
    using Datacratic::jsonDecode;
    ExcAssert(val.isArray());
    OpenRTB::List<T> res;
    res.reserve(val.size());
    for (unsigned i = 0;  i < val.size();  ++i)
        res.push_back(jsonDecode(val[i], (T*)0));
    return res;
}

} // namespace OpenRTB

namespace RTBKIT {

BOOST_STATIC_ASSERT(hasFromJson<Datacratic::Id>::value == true);
BOOST_STATIC_ASSERT(hasFromJson<int>::value == false);

/*****************************************************************************/
/* OPENRTB EXCHANGE CONNECTOR                                                */
/*****************************************************************************/

OpenRTBExchangeConnector::
OpenRTBExchangeConnector(ServiceBase & owner, const std::string & name)
    : HttpExchangeConnector(name, owner)
{
}

OpenRTBExchangeConnector::
OpenRTBExchangeConnector(const std::string & name,
                         std::shared_ptr<ServiceProxies> proxies)
    : HttpExchangeConnector(name, proxies)
{
}

std::shared_ptr<BidRequest>
OpenRTBExchangeConnector::
parseBidRequest(HttpAuctionHandler & connection,
                const HttpHeader & header,
                const std::string & payload)
{
    std::shared_ptr<BidRequest> res;

    // Check for JSON content-type
    if (header.contentType != "application/json") {
        connection.sendErrorResponse("non-JSON request");
        return res;
    }

    // Check for the x-openrtb-version header
    auto it = header.headers.find("x-openrtb-version");
    if (it == header.headers.end()) {
        connection.sendErrorResponse("no OpenRTB version header supplied");
        return res;
    }

    // Check that it's version 2.1
    std::string openRtbVersion = it->second;
    if (openRtbVersion != "2.1") {
        connection.sendErrorResponse("expected OpenRTB version 2.1; got " + openRtbVersion);
        return res;
    }

    // Parse the bid request
    ML::Parse_Context context("Bid Request", payload.c_str(), payload.size());
    res.reset(OpenRtbBidRequestParser::parseBidRequest(context,
                                                       exchangeName(),
                                                       exchangeName()));
    return res;
}

double
OpenRTBExchangeConnector::
getTimeAvailableMs(HttpAuctionHandler & connection,
                   const HttpHeader & header,
                   const std::string & payload)
{
    // Scan the payload quickly for the tmax parameter.
    static const std::string toFind = "\"tmax\":";
    std::string::size_type pos = payload.find(toFind);
    if (pos == std::string::npos)
        return 10.0;

    int tmax = atoi(payload.c_str() + pos + toFind.length());
    return tmax;
}

HttpResponse
OpenRTBExchangeConnector::
getResponse(const HttpAuctionHandler & connection,
            const HttpHeader & requestHeader,
            const Auction & auction) const
{
    const Auction::Data * current = auction.getCurrentData();

    if (current->hasError())
        return getErrorResponse(connection, auction,
                                current->error + ": " + current->details);

    OpenRTB::BidResponse response;
    response.id = auction.id;

    // Create a spot for each of the bid responses
    for (unsigned spotNum = 0; spotNum < current->responses.size(); ++spotNum) {
        if (!current->hasValidResponse(spotNum))
            continue;

        setSeatBid(auction, spotNum, response);
    }

    if (response.seatbid.empty())
        return HttpResponse(204, "none", "");

    static Datacratic::DefaultDescription<OpenRTB::BidResponse> desc;
    std::ostringstream stream;
    StreamJsonPrintingContext context(stream);
    desc.printJsonTyped(&response, context);

    return HttpResponse(200, "application/json", stream.str());
}

HttpResponse
OpenRTBExchangeConnector::
getDroppedAuctionResponse(const HttpAuctionHandler & connection,
                          const std::string & reason) const
{
    return HttpResponse(204, "application/json", "{}");
}

HttpResponse
OpenRTBExchangeConnector::
getErrorResponse(const HttpAuctionHandler & connection,
                 const Auction & auction,
                 const std::string & errorMessage) const
{
    Json::Value response;
    response["error"] = errorMessage;
    return HttpResponse(400, response);
}

std::shared_ptr<BidSource>
OpenRTBExchangeConnector::
getBidSource() const
{
    struct OpenRTBBidSource : public BidSource {
        ML::RNG rng;

        std::string host;
        std::string verb;
        std::string resource;

        OpenRTBBidSource(int port,
                         std::string verb,
                         std::string resource)
            : BidSource(NetworkAddress(port)),
              host(ML::fqdn_hostname(std::to_string(port)) + ":" + std::to_string(port)),
              verb(std::move(verb)),
              resource(std::move(resource))
        {
        }

        void generateRandomBidRequest() {
            OpenRTB::BidRequest req;
            req.id = Id(rng.random());
            req.tmax.val = 50;
	    req.at = AuctionType::SECOND_PRICE;
	    req.imp.emplace_back();
	    auto & imp = req.imp[0];
	    imp.id = Id(rng.random());
	    imp.banner.reset(new OpenRTB::Banner);
	    imp.banner->w.push_back(300);
	    imp.banner->h.push_back(250);

            StructuredJsonPrintingContext context;
            DefaultDescription<OpenRTB::BidRequest> desc;
            desc.printJson(&req, context);
            std::string content = context.output.toString();

            int length = content.length();

            std::string message = ML::format(
                "%s %s HTTP/1.1\r\n"
                "Content-Type: application/json\r\n"
                "Content-Length: %d\r\n"
                "accept: */*\r\n"
                "connection: Keep-Alive\r\n"
                "host: %s\r\n"
                "user-agent: be2/1.0\r\n"
                "x-openrtb-version: 2.1\r\n"
                "\r\n%s",
                verb.c_str(), resource.c_str(), length, host.c_str(), content.c_str());

            std::cerr << message << std::endl;
            write(message);
            std::cerr << read() << std::endl;
        }
    };

    return std::make_shared<OpenRTBBidSource>(port(),
                                              auctionVerb,
                                              auctionResource);
}

void
OpenRTBExchangeConnector::
setSeatBid(Auction const & auction,
           int spotNum,
           OpenRTB::BidResponse & response) const
{
    const Auction::Data * data = auction.getCurrentData();

    // Get the winning bid
    auto & resp = data->winningResponse(spotNum);

    int seatIndex = 0;
    if(response.seatbid.empty()) {
        response.seatbid.emplace_back();
    }

    OpenRTB::SeatBid & seatBid = response.seatbid.at(seatIndex);

    // Add a new bid to the array
    seatBid.bid.emplace_back();

    // Put in the variable parts
    auto & b = seatBid.bid.back();
    b.cid = Id(resp.agent);
    b.id = Id(auction.id, auction.request->imp[0].id);
    b.impid = auction.request->imp[spotNum].id;
    b.price.val = USD_CPM(resp.price.maxPrice);
}

} // namespace RTBKIT

namespace {
    using namespace RTBKIT;

    struct Init {
        Init() {
            ExchangeConnector::registerFactory<OpenRTBExchangeConnector>();
        }
    } init;
}

max_stars_repo_name: leobispo/rtbkit

max_issues_repo_name: leobispo/rtbkit

max_forks_repo_name: leobispo/rtbkit


text:
/*******************************************************************************
 * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/MIT
 *
 * Developers:
 *   Sebastian Niemann - Lead developer
 *   Daniel Kiechle - Unit testing
 ******************************************************************************/
#include <Expected.hpp>
using armadilloJava::Expected;

#include <iostream>
using std::cout;
using std::endl;

#include <utility>
using std::pair;

#include <armadillo>
using arma::ones;
using arma::zeros;

#include <InputClass.hpp>
using armadilloJava::InputClass;

#include <Input.hpp>
using armadilloJava::Input;

namespace armadilloJava {
	class ExpectedInPlaceGenColVec : public Expected {
    public:
		ExpectedInPlaceGenColVec() {
			cout << "Compute ExpectedInPlaceGenColVec(): " << endl;

			vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({
				InputClass::GenColVec
			});

			for (vector<pair<string, void*>> input : inputs) {
				_fileSuffix = "";

				int n = 0;
				for (pair<string, void*> value : input) {
					switch (n) {
						case 0:
							_fileSuffix += value.first;
							_genColVec = *static_cast<Col<double>*>(value.second);
							break;
					}
					++n;
				}

				cout << "Using input: " << _fileSuffix << endl;

				expectedColOnes();
				expectedColZeros();
				expectedColReset();
				expectedColClear();
				expectedColInPlaceIncrement();
				expectedColInPlaceDecrement();
			}

			cout << "done." << endl;
		}
	protected:
		Col<double> _genColVec;

		void expectedColOnes() {
			cout << "- Compute expectedColOnes() ... ";
			Col<double> expected = _genColVec;
			save<double>("Col.ones", (expected.ones()));
			cout << "done." << endl;
		}

		void expectedColZeros() {
			cout << "- Compute expectedColZeros() ... ";
			Col<double> expected = _genColVec;
			save<double>("Col.zeros", (expected.zeros()));
			cout << "done." << endl;
		}

		void expectedColReset() {
			cout << "- Compute expectedColReset() ... ";
			Col<double> expected = _genColVec;
			expected.reset();
			save<double>("Col.reset", expected);
			cout << "done." << endl;
		}

		void expectedColClear() {
			cout << "- Compute expectedColClear() ... ";
			Col<double> expected = _genColVec;
			expected.clear();
			save<double>("Col.clear", expected);
			cout << "done." << endl;
		}

		void expectedColInPlaceIncrement() {
			cout << "- Compute expectedColInPlaceIncrement() ... ";
			Col<double> expected = _genColVec;
			expected++;
			save<double>("Col.inPlaceIncrement", expected);
			cout << "done." << endl;
		}

		void expectedColInPlaceDecrement() {
			cout << "- Compute expectedColInPlaceDecrement() ... ";
			Col<double> expected = _genColVec;
			expected--;
			save<double>("Col.inPlaceDecrement", expected);
			cout << "done." << endl;
		}

	};
}

max_stars_repo_name: sebiniemann/ArmadilloJava

max_issues_repo_name: sebiniemann/ArmadilloJava

max_forks_repo_name: sebiniemann/ArmadilloJava


text:
#define BOOST_TEST_MODULE ByteQueueTest
#define BOOST_TEST_DYN_LINK

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

#include "CobraModelParser/ByteQueue.hpp"

BOOST_AUTO_TEST_SUITE(BYTEQUEUE_SUITE)

    BOOST_AUTO_TEST_CASE(CHECK_THROWS_IF_BYTES_ARE_NOT_MULTIPLE_OF_BLOCK_SIZE) {
        std::vector<CobraModelParser::Byte> corruptBytes(1);
        BOOST_CHECK_THROW(CobraModelParser::ByteQueue byteQueue(corruptBytes),
                CobraModelParser::ByteQueueConstructionException);
    }

    BOOST_AUTO_TEST_CASE(CHECK_BYTEQUEUE_POPS) {
        std::vector<CobraModelParser::Byte > bytes(256);
        CobraModelParser::ByteQueue bytequeue(bytes);
        bytequeue.popByteBlock();
        BOOST_CHECK(bytequeue.getRemainingBytes() == 248);
        bytequeue.popByteBlocks(31);
        BOOST_CHECK(bytequeue.getRemainingBytes() == 0);
    }

    BOOST_AUTO_TEST_CASE(CHECK_BYTEQUEUE_UNDEFINED_POPS) {
        std::vector<CobraModelParser::Byte> bytes(256);
        CobraModelParser::ByteQueue bytequeue(bytes);
        bytequeue.popUndefinedByteBlock();
        BOOST_CHECK(bytequeue.getRemainingBytes() == 248);
        bytequeue.popUndefinedByteBlocks(31);
        BOOST_CHECK(bytequeue.getRemainingBytes() == 0);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: qacwnfq/CobraModelParser

max_issues_repo_name: qacwnfq/CobraModelParser

max_forks_repo_name: qacwnfq/CobraModelParser


text:
#ifndef STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_RNG_HPP
#define STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_RNG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/prob/categorical_rng.hpp>
#include <boost/random/variate_generator.hpp>

namespace stan {
namespace math {

template <class RNG>
inline int ordered_logistic_rng(
    double eta, const Eigen::Matrix<double, Eigen::Dynamic, 1>& c, RNG& rng) {
  using boost::variate_generator;
  static const char* function = "ordered_logistic";
  check_finite(function, "Location parameter", eta);
  check_greater(function, "Size of cut points parameter", c.size(), 0);
  check_ordered(function, "Cut points parameter", c);
  check_finite(function, "Cut points parameter", c(c.size() - 1));
  check_finite(function, "Cut points parameter", c(0));

  Eigen::VectorXd cut(c.rows() + 1);
  cut(0) = 1 - inv_logit(eta - c(0));
  for (int j = 1; j < c.rows(); j++) {
    cut(j) = inv_logit(eta - c(j - 1)) - inv_logit(eta - c(j));
  }
  cut(c.rows()) = inv_logit(eta - c(c.rows() - 1));

  return categorical_rng(cut, rng);
}

}  // namespace math
}  // namespace stan
#endif


text:
/**
    @file
    block_ptr_test2.cpp

    @note
    Copyright (c) 2008 Phil Bouchard <pbouchard8@gmail.com>.

    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

    See http://www.boost.org/libs/smart_ptr/doc/index.html for documentation.
*/

#include <iostream>

#include <boost/smart_ptr/block_ptr.hpp>
#include <boost/current_function.hpp>

using namespace std;
using namespace boost;

struct A
{
    int i;
    block_ptr<A> p;

    A(block_proxy const & x, int i = 0) : i(i), p(x)
    {
        cout << BOOST_CURRENT_FUNCTION << ": " << i << endl;
    }

    ~A()
    {
        cout << BOOST_CURRENT_FUNCTION << ": " << i << endl;
    }
};

int main()
{

#if 1
    cout << "Cyclicism:" << endl;
    {
        proxy_ptr<A> x;
        block_ptr<A> p = block_ptr<A>(x, new block<A>(x, 7));
        block_ptr<A> q = block_ptr<A>(x, new block<A>(x, 8));
        block_ptr<A> r = block_ptr<A>(x, new block<A>(x, 9));

        //block_ptr<void> t = make_block<A>(10);
        block_ptr<int volatile> v = block_ptr<int volatile>(x, new block<int volatile>(11));

        p->p = p->p;
        q = r;
        v = block_ptr<int volatile>(x, new block<int volatile>(12));

        cout << "p->i = " << p->i << endl;
        cout << "q->i = " << q->i << endl;
        cout << "r->i = " << r->i << endl;
        cout << "* v = " << * v << endl;
    }
    cout << endl;

    // The following don't work with MSVC:
#if ! defined(_MSC_VER)
    cout << "Array access:" << endl;
    {
        proxy_ptr<char[9]> u = proxy_ptr<char[9]>(new block<char[9]>());

        u[4] = 'Z';

        cout << "u[4] = " << u[4] << endl;
    }
    cout << endl;
#endif
#endif

    cout << "Order of destruction:" << endl;
    {
        proxy_ptr<A> x;
        block_ptr<A> v = block_ptr<A>(x, new block<A>(x, 0));
        v->p = new block<A>(x, 1);
        v->p->p = new block<A>(x, 2);
        v->p->p->p = v->p;
    }
    cout << endl;
}


text:
/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ -- C Trampoline Support
 *
 * This file provides support for C trampolines, that is, converting C++
 * functionals to pairs of C function pointers and @c void*.  See
 * make_c_trampoline() for details.
 *
 * This file has no dependencies on any other part of IronBee or IronBee++.
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__C_TRAMPOLINE__
#define __IBPP__C_TRAMPOLINE__

#include <boost/any.hpp>
#include <boost/function.hpp>

#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition.hpp>

#ifndef IRONBEEPP_C_TRAMPOLINE_MAX_ARGS
/**
 * Maximum number of arguments of a function passed to make_c_trampoline().
 *
 * Can be defined before this file is included to change how many arguments
 * are supported.  The length of this file post-preprocessing is linear in the
 * value.
 *
 * Defaults to 10.
 */
#define IRONBEEPP_C_TRAMPOLINE_MAX_ARGS 10
#endif

namespace IronBee {

/// @cond Internal
namespace c_trampoline_implementation {

//! Generates member of boost::function that contains type of argument @a n.
#define CT_ARG(n) BOOST_PP_CAT(BOOST_PP_CAT(arg, n), _type)
//! Pulls type of argument @a n into current class.
#define CT_ARG_USING(z, n, unused) \
    typedef typename type_of_function::CT_ARG(n) BOOST_PP_CAT(type_of_arg, n);
//! Defines a partial specialization of make_c_trampoline_helper for n-1 args.
#define CT_TOP(n)                                                            \
    template <>                                                              \
    struct make_c_trampoline_helper<BOOST_PP_SUB(n, 1)>                      \
    {                                                                        \
        template <typename F>                                                \
        struct impl {                                                        \
            typedef boost::function<F> type_of_function;                     \
            typedef typename type_of_function::result_type type_of_result;   \
            BOOST_PP_REPEAT_FROM_TO(1, n, CT_ARG_USING, ~)                   \
            typedef type_of_result(*type_of_cptr)(                           \
                BOOST_PP_ENUM_SHIFTED_PARAMS(n, type_of_arg),                \
                void*                                                        \
            );                                                               \
            typedef std::pair<type_of_cptr, void*> type_of_pair;             \
                                                                             \
            static type_of_result trampoline(                                \
                BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(n, type_of_arg, a),      \
                void* cdata                                                  \
            )                                                                \
            {                                                                \
                return boost::any_cast<type_of_function>(                    \
                    *reinterpret_cast<boost::any*>(cdata)                    \
                )(                                                           \
                    BOOST_PP_ENUM_SHIFTED_PARAMS(n, a)                       \
                );                                                           \
            }                                                                \
        };                                                                   \
    };

/**
 * Helper struct for make_c_trampoline().
 *
 * When @a N is between 1 and IRONBEEPP_C_TRAMPOLINE_MAX_ARGS, this struct
 * will contain an internal template @c impl, templated on the function
 * signature.  The @c impl template will define:
 *
 * - @c type_of_cptr -- Function pointer type.
 * - @c type_of_pair -- Pair of @c type_of_cptr and @c void*.
 * - @c trampoline   -- Static trampoline function.
 *
 * See implementation of make_c_trampoline() for details on usage.
 *
 * @tparam N Arity of function to make trampoline for.
 */
template <int N>
struct make_c_trampoline_helper
{
    // Error case.
};

#ifndef DOXYGEN_SKIP
#include <boost/preprocessor/iteration/local.hpp>
#define BOOST_PP_LOCAL_MACRO(n) CT_TOP(BOOST_PP_ADD(n, 1))
#define BOOST_PP_LOCAL_LIMITS   (1, IRONBEEPP_C_TRAMPOLINE_MAX_ARGS)
#include BOOST_PP_LOCAL_ITERATE()

#undef CT_ARG
#undef CT_ARG_USING
#undef CT_TOP

// Special case for no args.
template<>
struct make_c_trampoline_helper<0>
{
    template <typename F>
    struct impl {
        typedef boost::function<F> type_of_function;
        typedef typename type_of_function::result_type type_of_result;
        typedef type_of_result(*type_of_cptr)(void*);
        typedef std::pair<type_of_cptr, void*> type_of_pair;

        static type_of_result trampoline(void* cdata)
        {
            return boost::any_cast<type_of_function>(
                *reinterpret_cast<boost::any*>(cdata)
            )();
        }
    };
};

#endif

} // c_trampoline_impl
/// @endcond

/**
 * Convert a C++ functional of signature @a F into a C trampoline.
 *
 * Example:
 *
 * @code
 * std::pair<int(*)(int, int, void*), void*> trampoline =
 *   IronBee::make_c_trampoline<int(int, int)>(
 *     std::plus<int>()
 *   );
 * int x = trampoline.first(1, 2, trampoline.second);
 * assert(x == 3);
 * IronBee::delete_c_trampoline(x.second);
 *
 * // C++11 example.
 * auto trampoline =
 *   IronBee::make_c_trampoline<int(int, int)>(
 *     [](int a, int b) {return a + b;}
 *   );
 * int x = trampoline.first(1, 2, trampoline.second);
 * assert(x == 3);
 * IronBee::delete_c_trampoline(x.second);
 * @endcode
 *
 * @tparam F Signature of @a f.  In many cases the compiler will not be able
 *           to deduce @a F from @a f and it will need to be explicitly
 *           specified.  Supports any number of arguments up to
 *           IRONBEEPP_C_TRAMPOLINE_MAX_ARGS which defaults to 10 but can be
 *           modified by defining before this file is included.
 * @param[in] f Function to convert.
 * @return pair of function pointer and @c void*.  Function pointer points to
 *         function with same return type as @a F initial arguments identical
 *         to @a F, plus a final void* argument.  When passed the @c void*
 *         portion to the final argument, will evaluate @a f with arguments
 *         and return result.  Caller is responsible for calling
 *         delete_c_trampoline() on @c void* portion to reclaim memory.
 */
template <typename F>
typename c_trampoline_implementation::make_c_trampoline_helper<
    boost::function<F>::arity
>::template impl<F>::type_of_pair
make_c_trampoline(boost::function<F> f)
{
    return std::make_pair(
        &c_trampoline_implementation::make_c_trampoline_helper<
            boost::function<F>::arity
        >::template impl<F>::trampoline,
        new boost::any(f)
    );
}

/**
 * Reclaim memory from a trampoline.
 *
 * @param[in] cdata @c void* portion of a trampoline returned from
 *                  make_c_trampoline().
 */
inline void delete_c_trampoline(void* cdata)
{
    delete reinterpret_cast<boost::any*>(cdata);
}

} // IronBee

#endif

max_issues_repo_name: ErikHendriks/ironbee

max_forks_repo_name: ErikHendriks/ironbee


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_no_rtti.cpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)

// note: this program tests the inter-operability of different
// extended typeinfo systems.  In this example, one class is
// identified using the default RTTI while the other uses a custom
// system based on the export key.
//
// As this program uses RTTI for one of the types, the test will fail
// on a system for which RTTI is not enabled or not existent.

#include <cstddef>
#include <fstream>
#include <iostream>

#include <boost/config.hpp>
#include <cstdio> // remove
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
    using ::remove;
}
#endif

#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/nvp.hpp>

#include "test_tools.hpp"

#include <boost/archive/polymorphic_oarchive.hpp>
#include <boost/archive/polymorphic_iarchive.hpp>

#define POLYMORPHIC_BASE_IMPORT
#include "polymorphic_base.hpp"

#include "polymorphic_derived1.hpp"

#define POLYMORPHIC_DERIVED2_IMPORT
#include "polymorphic_derived2.hpp"

// save derived polymorphic class
void save_derived(const char *testfile)
{
    test_ostream os(testfile, TEST_STREAM_FLAGS);
    test_oarchive oa_implementation(os, TEST_ARCHIVE_FLAGS);
    boost::archive::polymorphic_oarchive & oa_interface = oa_implementation;

    polymorphic_derived1 *rd1 = new polymorphic_derived1;
    polymorphic_derived2 *rd2 = new polymorphic_derived2;

    std::cout << "saving polymorphic_derived1 (no_rtti)\n";
    oa_interface << BOOST_SERIALIZATION_NVP(rd1);

    std::cout << "saving polymorphic_derived2\n";
    oa_interface << BOOST_SERIALIZATION_NVP(rd2);

    const polymorphic_base *rb1 =  rd1;
    polymorphic_base *rb2 = rd2;
    std::cout << "saving polymorphic_derived1 (no_rtti) through base (rtti)\n";
    oa_interface << BOOST_SERIALIZATION_NVP(rb1);
    std::cout << "saving polymorphic_derived2 through base\n";
    oa_interface << BOOST_SERIALIZATION_NVP(rb2);

    delete rd1;
    delete rd2;
}

void load_derived(const char *testfile)
{
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive  ia_implementation(is, TEST_ARCHIVE_FLAGS);
    boost::archive::polymorphic_iarchive & ia_interface = ia_implementation;

    polymorphic_derived1 *rd1 = NULL;
    polymorphic_derived2 *rd2 = NULL;

    std::cout << "loading polymorphic_derived1 (no_rtti)\n";
    ia_interface >> BOOST_SERIALIZATION_NVP(rd1);
    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance()
        ==
        * boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance().get_derived_extended_type_info(*rd1)
        ,
        "restored pointer d1 not of correct type"
    );

    std::cout << "loading polymorphic_derived2\n";
    ia_interface >> BOOST_SERIALIZATION_NVP(rd2);
    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance()
        ==
        * boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance().get_derived_extended_type_info(*rd2)
        ,
        "restored pointer d2 not of correct type"
    );
    polymorphic_base *rb1 = NULL;
    polymorphic_base *rb2 = NULL;

    // the above opereration registers the derived classes as a side
    // effect.  Hence, instances can now be correctly serialized through
    // a base class pointer.
    std::cout << "loading polymorphic_derived1 (no_rtti) through base (no_rtti)\n";
    ia_interface >> BOOST_SERIALIZATION_NVP(rb1);

    BOOST_CHECK_MESSAGE(
        rb1 == dynamic_cast<polymorphic_base *>(rd1),
        "serialized pointers not correctly restored"
    );

    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance()
        ==
        * boost::serialization::type_info_implementation<
            polymorphic_base
        >::type::get_const_instance().get_derived_extended_type_info(*rb1)
        ,
        "restored pointer b1 not of correct type"
    );
    std::cout << "loading polymorphic_derived2 through base (no_rtti)\n";
    ia_interface >> BOOST_SERIALIZATION_NVP(rb2);

    BOOST_CHECK_MESSAGE(
        rb2 ==  dynamic_cast<polymorphic_base *>(rd2),
        "serialized pointers not correctly restored"
    );
    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance()
        ==
        * boost::serialization::type_info_implementation<
            polymorphic_base
        >::type::get_const_instance().get_derived_extended_type_info(*rb2)
        ,
        "restored pointer b2 not of correct type"
    );
    delete rb1;
    delete rb2;
}

int
test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    save_derived(testfile);
    load_derived(testfile);
    std::remove(testfile);
    return EXIT_SUCCESS;
}

// EOF


text:
#ifndef NUMPY_HELPERS_HPP_INCLUDED
#define NUMPY_HELPERS_HPP_INCLUDED

#include "region_set.hpp"

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <optional>

namespace python = boost::python;
namespace numpy = boost::python::numpy;

grid::point numpyArrayToPoint(numpy::ndarray const &);

numpy::ndarray pointToNumpyArray(grid::point const &);

grid::region pointPairToRegion(numpy::ndarray const &, numpy::ndarray const &);

python::tuple regionToPointPair(grid::region const &);

#endif

max_stars_repo_name: formal-verification-research/VERAPAK

max_issues_repo_name: formal-verification-research/VERAPAK

max_forks_repo_name: formal-verification-research/VERAPAK


text:
//
//  TestSet.hpp
//
//  Created by Anton Leuski on 7/31/15.
//  Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
//  This file is part of Jerome.
//
//  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.
//

#ifndef __jerome_ir_training_TestSet_hpp__
#define __jerome_ir_training_TestSet_hpp__

#include <boost/range/adaptor/transformed.hpp>

#include <jerome/ir/evaluation.hpp>
#include <jerome/ir/rm/cl/link.hpp>

namespace jerome {
  namespace ir {
    namespace training {

			namespace detail {
				template <class Q, class D>
				using TestSetStorage = jerome::List<
					jerome::ir::evaluation::DataSetEntry<Q, D>
				>;
			}

      template <class Q, class D>
			struct TestSet : public ReferenceClassInterface<detail::TestSetStorage<Q,D>>{
        typedef detail::TestSetStorage<Q,D> entry_list_type;
				typedef ReferenceClassInterface<detail::TestSetStorage<Q,D>> parent_type;
				typedef typename parent_type::implementation_type implementation_type;
        typedef typename entry_list_type::value_type value_type;

        template <class QueryRange, class DocumentRange, class LinkRange>
        TestSet(const QueryRange& inQueries, const DocumentRange& inDocuments,
          const LinkRange& inLinks)
				: parent_type(std::make_shared<implementation_type>())
        {
          init(inQueries, inDocuments, inLinks);
        }

        template <class Data>
        TestSet(const Data& inData)
				: parent_type(std::make_shared<implementation_type>())
        {
          init(inData.questions(), inData.answers(),
            jerome::ir::rm::cl::makeIndexedLinkList(
              inData.questions(), inData.answers(), inData.links()));
        }

        template <class Data, class A>
        TestSet(const Data& inData, const A& inAnalyzer)
				: parent_type(std::make_shared<implementation_type>())
        {
          init(inData.questions() | boost::adaptors::transformed(inAnalyzer),
            inData.answers(),
            jerome::ir::rm::cl::makeIndexedLinkList(
              inData.questions(), inData.answers(), inData.links()));
        }

        const entry_list_type& entries() const
        {
          return this->implementation();
        }

			private:

				entry_list_type& entries()
				{
					return this->implementation();
				}

       template <class QueryRange, class DocumentRange, class LinkRange>
        void init(const QueryRange& inQueries, const DocumentRange& inDocuments,
                  const LinkRange& inLinks)
        {
          typedef typename jerome::ir::evaluation::DataSetEntry<
              typename QueryRange::value_type,
              typename DocumentRange::value_type> dse_type;
          typedef uint32_t index_type;

          entries().reserve(boost::size(inQueries));
          index_type i = 0;
          for (const auto& x : inQueries) {
            entries().push_back(dse_type(i++, x));
          }

          for (const auto& l : inLinks) {
            entries()[l.queryIndex].relevantSet().insert(
              inDocuments[l.documentIndex]);
          }
        }

      };
    }
  }
}

#endif // defined __jerome_ir_training_TestSet_hpp__

max_stars_repo_name: leuski-ict/jerome

max_issues_repo_name: leuski-ict/jerome

max_forks_repo_name: leuski-ict/jerome


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

#include <iostream>
#include "cfg.hpp"
#include "picapau/oracle/core/connect.hpp"
#include "picapau/oracle/core/for_each.hpp"
#include "picapau/oracle/core/query.hpp"
#include <boost/fusion/include/at_c.hpp>
#include <vector>

namespace db = picapau::oracle::core;
using namespace boost::fusion;

BOOST_AUTO_TEST_CASE(SuccessfulSelect)
{
    std::vector<int> v;
    db::connect(username, password, service)
        .bind([&](db::session s)
              { return db::exec_query<int>(std::move(s), "SELECT poco_cd_poco FROM poco"); })
        .map([&](db::query_result<int> r)
             {
                 db::for_each(r.rows, [&](boost::expected<vector1<int>, std::string> row)
                               {
                                   // std::cout << row.get_unexpected().value() << std::endl;
                                   BOOST_TEST(row.valid());
                                   v.push_back(at_c<0>(row.value()));
                               });
             });

    BOOST_TEST(v.size() == 2);
}

max_stars_repo_name: ricardocosme/picapau

max_issues_repo_name: ricardocosme/picapau

max_forks_repo_name: ricardocosme/picapau


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

#include "MemoryDirectParser.hpp"
#include "SymbolTable.hpp"

#include <memory>

struct MemoryDirectParserFixture
{
    std::unique_ptr<parsers::MemoryDirectParser> mem_dir_parser =
        std::make_unique<parsers::MemoryDirectParser>(
            std::make_shared<assembler::SymbolTable>());
    void test_equal(statement::operand_t expected, statement::operand_t actual)
    {
        BOOST_TEST(expected.addressing_mode == actual.addressing_mode);
        BOOST_TEST(expected.register_index == actual.register_index);
        BOOST_TEST(expected.operand == actual.operand); // element-wise compare
    }
};

BOOST_FIXTURE_TEST_SUITE(TestMemoryDirectParser, MemoryDirectParserFixture)

BOOST_AUTO_TEST_CASE(empty_string)
{
    auto res = mem_dir_parser->parse("");
    BOOST_TEST(res == nullptr);
}

BOOST_AUTO_TEST_CASE(gibberish_operand)
{
    auto res = mem_dir_parser->parse("%gibberish");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("%rx");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("%spx");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("%pcx");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("%pswx");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("gibberish*");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("rx*");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("spx*");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("pcx*");
    BOOST_TEST(res == nullptr);

    res = mem_dir_parser->parse("pswx*");
    BOOST_TEST(res == nullptr);
}

BOOST_AUTO_TEST_CASE(literals)
{
    statement::operand_t expected{ statement::MEMORY_DIRECT, 0, { 0, 0 } };
    auto res = mem_dir_parser->parse("0");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 5, 0 } };
    res      = mem_dir_parser->parse("5");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 022, 0 } };
    res      = mem_dir_parser->parse("022");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0xf, 0 } };
    res      = mem_dir_parser->parse("0xf");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    // Literals in memory direct parsing cannot be chars or negative integers!
    /*
    expected = { statement::MEMORY_DIRECT, 0, { 'a', 0 } };
    res = mem_dir_parser->parse("'a'");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0xff, 0xff } };
    res = mem_dir_parser->parse("-1");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);
    */

    res = mem_dir_parser->parse("*0");
    BOOST_TEST(res == nullptr);
}

BOOST_AUTO_TEST_CASE(literals_two_byte)
{
    statement::operand_t expected{ statement::MEMORY_DIRECT, 0, { 5, 2 } };
    auto res = mem_dir_parser->parse("517");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0x03, 0x08 } };
    res      = mem_dir_parser->parse("04003");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0x0f, 0x0f } };
    res      = mem_dir_parser->parse("0x0f0f");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);
}

BOOST_AUTO_TEST_CASE(literals_jump)
{
    statement::operand_t expected{ statement::MEMORY_DIRECT, 0, { 0, 0 } };
    auto res = mem_dir_parser->parse_jump_instruction("*0");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 5, 0 } };
    res      = mem_dir_parser->parse_jump_instruction("*5");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 022, 0 } };
    res      = mem_dir_parser->parse_jump_instruction("*022");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0xf, 0 } };
    res      = mem_dir_parser->parse_jump_instruction("*0xf");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    // Literals in memory direct parsing cannot be chars or negative integers!
    /*
    expected = { statement::MEMORY_DIRECT, 0, { 'a', 0 } };
    res = mem_dir_parser->parse_jump_instruction("*'a'");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0xff, 0xff } };
    res = mem_dir_parser->parse_jump_instruction("*-1");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);
    */

    res = mem_dir_parser->parse_jump_instruction("0");
    BOOST_TEST(res == nullptr);
}

BOOST_AUTO_TEST_CASE(literals_two_byte_jump)
{
    statement::operand_t expected{ statement::MEMORY_DIRECT, 0, { 5, 2 } };
    auto res = mem_dir_parser->parse_jump_instruction("*517");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0x03, 0x08 } };
    res      = mem_dir_parser->parse_jump_instruction("*04003");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);

    expected = { statement::MEMORY_DIRECT, 0, { 0x0f, 0x0f } };
    res      = mem_dir_parser->parse_jump_instruction("*0x0f0f");
    BOOST_TEST(res != nullptr);
    test_equal(expected, *res);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: bogdanbebic/AssemblerAndEmulator

max_issues_repo_name: bogdanbebic/AssemblerAndEmulator

max_forks_repo_name: bogdanbebic/AssemblerAndEmulator


text:
/*
  Copyright (c) <2014-2015>, <BenHJ>
  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 OWNER 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.
*/

/// Extracts a file or folder to a physical location

#pragma once

#include "knoxcrypt/CoreFS.hpp"
#include "utility/ContentFolderVisitor.hpp"
#include "utility/RecursiveFolderExtractor.hpp"
#include "utility/FolderExtractionVisitor.hpp"

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/iostreams/copy.hpp>

#include <fstream>
#include <sstream>

namespace knoxcrypt
{

    namespace utility
    {

        inline
        void extractToPhysical(knoxcrypt::CoreFS &theBfs,
                              std::string const &path,
                              std::string const &dst,
                              std::function<void(std::string)> callback)
        {
            std::string dstPath(dst);

            // make sure destination parent has a trailing slash on the end
            if(*dstPath.rbegin() != '/') {
                dstPath.append("/");
            }

            // remove trailing slash from path
            std::string srcPath(path);
            if(*srcPath.rbegin() == '/') {
                srcPath = std::string(path.begin(), path.end() - 1);
            }

            // append filename on to dst path
            boost::filesystem::path p(srcPath);
            dstPath.append(p.filename().string());

            // create source and sink
            if(theBfs.fileExists(srcPath)) {
                std::stringstream ss;
                ss << "Extracting file "<<dstPath<<"...";
                callback(dstPath);
                knoxcrypt::FileDevice device = theBfs.openFile(srcPath, knoxcrypt::OpenDisposition::buildReadOnlyDisposition());
                device.seek(0, std::ios_base::beg);
                std::ofstream out(dstPath.c_str(), std::ios_base::binary);
                boost::iostreams::copy(device, out);
            } else if(theBfs.folderExists(srcPath)) {
                boost::filesystem::create_directory(dstPath);
                FolderExtractionVisitor visitor(theBfs, srcPath, dstPath, callback);
                recursiveExtract(visitor, theBfs, srcPath);
            }
        }
    }
}

max_stars_repo_name: benhj/KnoxCrypt

max_issues_repo_name: benhj/KnoxCrypt

max_forks_repo_name: benhj/KnoxCrypt


text:
/**
 *  $Id: Rename.cxx 168812 2017-05-10 03:15:34Z olivas $
 *
 *  Copyright (C) 2007
 *  Troy D. Straszheim  <troy@icecube.umd.edu>
 *  and the IceCube Collaboration <http://www.icecube.wisc.edu>
 *
 *  This file is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
#include <boost/regex.hpp>

#include <icetray/I3Tray.h>
#include <icetray/I3TrayInfo.h>
#include <icetray/I3TrayInfoService.h>
#include <icetray/Utility.h>
#include <icetray/modules/Rename.h>

using namespace std;

I3_MODULE(Rename);

Rename::Rename(const I3Context& ctx) :
  I3ConditionalModule(ctx)
{
  AddParameter("Keys",
	       "Rename objects in frame by name: [From1, To1, From2, To2 ... FromN, ToN]",
	       rename_keys_);
}

void Rename::Configure()
{
  GetParameter("Keys", rename_keys_);
  if (rename_keys_.size() % 2)
    log_fatal("Rename takes an even number of Keys:\n"
	      "From_1, To_2, From_2, To_2, ... From_N, To_N");
}

void Rename::Process()
{
  I3FramePtr frame = PopFrame();
  do_rename(frame);
  PushFrame(frame);
}

void Rename::Finish()
{
}

void Rename::do_rename(I3FramePtr frame)
{
  for (vector<string>::const_iterator iter = rename_keys_.begin();
       iter != rename_keys_.end();
       iter++, iter++)
    {
      const std::string& from = *iter;
      const std::string& to = *(iter+1);

      if (!frame->Has(from))
	continue;
      if (frame->Has(to))
	log_fatal("Can't rename frame item '%s' to '%s' since the destination is full",
		  from.c_str(),  to.c_str());
      frame->Rename(from, to);
    }
}

ext: cxx


text:
/*
    Copyright (c) 2016-2021 Xavier Leclercq
    Released under the MIT License
    See https://github.com/ishiko-cpp/tests/blob/main/LICENSE.txt
*/

#include "ConsoleApplicationTestTests.h"
#include <boost/filesystem/operations.hpp>

using namespace Ishiko::Tests;
using namespace boost::filesystem;

ConsoleApplicationTestTests::ConsoleApplicationTestTests(const TestNumber& number, const TestEnvironment& environment)
    : TestSequence(number, "ConsoleApplicationTest tests", environment)
{
    append<HeapAllocationErrorsTest>("Creation test 1", CreationTest1);
    append<HeapAllocationErrorsTest>("run success test 1", RunSuccessTest1);
    append<HeapAllocationErrorsTest>("run success test 2", RunSuccessTest2);
    append<HeapAllocationErrorsTest>("run failure test 1", RunFailureTest1);
    append<HeapAllocationErrorsTest>("run success test 3", RunSuccessTest3);
    append<HeapAllocationErrorsTest>("run failure test 2", RunFailureTest2);
}

void ConsoleApplicationTestTests::CreationTest1(Test& test)
{
#ifdef __linux__
    path executablePath(test.environment().getTestDataDirectory() / "bin/WriteFileTestHelper");
#else
    path executablePath(test.environment().getTestDataDirectory() / "bin/WriteFileTestHelper.exe");
#endif

    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestCreationTest1",
        executablePath.string().c_str(), 0);

    ISHTF_PASS();
}

void ConsoleApplicationTestTests::RunSuccessTest1(Test& test)
{
#ifdef __linux__
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper");
#else
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper.exe");
#endif

    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestRunSuccessTest1",
        executablePath.string(), 0);
    applicationTest.run();

    ISHTF_FAIL_IF_NOT(applicationTest.passed());
    ISHTF_PASS();
}

void ConsoleApplicationTestTests::RunSuccessTest2(Test& test)
{
#ifdef __linux__
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper");
#else
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper.exe");
#endif

    std::string commandLine = executablePath.string() + " 3";
    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestRunSuccessTest2", commandLine, 3);
    applicationTest.run();

    ISHTF_FAIL_IF_NOT(applicationTest.passed());
    ISHTF_PASS();
}

void ConsoleApplicationTestTests::RunFailureTest1(Test& test)
{
#ifdef __linux__
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper");
#else
    path executablePath(test.environment().getTestDataDirectory() / "bin/ExitCodeTestHelper.exe");
#endif

    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestRunFailureTest1",
        executablePath.string(), 3);
    applicationTest.run();

    ISHTF_FAIL_IF(applicationTest.passed());
    ISHTF_PASS();
}

void ConsoleApplicationTestTests::RunSuccessTest3(Test& test)
{
    create_directories(test.environment().getTestOutputDirectory() / "ConsoleApplicationTestTests");

#ifdef __linux__
    path executablePath(test.environment().getTestDataDirectory() / "bin/StandardOutputTestHelper");
#else
    path executablePath(test.environment().getTestDataDirectory() / "bin/StandardOutputTestHelper.exe");
#endif
    path outputPath(test.environment().getTestOutputDirectory()
        / "ConsoleApplicationTestTests/ConsoleApplicationTestRunSuccessTest3.txt");
    remove(outputPath);
    path referencePath(test.environment().getReferenceDataDirectory()
        / "ConsoleApplicationTestTests/ConsoleApplicationTestRunSuccessTest3.txt");

    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestRunSuccessTest3",
        executablePath.string().c_str(), 0);
    applicationTest.setStandardOutputFilePath(outputPath);
    applicationTest.setStandardOutputReferenceFilePath(referencePath);
    applicationTest.run();

    ISHTF_FAIL_IF_NOT(applicationTest.passed());
    ISHTF_PASS();
}

void ConsoleApplicationTestTests::RunFailureTest2(Test& test)
{
    path executablePath(test.environment().getTestDataDirectory() / "bin/StandardOutputTestHelper.exe");
    path outputPath(test.environment().getTestOutputDirectory()
        / "ConsoleApplicationTestTests/ConsoleApplicationTestRunFailureTest2.txt");
    remove(outputPath);
    path referencePath(test.environment().getReferenceDataDirectory()
        / "ConsoleApplicationTestTests/ConsoleApplicationTestRunFailureTest2.txt");

    ConsoleApplicationTest applicationTest(TestNumber(), "ConsoleApplicationTestRunFailureTest2",
        executablePath.string().c_str(), 0);
    applicationTest.setStandardOutputFilePath(outputPath);
    applicationTest.setStandardOutputReferenceFilePath(referencePath);
    applicationTest.run();

    ISHTF_FAIL_IF(applicationTest.passed());
    ISHTF_PASS();
}

max_stars_repo_name: codesmithyide/ishiko-cpp-tests

max_issues_repo_name: codesmithyide/ishiko-cpp-tests

max_forks_repo_name: codesmithyide/ishiko-cpp-tests


text:
#define BOOST_TEST_MODULE ParserTest

#include <boost/test/unit_test.hpp>
#include <sdm/common.hpp>
#include <sdm/parser/parser.hpp>
#include <sdm/worlds.hpp>

BOOST_AUTO_TEST_CASE(dpomdpParser)
{
    auto dpomdp_world = sdm::parser::parse_file("../data/world/dpomdp/mabc.dpomdp");
    auto dpomdp_2 = dpomdp_world;

    BOOST_CHECK_EQUAL(dpomdp_world->getNumAgents(), 2);
    BOOST_CHECK_EQUAL(dpomdp_world->getStateSpace()->getNumItems(), 4);
    BOOST_CHECK_EQUAL(dpomdp_world->getActionSpace()->getNumItems(), 4);
    BOOST_CHECK_EQUAL(dpomdp_world->getObsSpace()->getNumItems(), 4);
}

BOOST_AUTO_TEST_CASE(zsposgParser)
{
    // sdm::ZSPOSG zs_posg1 = sdm::parser::parse_file("../data/world/zsposg/fake_prisoners.zsposg");

    // BOOST_CHECK_EQUAL(zs_posg1.getNumAgents(), 2);
    // BOOST_CHECK_EQUAL(zs_posg1.getNumStates(), 1);
    // BOOST_CHECK_EQUAL(zs_posg1.getNumJActions(), 4);
    // BOOST_CHECK_EQUAL(zs_posg1.getNumJObservations(), 1);
}

max_stars_repo_name: SDMStudio/sdms

max_issues_repo_name: SDMStudio/sdms

max_forks_repo_name: SDMStudio/sdms


text:
// (C) Copyright Jonathan Turkanis 2004-5.
// 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.)

// See http://www.boost.org/libs/iostreams for documentation.

#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/test.hpp>
#include <boost/iostreams/invert.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "detail/filters.hpp"
#include "detail/temp_file.hpp"

using namespace boost::iostreams;
using namespace boost::iostreams::test;
using boost::unit_test::test_suite;

void inverse_test()
{

    test_file       test;
    lowercase_file  lower;
    uppercase_file  upper;

    BOOST_CHECK( test_input_filter(
                    invert(tolower_filter()),
                    file_source(test.name(), in_mode),
                    file_source(lower.name(), in_mode) ) );

    BOOST_CHECK( test_output_filter(
                    invert(toupper_filter()),
                    file_source(test.name(), in_mode),
                    file_source(upper.name(), in_mode) ) );
}

test_suite* init_unit_test_suite(int, char* [])
{
    test_suite* test = BOOST_TEST_SUITE("reverse test");
    test->add(BOOST_TEST_CASE(&inverse_test));
    return test;
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
#include <iostream>
#include <vector>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int roll_die( boost::random::mt19937 &gen, int begin, int end) {
    boost::random::uniform_int_distribution<> dist(begin, end);
    return dist(gen);
}

constexpr int iter = 100000;

std::vector<int> data(iter);

int main(int argc, char** argv){
	//once per process
	boost::random::mt19937 gen0;
	int random_seed1 = roll_die(gen0, 0,100000); // should be generated for every thread

	// per thread
	boost::random::mt19937 gen(random_seed1);//random_seed1 to have different starting conditions in diff threads

	std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();

	for(int i = 0; i < iter; ++i){
		data[i] = roll_die(gen,0, 20);
	}
	std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
	 for(int i = 0; i < iter; ++i){
			 std::cout << data[i]<< std::endl;
		 	}
	int total =  std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
	 std::cout << "Loop took " <<total << " ms"<< std::endl;
	 std::cout << "Iter took " << ((double)total  / double(iter)) * 1000<< " ns"<< std::endl;

 return 0;
}
/*
 * Iter took 14.63 ns
 */


text:
#ifndef TEST_UNIT_MATH_PRIM_MAT_VECTORIZE_EXPECT_MATCH_RETURN_T_HPP
#define TEST_UNIT_MATH_PRIM_MAT_VECTORIZE_EXPECT_MATCH_RETURN_T_HPP

#include <stan/math/prim/mat/vectorize/apply_scalar_unary.hpp>
#include <boost/type_traits/is_same.hpp>
#include <gtest/gtest.h>

namespace stan {

namespace test {

/**
 * Tests that the return type of a vectorized function with a
 * specified argument type is a specified type.
 *
 * @tparam F Functor defining function to test.
 * @tparam T_result_expected  Expected result type.
 * @tparam T_arg Argument type.
 */
template <typename F, typename T_result_expected, typename T_arg>
void expect_match_return_t() {
  using stan::math::apply_scalar_unary;
  typedef typename apply_scalar_unary<F, T_arg>::return_t result_t;
  EXPECT_TRUE((boost::is_same<T_result_expected, result_t>::value));
}

}  // namespace test
}  // namespace stan
#endif

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @author Mathias Soeken
 */

#include <fstream>

#include <boost/format.hpp>

#include <core/utils/program_options.hpp>
#include <core/utils/range_utils.hpp>

#include <classical/approximate/bdd_level_approximation.hpp>
#include <classical/approximate/error_metrics.hpp>
#include <classical/dd/bdd.hpp>
#include <classical/dd/bdd_to_truth_table.hpp>
#include <classical/dd/size.hpp>
#include <classical/dd/visit_solutions.hpp>
#include <classical/io/read_into_bdd.hpp>
#include <classical/io/write_from_bdd.hpp>

#include <kitty/kitty.hpp>

using namespace cirkit;

int main( int argc, char ** argv )
{
  using boost::format;
  using boost::str;
  using boost::program_options::value;

  std::string filename, outname;
  auto mode           = 0u;
  auto level          = 0u;
  auto maximum_method = 0u;

  program_options opts;
  opts.add_options()
    ( "filename",       value( &filename ),                    "Filename (either *.aag or *.pla file)" )
    ( "outname",        value( &outname ),                     "Output filename (eigher *.aag or *.pla file)" )
    ( "mode",           value_with_default( &mode ),           "Mode (0: round-down, 1: round-up, 2: round-closest, 3: co-factor 0, 4: co-factor 1, 5: copy)" )
    ( "level",          value_with_default( &level ),          "Round or co-factor at level (round is inclusive)" )
    ( "maximum_method", value_with_default( &maximum_method ), "Maximum method (0: shift, 1: chi)" )
    ( "print,p",                                               "Print implicants of both functions" )
    ( "truthtable,t",                                          "Print truth table of both functions" )
    ( "verbose,v",                                             "Be verbose" )
    ;
  opts.parse( argc, argv );

  if ( !opts.good() || !opts.is_set( "filename" ) || mode > 5u )
  {
    std::cout << opts << std::endl;
    return 1;
  }

  /* read BDD */
  auto rib_settings = std::make_shared<properties>();
  rib_settings->set( "verbose", opts.is_set( "verbose" ) );
  auto rib_statistics = std::make_shared<properties>();

  bdd_manager_ptr  manager;
  std::vector<bdd> fs;
  std::tie( manager, fs ) = read_into_bdd( filename, rib_settings, rib_statistics );

  if ( opts.is_set( "verbose" ) )
  {
    std::cout << "[i] num_inputs:  " << manager->num_vars() << std::endl
              << "[i] num_outputs: " << fs.size() << std::endl;
  }
  std::cout << format( "[i] run-time (read): %.2f secs" ) % rib_statistics->get<double>( "runtime" ) << std::endl;

  if ( level > manager->num_vars() )
  {
    std::cerr << "[e] invalid level (must be less or equal to " << manager->num_vars() << ")" << std::endl;
    return 1;
  }

  auto settings = std::make_shared<properties>();
  auto statistics = std::make_shared<properties>();

  //if ( opts.is_set( "verbose" ) ) { std::cout << "[i] start approximation" << std::endl; }
  auto fshat = ( mode == 5u ) ? fs : bdd_level_approximation( fs, (bdd_level_approximation_mode)mode, level, settings, statistics );
  //if ( opts.is_set( "verbose" ) ) { std::cout << "[i] stop approximation" << std::endl; }

  /* print? */
  if ( opts.is_set( "print" ) )
  {
    std::cout << "[i] Original function:" << std::endl;
    print_paths( fs );
    std::cout << "[i] Approximated function:" << std::endl;
    print_paths( fshat );
  }

  /* truth table? */
  auto metric_settings = std::make_shared<properties>();
  if ( opts.is_set( "truthtable" ) )
  {
    std::cout << "[i] Original function:" << std::endl;
    for ( const auto& f : fs )
    {
      kitty::print_binary( bdd_to_truth_table( f ) );
      std::cout << std::endl;
    }
    std::cout << "[i] Approximated function:" << std::endl;
    for ( const auto& fhat : fshat )
    {
      kitty::print_binary( bdd_to_truth_table( fhat ) );
      std::cout << std::endl;
    }

    metric_settings->set( "print_truthtables", true );
  }

  /* write file? */
  if ( !outname.empty() )
  {
    rib_statistics->set( "complement_optimization", true );
    write_from_bdd( fshat, outname, rib_statistics ); /* statistics from rib contain input and output labels */
  }

  /* statistics */
  auto er_settings   = std::make_shared<properties>();
  auto er_statistics = std::make_shared<properties>();
  auto wc_statistics = std::make_shared<properties>();
  auto ac_statistics = std::make_shared<properties>();

  auto er       = error_rate( fs, fshat, er_settings, er_statistics );
  auto size     = dd_size( fs );
  auto size_hat = dd_size( fshat );

  metric_settings->set( "maximum_method", static_cast<worst_case_maximum_method>( maximum_method ) );

  if ( mode < 5u )
  {
    std::cout << format( "[i] run-time:        %.2f secs" ) % statistics->get<double>( "runtime" ) << std::endl;
  }
  std::cout << "[i] old size:        " << size << std::endl;
  std::cout << format( "[i] new size:        %d (%.2f %%)" ) % size_hat % ( ( size - size_hat ) * 100.0 / size ) << std::endl;
  std::cout << format( "[i] error rate:      %d (%.2f %%)" ) % er % ( (double)er / (1ull << manager->num_vars()) * 100.0 ) << std::endl;
  std::cout << "[i] worst case:      " << worst_case( fs, fshat, metric_settings, wc_statistics ) << std::endl;
  std::cout << format( "[i] average case:    %.2f" ) % average_case( fs, fshat, metric_settings, ac_statistics ) << std::endl;

  std::cout << format( "[i] run-time (er):   %.2f" ) % er_statistics->get<double>( "runtime" ) << std::endl;
  std::cout << format( "[i] run-time (wc):   %.2f" ) % wc_statistics->get<double>( "runtime" ) << std::endl;
  std::cout << format( "[i] run-time (ac):   %.2f" ) % ac_statistics->get<double>( "runtime" ) << std::endl;

  return 0;
}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit