text:
// PhotoMultiplier Id Map Test Suite - PhotoMultiplierIdMapTestSuite.cpp
#ifndef PHOTOMULTIPLIER_ID_MAP_TESTSUITE_H
#define PHOTOMULTIPLIER_ID_MAP_TESTSUITE_H

#define SHOW_DEBUG 0

#define BOOST_TEST_MODULE PhotoMultiplierIdMapTestSuite
#include <boost/test/included/unit_test.hpp>
#include "../HeaderFiles/PhotoMultiplierIdMap.h"
#include "SerializableMapBT.hpp"

namespace DB
{

namespace TEST
{

class PhotoMultiplierIdMapTestSuite : public SerializableMapBT<DATA::PhotoMultiplierIdMap >
{
public:
  PhotoMultiplierIdMapTestSuite(void);
  virtual ~PhotoMultiplierIdMapTestSuite(void);
};

PhotoMultiplierIdMapTestSuite::PhotoMultiplierIdMapTestSuite() : SerializableMapBT<DATA::PhotoMultiplierIdMap >()
{
}

PhotoMultiplierIdMapTestSuite::~PhotoMultiplierIdMapTestSuite()
{
}

// Tests
BOOST_AUTO_TEST_SUITE(PhotoMultiplierIdMapTS)

BOOST_FIXTURE_TEST_CASE(fillPhotoMultiplierIdMapCheckSizeTest, PhotoMultiplierIdMapTestSuite)
{
  #if SHOW_DEBUG
    std::cout << "TEST = " << boost::unit_test::framework::current_test_case().p_name << std::endl;
  #endif

  int l_runId = getFirstRunIdIfExist();

  if(l_runId != -1)
  {
    size_t l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();
    BOOST_REQUIRE( l_sizeOfPhotoMultiplierIdMap == 0 );

    m_map->fillMap(l_runId);

    l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();

    std::string l_run_id = boost::lexical_cast<std::string>(l_runId);
    std::string l_sqlQuerry = "SELECT * FROM photomultiplierIdBasedOnTOMBInputIdFunction(" + l_run_id + ");";
    pqxx::result l_runDbResults = m_dbHandlerInstance.querry(l_sqlQuerry);

    size_t l_sizeResultQuerry = l_runDbResults.size();

  #if SHOW_DEBUG
      size_t l_sizeOfRunTable = getSizeOfRunTable();
      std::cout << "l_sizeOfRunTable = " << l_sizeOfRunTable << " l_sizeResultQuerry = " << l_sizeResultQuerry << " l_sizeOfPhotoMultiplierIdMap = " << l_sizeOfPhotoMultiplierIdMap << std::endl;
      m_map->showMap();
  #endif
      BOOST_REQUIRE( l_sizeResultQuerry == l_sizeOfPhotoMultiplierIdMap );
  }
}

BOOST_FIXTURE_TEST_CASE(photoMultiplierIdForTOMBInputIdTest, PhotoMultiplierIdMapTestSuite)
{
#if SHOW_DEBUG
  std::cout << "TEST = " << boost::unit_test::framework::current_test_case().p_name << std::endl;
#endif

  int l_runId = getFirstRunIdIfExist();

  if(l_runId != -1)
  {
    std::string l_run_id = boost::lexical_cast<std::string>(l_runId);
    std::string l_sqlQuerry = "SELECT * FROM photomultiplierIdBasedOnTOMBInputIdFunction(" + l_run_id + ");";
    pqxx::result l_runDbResults = m_dbHandlerInstance.querry(l_sqlQuerry);

    size_t l_sizeResultQuerry = l_runDbResults.size();

  #if SHOW_DEBUG
    std::cout << "l_runDbResults.size() = " << l_sizeResultQuerry << std::endl;
  #endif

    if(l_sizeResultQuerry)
    {
      m_map->fillMap(l_runId);

      for(pqxx::result::const_iterator row = l_runDbResults.begin(); row != l_runDbResults.end(); ++row)
      {
        DATA::PHOTOMULTIPLIER_ID_MAP_KEY_TYPE l_tombinput_id = row["tombinput_id"].as<DATA::PHOTOMULTIPLIER_ID_MAP_KEY_TYPE >();
        DATA::PHOTOMULTIPLIER_ID_MAP_VALUE_TYPE l_photomultiplier_id = row["photomultiplier_id"].as<DATA::PHOTOMULTIPLIER_ID_MAP_VALUE_TYPE >();

        DATA::PHOTOMULTIPLIER_ID_MAP_VALUE_TYPE l_photomultiplierIdFromTRBThresholdMap = *m_map->valueFromMap(l_tombinput_id);

      #if SHOW_DEBUG
        std::cout << "l_tombinput_id = " << l_tombinput_id << " l_photomultiplier_id = " << l_photomultiplier_id << std::endl;
        std::cout << "l_photomultiplierIdFromTRBThresholdMap = " << l_photomultiplierIdFromTRBThresholdMap << std::endl;
      #endif
        BOOST_CHECK(l_photomultiplierIdFromTRBThresholdMap == l_photomultiplier_id);
      }
    }
  }
}

BOOST_FIXTURE_TEST_CASE(saveToFileAndRemoveFileWithPhotoMultiplierIdMapTest, PhotoMultiplierIdMapTestSuite)
{
  #if SHOW_DEBUG
    std::cout << "TEST = " << boost::unit_test::framework::current_test_case().p_name << std::endl;
  #endif

  int l_runId = getFirstRunIdIfExist();

  if(l_runId != -1)
  {
    size_t l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();
    BOOST_REQUIRE( l_sizeOfPhotoMultiplierIdMap == 0 );

    m_map->fillMap(l_runId);
    std::string l_fileNameToSavePhotoMultiplierIdMap = "PhotoMultiplierIdMap.txt";
    m_map->saveMapToFile(l_fileNameToSavePhotoMultiplierIdMap);

    bool l_removeFileWithPhotoMultiplierIdMapSuccessfuly = m_map->removeFileWithMap();
    BOOST_CHECK(l_removeFileWithPhotoMultiplierIdMapSuccessfuly == false);
  }
}

BOOST_FIXTURE_TEST_CASE(clearPhotoMultiplierIdMapTest, PhotoMultiplierIdMapTestSuite)
{
  #if SHOW_DEBUG
    std::cout << "TEST = " << boost::unit_test::framework::current_test_case().p_name << std::endl;
  #endif

  int l_runId = getFirstRunIdIfExist();

  if(l_runId != -1)
  {
    size_t l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();
    BOOST_REQUIRE( l_sizeOfPhotoMultiplierIdMap == 0 );

    m_map->fillMap(l_runId);

    l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();

    if(l_sizeOfPhotoMultiplierIdMap > 0)
    {
  #if SHOW_DEBUG
      std::cout << "l_sizeOfPhotoMultiplierIdMap = " << l_sizeOfPhotoMultiplierIdMap << std::endl;
  #endif
      m_map->clearMap();
      BOOST_REQUIRE( m_map->sizeOfMap() == 0 );
    }
  }
}

BOOST_FIXTURE_TEST_CASE(checkIfExistFirstElementAndEraseElementFromPhotoMultiplierIdMapTest, PhotoMultiplierIdMapTestSuite)
{
  #if SHOW_DEBUG
    std::cout << "TEST = " << boost::unit_test::framework::current_test_case().p_name << std::endl;
  #endif

  int l_runId = getFirstRunIdIfExist();

  if(l_runId != -1)
  {
    size_t l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();
    BOOST_REQUIRE( l_sizeOfPhotoMultiplierIdMap == 0 );

    m_map->fillMap(l_runId);

    if(m_map->firstElement() != boost::none)
    {
      l_sizeOfPhotoMultiplierIdMap = m_map->sizeOfMap();
      std::pair<DATA::PHOTOMULTIPLIER_ID_MAP_KEY_TYPE, DATA::PHOTOMULTIPLIER_ID_MAP_VALUE_TYPE > l_firstElementFromPhotoMultiplierIdMap = *m_map->firstElement();
      int l_firstKeyFromPhotoMultiplierIdMap = l_firstElementFromPhotoMultiplierIdMap.first;

  #if SHOW_DEBUG
      m_map->showMap();
      std::cout << "l_firstKeyFromPhotoMultiplierIdMap = " << l_firstKeyFromPhotoMultiplierIdMap << std::endl;
  #endif
      m_map->eraseElementFromMap(l_firstKeyFromPhotoMultiplierIdMap);
      BOOST_CHECK( m_map->sizeOfMap() == (l_sizeOfPhotoMultiplierIdMap - 1) );
    }
  }
}

BOOST_AUTO_TEST_SUITE_END()

} // namespace TEST

} // namespace DB

#endif // PHOTOMULTIPLIER_ID_MAP_TESTSUITE_H

max_stars_repo_name: kamilrakoczy/j-pet-framework

max_issues_repo_name: kamilrakoczy/j-pet-framework

max_forks_repo_name: kamilrakoczy/j-pet-framework


text:
#include <iostream>
#include <set>
#include <exception>
#include <fstream>
#include <utility>

#include <iomanip>
#include <cctype>

#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>

namespace pod = boost::program_options::detail;

#include "utilities/Properties.hpp"

namespace ice_engine
{
namespace utilities
{

Properties::Properties(fs::IFile* file)
{
	//parameters
	std::set<std::string> options;
	options.insert("*");

	std::istream& configInputStream = file->getInputStream();

	for (pod::config_file_iterator i(configInputStream, options), e ; i != e; ++i)
	{
		parameters_[i->string_key] = i->value[0];
	}
}

Properties::Properties(const std::string& properties)
{
	//parameters
	std::set<std::string> options;
	options.insert("*");

	std::istringstream configInputStream = std::istringstream(properties);

	for (pod::config_file_iterator i(configInputStream, options), e ; i != e; ++i)
	{
		parameters_[i->string_key] = i->value[0];
	}
}

}
}

ext: cpp


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

#include <switch_repeat_expr.h>

#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_switch_repeat_expr) {
    std::ifstream ifs("src/switch_tlv.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    switch_repeat_expr_t* r = new switch_repeat_expr_t(&ks);

    BOOST_CHECK_EQUAL(r->code(), 0x11);
    BOOST_CHECK_EQUAL(r->size(), 9);
    BOOST_CHECK_EQUAL((static_cast<switch_repeat_expr_t::one_t*>(r->body()->at(0)))->first(), std::string("Stuff\0Me\0", 9));

    delete r;
}


text:
//
//  Copyright (C) 2009-2012 Artyom Beilis (Tonkikh)
//
//  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 "test.h"

#include <booster/smart_ptr/sp_counted_base.h>
#include <iostream>

class counted : public booster::detail::sp_counted_base {
public:
	virtual void dispose() {}
	virtual void *get_deleter(booster::detail::sp_typeinfo const &) { return 0; }
	counted() {
		counter++;
	}
	virtual ~counted() {
		counter--;
	}
	static int counter;
};

int counted::counter;

int main()
{
	try {
		booster::detail::sp_counted_base *sp=new counted();
		TEST(counted::counter==1);
		TEST(sp->use_count()==1);
		sp->add_ref_copy();
		TEST(sp->use_count()==2);
		sp->add_ref_copy();
		TEST(sp->use_count()==3);
		sp->release();
		TEST(sp->use_count()==2);
		sp->weak_add_ref();
		TEST(sp->use_count()==2);
		TEST(sp->add_ref_lock()==true);
		TEST(sp->use_count()==3);
		sp->release();
		sp->release();
		TEST(sp->use_count()==1);
		sp->release();
		TEST(counted::counter==1);
		TEST(sp->use_count()==0);
		TEST(counted::counter==1);
		TEST(sp->add_ref_lock()==false);
		TEST(counted::counter==1);
		sp->weak_release();
		TEST(counted::counter==0);
		sp=new counted();
		TEST(counted::counter==1);
		sp->release();
		TEST(counted::counter==0);
		sp=new counted();
		TEST(counted::counter==1);
		sp->weak_add_ref();
		TEST(counted::counter==1);
		sp->weak_release();
		TEST(counted::counter==1);
		sp->release();
		TEST(counted::counter==0);
		sp=0;
	}
	catch(std::exception const &e) {
		std::cerr << "Fail" << e.what() << std::endl;
		return 1;
	}
	std::cout << "Ok" << std::endl;
	return 0;
}

max_stars_repo_name: ci-fuzz/cppcms

max_issues_repo_name: ci-fuzz/cppcms

max_forks_repo_name: ci-fuzz/cppcms


text:
#ifndef PICHI_API_SERVER_HPP
#define PICHI_API_SERVER_HPP

#include <array>
#include <boost/asio/io_context.hpp>
#include <boost/asio/strand.hpp>
#include <pichi/api/egress_manager.hpp>
#include <pichi/api/ingress_manager.hpp>
#include <pichi/api/rest.hpp>
#include <pichi/api/router.hpp>
#include <pichi/buffer.hpp>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>

namespace pichi::api {

class Server {
private:
  using Acceptor = boost::asio::basic_socket_acceptor<boost::asio::ip::tcp>;
  using ResolveResult = boost::asio::ip::tcp::resolver::results_type;

  template <typename Yield> void listen(Acceptor&, std::string_view, IngressVO const&, Yield);
  template <typename ExceptionPtr> void removeIngress(ExceptionPtr, std::string_view);
  EgressVO const& route(net::Endpoint const&, std::string_view ingress, AdapterType,
                        ResolveResult const&);
  template <typename Yield> bool isDuplicated(ConstBuffer<uint8_t>, Yield);

public:
  Server(Server const&) = delete;
  Server(Server&&) = delete;
  Server& operator=(Server const&) = delete;
  Server& operator=(Server&&) = delete;

  Server(boost::asio::io_context&, char const*);
  ~Server() = default;

  void listen(std::string_view, uint16_t);
  void startIngress(Acceptor&, std::string_view, IngressVO const&);

private:
  boost::asio::io_context::strand strand_;
  std::unordered_set<std::string> ivs_;
  Router router_;
  EgressManager egresses_;
  IngressManager ingresses_;
  Rest rest_;
};

} // namespace pichi::api

#endif // PICHI_API_SERVER_HPP

ext: hpp


text:
#include <boost/python.hpp>
#include "../../def_submodule.hpp"

#include "../../../../../light/circle.hpp"

typedef GS_DDMRM::S_IceRay::S_light::S_type::GT_size GTs_size;

typedef GS_DDMRM::S_IceRay::S_type::GT_scalar             GTs_scalar;
typedef GS_DDMRM::S_IceRay::S_type::S_color::GT_scalar    GTs_color;
typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D  GTs_coord3D;

typedef GS_DDMRM::S_IceRay::S_light::S_type::GC_spot   GTs_spot;
typedef GS_DDMRM::S_IceRay::S_light::GC__pure          GTs__pure;
typedef GS_DDMRM::S_IceRay::S_light::GC_circle         GTs_circle;

void expose_IceRay_light_Circle()
 {
  //MAKE_SUBMODULE( IceRay );
  MAKE_SUBMODULE( core );
  MAKE_SUBMODULE( light );

  typedef  GTs_spot const& (GTs_circle::*Tf_getSpot  )(void) const;
  Tf_getSpot I_getSpot = &GTs_circle::F_spot;
  typedef  bool (GTs_circle::*Tf_setSpot  )(GTs_spot const&);
  Tf_setSpot I_setSpot = &GTs_circle::F_spot;

  typedef  GTs_coord3D const& (GTs_circle::*Tf_getCoord  )(void) const;
  typedef  bool (GTs_circle::*Tf_setCoord  )(GTs_coord3D const&);

  Tf_getCoord I_getX = &GTs_circle::F_x;
  Tf_setCoord I_setX = &GTs_circle::F_x;
  Tf_getCoord I_getY = &GTs_circle::F_y;
  Tf_setCoord I_setY = &GTs_circle::F_y;

  typedef  GTs_size const& (GTs_circle::*Tf_getSize )(void) const;
  typedef  bool (GTs_circle::*Tf_setSize  )(GTs_size const&);
  Tf_getSize I_getSample = &GTs_circle::F_sample;
  Tf_setSize I_setSample = &GTs_circle::F_sample;

  Tf_getCoord I_getPosition = &GTs_circle::F_center;
  Tf_setCoord I_setPosition = &GTs_circle::F_center;

  boost::python::class_<GTs_circle, boost::python::bases<GTs__pure> >( "LightCircle" )
    .def( boost::python::init<>() )
    .def( boost::python::init<GTs_spot, GTs_coord3D, GTs_coord3D, GTs_size >() )
    .def("spot",   I_getSpot, boost::python::return_value_policy<boost::python::copy_const_reference>() )
    .def("spot",   I_setSpot    )
    .def("center",   I_getPosition, boost::python::return_value_policy<boost::python::copy_const_reference>() )
    .def("center",   I_setPosition      )
    .def("x",      I_getX, boost::python::return_value_policy<boost::python::copy_const_reference>() )
    .def("x",      I_setX      )
    .def("y",      I_getY, boost::python::return_value_policy<boost::python::copy_const_reference>() )
    .def("y",      I_setY      )
    .def("sample",  I_getSample, boost::python::return_value_policy<boost::python::copy_const_reference>() )
    .def("sample",  I_setSample      )
   ;

 }

max_stars_repo_name: dmilos/IceRay

max_issues_repo_name: dmilos/IceRay

max_forks_repo_name: dmilos/IceRay


text:
/*

Copyright (c) 2003-2012, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author 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.

*/

#include "libtorrent/pch.hpp"

#include <string>
#include <cctype>
#include <algorithm>
#include <boost/limits.hpp>
#include <cstring>

#include <boost/optional.hpp>
#include <boost/array.hpp>
#include <boost/tuple/tuple.hpp>

#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/escape_string.hpp"
#include "libtorrent/parse_url.hpp"
#include "libtorrent/random.hpp"

#ifdef TORRENT_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif

#include "libtorrent/utf8.hpp"
#include "libtorrent/thread.hpp"

#if TORRENT_USE_ICONV
#include <iconv.h>
#include <locale.h>
#endif

namespace libtorrent
{

	// lexical_cast's result depends on the locale. We need
	// a well defined result
	boost::array<char, 4 + std::numeric_limits<size_type>::digits10> to_string(size_type n)
	{
		boost::array<char, 4 + std::numeric_limits<size_type>::digits10> ret;
		char *p = &ret.back();
		*p = '\0';
		unsigned_size_type un = n;
		if (n < 0)  un = -un;
		do {
			*--p = '0' + un % 10;
			un /= 10;
		} while (un);
		if (n < 0) *--p = '-';
		std::memmove(&ret[0], p, &ret.back() - p + 1);
		return ret;
	}

	std::string unescape_string(std::string const& s, error_code& ec)
	{
		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			if(*i == '+')
			{
				ret += ' ';
			}
			else if (*i != '%')
			{
				ret += *i;
			}
			else
			{
				++i;
				if (i == s.end())
				{
					ec = errors::invalid_escaped_string;
					return ret;
				}

				int high;
				if(*i >= '0' && *i <= '9') high = *i - '0';
				else if(*i >= 'A' && *i <= 'F') high = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') high = *i + 10 - 'a';
				else
				{
					ec = errors::invalid_escaped_string;
					return ret;
				}

				++i;
				if (i == s.end())
				{
					ec = errors::invalid_escaped_string;
					return ret;
				}

				int low;
				if(*i >= '0' && *i <= '9') low = *i - '0';
				else if(*i >= 'A' && *i <= 'F') low = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') low = *i + 10 - 'a';
				else
				{
					ec = errors::invalid_escaped_string;
					return ret;
				}

				ret += char(high * 16 + low);
			}
		}
		return ret;
	}

	// http://www.ietf.org/rfc/rfc2396.txt
	// section 2.3
	static const char unreserved_chars[] =
		// when determining if a url needs encoding
		// % should be ok
		"%+"
		// reserved
		";?:@=&,$/"
		// unreserved (special characters) ' excluded,
		// since some buggy trackers fail with those
		"-_!.~*()"
		// unreserved (alphanumerics)
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
		"0123456789";

	static const char hex_chars[] = "0123456789abcdef";

	// the offset is used to ignore the first characters in the unreserved_chars table.
	static std::string escape_string_impl(const char* str, int len, int offset)
	{
		TORRENT_ASSERT(str != 0);
		TORRENT_ASSERT(len >= 0);
		TORRENT_ASSERT(offset >= 0);
		TORRENT_ASSERT(offset < int(sizeof(unreserved_chars))-1);

		std::string ret;
		for (int i = 0; i < len; ++i)
		{
			if (std::strchr(unreserved_chars+offset, *str) && *str != 0)
			{
				ret += *str;
			}
			else
			{
				ret += '%';
				ret += hex_chars[((unsigned char)*str) >> 4];
				ret += hex_chars[((unsigned char)*str) & 15];
			}
			++str;
		}
		return ret;
	}

	std::string escape_string(const char* str, int len)
	{
		return escape_string_impl(str, len, 11);
	}

	std::string escape_path(const char* str, int len)
	{
		return escape_string_impl(str, len, 10);
	}

	bool need_encoding(char const* str, int len)
	{
		for (int i = 0; i < len; ++i)
		{
			if (std::strchr(unreserved_chars, *str) == 0 || *str == 0)
				return true;
			++str;
		}
		return false;
	}

	void convert_path_to_posix(std::string& path)
	{
		for (std::string::iterator i = path.begin()
			, end(path.end()); i != end; ++i)
			if (*i == '\\') *i = '/';
	}

	std::string read_until(char const*& str, char delim, char const* end)
	{
		TORRENT_ASSERT(str <= end);

		std::string ret;
		while (str != end && *str != delim)
		{
			ret += *str;
			++str;
		}
		// skip the delimiter as well
		while (str != end && *str == delim) ++str;
		return ret;
	}

	std::string maybe_url_encode(std::string const& url)
	{
		std::string protocol, host, auth, path;
		int port;
		error_code ec;
		boost::tie(protocol, auth, host, port, path) = parse_url_components(url, ec);
		if (ec) return url;

		// first figure out if this url contains unencoded characters
		if (!need_encoding(path.c_str(), path.size()))
			return url;

		char msg[TORRENT_MAX_PATH*4];
		snprintf(msg, sizeof(msg), "%s://%s%s%s%s%s%s", protocol.c_str(), auth.c_str()
			, auth.empty()?"":"@", host.c_str()
			, port == -1 ? "" : ":"
			, port == -1 ? "" : to_string(port).elems
			, escape_path(path.c_str(), path.size()).c_str());
		return msg;
	}

	std::string base64encode(const std::string& s)
	{
		static const char base64_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
			'w', 'x', 'y', 'z', '0', '1', '2', '3',
			'4', '5', '6', '7', '8', '9', '+', '/'
		};

		unsigned char inbuf[3];
		unsigned char outbuf[4];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			// available input is 1,2 or 3 bytes
			// since we read 3 bytes at a time at most
			int available_input = (std::min)(3, int(s.end()-i));

			// clear input buffer
			std::fill(inbuf, inbuf+3, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xfc) >> 2;
			outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4);
			outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6);
			outbuf[3] = inbuf[2] & 0x3f;

			// write output
			for (int j = 0; j < available_input+1; ++j)
			{
				ret += base64_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 3 - available_input; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32encode(std::string const& s)
	{
		static const char base32_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', '2', '3', '4', '5', '6', '7'
		};

		int input_output_mapping[] = {0, 2, 4, 5, 7, 8};

		unsigned char inbuf[5];
		unsigned char outbuf[8];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(5, int(s.end()-i));

			// clear input buffer
			std::fill(inbuf, inbuf+5, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xf8) >> 3;
			outbuf[1] = ((inbuf[0] & 0x07) << 2) | ((inbuf[1] & 0xc0) >> 6);
			outbuf[2] = ((inbuf[1] & 0x3e) >> 1);
			outbuf[3] = ((inbuf[1] & 0x01) << 4) | ((inbuf[2] & 0xf0) >> 4);
			outbuf[4] = ((inbuf[2] & 0x0f) << 1) | ((inbuf[3] & 0x80) >> 7);
			outbuf[5] = ((inbuf[3] & 0x7c) >> 2);
			outbuf[6] = ((inbuf[3] & 0x03) << 3) | ((inbuf[4] & 0xe0) >> 5);
			outbuf[7] = inbuf[4] & 0x1f;

			// write output
			int num_out = input_output_mapping[available_input];
			for (int j = 0; j < num_out; ++j)
			{
				ret += base32_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 8 - num_out; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32decode(std::string const& s)
	{
		unsigned char inbuf[8];
		unsigned char outbuf[5];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(8, int(s.end()-i));

			int pad_start = 0;
			if (available_input < 8) pad_start = available_input;

			// clear input buffer
			std::fill(inbuf, inbuf+8, 0);
			for (int j = 0; j < available_input; ++j)
			{
				char in = std::toupper(*i++);
				if (in >= 'A' && in <= 'Z')
					inbuf[j] = in - 'A';
				else if (in >= '2' && in <= '7')
					inbuf[j] = in - '2' + ('Z' - 'A') + 1;
				else if (in == '=')
				{
					inbuf[j] = 0;
					if (pad_start == 0) pad_start = j;
				}
				else if (in == '1')
					inbuf[j] = 'I' - 'A';
				else
					return std::string();
				TORRENT_ASSERT(inbuf[j] == (inbuf[j] & 0x1f));
			}

			// decode inbuf to outbuf
			outbuf[0] = inbuf[0] << 3;
			outbuf[0] |= inbuf[1] >> 2;
			outbuf[1] = (inbuf[1] & 0x3) << 6;
			outbuf[1] |= inbuf[2] << 1;
			outbuf[1] |= (inbuf[3] & 0x10) >> 4;
			outbuf[2] = (inbuf[3] & 0x0f) << 4;
			outbuf[2] |= (inbuf[4] & 0x1e) >> 1;
			outbuf[3] = (inbuf[4] & 0x01) << 7;
			outbuf[3] |= (inbuf[5] & 0x1f) << 2;
			outbuf[3] |= (inbuf[6] & 0x18) >> 3;
			outbuf[4] = (inbuf[6] & 0x07) << 5;
			outbuf[4] |= inbuf[7];

			int input_output_mapping[] = {5, 1, 1, 2, 2, 3, 4, 4, 5};
			int num_out = input_output_mapping[pad_start];

			// write output
			std::copy(outbuf, outbuf + num_out, std::back_inserter(ret));
		}
		return ret;
	}

	std::string url_has_argument(
		std::string const& url, std::string argument, std::string::size_type* out_pos)
	{
		size_t i = url.find('?');
		if (i == std::string::npos) return std::string();
		++i;

		argument += '=';

		if (url.compare(i, argument.size(), argument) == 0)
		{
			size_t pos = i + argument.size();
			if (out_pos) *out_pos = pos;
			return url.substr(pos, url.find('&', pos) - pos);
		}
		argument.insert(0, "&");
		i = url.find(argument, i);
		if (i == std::string::npos) return std::string();
		size_t pos = i + argument.size();
		if (out_pos) *out_pos = pos;
		return url.substr(pos, url.find('&', pos) - pos);
	}

	TORRENT_EXTRA_EXPORT std::string to_hex(std::string const& s)
	{
		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			ret += hex_chars[((unsigned char)*i) >> 4];
			ret += hex_chars[((unsigned char)*i) & 0xf];
		}
		return ret;
	}

	TORRENT_EXTRA_EXPORT void to_hex(char const *in, int len, char* out)
	{
		for (char const* end = in + len; in < end; ++in)
		{
			*out++ = hex_chars[((unsigned char)*in) >> 4];
			*out++ = hex_chars[((unsigned char)*in) & 0xf];
		}
		*out = '\0';
	}

	TORRENT_EXTRA_EXPORT int hex_to_int(char in)
	{
		if (in >= '0' && in <= '9') return int(in) - '0';
		if (in >= 'A' && in <= 'F') return int(in) - 'A' + 10;
		if (in >= 'a' && in <= 'f') return int(in) - 'a' + 10;
		return -1;
	}

	TORRENT_EXTRA_EXPORT bool is_hex(char const *in, int len)
	{
		for (char const* end = in + len; in < end; ++in)
		{
			int t = hex_to_int(*in);
			if (t == -1) return false;
		}
		return true;
	}

	TORRENT_EXTRA_EXPORT bool from_hex(char const *in, int len, char* out)
	{
		for (char const* end = in + len; in < end; ++in, ++out)
		{
			int t = hex_to_int(*in);
			if (t == -1) return false;
			*out = t << 4;
			++in;
			t = hex_to_int(*in);
			if (t == -1) return false;
			*out |= t & 15;
		}
		return true;
	}

#if defined TORRENT_WINDOWS && TORRENT_USE_WSTRING
	std::wstring convert_to_wstring(std::string const& s)
	{
		std::wstring ret;
		int result = libtorrent::utf8_wchar(s, ret);
		if (result == 0) return ret;

		ret.clear();
		const char* end = &s[0] + s.size();
		for (const char* i = &s[0]; i < end;)
		{
			wchar_t c = '.';
			result = std::mbtowc(&c, i, end - i);
			if (result > 0) i += result;
			else ++i;
			ret += c;
		}
		return ret;
	}

	std::string convert_from_wstring(std::wstring const& s)
	{
		std::string ret;
		int result = libtorrent::wchar_utf8(s, ret);
		if (result == 0) return ret;

		ret.clear();
		const wchar_t* end = &s[0] + s.size();
		for (const wchar_t* i = &s[0]; i < end;)
		{
			char c[10];
			TORRENT_ASSERT(sizeof(c) >= MB_CUR_MAX);
			result = std::wctomb(c, *i);
			if (result > 0)
			{
				i += result;
				ret.append(c, result);
			}
			else
			{
				++i;
				ret += ".";
			}
		}
		return ret;
	}
#endif

#if TORRENT_USE_ICONV
	std::string iconv_convert_impl(std::string const& s, iconv_t h)
	{
		std::string ret;
		size_t insize = s.size();
		size_t outsize = insize * 4;
		ret.resize(outsize);
		char const* in = s.c_str();
		char* out = &ret[0];
		// posix has a weird iconv signature. implementations
		// differ on what this signature should be, so we use
		// a macro to let config.hpp determine it
		size_t retval = iconv(h, TORRENT_ICONV_ARG &in, &insize,
			&out, &outsize);
		if (retval == (size_t)-1) return s;
		// if this string has an invalid utf-8 sequence in it, don't touch it
		if (insize != 0) return s;
		// not sure why this would happen, but it seems to be possible
		if (outsize > s.size() * 4) return s;
		// outsize is the number of bytes unused of the out-buffer
		TORRENT_ASSERT(ret.size() >= outsize);
		ret.resize(ret.size() - outsize);
		return ret;
	}

	std::string convert_to_native(std::string const& s)
	{
		static mutex iconv_mutex;
		// only one thread can use this handle at a time
		mutex::scoped_lock l(iconv_mutex);

		// the empty string represents the local dependent encoding
		static iconv_t iconv_handle = iconv_open("", "UTF-8");
		if (iconv_handle == iconv_t(-1)) return s;
		return iconv_convert_impl(s, iconv_handle);
	}

	std::string convert_from_native(std::string const& s)
	{
		static mutex iconv_mutex;
		// only one thread can use this handle at a time
		mutex::scoped_lock l(iconv_mutex);

		// the empty string represents the local dependent encoding
		static iconv_t iconv_handle = iconv_open("UTF-8", "");
		if (iconv_handle == iconv_t(-1)) return s;
		return iconv_convert_impl(s, iconv_handle);
	}

#elif defined TORRENT_WINDOWS

	std::string convert_to_native(std::string const& s)
	{
		std::wstring ws;
		libtorrent::utf8_wchar(s, ws);
		std::string ret;
		ret.resize(ws.size() * 4);
		std::size_t size = WideCharToMultiByte(CP_ACP, 0, ws.c_str(), -1, &ret[0], ret.size(), NULL, NULL);
		if (size == std::size_t(-1)) return s;
		ret.resize(size);
		return ret;
	}

	std::string convert_from_native(std::string const& s)
	{
		std::wstring ws;
		ws.resize(s.size());
		std::size_t size = MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, &ws[0], ws.size());
		if (size == std::size_t(-1)) return s;
		ws.resize(size);
		std::string ret;
		libtorrent::wchar_utf8(ws, ret);
		return ret;
	}

#elif TORRENT_USE_LOCALE

	std::string convert_to_native(std::string const& s)
	{
		std::wstring ws;
		libtorrent::utf8_wchar(s, ws);
		std::size_t size = wcstombs(0, ws.c_str(), 0);
		if (size == std::size_t(-1)) return s;
		std::string ret;
		ret.resize(size);
		size = wcstombs(&ret[0], ws.c_str(), size + 1);
		if (size == std::size_t(-1)) return s;
		ret.resize(size);
		return ret;
	}

	std::string convert_from_native(std::string const& s)
	{
		std::wstring ws;
		ws.resize(s.size());
		std::size_t size = mbstowcs(&ws[0], s.c_str(), s.size());
		if (size == std::size_t(-1)) return s;
		std::string ret;
		libtorrent::wchar_utf8(ws, ret);
		return ret;
	}

#endif

}

max_stars_repo_name: majestrate/twister-core

max_issues_repo_name: majestrate/twister-core

max_forks_repo_name: twisterarmy/twister-core


text:
#pragma once

#include "webroutes.hpp"

#include <app.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/container/flat_set.hpp>
#include <common.hpp>
#include <forward_unauthorized.hpp>
#include <http_request.hpp>
#include <http_response.hpp>
#include <http_utility.hpp>
#include <pam_authenticate.hpp>

#include <random>
#include <utility>

namespace crow
{

namespace authorization
{

static void cleanupTempSession(Request& req)
{
    // TODO(ed) THis should really be handled by the persistent data
    // middleware, but because it is upstream, it doesn't have access to the
    // session information.  Should the data middleware persist the current
    // user session?
    if (req.session != nullptr &&
        req.session->persistence ==
            persistent_data::PersistenceType::SINGLE_REQUEST)
    {
        persistent_data::SessionStore::getInstance().removeSession(req.session);
    }
}

#ifdef BMCWEB_ENABLE_BASIC_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performBasicAuth(const boost::asio::ip::address& clientIp,
                     std::string_view authHeader)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";

    if (!boost::starts_with(authHeader, "Basic "))
    {
        return nullptr;
    }

    std::string_view param = authHeader.substr(strlen("Basic "));
    std::string authData;

    if (!crow::utility::base64Decode(param, authData))
    {
        return nullptr;
    }
    std::size_t separator = authData.find(':');
    if (separator == std::string::npos)
    {
        return nullptr;
    }

    std::string user = authData.substr(0, separator);
    separator += 1;
    if (separator > authData.size())
    {
        return nullptr;
    }
    std::string pass = authData.substr(separator);

    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] User IPAddress: "
                     << clientIp.to_string();

    int pamrc = pamAuthenticateUser(user, pass);
    bool isConfigureSelfOnly = pamrc == PAM_NEW_AUTHTOK_REQD;
    if ((pamrc != PAM_SUCCESS) && !isConfigureSelfOnly)
    {
        return nullptr;
    }

    // TODO(ed) generateUserSession is a little expensive for basic
    // auth, as it generates some random identifiers that will never be
    // used.  This should have a "fast" path for when user tokens aren't
    // needed.
    // This whole flow needs to be revisited anyway, as we can't be
    // calling directly into pam for every request
    std::string unsupportedClientId = "";
    return persistent_data::SessionStore::getInstance().generateUserSession(
        user, clientIp.to_string(), unsupportedClientId,
        persistent_data::PersistenceType::SINGLE_REQUEST, isConfigureSelfOnly);
}
#endif

#ifdef BMCWEB_ENABLE_SESSION_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performTokenAuth(std::string_view authHeader)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";
    if (!boost::starts_with(authHeader, "Token "))
    {
        return nullptr;
    }
    std::string_view token = authHeader.substr(strlen("Token "));
    auto sessionOut =
        persistent_data::SessionStore::getInstance().loginSessionByToken(token);
    return sessionOut;
}
#endif

#ifdef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performXtokenAuth(const boost::beast::http::header<true>& reqHeader)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";

    std::string_view token = reqHeader["X-Auth-Token"];
    if (token.empty())
    {
        return nullptr;
    }
    auto sessionOut =
        persistent_data::SessionStore::getInstance().loginSessionByToken(token);
    return sessionOut;
}
#endif

#ifdef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performCookieAuth(boost::beast::http::verb method,
                      const boost::beast::http::header<true>& reqHeader)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";

    std::string_view cookieValue = reqHeader["Cookie"];
    if (cookieValue.empty())
    {
        return nullptr;
    }

    auto startIndex = cookieValue.find("SESSION=");
    if (startIndex == std::string::npos)
    {
        return nullptr;
    }
    startIndex += sizeof("SESSION=") - 1;
    auto endIndex = cookieValue.find(';', startIndex);
    if (endIndex == std::string::npos)
    {
        endIndex = cookieValue.size();
    }
    std::string_view authKey =
        cookieValue.substr(startIndex, endIndex - startIndex);

    std::shared_ptr<persistent_data::UserSession> sessionOut =
        persistent_data::SessionStore::getInstance().loginSessionByToken(
            authKey);
    if (sessionOut == nullptr)
    {
        return nullptr;
    }
#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
    // RFC7231 defines methods that need csrf protection
    if (method != boost::beast::http::verb::get)
    {
        std::string_view csrf = reqHeader["X-XSRF-TOKEN"];
        // Make sure both tokens are filled
        if (csrf.empty() || sessionOut->csrfToken.empty())
        {
            return nullptr;
        }

        if (csrf.size() != persistent_data::sessionTokenSize)
        {
            return nullptr;
        }
        // Reject if csrf token not available
        if (!crow::utility::constantTimeStringCompare(csrf,
                                                      sessionOut->csrfToken))
        {
            return nullptr;
        }
    }
#endif
    return sessionOut;
}
#endif

#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performTLSAuth(Response& res,
                   const boost::beast::http::header<true>& reqHeader,
                   const std::weak_ptr<persistent_data::UserSession>& session)
{
    if (auto sp = session.lock())
    {
        // set cookie only if this is req from the browser.
        if (reqHeader["User-Agent"].empty())
        {
            BMCWEB_LOG_DEBUG << " TLS session: " << sp->uniqueId
                             << " will be used for this request.";
            return sp;
        }
        std::string_view cookieValue = reqHeader["Cookie"];
        if (cookieValue.empty() ||
            cookieValue.find("SESSION=") == std::string::npos)
        {
            // TODO: change this to not switch to cookie auth
            res.addHeader(
                "Set-Cookie",
                "XSRF-TOKEN=" + sp->csrfToken +
                    "; SameSite=Strict; Secure\r\nSet-Cookie: SESSION=" +
                    sp->sessionToken +
                    "; SameSite=Strict; Secure; HttpOnly\r\nSet-Cookie: "
                    "IsAuthenticated=true; Secure");
            BMCWEB_LOG_DEBUG << " TLS session: " << sp->uniqueId
                             << " with cookie will be used for this request.";
            return sp;
        }
    }
    return nullptr;
}
#endif

// checks if request can be forwarded without authentication
static bool isOnWhitelist(std::string_view url, boost::beast::http::verb method)
{
    if (boost::beast::http::verb::get == method)
    {
        if (url == "/redfish/v1" || url == "/redfish/v1/" ||
            url == "/redfish" || url == "/redfish/" ||
            url == "/redfish/v1/odata" || url == "/redfish/v1/odata/")
        {
            return true;
        }
        if (crow::webroutes::routes.find(std::string(url)) !=
            crow::webroutes::routes.end())
        {
            return true;
        }
    }

    // it's allowed to POST on session collection & login without
    // authentication
    if (boost::beast::http::verb::post == method)
    {
        if ((url == "/redfish/v1/SessionService/Sessions") ||
            (url == "/redfish/v1/SessionService/Sessions/") ||
            (url == "/login"))
        {
            return true;
        }
    }

    return false;
}

static std::shared_ptr<persistent_data::UserSession> authenticate(
    boost::asio::ip::address& ipAddress [[maybe_unused]],
    Response& res [[maybe_unused]], boost::beast::http::verb method,
    const boost::beast::http::header<true>& reqHeader,
    [[maybe_unused]] const std::shared_ptr<persistent_data::UserSession>&
        session)
{
    const persistent_data::AuthConfigMethods& authMethodsConfig =
        persistent_data::SessionStore::getInstance().getAuthMethodsConfig();

    std::shared_ptr<persistent_data::UserSession> sessionOut = nullptr;
#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
    if (authMethodsConfig.tls)
    {
        sessionOut = performTLSAuth(res, reqHeader, session);
    }
#endif
#ifdef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
    if (sessionOut == nullptr && authMethodsConfig.xtoken)
    {
        sessionOut = performXtokenAuth(reqHeader);
    }
#endif
#ifdef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
    if (sessionOut == nullptr && authMethodsConfig.cookie)
    {
        sessionOut = performCookieAuth(method, reqHeader);
    }
#endif
    std::string_view authHeader = reqHeader["Authorization"];
    BMCWEB_LOG_WARNING << "authHeader=" << authHeader;

    if (sessionOut == nullptr && authMethodsConfig.sessionToken)
    {
#ifdef BMCWEB_ENABLE_SESSION_AUTHENTICATION
        sessionOut = performTokenAuth(authHeader);
#endif
    }
    if (sessionOut == nullptr && authMethodsConfig.basic)
    {
#ifdef BMCWEB_ENABLE_BASIC_AUTHENTICATION
        sessionOut = performBasicAuth(ipAddress, authHeader);
#endif
    }
    if (sessionOut != nullptr)
    {
        return sessionOut;
    }

    return nullptr;
}

} // namespace authorization
} // namespace crow

max_stars_repo_name: murali-srinivasan/bmcweb

max_issues_repo_name: murali-srinivasan/bmcweb

max_forks_repo_name: murali-srinivasan/bmcweb


text:
//==============================================================================
//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_SDK_ERROR_TRAP_HPP_INCLUDED
#define NT2_SDK_ERROR_TRAP_HPP_INCLUDED

/**
* @file
* @brief Provides portable, conditionnal breakpoint traps
**/

#include <boost/config.hpp>
#include <boost/utility/enable_if.hpp>

//==============================================================================
// Detects and define how to emit a TRAP signal
//==============================================================================
#if (   defined(_M_IX86) || defined(__i386__)   \
    ||  defined(_M_IA64) || defined(__ia64__)   \
    )                                           \
    &&  defined(__GNUC__)
#define NT2_DEBUG_TRAP()  __asm("int3")
#elif defined(_MSC_VER)
#define NT2_DEBUG_TRAP()  __debugbreak()
#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <csignal>
#define NT2_DEBUG_TRAP() ::raise(SIGTRAP)
#else
#define NT2_DEBUG_TRAP()
#endif

namespace nt2
{
  /**
  * @brief Runtime conditionnal breakpoint trap
  *
  * If @c cond evaluates to true, triggers a breakpoint trap.
  *
  * @param cond Conditionnal trigger for the breakpoint trap
  **/
  BOOST_FORCEINLINE void trap(bool cond) { if(!cond) NT2_DEBUG_TRAP(); }

  /**
  * @brief Runtime inconditionnal breakpoint trap
  *
  * Triggers a breakpoint trap.
  **/
  BOOST_FORCEINLINE void trap() { NT2_DEBUG_TRAP(); }

  /**
  * @brief Compile-time conditionnal breakpoint trap
  *
  * If @c Condition::value evaluates true, triggers a breakpoint trap.
  *
  * @tparam Condition Compile-time boolean integral constant
  **/
  template<class Condition>
  BOOST_FORCEINLINE void
  trap( typename boost::enable_if_c<Condition::value>::type* = 0 )
  {
    NT2_DEBUG_TRAP();
  }

  template<class Condition> BOOST_FORCEINLINE
  void trap( typename boost::disable_if_c<Condition::value>::type* = 0 )
  {}
}

#endif


text: #include <boost/wave/wave_config.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman
    Copyright (c) 2001-2008 Hartmut Kaiser

    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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_AUXILIARY_FEB_03_2007_0355PM)
#define BOOST_SPIRIT_STRING_FEB_03_2007_0355PM

#include <boost/spirit/home/qi/auxiliary/none.hpp>
#include <boost/spirit/home/qi/auxiliary/eps.hpp>
#include <boost/spirit/home/qi/auxiliary/lazy.hpp>
#include <boost/spirit/home/qi/auxiliary/functor.hpp>
#include <boost/spirit/home/qi/auxiliary/functor_director.hpp>
#include <boost/spirit/home/qi/auxiliary/primitives.hpp>
#include <boost/spirit/home/qi/auxiliary/meta_grammar.hpp>

#endif


text:
// Copyright (C) 2012  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.

#include <dlib/optimization.h>
#include <dlib/svm.h>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>

#include "tester.h"

namespace
{

    using namespace test;
    using namespace dlib;
    using namespace std;

    logger dlog("test.oca");

// ----------------------------------------------------------------------------------------

    class test_oca : public tester
    {

    public:
        test_oca (
        ) :
            tester ("test_oca",
                    "Runs tests on the oca component.")
        {
        }

        void perform_test(
        )
        {
            print_spinner();

            typedef matrix<double,0,1> w_type;
            w_type w;

            decision_function<linear_kernel<w_type> > df;
            svm_c_linear_trainer<linear_kernel<w_type> > trainer;
            trainer.set_c_class1(2);
            trainer.set_c_class1(3);
            trainer.set_learns_nonnegative_weights(true);
            trainer.set_epsilon(1e-12);

            std::vector<w_type> x;
            w_type temp(2);
            temp = -1, 1;
            x.push_back(temp);
            temp = 1, -1;
            x.push_back(temp);

            std::vector<double> y;
            y.push_back(+1);
            y.push_back(-1);

            w_type true_w(3);

            oca solver;

            // test the version without a non-negativity constraint on w.
            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 0);
            dlog << LINFO << trans(w);
            true_w = -0.5, 0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            w_type prior = true_w;
            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);
            dlog << LINFO << trans(w);
            true_w = -0.5, 0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            prior = 0,0,0;
            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);
            dlog << LINFO << trans(w);
            true_w = -0.5, 0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            prior = -1,1,0;
            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);
            dlog << LINFO << trans(w);
            true_w = -1.0, 1.0, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            prior = -0.2,0.2,0;
            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);
            dlog << LINFO << trans(w);
            true_w = -0.5, 0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            prior = -10.2,-1,0;
            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);
            dlog << LINFO << trans(w);
            true_w = -10.2, -1.0, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            // test the version with a non-negativity constraint on w.
            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 9999);
            dlog << LINFO << trans(w);
            true_w = 0, 1, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            df = trainer.train(x,y);
            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));
            true_w = 0, 1, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            // test the version with a non-negativity constraint on w.
            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 2);
            dlog << LINFO << trans(w);
            true_w = 0, 1, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            // test the version with a non-negativity constraint on w.
            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 1);
            dlog << LINFO << trans(w);
            true_w = 0, 1, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            // switching the labels should change which w weight goes negative.
            y.clear();
            y.push_back(-1);
            y.push_back(+1);

            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 0);
            dlog << LINFO << trans(w);
            true_w = 0.5, -0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 1);
            dlog << LINFO << trans(w);
            true_w = 0.5, -0.5, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 2);
            dlog << LINFO << trans(w);
            true_w = 1, 0, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            print_spinner();

            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 5);
            dlog << LINFO << trans(w);
            true_w = 1, 0, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            df = trainer.train(x,y);
            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));
            true_w = 1, 0, 0;
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            x.clear();
            y.clear();
            temp = -2, 2;
            x.push_back(temp);
            temp = 0, -0;
            x.push_back(temp);

            y.push_back(+1);
            y.push_back(-1);

            trainer.set_c(10);
            df = trainer.train(x,y);
            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));
            true_w = 0, 1, -1;
            dlog << LINFO << "w: " << trans(w);
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

            x.clear();
            y.clear();
            temp = -2, 2;
            x.push_back(temp);
            temp = 0, -0;
            x.push_back(temp);

            y.push_back(-1);
            y.push_back(+1);

            trainer.set_c(10);
            df = trainer.train(x,y);
            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));
            true_w = 1, 0, 1;
            dlog << LINFO << "w: " << trans(w);
            dlog << LINFO << "error: "<< max(abs(w-true_w));
            DLIB_TEST(max(abs(w-true_w)) < 1e-10);

        }

    } a;

}

max_stars_repo_name: Chpark/itomp

max_issues_repo_name: Chpark/itomp

max_forks_repo_name: Chpark/itomp


text:
#include "test_data.hpp"
#include "../src/shared_operations.hpp"
#include "logging.h"
#include <boost/test/unit_test.hpp>
#include "libs/ml_models/logistic_regression.h"
#include <opencv/cxcore.h>
#include <iostream>
//#define TEST_CODE_FOR_MODEL_LOG_REG
#ifdef TEST_CODE_FOR_MODEL_LOG_REG
#include <map>

using forward_m = std::map<int, int>;

bool set_label_map(const cv::Mat &_labels_i, forward_m& fm);
cv::Mat remap_labels(const cv::Mat& _labels_i, const forward_m& lmap);

void simulate(cv::Mat _labels_i)
{
    //std::cout<<"the type of the matrix that we are working with is "<<_labels_i<<std::endl;
    forward_m forward_mapper;
    /*for (auto i = 0; i < _labels_i.rows; ++i) {
        float t = _labels_i.at<float>(i, 0);
        std::cout<< " ["<<i<<"] = "<<t;
    }
    std::cout<<std::endl;*/
#if 0
        auto ii = t + 0.123f;
        //std::cout<<"t "<<t<<", ii "<<ii<<", ";
        _labels_i.at<float>(i, 0) = ii;
    }
    std::cout<<std::endl;
#endif
    set_label_map(_labels_i, forward_mapper);
    cv::Mat labels_l = remap_labels(_labels_i, forward_mapper);
    int num_classes = (int) forward_mapper.size();
    if(num_classes < 2)
    {
        std::cerr<<"number of classes must be at least 2\n";
    } else {
        std::cout<<"number of classes is "<<num_classes<<std::endl;
    }
}

cv::Mat remap_labels(const cv::Mat& _labels_i, const forward_m& lmap)
{
    cv::Mat labels;
    _labels_i.convertTo(labels, CV_32S);

    cv::Mat new_labels = cv::Mat::zeros(labels.rows, labels.cols, labels.type());

    for(int i =0;i<labels.rows;i++) {
        new_labels.at<int>(i,0) = lmap.find(labels.at<int>(i,0))->second;
    }
    return new_labels;
}

bool set_label_map(const cv::Mat &_labels_i, forward_m& forward_mapper)
{
    // this function creates two maps to map user defined labels to program friendly labels two ways.
    int ii = 0;
    cv::Mat labels;

    auto labels_o = cv::Mat(0,1, CV_8U);
    auto labels_n = cv::Mat(0,1, CV_8U);

    _labels_i.convertTo(labels, CV_32S);

    for(int i = 0;i<labels.rows;i++)
    {
        forward_mapper[labels.at<int>(i)] += 1;
        //std::cout<<"setting "<<labels.at<int>(i)<<" to "<<forward_mapper[labels.at<int>(i)]<<" from "<<_labels_i.at<float>(i, 0)<<"\n";
    }

    for(auto it = forward_mapper.begin(); it != forward_mapper.end(); ++it)
    {
        forward_mapper[it->first] = ii;
        labels_o.push_back(it->first);
        labels_n.push_back(ii);
        ii += 1;
    }
    return true;
}
#endif  // TEST_CODE_FOR_MODEL_LOG_REG
BOOST_AUTO_TEST_CASE(empty_data_set_test_lr)
{
    mlmodels::regression_LR_model model;
    auto m = model.train(mlmodels::training_data{},
            mlmodels::class_data{},
            mlmodels::logistic_regression::args{}
        );
    BOOST_TEST((m.get() == nullptr), "the model that we should get back from empty data set should be empty as well");
    mlmodels::testing_result out;
    auto r = model.predict(m, mlmodels::testing_data{}, out);
    BOOST_TEST(r == false, "should failed because training did not run");
    BOOST_TEST(out.empty(), "there should not be any data from the test");
}

BOOST_AUTO_TEST_CASE(test_model_create_lr)
{
    const auto& samples = ut_data::unittest_data();
    const auto& classes = ut_data::classes4ut();
    BOOST_TEST_REQUIRE(mlmodels::rows(samples) == classes.size());
#ifdef TEST_CODE_FOR_MODEL_LOG_REG
        simulate(mlmodels::detail::prepare_labels(classes, CV_32F));
#else
    try {
        mlmodels::regression_LR_model lg;
        auto m = lg.train(samples,
                classes,
                mlmodels::logistic_regression::args{}
        );
        BOOST_TEST_REQUIRE((m.get() != nullptr), "we are expecting that this train would succeed");
        const auto& test_samples = ut_data::samples4test();
        BOOST_TEST_REQUIRE(mlmodels::rows(test_samples) < mlmodels::rows(samples));
        BOOST_TEST_REQUIRE(mlmodels::columns(test_samples) == mlmodels::columns(samples));
        auto p = lg.test(m, test_samples, ut_data::NUMBER_OF_CLASSES);
        BOOST_TEST_REQUIRE(!p.empty(), "we are expecting to get entries from the test");
        BOOST_TEST_REQUIRE(p.size() == mlmodels::rows(test_samples));
    //mlmodels::save_model(m);
#ifdef PRINT_MODEL_RESULTS
        for (auto f : p) {
            std::cout<<"["<<f<<"]";
        }
        std::cout<<std::endl;
#endif
    } catch (const std::exception& e) {
        BOOST_TEST(false, "we do not except an exception but we've got "<<e.what());
    } catch (...) {
        BOOST_TEST(false, "unknown exception while running unit test");
    }
#endif  // TEST_CODE_FOR_MODEL_LOG_REG
}


text:
/**
 * @brief Scene HelloTriangle Class
 */

// ********************************************************************************
// Including files
// ********************************************************************************

#include <boost/assert.hpp>
#include <iostream>

#include "SceneHelloTriangle.h"

// ********************************************************************************
// Override functions
// ********************************************************************************

void SceneHelloTriangle::OnInit() {
  if (const auto msg = CompileAndLinkShader()) {
    std::cerr << msg.value() << std::endl;
    BOOST_ASSERT_MSG(false, "failed to compile or link!");
  }

  CreateVAO();
}

void SceneHelloTriangle::OnDestroy() {
  glDeleteVertexArrays(1, &vao_);
  glDeleteBuffers(static_cast<GLsizei>(vbo_.size()), vbo_.data());
}

void SceneHelloTriangle::OnUpdate(float d) { static_cast<void>(d); }

void SceneHelloTriangle::OnRender() {
  prog_.Use();

  glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT);

  glBindVertexArray(vao_);
  glDrawArrays(GL_TRIANGLES, 0, 3);
  glBindVertexArray(0);
}

void SceneHelloTriangle::OnResize(int w, int h) {
  SetDimensions(w, h);
  glViewport(0, 0, w, h);
}

// ********************************************************************************
// Shader prepare
// ********************************************************************************

std::optional<std::string> SceneHelloTriangle::CompileAndLinkShader() {
  // compile and links
  return prog_.CompileAndLink(
      {{"./Assets/Shaders/Basic/Basic.vs.glsl", ShaderType::Vertex},
       {"./Assets/Shaders/Basic/Basic.fs.glsl", ShaderType::Fragment}});
}

void SceneHelloTriangle::CreateVAO() {
  const float position[] = {
      -0.8f, -0.8f, 0.0f, 0.8f, -0.8f, 0.0f, 0.0f, 0.8f, 0.0f,
  };

  const float color[] = {
      1.0f, 0.0f, 0.0, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
  };

  glGenBuffers(static_cast<GLsizei>(vbo_.size()), vbo_.data());

  glBindBuffer(GL_ARRAY_BUFFER, vbo_[Position]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(position), position, GL_STATIC_DRAW);

  glBindBuffer(GL_ARRAY_BUFFER, vbo_[Color]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(color), color, GL_STATIC_DRAW);

  glGenVertexArrays(1, &vao_);
  glBindVertexArray(vao_);

  glEnableVertexAttribArray(0); // Vertex position
  glEnableVertexAttribArray(1); // Vertex color

  glBindBuffer(GL_ARRAY_BUFFER, vbo_[Position]);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

  glBindBuffer(GL_ARRAY_BUFFER, vbo_[Color]);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);
}

ext: cc

max_stars_repo_name: mnrn/ReGL

max_issues_repo_name: mnrn/ReGL

max_forks_repo_name: mnrn/ReGL


text:
#pragma once

#include "RelaxedUT.h"
#include <Eigen/QR>

using namespace RelaxedUnscentedTransformation;

void RelaxedUnscentedTransformation::genQ(int n, const Eigen::VectorXi& inl, const MixedNonlinearityList& mix,
	Eigen::SparseMatrix<double>& Q,
	Eigen::SparseMatrix<double>& Q1) {
	// Construct M matrix from the weights keeping it orthogonal to inl
	typedef Eigen::MatrixXd Matrix;
	Matrix M = Matrix::Zero(mix.size() + inl.size(), n);
	for (int n = 0; n < inl.size(); n++)
		M(n, inl(n)) = 1;
	for (int n = 0; n < mix.size(); n++)
		for (int i0 = 0; i0 < mix[n].i.size(); i0++) {
			bool flag = false;
			for (int i = 0; i < inl.size(); i++)
				if (mix[n].i[i0] == inl(i))
					flag = true;
			if (!flag)
				M(n + inl.size(), mix[n].i[i0]) = mix[n].M(i0);
		}
	// RQ factorization
	Eigen::HouseholderQR<Matrix> solver(M.transpose());
	Eigen::MatrixXd Qdense = solver.householderQ().transpose();
	double rel_treshold = 1e-6;
	// Compute rank
	int rank = n;
	{
		Eigen::MatrixXd to_compute_rank = (M * Qdense.transpose()).cwiseAbs();
		double treshold = to_compute_rank.maxCoeff() * rel_treshold;
		for (int i = 0; i < to_compute_rank.cols(); i++)
			if (to_compute_rank.col(i).maxCoeff() < treshold) {
				rank = i;
				break;
			}
	}
	// make it sparse
	for (int i = 0; i < Qdense.rows(); i++)
		for (int j = 0; j < Qdense.cols(); j++)
			if (abs(Qdense(i, j)) < 1e-8)
				Qdense(i, j) = 0;
	// save it sparse
	Q = Qdense.sparseView();
	Q1 = Q.block(0, 0, rank, n);
}


text:
// Copyright (c) 2016 Klemens D. Morgenstern
//
// 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)

#ifndef BOOST_PROCESS_DETAIL_WINDOWS_JOB_WORKAROUND_HPP_
#define BOOST_PROCESS_DETAIL_WINDOWS_JOB_WORKAROUND_HPP_

#include <boost/winapi/config.hpp>
#include <boost/winapi/basic_types.hpp>
#include <boost/winapi/dll.hpp>
#include <boost/winapi/overlapped.hpp>

#if defined( BOOST_USE_WINDOWS_H )
#include <windows.h>
#else
extern "C"
{
BOOST_SYMBOL_IMPORT ::boost::winapi::HANDLE_ BOOST_WINAPI_WINAPI_CC CreateIoCompletionPort(
        ::boost::winapi::HANDLE_    FileHandle,
        ::boost::winapi::HANDLE_    ExistingCompletionPort,
        ::boost::winapi::ULONG_PTR_ CompletionKey,
        ::boost::winapi::DWORD_     NumberOfConcurrentThreads
);

BOOST_SYMBOL_IMPORT ::boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC GetQueuedCompletionStatus(
        ::boost::winapi::HANDLE_       CompletionPort,
        ::boost::winapi::LPDWORD_      lpNumberOfBytes,
        ::boost::winapi::ULONG_PTR_    *lpCompletionKey,
        _OVERLAPPED **lpOverlapped,
        ::boost::winapi::DWORD_        dwMilliseconds
);

}
#endif
namespace boost { namespace process { namespace detail { namespace windows { namespace workaround {

extern "C"
{

struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT_
{
    ::boost::winapi::PVOID_  CompletionKey;
    ::boost::winapi::HANDLE_ CompletionPort;
};

constexpr static int JOB_OBJECT_MSG_END_OF_JOB_TIME_          = 1;
constexpr static int JOB_OBJECT_MSG_END_OF_PROCESS_TIME_      = 2;
constexpr static int JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT_     = 3;
constexpr static int JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO_      = 4;
constexpr static int JOB_OBJECT_MSG_NEW_PROCESS_              = 6;
constexpr static int JOB_OBJECT_MSG_EXIT_PROCESS_             = 7;
constexpr static int JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS_    = 8;
constexpr static int JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT_     = 9;
constexpr static int JOB_OBJECT_MSG_JOB_MEMORY_LIMIT_         = 10;
constexpr static int JOB_OBJECT_MSG_NOTIFICATION_LIMIT_       = 11;
constexpr static int JOB_OBJECT_MSG_JOB_CYCLE_TIME_LIMIT_     = 12;
constexpr static int JOB_OBJECT_MSG_SILO_TERMINATED_          = 13;

}

BOOST_FORCEINLINE ::boost::winapi::BOOL_  get_queued_completion_status(
        ::boost::winapi::HANDLE_       CompletionPort,
        ::boost::winapi::LPDWORD_      lpNumberOfBytes,
        ::boost::winapi::ULONG_PTR_    *lpCompletionKey,
        ::boost::winapi::LPOVERLAPPED_ *lpOverlapped,
        ::boost::winapi::DWORD_        dwMilliseconds)
{
    return ::GetQueuedCompletionStatus(
                CompletionPort,
                lpNumberOfBytes,
                lpCompletionKey,
                reinterpret_cast<::_OVERLAPPED**>(lpOverlapped),
                dwMilliseconds);
}

#if defined( BOOST_USE_WINDOWS_H )

constexpr auto static JobObjectExtendedLimitInformation_ = ::JobObjectExtendedLimitInformation;
constexpr auto static JobObjectAssociateCompletionPortInformation_ = ::JobObjectAssociateCompletionPortInformation;
constexpr auto static JobObjectBasicAccountingInformation_ = ::JobObjectBasicAccountingInformation;

using JOBOBJECT_BASIC_LIMIT_INFORMATION_ = ::JOBOBJECT_BASIC_LIMIT_INFORMATION;
using JOBOBJECTINFOCLASS_ = ::JOBOBJECTINFOCLASS;
using IO_COUNTERS_ = ::IO_COUNTERS;
using JOBOBJECT_EXTENDED_LIMIT_INFORMATION_ = ::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
using JOBOBJECT_BASIC_ACCOUNTING_INFORMATION_ = ::JOBOBJECT_BASIC_ACCOUNTING_INFORMATION;

inline ::boost::winapi::BOOL_ query_information_job_object(
        ::boost::winapi::HANDLE_ hJob,
        JOBOBJECTINFOCLASS_ JobObjectInfoClass,
        void * lpJobObjectInfo,
        ::boost::winapi::DWORD_ cbJobObjectInfoLength,
        ::boost::winapi::DWORD_ *lpReturnLength)
{
    return ::QueryInformationJobObject(hJob, JobObjectInfoClass, lpJobObjectInfo, cbJobObjectInfoLength, lpReturnLength);
}

inline ::boost::winapi::BOOL_ set_information_job_object(
        ::boost::winapi::HANDLE_ hJob,
        JOBOBJECTINFOCLASS_ JobObjectInfoClass,
        void * lpJobObjectInfo,
        ::boost::winapi::DWORD_ cbJobObjectInfoLength)
{
    return ::SetInformationJobObject(hJob, JobObjectInfoClass, lpJobObjectInfo, cbJobObjectInfoLength);
}

#else

//this import workaround is to keep it a header-only library. and enums cannot be imported from the winapi.

extern "C"
{

typedef enum _JOBOBJECTINFOCLASS_
{
    JobObjectBasicAccountingInformation_ = 1,
    JobObjectBasicLimitInformation_,
    JobObjectBasicProcessIdList_,
    JobObjectBasicUIRestrictions_,
    JobObjectSecurityLimitInformation_,
    JobObjectEndOfJobTimeInformation_,
    JobObjectAssociateCompletionPortInformation_,
    JobObjectBasicAndIoAccountingInformation_,
    JobObjectExtendedLimitInformation_,
    JobObjectJobSetInformation_,
    JobObjectGroupInformation_,
    JobObjectNotificationLimitInformation_,
    JobObjectLimitViolationInformation_,
    JobObjectGroupInformationEx_,
    JobObjectCpuRateControlInformation_,
    JobObjectCompletionFilter_,
    JobObjectCompletionCounter_,
    JobObjectReserved1Information_ = 18,
    JobObjectReserved2Information_,
    JobObjectReserved3Information_,
    JobObjectReserved4Information_,
    JobObjectReserved5Information_,
    JobObjectReserved6Information_,
    JobObjectReserved7Information_,
    JobObjectReserved8Information_,
    MaxJobObjectInfoClass_
} JOBOBJECTINFOCLASS_;

typedef struct _JOBOBJECT_BASIC_LIMIT_INFORMATION_
{
    ::boost::winapi::LARGE_INTEGER_ PerProcessUserTimeLimit;
    ::boost::winapi::LARGE_INTEGER_ PerJobUserTimeLimit;
    ::boost::winapi::DWORD_ LimitFlags;
    ::boost::winapi::SIZE_T_ MinimumWorkingSetSize;
    ::boost::winapi::SIZE_T_ MaximumWorkingSetSize;
    ::boost::winapi::DWORD_ ActiveProcessLimit;
    ::boost::winapi::ULONG_PTR_ Affinity;
    ::boost::winapi::DWORD_ PriorityClass;
    ::boost::winapi::DWORD_ SchedulingClass;
} JOBOBJECT_BASIC_LIMIT_INFORMATION_;

typedef struct _JOBOBJECT_BASIC_ACCOUNTING_INFORMATION_ {
    ::boost::winapi::LARGE_INTEGER_ TotalUserTime;
    ::boost::winapi::LARGE_INTEGER_ TotalKernelTime;
    ::boost::winapi::LARGE_INTEGER_ ThisPeriodTotalUserTime;
    ::boost::winapi::LARGE_INTEGER_ ThisPeriodTotalKernelTime;
    ::boost::winapi::DWORD_         TotalPageFaultCount;
    ::boost::winapi::DWORD_         TotalProcesses;
    ::boost::winapi::DWORD_         ActiveProcesses;
    ::boost::winapi::DWORD_         TotalTerminatedProcesses;
} JOBOBJECT_BASIC_ACCOUNTING_INFORMATION_;

typedef struct _IO_COUNTERS_
{
    ::boost::winapi::ULONGLONG_ ReadOperationCount;
    ::boost::winapi::ULONGLONG_ WriteOperationCount;
    ::boost::winapi::ULONGLONG_ OtherOperationCount;
    ::boost::winapi::ULONGLONG_ ReadTransferCount;
    ::boost::winapi::ULONGLONG_ WriteTransferCount;
    ::boost::winapi::ULONGLONG_ OtherTransferCount;
} IO_COUNTERS_;

typedef struct _JOBOBJECT_EXTENDED_LIMIT_INFORMATION_
{
    JOBOBJECT_BASIC_LIMIT_INFORMATION_ BasicLimitInformation;
    IO_COUNTERS_ IoInfo;
    ::boost::winapi::SIZE_T_ ProcessMemoryLimit;
    ::boost::winapi::SIZE_T_ JobMemoryLimit;
    ::boost::winapi::SIZE_T_ PeakProcessMemoryUsed;
    ::boost::winapi::SIZE_T_ PeakJobMemoryUsed;
} JOBOBJECT_EXTENDED_LIMIT_INFORMATION_;

/*BOOL WINAPI QueryInformationJobObject(
  _In_opt_  HANDLE             hJob,
  _In_      JOBOBJECTINFOCLASS JobObjectInfoClass,
  _Out_     LPVOID             lpJobObjectInfo,
  _In_      DWORD              cbJobObjectInfoLength,
  _Out_opt_ LPDWORD            lpReturnLength
);
 */
typedef ::boost::winapi::BOOL_ (BOOST_WINAPI_WINAPI_CC *query_information_job_object_p)(
        ::boost::winapi::HANDLE_,
        JOBOBJECTINFOCLASS_,
        void *,
        ::boost::winapi::DWORD_,
        ::boost::winapi::DWORD_ *);

inline ::boost::winapi::BOOL_ query_information_job_object(
        ::boost::winapi::HANDLE_ hJob,
        JOBOBJECTINFOCLASS_ JobObjectInfoClass,
        void *lpJobObjectInfo,
        ::boost::winapi::DWORD_ cbJobObjectInfoLength,
        ::boost::winapi::DWORD_ *lpReturnLength)
{
    static ::boost::winapi::HMODULE_ h = ::boost::winapi::get_module_handle(
            L"Kernel32.dll");
    static query_information_job_object_p f = reinterpret_cast<query_information_job_object_p>(::boost::winapi::get_proc_address(
            h, "QueryInformationJobObject"));

    return (*f)(hJob, JobObjectInfoClass, lpJobObjectInfo,
                cbJobObjectInfoLength, lpReturnLength);
}

/*BOOL WINAPI SetInformationJobObject(
  _In_ HANDLE             hJob,
  _In_ JOBOBJECTINFOCLASS JobObjectInfoClass,
  _In_ LPVOID             lpJobObjectInfo,
  _In_ DWORD              cbJobObjectInfoLength
);*/

typedef ::boost::winapi::BOOL_ (BOOST_WINAPI_WINAPI_CC *set_information_job_object_p)(
        ::boost::winapi::HANDLE_,
        JOBOBJECTINFOCLASS_,
        void *,
        ::boost::winapi::DWORD_);

}

inline ::boost::winapi::BOOL_ set_information_job_object(
        ::boost::winapi::HANDLE_ hJob,
        JOBOBJECTINFOCLASS_ JobObjectInfoClass,
        void *lpJobObjectInfo,
        ::boost::winapi::DWORD_ cbJobObjectInfoLength)
{
    static ::boost::winapi::HMODULE_ h = ::boost::winapi::get_module_handle(
            L"Kernel32.dll");
    static set_information_job_object_p f = reinterpret_cast<set_information_job_object_p>(::boost::winapi::get_proc_address(
            h, "SetInformationJobObject"));

    return (*f)(hJob, JobObjectInfoClass, lpJobObjectInfo,
                cbJobObjectInfoLength);
}

#endif

constexpr static ::boost::winapi::DWORD_ JOB_OBJECT_LIMIT_BREAKAWAY_OK_ = 0x00000800;

}}}}}

#endif /* BOOST_PROCESS_DETAIL_WINDOWS_JOB_WORKAROUND_HPP_ */


text:
/* Copyright (C) 2017 IBM Corp.
 *  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.
 */
/*****************************************************************************
 * GGH15.h - an implementation of the graph-based multilinear maps from
 *           [Gentry-Gorbunov-Halevi, TCC 2015]
 *****************************************************************************/
#include <stdexcept>
#include <unistd.h>
#include <sys/stat.h>

#if defined(__unix__) || defined(__unix) || defined(unix)
#include <sys/time.h>
#include <sys/resource.h>
#endif

#include <NTL/BasicThreadPool.h>

#include "mat_l.h"
#include "GGH15.h"
#include "utils/tools.h"

bool bGGH15threading=1;

//#define DEBUGPRINT
//#define PRINTDOT
#ifdef PRINTDOT
#define printDot cerr << "." << std::flush
#else
#define printDot
#endif

// A lower bound on |q|/2^10 for an L-edge chain. We need to bound the size
// of a product of L matrices of dim m-by-m, where L-1 have entries drawn
// with parameter sqrt{sigmaX) and one has entries with parameter sec.
// The formula we use is q/2^10 > largest-singular-val(product), which
// translates to
//    q/2^10 > (2*sqrt(m)*sqrt(sigmaX))^{L-1} * lambda*sqrt(m+n)
//      \approx lambda * sigmaX^{(L-1)/2} * m^{L/2} * 2^L
long qBound(long sigmaX, long m, long L)
{
  // cerr << "@ L="<<L<<", sigmaX="<<sigmaX
  //      <<",log_2(sqrt(sigmaX))="<<(log(sigmaX)/(log(2)*2))
  //      <<", log_2(m)="<<(log(m)/log(2)) << endl;

  double logQ = ((L-1)*log(sigmaX) + L*log(m))/2.0;
  return ceil(logQ/log(2.0)) + L + 16;
}

// Computing basic parameters for length-'diam' MMAPs. In particular,
// assuming that "fresh" sampled encodings use "varince" sigmaX, we need
// to ensure that
//  (a) log q > qBound(sigmaX, m, L, sec)      (qBound from above)
//  (b)     m > mBound(log q, errBits=7, sec)  (mBound from TDMatrixParams)
//
// Since the size of q is determined by the number of small factors, i.e.,
// q = \prod_{i=0}^{k-1} p_i^e, we just try to find the smallest k for which
// the above constraints are satisfied.
//
// In addition, we also need to ensure that m >= n*k*e + mBar, where
// n = nStates + ceil(sqrt(sec)/2) and mBar = mbarBound(log q, n, sec)
// (from TDMatrixParams).

GGH15basicParams::GGH15basicParams(COMP_PARAMS_TYPE comp, //=COMP_GGH15PRMS
                                   long nStates, long L, long sec, long ee)
{
    FHE_TIMER_START;

    e = ee;
    n = nStates + ceil(sqrt(sec)/2);

    // k will never be smaller than L
    for (k=L; k<TDMATRIX_NUM_SMALL_FACTORS; k++) {
      long qBits = get_qBits(k, e);
      m = mBound(qBits, /*errBits=*/7, sec);

      long mBar = mbarBound(qBits, n, sec);
      long wLen = n*k*e;
      if (m < mBar+wLen) m = mBar+wLen;
      else               mBar = m-wLen;

      long sigmaX = getsigmaXVal(wLen, mBar, /*maxFactor=*/181);
      long qbound = qBound(sigmaX,m,L);

      if (qBits >= qbound) // all constraints are satisfied
	break;

      // otherwise we try a larger value of k
    }
    if (k >= TDMATRIX_NUM_SMALL_FACTORS) { // could not find a solution
      throw std::logic_error("Cannot set GGH15 parameters");
    }
}

// Initialize a single node, choose A w/ trapdoor and T, Tinv
void GGH15node::initGGH15node(TDMatrixParams& prms, long idx)
{
    #ifdef DEBUGPRINT
        fprintf(stderr,"initGGH15node %s %d\n", __FILE__, __LINE__);
    #endif // DEBUGPRINT

    FHE_TIMER_START;
    index = idx;
    params = &prms;

    A.initTDmatrix(prms); // Choose matrix A with trapdoor

    #ifdef DEBUGPRINT
        fprintf(stderr,"initGGH15node %s %d\n", __FILE__, __LINE__);
    #endif // DEBUGPRINT

    // Choose a small n-by-n matrix P, set Pinv as its inverse mod q
    Pinv.params = &prms;
    do {
      setSmall(P, prms.n, prms.n, /*howSmall=*/prms.maxFactor);
    #ifdef DEBUGPRINT
        fprintf(stderr,"initGGH15node %s %d\n", __FILE__, __LINE__);
    #endif // DEBUGPRINT
    }
    while (!Pinv.invert(P)); // Repeat until you get an invertible P mod q

    #ifdef DEBUGPRINT
        fprintf(stderr,"initGGH15node %s %d\n", __FILE__, __LINE__);
    #endif // DEBUGPRINT

    // choose T, Tinv as random inverses of each other mod q
    T.params = Tinv.params = &prms;
    generateMatrixPair(T, Tinv, prms.m);
}

// Initilize an instance with n nodes
GGH15mmaps::GGH15mmaps(TDMatrixParams& p, long n)
{
    FHE_TIMER_START;
    assert (n>0);

    params = &p;

    nodes.SetLength(n-2);

    //the flag allows parallelizing when it is set to false
    NTL_GEXEC_RANGE(!bGGH15threading, n-2, first, last)

    for (long i=first; i< last; i++)
    {
#ifdef DEBUGPRINT
        cout << "initializing node:" << i << endl;
#if (defined(__unix__) || defined(__unix) || defined(unix))
        struct rusage rusage;
        getrusage( RUSAGE_SELF, &rusage );
        cout << "  rusage.ru_maxrss="<<rusage.ru_maxrss << endl;
#endif
#endif // DEBUGPRINT

        nodes[i].initGGH15node(p, i+1);

#ifdef DEBUGPRINT
        cout << "after initializing node:" << i << endl;
#endif // DEBUGPRINT
    }
    NTL_GEXEC_RANGE_END

#ifdef DEBUGPRINT
    cout << "before randomfill:"  << endl;
#endif // DEBUGPRINT

    // The right bracket is a random non-small n-by-1 matrix
    randomFill(An, /*rows=*/p.n, /*cols=*/1, p);

#ifdef DEBUGPRINT
    cout << "after randomfill:"  << endl;
#endif // DEBUGPRINT
}

long GGH15mmaps::writeToFile(FILE* handle)
{
    FHE_TIMER_START;
    long count = params->writeToFile(handle);
    count += An.writeToFile(handle);
    long nNodes = numNodes()-2;
    count += fwrite(&nNodes,sizeof(long),1,handle);
    for (long i = 0; i < nNodes; i++)
    {
        count+= nodes[i].writeToFile(handle);
    }
    return count;
}

long GGH15mmaps::readFromFile(FILE* handle, TDMatrixParams* prmBuf)
{
    FHE_TIMER_START;
    assert(params != NULL || prmBuf != NULL); // some pointer must be provided

    long count=0;

    if (prmBuf != NULL)
    {
        TDMatrixParams p;
        count = p.readFromFile(handle);
        assert(p == *prmBuf); // sanity check
        params = prmBuf;      // point to given params
    }
    else
        count = params->readFromFile(handle); // overwrite params from input

    count += An.readFromFile(handle,params);

    // Read the actual nodes from disk, one at a time

    long nNodes;
    count += fread(&nNodes,sizeof(nNodes),1,handle);

    nodes.SetLength(nNodes);
    for (long i = 0; i < (nNodes); i++)
    {
        count+= nodes[i].readFromFile(handle, params);
    }
    return count;
}

// Write one GGH15 node to output
long GGH15node::writeToActualFile(FILE* handle)
{
    FHE_TIMER_START;
    long count = params->writeToFile(handle);

    count += fwrite(&index, sizeof(index),1, handle);
    count += A.writeToFile(handle);

    count += ::writeToFile(P,handle);
    count += T.writeToFile(handle);
    count += Tinv.writeToFile(handle);
    count += Pinv.writeToFile(handle);

    return count;
}

long GGH15node::readFromFile(FILE* handle, TDMatrixParams* prmBuf)
{
    FHE_TIMER_START;
    assert(params != NULL || prmBuf != NULL); // some pointer must be provided

    long count = 0;
    if (prmBuf != NULL)
    {
        TDMatrixParams p;
        count = p.readFromFile(handle);
        assert(p == *prmBuf); // sanity check
        params = prmBuf;     // point to given params
    }
    else
        count = params->readFromFile(handle); // overwrite params from input

    count += fread(&index, sizeof(index),1, handle);
    count += A.readFromFile(handle, params);

    count += ::readFromFile(P,handle);
    count += T.readFromFile(handle, params);

    count += Tinv.readFromFile(handle, params);
    count += Pinv.readFromFile(handle, params);

    return count;
}

long GGH15encoding::writeToFile(FILE* handle)
{
    FHE_TIMER_START;
    long count = fwrite(&from, sizeof(from),1, handle);
    count += fwrite(&to, sizeof(to),1, handle);

    count += data.writeToFile(handle);

    return count;
}

long GGH15encoding::readFromFile(FILE* handle, TDMatrixParams& prms)
{
    FHE_TIMER_START;
    long count = fread(&from, sizeof(from),1, handle);
    count += fread(&to, sizeof(to),1, handle);
    return count + data.readFromFile(handle, &prms);
}

/*************************************************************/
/** Encding routines: there are four such routines,         **/
/** depending on whether or not i=0 and whether or not j=n. **/
/*************************************************************/

/* GGH15 encoding for 0<i,j<n. Set C = Tinv_i * CC * T_j, where
 * CC satisfies A_i*CC = (Pinv_i*S*P_j)*A_j+E (mod q). We assume
 * that toA was already multiplied by P_j.
 */
static void encodeGGH15(CRTmatrix& C, const mat_l& S,
                        const GGH15node& from, const GGH15node& to,
                        const CRTmatrix& toA)
{
    FHE_TIMER_START;
    const TDMatrixParams* prms = from.getPrms();

    // Set B = (Pinv_i x S x P_j) x A + E

    CRTmatrix B = from.getPinv(); // Pinv_i
    B *= S;                       // Pinv_i x S
    B *= toA;                     // (Pinv_i x S x P_j) x A

    mat_l E;  // Choose a small n-by-m noise matrix E
    setSmall(E, S.NumRows(), toA.NumCols(), /*sigma=*/prms-> r);

    B += E;  // (Pinv_i x S x P_j) x A  + E

    // Sample small C s.t. fromA x CC = B
    mat_l CC(INIT_SIZE, prms->m, B.NumCols());

    #ifdef DEBUGPRINT
        cout << "encoding" << endl;
    #endif
    //NTL_GEXEC_RANGE(!bGGH15threading, B.NumCols(), first, last)
    GEXEC_RANGE(!bGGH15threading, B.NumCols(), first, last)
    for (long j=first; j< last; j++)
    {
        // Sample vector x_j s.t. A*x_j = j'th column of B
        Vec<vec_zz_p> colMod;
        B.getColumn(colMod, j); // The j'th column of B in CRT format

        vec_l sampledColumn;    // this is where we put the vector x_j

        from.getA().sampleWithTrapdoor(sampledColumn, colMod);// sample a column

        for (long i=0; i<CC.NumRows(); i++)                    // store it in CC
            CC[i][j] = sampledColumn[i];
    }
    //NTL_GEXEC_RANGE_END
    GEXEC_RANGE_END(!bGGH15threading)

    // Compute C = Tinv_i * CC * T_j
    C = from.getTinv();
    C *= CC;
    C *= to.getT();
}
//------------------------------------------------------------------//

/* GGH15 encoding for i=0<j<n. Set C =(S*P_j*A_j +E) *T_j (mod q).
 * We assume that toA it was already multiplied by P_j.
 */
static void encodeGGH15first(CRTmatrix& C, const mat_l& S,
                             const GGH15node& to, const CRTmatrix& toA)
{
    FHE_TIMER_START;
    const TDMatrixParams* prms = to.getPrms();

    // Set C = S x P_j x A + E
    const mat_l& tmpS = S;

    mat_l E;  // Choose a small 1-by-m noise matrix E
    setSmall(E, tmpS.NumRows(), toA.NumCols(), /*sigma=*/prms->r);

    C = toA;            // P_j x A
    C.leftMultBy(tmpS); // S x P_j x A
    C += E;             // S x P_j x A + E

    C *= to.getT();
}
//------------------------------------------------------------------//

/* GGH15 encoding for 0<i<j=n. Set C = Tinv_i * CC, where CC
 * satisfies A_i*CC = (Pinv_i*S)*A_n + E (mod q).
 */
static void encodeGGH15last(CRTmatrix& C, const mat_l& S,
                            const GGH15node& from, const CRTmatrix& toA)
{
    FHE_TIMER_START;
    const TDMatrixParams* prms = from.getPrms();

    // Set B = (Pinv_i x S) x A_n + E

    CRTmatrix B = from.getPinv(); // Pinv_i
    B *= S;                       // Pinv_i x S
    B *= toA;                     // Pinv_i x S x A_n

    mat_l E;  // Choose a small n-by-m noise matrix E
    setSmall(E, B.NumRows(), B.NumCols(), /*sigma=*/prms->r);

    B += E;                       // Pinv_i x S x A_n + E

    // Sample small CC s.t. fromA x CC = B
    mat_l CC(INIT_SIZE, prms->m, B.NumCols());
    for (long j=0; j<B.NumCols(); j++)
    {
        // Sample vector x_j s.t. A*x_j = j'th column of B

        Vec<vec_zz_p> colMod;
        B.getColumn(colMod, j); // The j'th column of B in CRT format

        vec_l sampledColumn;    // this is where we put the vector x_j

        from.getA().sampleWithTrapdoor(sampledColumn, colMod);// sample a column
        for (long i=0; i<CC.NumRows(); i++)                    // store it in CC
            CC[i][j] = sampledColumn[i];
    }

    // Compute C = Tinv_i * CC
    C = from.getTinv();
    C *= CC;
}
//------------------------------------------------------------------//

/* GGH15 encoding for i=0<j=n, set C =(S*A_n +E) (mod q).
 */
static void encodeGGH15_0_n(CRTmatrix& C, const mat_l& S, const CRTmatrix& toA)
{
    FHE_TIMER_START;
    const mat_l& tmpS = S;

    C = toA;            // A_n
    C.leftMultBy(tmpS); // u x S x A

    mat_l E;  // Choose a small 1-by-m noise matrix E
    setSmall(E, tmpS.NumRows(), toA.NumCols(), /*sigma=*/toA.params->r);

    C += E;             // u x S x A + E
}

bool encodeMatrix(const std::string& dirName, GGH15encoding& C, const mat_l& S,
		  long i, long j, GGH15node* iNode, GGH15node* jNode,
		  CRTmatrix& An, TaggedCRTmatrix* toAptr,
		  TDMatrixParams *params, int nNodes)

{
#ifdef DEBUGPRINT
    cout << "begin encode matrix" << endl;
#endif // DEBUGPRINT

    FHE_TIMER_START;

    #ifdef DEBUGPRINT
        cout << "j=" << ToString(j) << endl;
    #endif

    // FIXME: should we enforce i<j ??
    assert(i>=0 && i<nNodes-1);
    assert(j>0  && j<nNodes);

    // Get the destination matrix A in explicit CRT form
    TaggedCRTmatrix toA(params);
    if (toAptr==NULL) toAptr = &toA;

    bool isLast = (nNodes-1 == j);

#ifdef DEBUGPRINT
    cout << "after reading jNode" << endl;
    //getcwd(cwd, sizeof(cwd));
    //cout << "read node info, current directory = " << cwd << endl;
#endif

    // If the caller did not supply a good toA, then compute it now
    if (toAptr->tag != j && !isLast)   // If target is NOT the last node
    {
        jNode->getCRTA(toAptr->data);
        toAptr->data.leftMultBy( jNode->getP() ); // set toA = P_j x A_j
        toAptr->tag = j;
    }

    // Do the actual encoding
    C.setFrom(i);
    C.setTo(j);
    printDot;
    if (i == 0)    // encoding wrt 0 -> ...
    {
      if (isLast)  // encoding wrt 0 -> n
      {
#ifdef DEBUGPRINT
	cout << "encoding encodeGGH15_0_n" << endl;
#endif
	encodeGGH15_0_n(C.getData(), S, An);
      }
      else         // encoding wrt 0 -> j<n
      {
#ifdef DEBUGPRINT
	cout << "encoding first" << endl;
#endif
	encodeGGH15first(C.getData(), S, *jNode, toAptr->data);
      }
    }
    else           // encoding wrt 0<i -> ...
    {

      if (isLast)  // encoding wrt 0<i -> n
      {
#ifdef DEBUGPRINT
	cout << "Encoding last" << endl;
#endif
	encodeGGH15last(C.getData(), S, *iNode, An);
      }
      else         // encoding wrt 0<i -> j<n
      {
	encodeGGH15(C.getData(), S, *iNode, *jNode, toAptr->data);
      }
    }
    return true;
}

bool readEncodeMatrix(const std::string& dirName, GGH15encoding& C, const mat_l& S, long i, long j,
                  TaggedCRTmatrix* toAptr, TDMatrixParams *params, int nNodes)
{
#ifdef DEBUGPRINT
    cout << "begin encode matrix" << endl;
#endif // DEBUGPRINT

    FHE_TIMER_START;
    // FIXME: should we enforce i<j ??
    assert(i>=0 && i<nNodes-1);
    assert(j>0  && j<nNodes);

    // Get the destination matrix A in explicit CRT form
    TaggedCRTmatrix toA(params);
    if (toAptr==NULL) toAptr = &toA;

    bool isLast = (nNodes-1 == j);

    GGH15node jNode, iNode;

#ifdef DEBUGPRINT
    char cwd[1024];
    getcwd(cwd, sizeof(cwd));
    cout << "read node info, current directory = " << cwd << endl;
    cout << "reading jNode" << endl;
#endif

//  load the correct node
    std::string fileName = "node"+ToString(j)+ ".dat";
    FILE* handle = fopen(fileName.c_str(), "rb");
    if (handle != 0)
    {
        jNode.readFromFile(handle, params);
        fclose(handle);
    }

#ifdef DEBUGPRINT
    cout << "after reading jNode" << endl;
    getcwd(cwd, sizeof(cwd));
    cout << "read node info, current directory = " << cwd << endl;
#endif
    //load An
    CRTmatrix An;// The An matrix (actually n-by-1 "matrix")
    fileName = "nAn.dat";
    handle = fopen(fileName.c_str(), "rb");
    if (handle != 0)
    {
        long n;
        long count = fread(&n, sizeof(n),1, handle);
        count+=An.readFromFile(handle, params);
        fclose(handle);
    }
    else NTL::Error("Cannot read An");

    // If the caller did not supply a good toA, then compute it now
    if (toAptr->tag != j && !isLast)   // If target is NOT the last node
    {
        jNode.getCRTA(toAptr->data);
        toAptr->data.leftMultBy( jNode.getP() ); // set toA = P_j x A_j
        toAptr->tag = j;
    }

    // Do the actual encoding
    C.setFrom(i);
    C.setTo(j);
    printDot;
    if (i == 0)    // encoding wrt 0 -> ...
    {
      if (isLast)  // encoding wrt 0 -> n
      {
#ifdef DEBUGPRINT
	cout << "encoding encodeGGH15_0_n" << endl;
#endif
	encodeGGH15_0_n(C.getData(), S, An);
      }
      else         // encoding wrt 0 -> j<n
      {
#ifdef DEBUGPRINT
	cout << "encoding first" << endl;
#endif
	encodeGGH15first(C.getData(), S, jNode, toAptr->data);
      }
    }
    else           // encoding wrt 0<i -> ...
    {
      //get iNode - we are already in the correct directory
      fileName = "node"+ToString(i)+ ".dat";
      handle = fopen(fileName.c_str(), "rb");
      if (handle != 0)
      {
	iNode.readFromFile(handle , params);
	fclose(handle);
      }
      if (isLast)  // encoding wrt 0<i -> n
      {
#ifdef DEBUGPRINT
	cout << "Encoding last" << endl;
#endif
	encodeGGH15last(C.getData(), S, iNode, An);
      }
      else         // encoding wrt 0<i -> j<n
      {
	encodeGGH15(C.getData(), S, iNode, jNode, toAptr->data);
      }
    }
    return true;
}

// Encode plaintext matrix wrt the path i -> j. The toAptr argument is
// an optimization:
//  + If toAptr is non-NULL and toAptr->tag==j, then it is assumed
//    that to toAptr->data is the matrx P_j x A_j.
//  + If toAptr is non-NULL and toAptr->tag!=j, then toA->data is set
//    P_j x A_j and toAptr->tag is set to j.
bool GGH15mmaps::encode(GGH15encoding& C, const mat_l& S, long i, long j,
                        TaggedCRTmatrix* toAptr)
{
    FHE_TIMER_START;
    // FIXME: should we enforce i<j ??
    assert(i>=0 && i<numNodes()-1);
    assert(j>0  && j<numNodes());

    // Get the destination matrix A in explicit CRT form
    TaggedCRTmatrix toA(params);
    if (toAptr==NULL) toAptr = &toA;

    bool isLast = (numNodes()-1 == j);

    // If the caller did not supply a good toA, then compute it now
    if (toAptr->tag != j && !isLast)   // If target is NOT the last node
    {
        nodes[j-1].getCRTA(toAptr->data);
        toAptr->data.leftMultBy( nodes[j-1].getP() ); // set toA = P_j x A_j
        toAptr->tag = j;
    }

    // Do the actual encoding
    C.from = i;
    C.to = j;

    printDot;
    if (i == 0)    // encoding wrt 0 -> ...
    {
        if (isLast)  // encoding wrt 0 -> n
            encodeGGH15_0_n(C.data, S, An);

        else         // encoding wrt 0 -> j<n
            encodeGGH15first(C.data, S, nodes[j-1], toAptr->data);
    }
    else           // encoding wrt 0<i -> ...
    {

        if (isLast)  // encoding wrt 0<i -> n
            encodeGGH15last(C.data, S, nodes[i-1], An);

        else         // encoding wrt 0<i -> j<n
            encodeGGH15(C.data, S, nodes[i-1], nodes[j-1], toAptr->data);

    }
    return true;
}

// A debugging method to check that an encoding was done right
bool GGH15mmaps::verifyEncoding(const GGH15encoding& C,	const mat_l& S) const
{
    FHE_TIMER_START;
    long i = C.fromNode();
    long j = C.toNode();

    CRTmatrix CC(params), SS(params), toA(params), fromA(params);
    if (i!=0)
    {
        nodes[i-1].getCRTA(fromA);

        if (j!=(numNodes()-1))   // 0<i -> j<n
        {
            nodes[j-1].getCRTA(toA);

            CC = nodes[i-1].getT();
            CC *= C.data;
            CC *= nodes[j-1].getTinv();

            SS = nodes[i-1].getPinv();
            SS *= S;
            SS *= nodes[j-1].getP();
        }
        else                 // 0<i -> j=n
        {
            toA = An;

            CC = nodes[i-1].getT();
            CC *= C.data;

            SS = nodes[i-1].getPinv();
            SS *= S;
        }
    }
    else // i==0
    {
        if (j!=(numNodes()-1))   // 0=i -> j<n
        {
            nodes[j-1].getCRTA(toA);

            CC = C.data;
            CC *= nodes[j-1].getTinv();

            SS = nodes[j-1].getP();
            SS.leftMultBy(S);
        }
        else                 // 0=i -> j=n
        {
            toA = An;
            CC = C.data;
            SS = S;
        }
    }

    if (i>0)   // Check that CC and EE = fromA*CC - SS*toA are small
    {
        fromA *= CC;
        SS *= toA;
        fromA -= SS;
        return (CC.isSmall() && fromA.isSmall());
    }
    else   // Check that EE = CC - SS*toA is small
    {
        SS *= toA;
        CC -= SS;
        return CC.isSmall();
    }
}

bool operator==(const GGH15mmaps& A, const GGH15mmaps& B)
{
    FHE_TIMER_START;

    if (A.getParams()!=B.getParams())
        return false;

    if (A.numNodes()!=B.numNodes())
        return false;

    for (long iNode = 0; iNode < (A.numNodes()-2); iNode++)
    {
        if (A.getNode(iNode)!=B.getNode(iNode))
            return false;
    }

    if (A.getAn()!=B.getAn())
        return false;

    return true;
}

// checks whether two nodes are identical, i.e., have the exact same
// variable values in them. if so, returns true.

bool operator==(const GGH15node& A, const GGH15node& B)
{
    if (A.getIndex()!=B.getIndex())
        return false;
    if (A.getPrms()!=B.getPrms())
        return false;
    if (A.getA()!=B.getA())
        return false;
    if (A.getP()!=B.getP())
        return false;
    if (A.getPinv()!=B.getPinv())
        return false;
    if (A.getT()!=B.getT())
        return false;
    if (A.getTinv()!=B.getTinv())
        return false;

    return true;
}

max_stars_repo_name: shaih/BPobfus

max_issues_repo_name: shaih/BPobfus

max_forks_repo_name: shaih/BPobfus


text:
//
// Expansion Hunter
// Copyright 2016-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Xiao Chen <xchen2@illumina.com>
//         Egor Dolzhenko <edolzhenko@illumina.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#include "genotyping/CopyNumberGenotyper.hh"
#include <boost/math/distributions/normal.hpp>
#include <math.h>
#include <numeric>

using boost::optional;
using boost::math::normal_distribution;
using std::vector;

namespace ehunter
{

CopyNumberGenotyper::CopyNumberGenotyper(
    int maxCopyNumber, double depthScaleFactor, double standardDeviationOfCN2,
    const std::vector<double>& meanDepthValues, const std::vector<double>& priorCopyNumberFreq)
    : maxCopyNumber_(maxCopyNumber)
    , depthScaleFactor_(depthScaleFactor)
    , standardDeviationOfCN2_(standardDeviationOfCN2)
    , meanDepthValues_(meanDepthValues)
    , priorCopyNumberFreq_(priorCopyNumberFreq)
{
    if (maxCopyNumber_ + 1 != static_cast<int>(meanDepthValues_.size()))
    {
        throw std::runtime_error("Number of mean values is inconsistent with total copy number states.");
    }

    if (maxCopyNumber_ + 1 != static_cast<int>(priorCopyNumberFreq_.size()))
    {
        throw std::runtime_error("Number of prior frequencies is inconsistent with total copy number states.");
    }
}

boost::optional<int> CopyNumberGenotyper::genotype(double normalizedDepth) const
{
    const double adjustedDepth = normalizedDepth / depthScaleFactor_;
    std::vector<double> likelihoodOfAllCN;
    std::vector<double> pvalueOfAllCN;

    for (int currentGenotype = 0; currentGenotype != maxCopyNumber_ + 1; currentGenotype++)
    {
        std::pair<double, double> likelihoodAndPvalue = genotypeLikelihoodAndPvalue(currentGenotype, adjustedDepth);
        double currentLikelihood = likelihoodAndPvalue.first;
        double currentPvalue = likelihoodAndPvalue.second;
        likelihoodOfAllCN.emplace_back(currentLikelihood);
        pvalueOfAllCN.emplace_back(currentPvalue);
    }

    const std::pair<int, double> bestGenotypeAndPosterior = getBestGenotypeAndPosterior(likelihoodOfAllCN);
    const int bestGenotype = bestGenotypeAndPosterior.first;
    const double posteriorProbabilityOfBestGenotype = bestGenotypeAndPosterior.second;
    const bool posteriorCheck = posteriorProbabilityOfBestGenotype > posteriorProbabilityThreshold_;
    const bool pvalueCheck = pvalueOfAllCN[bestGenotype] > pvalueThreshold_;
    const optional<int> genotype = (posteriorCheck && pvalueCheck) ? bestGenotype : optional<int>();
    return genotype;
}

std::pair<int, double>
CopyNumberGenotyper::getBestGenotypeAndPosterior(const std::vector<double>& likelihoodOfAllCN) const
{
    double sumOfLikelihood = 0;
    for (double likelihoodValue : likelihoodOfAllCN)
    {
        sumOfLikelihood += likelihoodValue;
    }

    assert(!likelihoodOfAllCN.empty());
    auto maxElement = max_element(likelihoodOfAllCN.begin(), likelihoodOfAllCN.end());
    const double maxLikelihood = *maxElement;
    std::pair<int, double> bestGenotypeAndPosterior;
    bestGenotypeAndPosterior.first = distance(likelihoodOfAllCN.begin(), maxElement);
    bestGenotypeAndPosterior.second = maxLikelihood / sumOfLikelihood;

    return bestGenotypeAndPosterior;
}

std::pair<double, double>
CopyNumberGenotyper::genotypeLikelihoodAndPvalue(int currentGenotype, double adjustedDepth) const
{
    assert(currentGenotype < (int)meanDepthValues_.size());
    assert(currentGenotype < (int)priorCopyNumberFreq_.size());

    const double meanValue = meanDepthValues_[currentGenotype];
    // standard deviation for each CN state can be computed from CN2 except for CN0 it is pre-defined
    const double standardDeviation
        = currentGenotype == 0 ? standardDeviationOfCN0_ : standardDeviationOfCN2_ * sqrt(double(currentGenotype) / 2);
    const double priorFreq = priorCopyNumberFreq_[currentGenotype];

    const normal_distribution<> cnDistribution(meanValue, standardDeviation);
    const double genotypeLikelihood = priorFreq * pdf(cnDistribution, adjustedDepth);
    const double cumulativeFrequency = cdf(cnDistribution, adjustedDepth);
    const double pvalue = std::min(cumulativeFrequency, 1 - cumulativeFrequency);

    std::pair<double, double> likelihoodAndPvalue;
    likelihoodAndPvalue.first = genotypeLikelihood;
    likelihoodAndPvalue.second = pvalue;

    return likelihoodAndPvalue;
}
}

max_stars_repo_name: AlesMaver/ExpansionHunter

max_issues_repo_name: AlesMaver/ExpansionHunter

max_forks_repo_name: AlesMaver/ExpansionHunter