text:
// 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)

// Copyright (c) 2006 Johan Rade
// Copyright (c) 2011 Paul A. Bristow

/*!
\file
\brief Tests of nonfinite signaling NaN loopback.

\detail  nonfinite signaling NaN
test outputs using nonfinite facets
(output and input) and reads back in, and checks if loopback OK.

Not expected to work on all platforms (if any).  But shows that on MSVC,
this legacy locale can ensure a consistent quiet NaN input from representations
"1.#QNAN", "1.#SNAN" and "1.#IND"

*/

#ifdef _MSC_VER
#   pragma warning(disable : 4702)
#endif

#include <boost/math/special_functions/nonfinite_num_facets.hpp>
using boost::math::nonfinite_num_get;
using boost::math::nonfinite_num_put;

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

#include <locale>
using std::locale;

#include <string>
using std::string;

#include <sstream>
  using std::stringstream;
  using std::istringstream;

#include <limits>
using std::numeric_limits;

int main()
{
    if((std::numeric_limits<double>::has_infinity == false) || (std::numeric_limits<double>::infinity() == 0))
  {
    std::cout << "Infinity not supported on this platform." << std::endl;
    return 0;
  }

  if((std::numeric_limits<double>::has_quiet_NaN == false) || (std::numeric_limits<double>::quiet_NaN() == 0))
  {
    std::cout << "NaN not supported on this platform." << std::endl;
    return 0;
  }

  locale default_locale; // Current global locale.
  // Try to use the default locale first.
  // On MSVC this doesn't work.

  { // Try Quiet NaN
    stringstream ss; // Both input and output.
    ss.imbue(default_locale); // Redundant, of course.
    string infs;
    if(numeric_limits<double>::has_quiet_NaN)
    {  // Make sure quiet NaN is specialised for type double.
      double qnan = numeric_limits<double>::quiet_NaN();
      ss << qnan; // Output quiet_NaN.
      infs = ss.str();  //
    }
    else
    { // Need to provide a suitable string for quiet NaN.
     infs =  "1.#QNAN";
      ss << infs;
    }
    double r;
    ss >> r; // Read back in.

    cout << "quiet_NaN output was " << infs << endl; // "1.#QNAN"
    cout << "quiet_NaN input was " << r << endl; // "1"
  }

#if (!defined __BORLANDC__ && !defined __CODEGEARC__)
  // These compilers trap when trying to create a signaling_NaN!
  { // Try Signaling NaN
    stringstream ss; // Both input and output.
    ss.imbue(default_locale); // Redundant, of course.
    string infs;
    if(numeric_limits<double>::has_signaling_NaN)
    {  // Make sure signaling NaN is specialised for type double.
      double qnan = numeric_limits<double>::signaling_NaN();
      ss << qnan; // Output signaling_NaN.
      infs = ss.str();  //
    }
    else
    { // Need to provide a suitable string for signaling NaN.
     infs =  "1.#SNAN";
      ss << infs;
    }
    double r;
    ss >> r; // Read back in.

    cout << "signaling_NaN output was " << infs << endl; // "1.#QNAN" (or "1.#SNAN"?)
    cout << "signaling_NaN input was " << r << endl; // "1"
  }
#endif // Not Borland or CodeGear.

  // Create legacy_locale and store the nonfinite_num_get facet (with legacy flag) in it.
  locale legacy_locale(default_locale, new nonfinite_num_get<char>(boost::math::legacy));
  // Note that the legacy flag has no effect on the nonfinite_num_put output facet.

  cout << "Use legacy locale." << endl;

  { // Try infinity.
    stringstream ss; // Both input and output.
    ss.imbue(legacy_locale);
    string infs;
    if(numeric_limits<double>::has_infinity)
    {  // Make sure infinity is specialised for type double.
      double inf = numeric_limits<double>::infinity();
      ss << inf; // Output infinity.
      infs = ss.str();  //
    }
    else
    { // Need to provide a suitable string for infinity.
     infs =  "1.#INF";
      ss << infs;
    }
    double r;
    ss >> r; // Read back in.

    cout << "infinity output was " << infs << endl; // "1.#INF"
    cout << "infinity input was " << r << endl; // "1.#INF"
  }

  { // Try input of "1.#SNAN".
    //double inf = numeric_limits<double>::signaling_NaN(); // Assigns "1.#QNAN" on MSVC.
    // So must use explicit string "1.#SNAN" instead.
    stringstream ss; // Both input and output.
    ss.imbue(legacy_locale);
    string s = "1.#SNAN";

    ss << s; // Write out.
    double r;

    ss >> r; // Read back in.

    cout << "SNAN output was " << s << endl; // "1.#SNAN"
    cout << "SNAN input was " << r << endl;  // "1.#QNAN"
  }

  { // Try input of "1.#IND" .
    stringstream ss; // Both input and output.
    ss.imbue(legacy_locale);
    string s = "1.#IND";
    ss << s; // Write out.
    double r;
    ss >> r; // Read back in.

    cout << "IND output was " << s << endl; // "1.#IND"
    cout << "IND input was " << r << endl;  // "1.#QNAN"
  }

} // int main()

/*

Output:
  nonfinite_signaling_NaN.vcxproj -> J:\Cpp\fp_facet\fp_facet\Debug\nonfinite_signaling_NaN.exe

  quiet_NaN output was 1.#QNAN
  quiet_NaN input was 1
  signaling_NaN output was 1.#QNAN
  signaling_NaN input was 1
  Use legacy locale.
  infinity output was 1.#INF
  infinity input was 1.#INF
  SNAN output was 1.#SNAN
  SNAN input was 1.#QNAN
  IND output was 1.#IND
  IND input was 1.#QNAN

*/

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text: #include <boost/preprocessor/seq/pop_front.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * GraphBLAS Template Library (GBTL), Version 3.0
 *
 * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and
 * Authors.
 *
 * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF
 * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE
 * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF
 * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR
 * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE
 * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
 * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,
 * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS
 * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED
 * RIGHTS.
 *
 * Released under a BSD-style license, please see LICENSE file or contact
 * permission@sei.cmu.edu for full terms.
 *
 * [DISTRIBUTION STATEMENT A] This material has been approved for public release
 * and unlimited distribution.  Please see Copyright notice for non-US
 * Government use and distribution.
 *
 * This Software includes and/or makes use of the following Third-Party Software
 * subject to its own license:
 *
 * 1. Boost Unit Test Framework
 * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)
 * Copyright 2001 Boost software license, Gennadiy Rozental.
 *
 * DM20-0442
 */

#include <iostream>

#include <graphblas/graphblas.hpp>

using namespace grb;

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE matrix_methods_test_suite

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

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)

//****************************************************************************
BOOST_AUTO_TEST_CASE(matrix_resize_test)
{
    IndexArrayType      i = {1, 2, 3, 4};
    std::vector<double> v = {1, 2, 3, 4};

    // matrix = diag{ -, 1, 2, 3, 4, -};

    IndexType const NSIZE = 6;
    Matrix<double> m1(NSIZE, NSIZE);
    m1.build(i, i, v);
    //print_matrix(std::cerr, m1, "m1(6,6)");

    BOOST_CHECK_EQUAL(m1.nvals(), i.size());
    BOOST_CHECK_EQUAL(m1.nrows(), NSIZE);
    BOOST_CHECK_EQUAL(m1.ncols(), NSIZE);

    // Make it bigger and set an element
    m1.resize(2*NSIZE, 2*NSIZE);
    //print_matrix(std::cerr, m1, "m1(12,12)");
    BOOST_CHECK_EQUAL(m1.nvals(), i.size());
    BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE);
    BOOST_CHECK_EQUAL(m1.ncols(), 2*NSIZE);

    m1.setElement(NSIZE + 1, NSIZE + 1, 99);

    BOOST_CHECK_EQUAL(m1.nvals(), i.size() + 1);
    BOOST_CHECK_EQUAL(m1.extractElement(NSIZE + 1, NSIZE + 1), 99);

    // Reduce num columns check remaining elements
    m1.resize(2*NSIZE, 4UL);
    //print_matrix(std::cerr, m1, "m1(12, 4)");
    BOOST_CHECK_EQUAL(m1.nvals(), 3);
    BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE);
    BOOST_CHECK_EQUAL(m1.ncols(), 4);
    BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1);
    BOOST_CHECK_EQUAL(m1.extractElement(2, 2), 2);
    BOOST_CHECK_EQUAL(m1.extractElement(3, 3), 3);

    // Reduce num rows check remaining elements
    m1.resize(3UL, 4UL);
    //print_matrix(std::cerr, m1, "m1(3, 4)");
    BOOST_CHECK_EQUAL(m1.nvals(), 2);
    BOOST_CHECK_EQUAL(m1.nrows(), 3);
    BOOST_CHECK_EQUAL(m1.ncols(), 4);
    BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1);
    BOOST_CHECK_EQUAL(m1.extractElement(2, 2), 2);

    // reduce both and check remaining elements
    m1.resize(2UL, 2UL);
    //print_matrix(std::cerr, m1, "m1(2,2)");
    BOOST_CHECK_EQUAL(m1.nvals(), 1);
    BOOST_CHECK_EQUAL(m1.nrows(), 2);
    BOOST_CHECK_EQUAL(m1.ncols(), 2);
    BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1);

    // Make it bigger show that elements don't reappear
    m1.resize(2*NSIZE, 2*NSIZE);
    //print_matrix(std::cerr, m1, "m1(12,12)");
    BOOST_CHECK_EQUAL(m1.nvals(), 1);
    BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE);
    BOOST_CHECK_EQUAL(m1.ncols(), 2*NSIZE);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(matrix_removeElement_test)
{
    IndexArrayType      i = {0, 0, 0, 1, 1, 1, 2, 2};
    IndexArrayType      j = {1, 2, 3, 0, 2, 3, 0, 1};
    std::vector<double> v = {1, 2, 3, 4, 6, 7, 8, 9};

    //std::vector<std::vector<double> > mat = {{0, 1, 2, 3},
    //                                         {4, 0, 6, 7},
    //                                         {8, 9, 0, 0}};

    Matrix<double, DirectedMatrixTag> m1(3, 4);
    m1.build(i, j, v);

    BOOST_CHECK_EQUAL(m1.nvals(), i.size());

    // remove something that does not exist
    BOOST_CHECK(!m1.hasElement(1, 1));
    m1.removeElement(1, 1);
    BOOST_CHECK_EQUAL(m1.nvals(), i.size());
    BOOST_CHECK(!m1.hasElement(1, 1));

    // remove something that exists
    BOOST_CHECK(m1.hasElement(1, 2));
    m1.removeElement(1, 2);
    BOOST_CHECK_EQUAL(m1.nvals(), i.size() - 1);
    BOOST_CHECK(!m1.hasElement(1, 2));
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: KIwabuchi/gbtl

max_issues_repo_name: KIwabuchi/gbtl

max_forks_repo_name: KIwabuchi/gbtl


text:
/*
 * LicenseReader.cpp
 *
 *  Created on: Mar 30, 2014
 *
 */

#ifdef _WIN32
# pragma warning(disable: 4786)
#else
# include <unistd.h>
#endif
#include <cstring>
#include <ctime>
#include <vector>
#include <iostream>
#include <iterator>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include "pc-identifiers.h"
#include "LicenseReader.h"
#include "base/StringUtils.h"
#include "base/logger.h"
#include "public-key.h"
#include <build_properties.h>
#include "ini/SimpleIni.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include<fstream>

namespace license {

const char *FullLicenseInfo::UNUSED_TIME = "0000-00-00";

FullLicenseInfo::FullLicenseInfo(const string& source, const string& product,const string& license_signature, int licenseVersion, string from_date,
string to_date,const string& client_signature,const string& server_signature,	unsigned int from_sw_version, unsigned int to_sw_version,const string& extra_data,bool has_use_limit,double use_limit,double  usage_remain) :source(source),product(product), license_signature(license_signature), server_signature(server_signature), license_version(licenseVersion), //
		from_date(from_date), to_date(to_date), //
		has_expiry(to_date != UNUSED_TIME), // todo uncomment if necessery
	client_signature(client_signature), has_client_sig(client_signature.length() > 0), //
		from_sw_version(from_sw_version), to_sw_version(to_sw_version), //
		has_versions(from_sw_version != UNUSED_SOFTWARE_VERSION|| to_sw_version != UNUSED_SOFTWARE_VERSION), //
		extra_data(extra_data), //
		has_use_limit(use_limit != 0),//
		use_limit(use_limit),//
		usage_remain(usage_remain){
}

FullLicenseInfo::FullLicenseInfo(){
}

EventRegistry FullLicenseInfo::validate(int sw_version) {
	EventRegistry er;
#ifndef CLIENT_
	os_initialize();
	FUNCTION_RETURN sigVer = verifySignature(printForSign().c_str(),license_signature.c_str());
	bool sigVerified = sigVer == FUNC_RET_OK;
	if (sigVerified) {
		er.addEvent(LICENSE_VERIFIED, SVRT_INFO);
	} else {
		er.addEvent(LICENSE_CORRUPTED, SVRT_ERROR);
		cout<<expires_on()<<"LICENSE_CORRUPTED!!!!"<<endl;
	}
#endif
	if (has_expiry) {
		time_t now = time(NULL);
		if (expires_on() < now) {
			er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR, "");
			cout<<__LINE__<<expires_on()<<"time limit has been exceed!!!!"<<endl;
		}
		if (valid_from() > now) {
			er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR);
			cout<<__LINE__<<valid_from()<<"time limit has been exceed!!!!"<<endl;
		}
	}
	if (has_client_sig) {
		PcSignature str_code;
		strncpy(str_code, client_signature.c_str(), sizeof(str_code));
		EVENT_TYPE event = validate_pc_signature(str_code);
		if (event != LICENSE_OK) {
			er.addEvent(event, SVRT_ERROR);
		}
	}
	if(has_use_limit){
		if(use_limit<=usage_remain){
			cout<<"remainning usage limit has been exceed!!!!"<<use_limit<<"|"<<usage_remain<<endl;
			er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR);
		}
	}
	return er;
}

void FullLicenseInfo::toLicenseInfo(LicenseInfo* license) const {
	if (license != NULL) {
		strncpy(license->proprietary_data, extra_data.c_str(),
		PROPRIETARY_DATA_SIZE);

		license->linked_to_pc = has_client_sig;

		license->has_expiry = has_expiry;
		if (!has_expiry) {
			license->expiry_date[0] = '\0';
			license->days_left = 999999;
		} else {
			strncpy(license->expiry_date, to_date.c_str(), 11);
			double secs = difftime(time(NULL),
					seconds_from_epoch(to_date.c_str()));
			license->days_left = (int) secs / 60 * 60 * 24;
		}
		license->use_limit=use_limit;
		license->usage_remain=usage_remain;

	}
}

LicenseReader::LicenseReader(const LicenseLocation& licenseLocation) :
		licenseLocation(licenseLocation) {

}

EventRegistry LicenseReader::readLicenses(const string &product,
		vector<FullLicenseInfo>& licenseInfoOut) {
	vector<string> diskFiles;
	EventRegistry result = getLicenseDiskFiles(diskFiles);
	if (!result.isGood()) {
		return result;
	}
	bool loadAtLeastOneFile = false;
	bool atLeastOneProductLicensed = false;
	bool atLeastOneLicenseComplete = false;
	CSimpleIniA ini;
	for (auto it = diskFiles.begin(); it != diskFiles.end(); it++) {
		ini.Reset();
		SI_Error rc = ini.LoadFile((*it).c_str());
		if (rc < 0) {
			result.addEvent(FILE_FORMAT_NOT_RECOGNIZED, SVRT_WARN, *it);
			continue;
		} else {
			loadAtLeastOneFile = true;
		}
		const char* productNamePtr = product.c_str();
		int sectionSize = ini.GetSectionSize(productNamePtr);
		if (sectionSize <= 0) {
			result.addEvent(PRODUCT_NOT_LICENSED, SVRT_WARN, *it);
			continue;
		} else {
			atLeastOneProductLicensed = true;
		}
		/*
		 *  sw_version_from = (optional int)
		 *  sw_version_to = (optional int)
		 *  from_date = YYYY-MM-DD (optional)
		 *  to_date  = YYYY-MM-DD (optional)
		 *  client_signature = XXXX-XXXX-XXXX-XXXX (optional string 16)
		 *  license_signature = XXXXXXXXXX (mandatory, 1024)
		 *  application_data = xxxxxxxxx (optional string 16)
		 */
#ifndef CLIENT_
		const char * license_signature = ini.GetValue(productNamePtr,
				"license_signature", NULL);
		const char * server_signature = ini.GetValue(productNamePtr,"server_signature", NULL);

#endif
		long license_version = ini.GetLongValue(productNamePtr,
				"license_version", -1);
		long use_limit = ini.GetLongValue(productNamePtr,
						"use_limit", -1);
		long usage_remain = ini.GetLongValue(productNamePtr,
								"usage_remain", -1);
		if (license_signature != NULL && license_version > 0) {
			string from_date = trim_copy(
					ini.GetValue(productNamePtr, "from_date",
							FullLicenseInfo::UNUSED_TIME));
			string to_date = trim_copy(
					ini.GetValue(productNamePtr, "to_date",
							FullLicenseInfo::UNUSED_TIME));
			string client_signature = trim_copy(
					ini.GetValue(productNamePtr, "client_signature", ""));
			/*client_signature.erase(
			 std::remove(client_signature.begin(), client_signature.end(), '-'),
			 client_signature.end());*/
			int from_sw_version = ini.GetLongValue(productNamePtr,
					"from_sw_version",
					FullLicenseInfo::UNUSED_SOFTWARE_VERSION);
			int has_use_limit = ini.GetBoolValue(productNamePtr,
								"has_use_limit",
								false);
			int use_limit = ini.GetDoubleValue(productNamePtr,
											"use_limit",
											-1);
			int usage_remain = ini.GetDoubleValue(productNamePtr,
														"usage_remain",
														-1);
			int to_sw_version = ini.GetLongValue(productNamePtr,
					"to_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION);
			FullLicenseInfo licInfo(*it, product, license_signature,
								(int) license_version, from_date, to_date, client_signature,server_signature,
								from_sw_version, to_sw_version,"",has_use_limit,use_limit,usage_remain);
			licenseInfoOut.push_back(licInfo);
			atLeastOneLicenseComplete = true;
		} else {
			result.addEvent(LICENSE_MALFORMED, SVRT_WARN, *it);
		}
	}
	if (!loadAtLeastOneFile) {
		result.turnEventIntoError(FILE_FORMAT_NOT_RECOGNIZED);
	}
	if (!atLeastOneProductLicensed) {
		result.turnEventIntoError(PRODUCT_NOT_LICENSED);
	}
	if (!atLeastOneLicenseComplete) {
		result.turnEventIntoError(LICENSE_MALFORMED);
	}
	return result;
}

EventRegistry LicenseReader::deleteLicenses(const string &product) {
	vector<string> diskFiles;
	EventRegistry result = getLicenseDiskFiles(diskFiles);
	if (!result.isGood()) {
		return result;
	}
	bool loadAtLeastOneFile = false;
	bool atLeastOneProductLicensed = false;
	bool atLeastOneLicenseComplete = false;
	CSimpleIniA ini;
	for (auto it = diskFiles.begin(); it != diskFiles.end(); it++) {
		ini.Reset();
		SI_Error rc = ini.LoadFile((*it).c_str());
		if (rc < 0) {
			result.addEvent(FILE_FORMAT_NOT_RECOGNIZED, SVRT_WARN, *it);
			continue;
		} else {
			loadAtLeastOneFile = true;
		}
		const char* productNamePtr = product.c_str();
		int sectionSize = ini.GetSectionSize(productNamePtr);
		if (sectionSize <= 0) {
			result.addEvent(PRODUCT_NOT_LICENSED, SVRT_WARN, *it);
			continue;
		} else {
			atLeastOneProductLicensed = true;
		}
		/*
		 *  sw_version_from = (optional int)
		 *  sw_version_to = (optional int)
		 *  from_date = YYYY-MM-DD (optional)
		 *  to_date  = YYYY-MM-DD (optional)
		 *  client_signature = XXXX-XXXX-XXXX-XXXX (optional string 16)
		 *  license_signature = XXXXXXXXXX (mandatory, 1024)
		 *  application_data = xxxxxxxxx (optional string 16)
		 */

#ifndef CLIENT_
		ini.Delete(productNamePtr,"license_signature", NULL);
		ini.Delete(productNamePtr,"server_signature", NULL);
		ini.Delete(productNamePtr,"server_signature", NULL);
#endif
		ini.Delete(productNamePtr,"license_version", -1);
		ini.Delete(productNamePtr,"use_limit", -1);
		ini.Delete(productNamePtr,"usage_remain", -1);
		ini.Delete(productNamePtr, "from_date",FullLicenseInfo::UNUSED_TIME);
		ini.Delete(productNamePtr, "to_date",FullLicenseInfo::UNUSED_TIME);
		ini.Delete(productNamePtr, "client_signature", "");
		ini.Delete(productNamePtr,"from_sw_version",	FullLicenseInfo::UNUSED_SOFTWARE_VERSION);
		ini.Delete(productNamePtr,"has_use_limit",false);
		ini.Delete(productNamePtr,"use_limit",-1);
		ini.Delete(productNamePtr,"usage_remain",-1);
		ini.Delete(productNamePtr,"to_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION);
		ini.SetValue(productNamePtr, "client_signature", "hello test client......");
		cout<<"here file to save:"<<*it<<endl;
		ini.Save((*it),false);
		}

	return result;
}

bool LicenseReader::findLicenseWithExplicitLocation(vector<string>& diskFiles,
		EventRegistry& eventRegistry) {
//bool hasFileLocation = false;
	bool licenseFoundWithExplicitLocation = false;
	if (licenseLocation.licenseFileLocation != NULL
			&& licenseLocation.licenseFileLocation[0] != '\0') {
		//hasFileLocation = true;
		string varName(licenseLocation.licenseFileLocation);
		vector<string> declared_positions = splitLicensePositions(varName);
		vector<string> existing_pos = filterExistingFiles(declared_positions);
		if (existing_pos.size() > 0) {
			if (existing_pos.size() > 0) {
				licenseFoundWithExplicitLocation = true;
				for (auto it = existing_pos.begin(); it != existing_pos.end();
						++it) {
					diskFiles.push_back(*it);
					eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, *it);
				}
			}
		} else {
			eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, varName);
		}
	}
	return licenseFoundWithExplicitLocation;
}

bool LicenseReader::findFileWithEnvironmentVariable(vector<string>& diskFiles,
		EventRegistry& eventRegistry) {
	bool licenseFileFoundWithEnvVariable = false;
	if (licenseLocation.environmentVariableName != NULL
			&& licenseLocation.environmentVariableName[0] != '\0') {
		string varName(licenseLocation.environmentVariableName);
		if (varName.length() > 0) {
			//var name is passed in by the calling application.
			char* env_var_value = getenv(varName.c_str());
			if (env_var_value != NULL && env_var_value[0] != '\0') {
				vector<string> declared_positions = splitLicensePositions(
						string(env_var_value));
				vector<string> existing_pos = filterExistingFiles(
						declared_positions);
				if (existing_pos.size() > 0) {
					licenseFileFoundWithEnvVariable = true;
					for (auto it = existing_pos.begin();
							it != existing_pos.end(); ++it) {
						diskFiles.push_back(*it);
						eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO,
								*it);
					}
				} else {
					eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN,
							env_var_value);
				}
			} else {
				eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED,
						SVRT_WARN);
			}
		} else {
			eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, SVRT_WARN);
		}
	}
	return licenseFileFoundWithEnvVariable;
}

EventRegistry LicenseReader::getLicenseDiskFiles(vector<string>& diskFiles) {
	EventRegistry eventRegistry;
	bool licenseFoundWithExplicitLocation = findLicenseWithExplicitLocation(
			diskFiles, eventRegistry);
	bool foundNearModule = false;
	if (licenseLocation.openFileNearModule) {
		char fname[MAX_PATH] = { 0 };
		FUNCTION_RETURN fret = getModuleName(fname);
		if (fret == FUNC_RET_OK) {
			string temptativeLicense = string(fname) + ".lic";
			ifstream f(temptativeLicense.c_str());
			if (f.good()) {
				foundNearModule = true;
				diskFiles.push_back(temptativeLicense);
				eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO,
						temptativeLicense);
			} else {
				eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN,
						temptativeLicense);
			}
			f.close();
		} else {
			LOG_WARN("Error determining module name.");
		}
	}
	bool licenseFileFoundWithEnvVariable = findFileWithEnvironmentVariable(
			diskFiles, eventRegistry);

	if (!foundNearModule && !licenseFoundWithExplicitLocation
			&& !licenseFileFoundWithEnvVariable) {
		eventRegistry.turnEventIntoError(ENVIRONMENT_VARIABLE_NOT_DEFINED);
		eventRegistry.turnEventIntoError(LICENSE_FILE_NOT_FOUND);
	}
	return eventRegistry;
}

vector<string> LicenseReader::filterExistingFiles(
		vector<string> licensePositions) {
	vector<string> existingFiles;
	for (auto it = licensePositions.begin(); it != licensePositions.end();
			it++) {
		ifstream f(it->c_str());
		if (f.good()) {
			existingFiles.push_back(*it);
		}
		f.close();
	}
	return existingFiles;
}

vector<string> LicenseReader::splitLicensePositions(string licensePositions) {
	std::stringstream streamToSplit(licensePositions);
	std::string segment;
	std::vector<string> seglist;

	while (std::getline(streamToSplit, segment, ';')) {
		seglist.push_back(segment);
	}
	return seglist;
}

LicenseReader::~LicenseReader() {

}

string FullLicenseInfo::printForSign() const {
	ostringstream oss;
	oss << toupper_copy(trim_copy(this->product));
	oss << SHARED_RANDOM;

	if (has_client_sig) {
		oss << trim_copy(this->client_signature);
	}
	if (has_versions) {
		oss << "|" << this->from_sw_version << "-" << this->to_sw_version;
	}
	if (has_expiry) {
		oss << "|" << this->from_date << "|" << this->to_date;
	}
	if (this->extra_data.length() > 0) {
		oss << "|" << extra_data;
	}
	oss << "|" <<this->has_use_limit;

	if (has_use_limit) {
			oss << "|" << this->use_limit;
			oss << "|" << this->usage_remain;
	}
#ifdef _DEBUG
	cout << "[" << oss.str() << "]" << endl;
#endif
	return oss.str();

}

string FullLicenseInfo::printForSignServer() const {
	ostringstream oss;
	oss << toupper_copy(trim_copy(this->product));
	oss << SHARED_RANDOM;

	if (has_client_sig) {
		oss << trim_copy(this->client_signature);
	}
	if (has_versions) {
		oss << "|" << this->from_sw_version << "-" << this->to_sw_version;
	}
	if (has_expiry) {
		oss << "|" << this->from_date << "|" << this->to_date;
	}
	if (this->extra_data.length() > 0) {
		oss << "|" << extra_data;
	}
	oss << "|" <<this->has_use_limit;

	if (has_use_limit) {
			oss << "|" << this->use_limit;
	//		oss << "|" << this->usage_remain;
	}
	oss <<"CompanyName:softonnet.com";
#ifdef _DEBUG
	cout << "[" << oss.str() << "]" << endl;
#endif
	return oss.str();

}

void FullLicenseInfo::printAsIni(ostream & a_ostream) const {
	CSimpleIniA ini;
	string result;
	string product = toupper_copy(trim_copy(this->product));
	CSimpleIniA::StreamWriter sw(a_ostream);
	ini.SetLongValue(product.c_str(), "license_version",
	PROJECT_INT_VERSION);
#ifndef CLIENT_
	ini.SetValue(product.c_str(), "license_signature",
			this->license_signature.c_str());
	ini.SetValue(product.c_str(), "server_signature",
				this->server_signature.c_str());
#endif
	if (has_client_sig) {
		ini.SetValue(product.c_str(), "client_signature",
				this->client_signature.c_str());
	}
	if (has_versions) {
		ini.SetLongValue(product.c_str(), "from_sw_version", from_sw_version);
		ini.SetLongValue(product.c_str(), "to_sw_version", to_sw_version);
	}

	if (this->from_date != UNUSED_TIME) {
		ini.SetValue(product.c_str(), "from_date", from_date.c_str());
	}
	if (this->to_date != UNUSED_TIME) {
		ini.SetValue(product.c_str(), "to_date", to_date.c_str());
	}
	if (this->extra_data.length() > 0) {
		ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str());
	}
	if (this->extra_data.length() > 0) {
			ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str());
		}
	if (has_use_limit) {
			ini.SetDoubleValue(product.c_str(), "use_limit", this->use_limit);
			ini.SetDoubleValue(product.c_str(), "usage_remain", this->usage_remain);
	}
	ini.Save(sw);
}

void FullLicenseInfo::printAsIniAndSetCom(ostream & a_ostream,LicenseComm & lc) const {
	CSimpleIniA ini;
	string result;
	string product = toupper_copy(trim_copy(this->product));
	CSimpleIniA::StreamWriter sw(a_ostream);
	ini.SetLongValue(product.c_str(), "license_version",
	PROJECT_INT_VERSION);
	lc.license_version=PROJECT_INT_VERSION;

#ifndef CLIENT_
	lc.license_signature=this->license_signature;

	ini.SetValue(product.c_str(), "license_signature",
			this->license_signature.c_str());
#endif

	if (has_client_sig) {
		lc.has_client_sig=true;
		ini.SetValue(product.c_str(), "client_signature",
				this->client_signature.c_str());
		lc.client_signature=this->client_signature;
	}
	if (has_versions) {
		lc.has_versions=true;
		lc.from_sw_version=from_sw_version;
		lc.to_sw_version=to_sw_version;
		ini.SetLongValue(product.c_str(), "from_sw_version", from_sw_version);
		ini.SetLongValue(product.c_str(), "to_sw_version", to_sw_version);
	}

	if (this->from_date != UNUSED_TIME) {
		lc.from_date=from_date;
		ini.SetValue(product.c_str(), "from_date", from_date.c_str());
	}
	if (this->to_date != UNUSED_TIME) {
		lc.to_date=to_date;
		ini.SetValue(product.c_str(), "to_date", to_date.c_str());
	}
	if (this->extra_data.length() > 0) {
		lc.extra_data=this->extra_data;
		ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str());
	}
	lc.has_use_limit=has_use_limit;
	ini.SetDoubleValue(product.c_str(), "has_use_limit", has_use_limit);
	if (has_use_limit) {
		lc.use_limit=use_limit;
		lc.usage_remain=usage_remain;
		ini.SetDoubleValue(product.c_str(), "use_limit", use_limit);
		ini.SetDoubleValue(product.c_str(), "usage_remain",usage_remain);
	}
	ini.Save(sw);
}

void FullLicenseInfo::printAsIniFromCom(ostream & a_ostream,LicenseComm & lc) const {
	CSimpleIniA ini;
	string result;
	string product = toupper_copy(trim_copy(lc.products[0]));
	CSimpleIniA::StreamWriter sw(a_ostream);
	ini.SetLongValue(product.c_str(), "license_version",
	PROJECT_INT_VERSION);

#ifndef CLIENT_

	ini.SetValue(product.c_str(), "license_signature",
			lc.license_signature.c_str());
#endif

	if (lc.has_client_sig) {
		ini.SetValue(product.c_str(), "client_signature",
				lc.client_signature.c_str());

	}
	if (lc.has_versions) {
		ini.SetLongValue(product.c_str(), "from_sw_version", lc.from_sw_version);
		ini.SetLongValue(product.c_str(), "to_sw_version", lc.to_sw_version);
	}

	if (lc.from_date != UNUSED_TIME) {
		lc.from_date=from_date;
		ini.SetValue(product.c_str(), "from_date", lc.from_date.c_str());
	}
	if (lc.to_date != UNUSED_TIME) {
		lc.to_date=to_date;
		ini.SetValue(product.c_str(), "to_date", lc.to_date.c_str());
	}
	if (lc.extra_data.length() > 0) {

		ini.SetValue(product.c_str(), "extra_data", lc.extra_data.c_str());
	}

		ini.SetBoolValue(product.c_str(), "has_use_limit", lc.has_use_limit);
		ini.SetDoubleValue(product.c_str(), "usage_remain", lc.usage_remain);
		ini.SetDoubleValue(product.c_str(), "use_limit", lc.use_limit);

	ini.Save(sw);
}

time_t FullLicenseInfo::expires_on() const {
	return seconds_from_epoch(this->to_date.c_str());
}

time_t FullLicenseInfo::valid_from() const {
	return seconds_from_epoch(this->from_date.c_str());
}

}

max_stars_repo_name: YAS-CODE/License-Manager

max_issues_repo_name: YAS-CODE/Open-source-dev

max_forks_repo_name: YAS-CODE/Open-source-dev


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

/*
 * CommunicationManager.cpp
 *
 *  Created on: Nov 21, 2012
 *      Author: redheli
 */

#include "CommunicationManager.hpp"

#include <boost/thread.hpp>

#include "CommunicationDataManager.hpp"
#include "ControlManager.hpp"

using boost::asio::ip::tcp;
using namespace sim_mob;

void sim_mob::CommunicationDataManager::sendTrafficData(std::string &s)
{
        boost::mutex::scoped_lock lock(trafficDataGuard);
        trafficDataQueue.push(s);
}
void sim_mob::CommunicationDataManager::sendRoadNetworkData(const std::string &s)
{
        boost::mutex::scoped_lock lock(roadNetworkDataGuard);
        roadNetworkDataQueue.push(s);
}
bool sim_mob::CommunicationDataManager::getTrafficData(std::string &s) {
        if(!trafficDataQueue.empty())
        {
            boost::mutex::scoped_lock lock(trafficDataGuard);
            s = trafficDataQueue.front();
            trafficDataQueue.pop();
            return true;
        }
        return false;
}
bool sim_mob::CommunicationDataManager::getCmdData(std::string &s) {
        if(!cmdDataQueue.empty())
        {
            boost::mutex::scoped_lock lock(cmdDataGuard);
            s = cmdDataQueue.front();
            cmdDataQueue.pop();
            return true;
        }
        return false;
}
bool sim_mob::CommunicationDataManager::getRoadNetworkData(std::string &s) {
        if(!roadNetworkDataQueue.empty())
        {
            boost::mutex::scoped_lock lock(roadNetworkDataGuard);
            s = roadNetworkDataQueue.front();
            roadNetworkDataQueue.pop();
            return true;
        }
        return false;
}


text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

#pragma once
#include "add_parentheses.hxx"
#include "boostx.hxx"
#include "seq_join.hxx"
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition.hpp>
#include <boost/preprocessor/seq.hpp>
#include <boost/preprocessor/seq/fold_left.hpp>
#include <boost/preprocessor/seq/pop_back.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/tuple.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/rem.hpp>
#include <boost/preprocessor/tuple/size.hpp>

// XXX: Move.
#if BOOST_PP_VARIADICS
#define __UNWRAP_TUPLE(t) BOOST_PP_TUPLE_REM(BOOST_PP_TUPLE_SIZE(t)) t
#else
//#error No Variadic support
#endif

//
// Namespaces
//
#define __MONETA_PP_NAMESPACE_BEGIN(r, data, t) namespace t {
#define MONETA_PP_NAMESPACE_BEGIN(ns_seq) BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_NAMESPACE_BEGIN, _, ns_seq)

#define __MONETA_PP_NAMESPACE_END(r, data, t) }
#define MONETA_PP_NAMESPACE_END(ns_seq) BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_NAMESPACE_END, _, ns_seq)

// Usage: MONETA_PP_NAMESPACE_JOIN((a)(b)(c), ::) --> a::b::c::
#define __MONETA_PP_NAMESPACE_JOIN(r, data, t) t data
#define MONETA_PP_NAMESPACE_JOIN(ns_seq, token) BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_NAMESPACE_JOIN,token,ns_seq)

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

#define MONETA_PP_MEMBER_FROM_TNT_PAIR(entity, pair) \
	MONETA_MEMBER(entity, BOOST_PP_TUPLE_ELEM(2, 0, pair), BOOST_PP_TUPLE_ELEM(2, 1, pair))

// ---

#define __MONETA_PP_EXPAND_ENTITY_MEMBER_NAMES(r, entity, pair)                                       \
	namespace moneta { namespace traits {                                                         \
		template <>                                                                           \
		struct member_name<MONETA_PP_MEMBER_FROM_TNT_PAIR(entity, pair)> : boost::true_type { \
			typedef std::string trait_type;                                               \
			static trait_type get() {                                                     \
				return BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2, 1, pair));           \
			}                                                                             \
		};                                                                                \
	}}

#define MONETA_PP_EXPAND_ENTITY_MEMBER_NAMES(entity, members) \
	BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_EXPAND_ENTITY_MEMBER_NAMES, entity, members)

// ---

#define __MONETA_PP_EXPAND_ENTITY_MEMBERS(r, entity, pair) \
	BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(r, 2)) MONETA_PP_MEMBER_FROM_TNT_PAIR(entity, pair)

#define MONETA_PP_EXPAND_ENTITY_MEMBERS(entity, members)                                          \
	namespace moneta { namespace traits {                                                     \
		template <>                                                                       \
		struct members_of<entity> : boost::mpl::vector<                                   \
			BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_EXPAND_ENTITY_MEMBERS, entity, members) \
		>{};                                                                              \
	}}

// ---

#define __MONETA_PP_DEFINE_MEMBERS(r, _, tuple) \
	BOOST_PP_TUPLE_ELEM(2, 0, tuple) BOOST_PP_TUPLE_ELEM(2, 1, tuple);

#define MONETA_PP_DEFINE_MEMBERS(members) \
	BOOST_PP_SEQ_FOR_EACH(__MONETA_PP_DEFINE_MEMBERS, _, members)

// ---

#define MONETA_PP_DEFINE_ENTITY_STRUCT(entity, members) \
	struct entity {                                 \
		MONETA_PP_DEFINE_MEMBERS(members)       \
	};

ext: hxx

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REC_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REC_HPP_INCLUDED

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/detail/traits.hpp>
#include <boost/simd/function/if_else.hpp>
#include <boost/simd/function/if_else_allbits.hpp>
#include <boost/simd/function/if_else_zero.hpp>
#include <boost/simd/function/if_one_else_zero.hpp>
#include <boost/simd/function/abs.hpp>
#include <boost/simd/function/raw.hpp>
#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/constant/one.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  namespace bs = boost::simd;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  /// rec for integral types
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  BOOST_DISPATCH_OVERLOAD_IF( rec_
                            , (typename A0, typename X)
                            , (detail::is_native<X>)
                            , bd::cpu_
                            , bs::pack_<bd::uint_<A0>, X>
                            )
  {
    BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT
    {
      return if_else_allbits(a0, if_one_else_zero(a0 == One<A0>()));
    }
  };

  BOOST_DISPATCH_OVERLOAD_IF( rec_
                            , (typename A0, typename X)
                            , (detail::is_native<X>)
                            , bd::cpu_
                            , bs::pack_<bd::int_<A0>, X>
                            )
  {
    BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT
    {
      return if_else(a0, if_else_zero(bs::abs(a0) == One<A0>(), a0), Valmax<A0>());
    }
  };

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  /// rec for floating types: take all version when no better exists reverting to division
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  BOOST_DISPATCH_OVERLOAD( rec_
                         , (typename A0, typename X)
                         , bd::cpu_
                         , bs::pack_<bd::floating_<A0>, X>
                         )
  {
    BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT
    {
      return One<A0>()/a0;
    }
  };

  BOOST_DISPATCH_OVERLOAD_IF( rec_
                            , (typename T, typename X)
                            , (detail::is_native<X>)
                            , bd::cpu_
                            , bs::raw_tag
                            , bs::pack_<bd::unspecified_<T>, X>
                            )
  {
    BOOST_FORCEINLINE T operator()(const raw_tag &, T const& a) const BOOST_NOEXCEPT
    {
      return rec(a);
    }
  };
} } }

#endif


text:
#ifndef INCLUDED_DAL_RASTERDAL
#include "dal_RasterDal.h"
#define INCLUDED_DAL_RASTERDAL
#endif

// Library headers.
#ifndef INCLUDED_BOOST_SCOPED_PTR
#include <boost/scoped_ptr.hpp>
#define INCLUDED_BOOST_SCOPED_PTR
#endif

#ifndef INCLUDED_GDAL_PRIV
#include "gdal_priv.h"
#define INCLUDED_GDAL_PRIV
#endif

// PCRaster library headers.

// Module headers.
#ifndef INCLUDED_DAL_CSFRASTERDRIVER
#include "dal_CSFRasterDriver.h"
#define INCLUDED_DAL_CSFRASTERDRIVER
#endif

#ifndef INCLUDED_DAL_DATASET
#include "dal_Dataset.h"
#define INCLUDED_DAL_DATASET
#endif

#ifndef INCLUDED_DAL_GDALRASTERDRIVER
#include "dal_GDALRasterDriver.h"
#define INCLUDED_DAL_GDALRASTERDRIVER
#endif

#ifndef INCLUDED_DAL_LIBRARY
#include "dal_Library.h"
#define INCLUDED_DAL_LIBRARY
#endif

#ifndef INCLUDED_DAL_MEMORYRASTERDRIVER
#include "dal_MemoryRasterDriver.h"
#define INCLUDED_DAL_MEMORYRASTERDRIVER
#endif

#ifndef INCLUDED_DAL_RASTER
#include "dal_Raster.h"
#define INCLUDED_DAL_RASTER
#endif

#ifndef INCLUDED_DAL_RASTERDRIVER
#include "dal_RasterDriver.h"
#define INCLUDED_DAL_RASTERDRIVER
#endif

#ifndef INCLUDED_DAL_UTILS
#include "dal_Utils.h"
#define INCLUDED_DAL_UTILS
#endif

/*!
  \file
  This file contains the implementation of the RasterDal class.
*/

namespace dal {

//------------------------------------------------------------------------------
// DEFINITION OF STATIC RASTERDAL MEMBERS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF RASTERDAL MEMBERS
//------------------------------------------------------------------------------

//! Constructor.
/*!
  \param     addAllDrivers Whether or not to add all available drivers automatically.

  If \a addAllDrivers is false (the default case) no drivers are added
  to the object. In this case you need to explicitly add the drivers your
  application uses.
*/
RasterDal::RasterDal(
         bool addAllDrivers)

  : Dal(false)

{
  if(addAllDrivers) {
    #include "autoAddRasterDrivers.cc"
  }
}

//! Destructor.
/*!
*/
RasterDal::~RasterDal()
{
}

bool RasterDal::exists(
         std::string const& name,
         DataSpace const& space,
         DataSpaceAddress const& address) const
{
  assert(nrDrivers() > 0);

  return Dal::exists(name, space, address, RASTER);
}

//! Opens the raster dataset pointed to by \a name.
/*!
  \param     name Name of raster dataset.
  \return    A pointer to a newly created Raster object or 0 if no driver could open \a name.

  The caller is responsible of deleting the Raster object again.
*/
boost::tuple<boost::shared_ptr<Raster>, RasterDriver*> RasterDal::open(
         std::string const& name) const
{
  assert(nrDrivers() > 0);
  boost::shared_ptr<Dataset> dataset;
  Driver* driver;
  boost::tie(dataset, driver) = Dal::open(name, RASTER);
  return boost::make_tuple(boost::dynamic_pointer_cast<Raster>(dataset),
      dynamic_cast<RasterDriver*>(driver));
}

boost::tuple<boost::shared_ptr<Raster>, RasterDriver*> RasterDal::open(
         std::string const& name,
         DataSpace const& space,
         DataSpaceAddress const& address) const
{
  assert(nrDrivers() > 0);
  boost::shared_ptr<Dataset> dataset;
  Driver* driver;
  boost::tie(dataset, driver) = Dal::open(name, space, address, RASTER);
  return boost::make_tuple(boost::dynamic_pointer_cast<Raster>(dataset),
      dynamic_cast<RasterDriver*>(driver));
}

//! Reads the raster dataset pointed to by \a name.
/*!
  \param     name Name of raster dataset.
  \param     typeId Type id of values to use.
  \return    A pointer to a newly created Raster object.
  \exception Exception If no driver could read \a name.
*/
boost::shared_ptr<Raster> RasterDal::read(
         std::string const& name,
         TypeId typeId) const
{
  assert(nrDrivers() > 0);

  boost::shared_ptr<Raster> raster;
  RasterDriver* driver;
  boost::tie(raster, driver) = open(name);

  if(!raster) {
    throwCannotBeOpened(name, RASTER);
  }

  assert(driver);

  return boost::shared_ptr<Raster>(driver->read(name, typeId));
}

void RasterDal::read(
         Raster& raster,
         std::string const& name,
         DataSpace const& space,
         DataSpaceAddress const& address) const
{
  RasterDriver const* driver(driverByDataset(name, space));
  assert(driver); // TODO
  driver->read(raster, name, space, address);
}

void RasterDal::read(
         void* cell,
         TypeId typeId,
         std::string const& name,
         DataSpace const& space,
         DataSpaceAddress const& address) const
{
  RasterDriver const* driver(driverByDataset(name, space));
  assert(driver); // TODO
  driver->read(cell, typeId, name, space, address);
}

bool RasterDal::extremes(
         boost::any& min,
         boost::any& max,
         TypeId typeId,
         std::string const& name,
         DataSpace const& space) const
{
  RasterDriver const* driver(driverByDataset(name, space));
  assert(driver); // TODO
  return driver->extremes(min, max, typeId, name, space);
}

RasterDriver* RasterDal::driverByDataset(
         std::string const& name,
         DataSpace const& space) const
{
  return dynamic_cast<RasterDriver*>(Dal::driverByDataset(name, space));
}

//! Returns the driver with name \a name.
/*!
  \param     name Name of driver to look for.
  \return    Pointer to the driver.
*/
RasterDriver* RasterDal::driverByName(
         std::string const& name)
{
  return dynamic_cast<RasterDriver*>(Dal::driverByName(name));
}

} // namespace dal

//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
/**
 * \file NGramGraph.cpp
 *
 * \author Panagiotis Fotopoulos
 *
 * \copyright Copyright 2018 NCSR Demokritos Greece \n
 * 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. \n
 */

#include "NGramGraph.hpp"
#include "ProximityApproach.hpp"
#include <boost/graph/graph_utility.hpp>

NGramGraph::NGramGraph()
{
    CorrelationWindow = CORRELATIONWINDOW_DEFAULT_VALUE;
    splitter = nullptr;
    evaluator = nullptr;
    payload = nullptr;
}

NGramGraph::NGramGraph(ProximityEvaluator<std::string> *newProximityEvaluator, StringSplitter *newSplitter, StringPayload *newPayload, unsigned int CorrelationWindowValue, ProximityApproach* proximityApproach)
{
    evaluator = newProximityEvaluator;
    splitter = newSplitter;
    payload = newPayload;
    CorrelationWindow = CorrelationWindowValue;
    approach = proximityApproach;

}

NGramGraph::~NGramGraph()
{
    //dtor
}

void NGramGraph::createGraph()
{
    approach->createGraph(this);
}

bool NGramGraph::operator==(const NGramGraph& other)
{
	if (numberOfEdges() != other.numberOfEdges()) {
		return false;
	}

	bool ret = true;
	std::unordered_map<std::string, EDGE_WEIGHT_TYPE>::const_iterator got;
	for (auto const& elem : other.getEdgeNameToWeightMap()) {
		got = edgeNameToWeightMap.find(elem.first);
		if (got == edgeNameToWeightMap.end()) { // Edge name not found.
			ret = false;
			break;
		}
		else if (got->second != elem.second) { //Edge name found but with different weight.
			// TODO Check float inequality in a better way
			ret = false;
			break;
		}
	}

	return ret;
}

max_stars_repo_name: NikolasGialitsis/NGramGraphParallel

max_issues_repo_name: NikolasGialitsis/NGramGraphParallel

max_forks_repo_name: NikolasGialitsis/NGramGraphParallel


text:
//////////////////////////////////////////////////////////////////////////////
// Copyright 2005-2006 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////

#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>

#include <boost/mpl/list.hpp>
#include <boost/intrusive_ptr.hpp>

#include <boost/test/test_tools.hpp>

namespace sc = boost::statechart;
namespace mpl = boost::mpl;

struct EvToB : sc::event< EvToB > {};
struct EvToF : sc::event< EvToF > {};
struct EvCheck : sc::event< EvCheck > {};

struct A;
struct StateCastTest : sc::state_machine< StateCastTest, A >
{
  template< class State >
  void AssertInState()
  {
    BOOST_REQUIRE( state_downcast< const State * >() != 0 );
    BOOST_REQUIRE_NO_THROW( state_downcast< const State & >() );
    BOOST_REQUIRE( state_cast< const State * >() != 0 );
    BOOST_REQUIRE_NO_THROW( state_cast< const State & >() );
  }

  template< class State >
  void AssertNotInState()
  {
    BOOST_REQUIRE( state_downcast< const State * >() == 0 );
    BOOST_REQUIRE_THROW( state_downcast< const State & >(), std::bad_cast );
    BOOST_REQUIRE( state_cast< const State * >() == 0 );
    BOOST_REQUIRE_THROW( state_cast< const State & >(), std::bad_cast );
  }
};

template< class State, class FromState >
void AssertInState( const FromState & theState )
{
  BOOST_REQUIRE( theState.template state_downcast< const State * >() != 0 );
  BOOST_REQUIRE_NO_THROW( theState.template state_downcast< const State & >() );
  BOOST_REQUIRE( theState.template state_cast< const State * >() != 0 );
  BOOST_REQUIRE_NO_THROW( theState.template state_cast< const State & >() );
}

template< class State, class FromState >
void AssertNotInState( const FromState & theState )
{
  BOOST_REQUIRE( theState.template state_downcast< const State * >() == 0 );
  BOOST_REQUIRE_THROW( theState.template state_downcast< const State & >(), std::bad_cast );
  BOOST_REQUIRE( theState.template state_cast< const State * >() == 0 );
  BOOST_REQUIRE_THROW( theState.template state_cast< const State & >(), std::bad_cast );
}

struct B;
struct C;
struct D;
struct A : sc::simple_state< A, StateCastTest, mpl::list< C, D > >
{
  typedef sc::transition< EvToB, B > reactions;
};

  struct E;
  struct C : sc::simple_state< C, A::orthogonal< 0 >, E > {};

    struct E : sc::state< E, C >
    {
      typedef sc::custom_reaction< EvCheck > reactions;

      E( my_context ctx ) : my_base( ctx )
      {
        post_event( boost::intrusive_ptr< EvCheck >( new EvCheck() ) );
      }

      sc::result react( const EvCheck & );
    };

    struct F : sc::state< F, C >
    {
      typedef sc::custom_reaction< EvCheck > reactions;

      F( my_context ctx ) : my_base( ctx )
      {
        post_event( boost::intrusive_ptr< EvCheck >( new EvCheck() ) );
      }

      sc::result react( const EvCheck & );
    };

  struct G;
  struct D : sc::simple_state< D, A::orthogonal< 1 >, G > {};

    struct G : sc::simple_state< G, D > {};
    struct H : sc::simple_state< H, D > {};

struct B : sc::simple_state< B, StateCastTest >
{
  typedef sc::transition< EvToF, F > reactions;
};

sc::result E::react( const EvCheck & )
{
  AssertInState< A >( *this );
  AssertNotInState< B >( *this );
  AssertInState< C >( *this );
  AssertInState< D >( *this );
  AssertInState< E >( *this );
  AssertNotInState< F >( *this );
  AssertInState< G >( *this );
  AssertNotInState< H >( *this );
  return discard_event();
}

sc::result F::react( const EvCheck & )
{
  AssertInState< A >( *this );
  AssertNotInState< B >( *this );
  AssertInState< C >( *this );
  AssertInState< D >( *this );
  AssertNotInState< E >( *this );
  AssertInState< F >( *this );
  AssertInState< G >( *this );
  AssertNotInState< H >( *this );
  return discard_event();
}

int test_main( int, char* [] )
{
  StateCastTest machine;

  machine.AssertNotInState< A >();
  machine.AssertNotInState< B >();
  machine.AssertNotInState< C >();
  machine.AssertNotInState< D >();
  machine.AssertNotInState< E >();
  machine.AssertNotInState< F >();
  machine.AssertNotInState< G >();
  machine.AssertNotInState< H >();

  machine.initiate();

  machine.AssertInState< A >();
  machine.AssertNotInState< B >();
  machine.AssertInState< C >();
  machine.AssertInState< D >();
  machine.AssertInState< E >();
  machine.AssertNotInState< F >();
  machine.AssertInState< G >();
  machine.AssertNotInState< H >();

  machine.process_event( EvToB() );

  machine.AssertNotInState< A >();
  machine.AssertInState< B >();
  machine.AssertNotInState< C >();
  machine.AssertNotInState< D >();
  machine.AssertNotInState< E >();
  machine.AssertNotInState< F >();
  machine.AssertNotInState< G >();
  machine.AssertNotInState< H >();

  machine.process_event( EvToF() );

  machine.AssertInState< A >();
  machine.AssertNotInState< B >();
  machine.AssertInState< C >();
  machine.AssertInState< D >();
  machine.AssertNotInState< E >();
  machine.AssertInState< F >();
  machine.AssertInState< G >();
  machine.AssertNotInState< H >();

  machine.terminate();

  machine.AssertNotInState< A >();
  machine.AssertNotInState< B >();
  machine.AssertNotInState< C >();
  machine.AssertNotInState< D >();
  machine.AssertNotInState< E >();
  machine.AssertNotInState< F >();
  machine.AssertNotInState< G >();
  machine.AssertNotInState< H >();

  return 0;
}


text:
// Copyright (c) 2005-2009 Jaroslav Gresula
//
// Distributed under the MIT license (See accompanying file
// LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
//

#include "precompiled.h"
#define JAG_INCLUDE_STRING_UTILS_EX
#include <core/jstd/configimpl.h>
#include <core/generic/refcountedimpl.h>
#include <core/generic/assert.h>
#include <core/errlib/errlib.h>
#include <msg_jstd.h>
#include <interfaces/streams.h>
#include <core/generic/stringutils.h>
#include <core/jstd/file_stream.h>
#include <core/jstd/memory_stream.h>
#include <core/jstd/streamhelpers.h>
#include <core/generic/checked_cast.h>
#include <core/generic/stringutils.h>
#include <boost/algorithm/string/find_iterator.hpp>
#include <boost/algorithm/string/finder.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/range/iterator_range.hpp>

#if defined(_MSC_VER)
# pragma warning(push)
// unreachable code
# pragma warning(disable:4702)
#endif
  #include <boost/lexical_cast.hpp>
#if defined(_MSC_VER)
# pragma warning(pop)
#endif

using namespace boost;
//using namespace boost::spirit;

namespace jag {
namespace jstd {

//
// some operations on the default config definition
//
namespace
{
  // linear search through the unsorted list of strings
  cfg_pair_t const* find_cfg_pair(cfg_pair_t const* symbols, char const* kwd)
  {
      for(cfg_pair_t const* it=symbols; it->name; ++it)
      {
          if (!strcmp(kwd, it->name))
              return it;
      }
      return 0;
  }

  // retrieves a default value for the given symbol
  char const* default_value(cfg_pair_t const* symbols, char const* kwd)
  {
      cfg_pair_t const* pair = find_cfg_pair(symbols, kwd);
      if (pair)
      {
          JAG_ASSERT_MSG(pair->default_value, "option's default value is NULL");
          return pair->default_value;
      }
      else
      {
          return 0;
      }
  }

  // figures out whether the given symbol is valid
  bool is_valid_kwd(cfg_pair_t const* symbols, char const* kwd)
  {
      return find_cfg_pair(symbols, kwd);
  }
} // anonymous namespace

///////////////////////////////////////////////////////////////////////////
// class ConfigImpl

//
//
//
ConfigImpl::ConfigImpl(cfg_pair_t const* symbols)
    : m_symbols(symbols)
    , m_verification_active(true)
{}

//
//
//
void ConfigImpl::set(Char const* option, Char const* value)
{
    if (!is_empty(option))
    {
        set_r(option, option+strlen(option),
              value, value+strlen(value));
    }
}

//
//
//
void ConfigImpl::set_r(Char const* kwd_begin, Char const* kwd_end,
                        Char const* value_begin, Char const* value_end)
{
    // verify that the passed option is valid
    string_t kwd(kwd_begin, kwd_end);
    verify(kwd.c_str());

    // update the map
    config_map_t::iterator it = m_config_map.find(kwd);
    if (it != m_config_map.end())
        m_config_map.erase(it);

    m_config_map.insert(config_map_t::value_type(
                            kwd,
                            string_t(value_begin, value_end)));
}

//
//
//
Char const* ConfigImpl::get(Char const* kwd) const
{
    verify(kwd);
    Char const* value = 0;
    config_map_t::const_iterator it = m_config_map.find(kwd);
    value = (it == m_config_map.end())
        ? default_value(m_symbols, kwd)
        : it->second.c_str();

    if (!value)
        JAG_INTERNAL_ERROR;

    return value;
}

//
//
//
int ConfigImpl::get_int(Char const* kwd) const
{
    Char const* val = get(kwd);
    try
    {
        // suboptimal: lexical_cast make a copy of the string, spirit::int_p
        // might be better here
        return lexical_cast<int>(val);
    }
    catch(bad_lexical_cast const&)
    {
        throw exception_invalid_value(
            msg_config_integer_value(kwd)) << JAGLOC;
    }
}

//
//
//
void ConfigImpl::verify(Char const* kwd) const
{
    JAG_PRECONDITION(m_symbols);
    if (!m_verification_active)
        return;

    if (!is_valid_kwd(m_symbols, kwd))
    {
        throw exception_invalid_value(
            msg_config_unknown_option(kwd)) << JAGLOC;
    }
}

//
//
//
void ConfigImpl::save(ISeqStreamOutput& stream) const
{
    // the order is the same as in the symbol definition list
    for(cfg_pair_t const* sym=m_symbols; sym->name; ++sym)
    {
        char const* val = get(sym->name);

        stream.write(sym->name, strlen(sym->name));
        stream.write("=", 1);
        stream.write(val, strlen(val));
        stream.write("\n", 1);
    }
}

//
//
//
void ConfigImpl::save_to_file(Char const* fname) const
{
    FileStreamOutput fout(fname);
    save(fout);
}

//
//
//
intrusive_ptr<IProfileInternal> ConfigImpl::clone() const
{
    intrusive_ptr<ConfigImpl> result(
        new RefCountImpl<ConfigImpl,RefCountMT>(m_symbols));

    result->m_config_map = m_config_map;
    // intentionally do not copy m_verification_active
    return result;
}

///////////////////////////////////////////////////////////////////////////
// parsing a config from a stream

namespace
{
  //
  // Handles parsing events and redirects them to a config object
  //
  class ParseHandler
  {
      ConfigImpl& m_cfg;
      char const* m_kwd_start;
      char const* m_kwd_end;

  public:
      ParseHandler(ConfigImpl& cfg)
          : m_cfg(cfg)
          , m_kwd_start(0)
          , m_kwd_end(0)
      {}

      void on_kwd(char const* str, char const* end) {
          m_kwd_start=str;
          m_kwd_end=end;
      }

      void on_val(char const* str, char const* end) {
          JAG_PRECONDITION(m_kwd_start && m_kwd_end);
          m_cfg.set_r(m_kwd_start, m_kwd_end, str, end);
      }
  };

  //
  // Parses the configuration form the passed string.
  //
  intrusive_ptr<ConfigImpl> load_from_string_r(
      Char const* str,
      std::size_t len,
      cfg_pair_t const* symbols)
  {
      intrusive_ptr<ConfigImpl> cfg(
          new RefCountImpl<ConfigImpl,RefCountMT>(symbols));

      ParseHandler handler(*cfg);

      typedef algorithm::split_iterator<char const*> split_iter_t;
      typedef iterator_range<char const*> iter_rng_t;

      split_iter_t end;
      split_iter_t line_iter(str, str + len,
                             algorithm::token_finder(is_any_of("\n\r"),
                                                     token_compress_on));

      for(; line_iter != end; ++line_iter)
      {
          // trim the whole line, ignore blank lines and comments
          iter_rng_t line(trim_range(line_iter->begin(), line_iter->end()));
          if (line.begin() >= line.end()) continue;
          if (*line.begin() == '#') continue;

          iter_rng_t eq_pos(algorithm::find_first(line, "="));
          if (eq_pos.empty())
          {
              throw exception_invalid_value(
                  msg_config_parse_error()) << JAGLOC;
          }

          iter_rng_t kwd(trim_range(line.begin(), eq_pos.begin()));
          iter_rng_t val(trim_range(eq_pos.end(), line.end()));

          // TEST: change the following if it is tested somewhere
          handler.on_kwd(kwd.begin(), kwd.end());
          handler.on_val(val.begin(), val.end());
      }

      return cfg;
  }
} // anonymous namespace

//
//
//
intrusive_ptr<ConfigImpl> load_from_string(
    Char const* str,
    cfg_pair_t const* symbols)
{
    return load_from_string_r(str, strlen(str), symbols);
}

//
//
//
intrusive_ptr<ConfigImpl> load_from_file(
    Char const* fname,
    cfg_pair_t const* symbols)
{
    FileStreamInput fin(fname);
    MemoryStreamOutput mout;
    copy_stream(fin, mout);
    return load_from_string_r(jag_reinterpret_cast<Char const*>(mout.data()),
                              static_cast<size_t>(mout.tell()), symbols);
}

}} // namespace jag::jstd

max_stars_repo_name: jgresula/jagpdf

max_issues_repo_name: jgresula/jagpdf

max_forks_repo_name: jgresula/jagpdf


text:
#include <iostream>

#include <Eigen/Dense>
#include <fstream>
#include <vector>
#include <iomanip>      // std::setprecision

using Eigen::MatrixXd;
int main() {

    Eigen::Matrix<double, 2, 1> xi;
    Eigen::Matrix<double, 2, 1> particle_size;

    //! Dimension
    const unsigned Dim = 2;
    //! Nodes in GIMP function
    // 16 for 2D 4 for 1D
    const unsigned Nfunctions = 4;

    //! To store shape functions
    Eigen::Matrix<double, 16, 1> shapefn;

    //! To store grad shape functions
    Eigen::Matrix<double, 16, 2> grad_shapefn;

    //! length of element in local coordinate
    // Keep this value constant
    const double element_length = 2.;

    // Local coordinates of 2D GIMP cells
    /*const Eigen::Matrix<double, Nfunctions, Dim> local_nodes =
            (Eigen::Matrix<double, Nfunctions, Dim>() << -1., -1.,

                    1., -1.,
                    1.,  1.,
                    -1.,  1.,
                    -3., -3.,
                    -1., -3.,
                    1., -3.,
                    3., -3.,
                    3., -1.,
                    3.,  1.,
                    3.,  3.,
                    1.,  3.,
                    -1.,  3.,
                    -3.,  3.,
                    -3.,  1.,
                    -3., -1.).finished();*/

    // Local coordinates of 1D GIMP cells
    const Eigen::Matrix<double, Nfunctions, Dim> local_nodes =
            (Eigen::Matrix<double, Nfunctions, Dim>() <<

		-3.,0.,
		-1.,0.,
		 1.,0.,
		 3.,0.
		).finished();

    // particle location
    xi << -4.0, 0.0;
    // particle size
    particle_size << 1.1, 1.1;

    double interval = 0.05;

    std::vector<double> function_store;
    std::vector<double> gfunction_store;

    for (unsigned k = 0; k < 120; ++k) {

	xi(0) += interval;

	//Function loop
        for (unsigned n = 0; n < Nfunctions; ++n) {
            Eigen::Matrix<double, 2, 1> sni;
            Eigen::Matrix<double, 2, 1> dni;

		// GIMP conditional statement loop
            for (unsigned i = 0; i < Dim; ++i) {
		//length of particle
                double lp = particle_size(i) * 0.5;
		// active node
                double ni = local_nodes(n, i);
		// local particle  - local node
                double npni = xi(i) - ni;
                //! Conditional shape function statement
                // see: Pruijn, N.S., 2016. Eq(4.30)
                if (npni <= (-element_length - lp)) {
                    sni(i) = 0.;
                    dni(i) = 0.;
                } else if ((-element_length - lp) < npni &&
                           npni <= (-element_length + lp)) {

                    sni(i) = std::pow(element_length + lp + npni, 2.) /
                             (4. * (element_length * lp));
                    dni(i) = (element_length + lp + npni) / (2. * element_length * lp);
                } else if ((-element_length + lp) < npni && npni <= -lp) {
                    sni(i) = 1. + (npni / element_length);
                    dni(i) = 1. / element_length;
                } else if (-lp < npni && npni <= lp) {
                    sni(i) =
                            1. - (((npni * npni) + (lp * lp)) / (2. * element_length * lp));
                    dni(i) = -(npni / (element_length * lp));
                } else if (lp < npni && npni <= (element_length - lp)) {
                    sni(i) = 1. - (npni / element_length);
                    dni(i) = -(1. / element_length);
                } else if ((element_length - lp) < npni &&
                           npni <= (element_length + lp)) {
                    sni(i) = std::pow(element_length + lp - npni, 2.) /
                             (4. * element_length * lp);
                    dni(i) = -((element_length + lp - npni) / (2. * element_length * lp));
                } else if ((element_length + lp) < npni) {
                    sni(i) = 0.;
                    dni(i) = 0.;
                } else {
                    throw std::runtime_error(
                            "GIMP grad shapefn: Point location outside area of influence");
                }
            }
            // 2D Shape
            //shapefn(n) = sni(0) * sni(1);

            // 1D Shape value @ node n
	    shapefn(n) = sni(0);

	    // store 1D shape function value at specific node (n)
	    if (n == 1 )
	    function_store.push_back(shapefn(n));

            // 2D Grad
            //grad_shapefn(n, 0) = dni(0) * sni(1);
            //grad_shapefn(n, 1) = dni(1) * sni(0);

            // 1D Grad
            grad_shapefn(n, 0) = dni(0);

	    // store 1D grad function value at specific node (n)
	    if (n == 1 )
	    gfunction_store.push_back(grad_shapefn(n,0));
        }
    }
    std::cout << "function store size: " << function_store.size() << '\n';
    for (unsigned n = 0; n < Nfunctions; ++n) {
        std::cout << n << " "
                  << " s(" << local_nodes(n, 0) << " , " << local_nodes(n, 1)
                  << ") : " << shapefn(n) << '\n';
        //std::cout << n << " " << std::setprecision(9) << grad_shapefn(n,1) << '\n';
    }

    //! Output file
    std::string xvalfilename = "snvals.txt";
    std::fstream xvalfile;
    xvalfile.open(xvalfilename, std::ios::out);

    if (xvalfile.is_open()) {
        //! Write
	//function_store for shape function, gfunction_store for gradient
        for (auto const& xvals : gfunction_store) {
            xvalfile << xvals << '\n';
        }
        xvalfile.close();
    }
}


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

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

///////////////////////////////////#include "allowed_args.h"
#include "arith_uint256.h"
#include "chainparamsbase.h"
#include "fs.h"
#include "hash.h"
#include "primitives/block.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "streams.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"

#include <boost/thread.hpp>

#include <cstdlib>
#include <stdio.h>

#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/keyvalq_struct.h>

#include <univalue.h>

using namespace std;

typedef unsigned int extra_nonce_type;

// Internal miner
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// The nonce is usually preserved between calls, but periodically or if the
// nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
// zero.
bool static ScanHash(const CBlockHeader *pblock, uint32_t &nNonce, uint256 *phash)
{
    // Write the first 76 bytes of the block header to a double-SHA256 state.
    CHash256 hasher;
    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    ss << *pblock;
    assert(ss.size() == 80);
    hasher.Write((unsigned char *)&ss[0], 76);

    while (true)
    {
        nNonce++;

        // Write the last 4 bytes of the block header (the nonce) to a copy of
        // the double-SHA256 state, and compute the result.
        CHash256(hasher).Write((unsigned char *)&nNonce, 4).Finalize((unsigned char *)phash);

        // Return the nonce if the hash has at least some zero bits,
        // caller will check if it has enough to reach the target
        if (*std::next(phash->begin(), 31) == 0 && *std::next(phash->begin(), 30) == 0)
            return true;

        // If nothing found after trying for a while, return -1
        if ((nNonce & 0xfff) == 0)
            return false;
    }
}

// Not ideal - a modified copy of the options from bitcoin-cli
std::string HelpMessageCli()
{
     const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
     const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);

     std::string strUsage;
     strUsage += HelpMessageGroup(_("Options:"));
     strUsage += HelpMessageOpt("-?", _("This help message"));
     strUsage += HelpMessageOpt( "-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
     strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));

     strUsage += HelpMessageGroup(_("RPC options:"));
     strUsage += HelpMessageOpt("-named", strprintf(_("Pass named parameters instead of positional arguments (default: %s)"), DEFAULT_NAMED));
     strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
     strUsage += HelpMessageOpt("-standalone", strprintf(_(""), DEFAULT_RPCCONNECT));
     strUsage += HelpMessageOpt("-rpcport=<port>",
         strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"),
             defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
     strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
     strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
     strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
     strUsage += HelpMessageOpt("-rpcclienttimeout=<n>",
                        strprintf(_("Timeout in seconds during HTTP requests, "
                                    "or 0 for no timeout. (default: %d)"),
                                  DEFAULT_HTTP_CLIENT_TIMEOUT));

     strUsage += HelpMessageOpt("-stdinrpcpass",
         strprintf(_("Read RPC password from standard input as a single line.  "
                     "When combined with -stdin, the first line from standard "
                     "input is used for the RPC password.")));
     strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line "
                     "until EOF/Ctrl-D (recommended for sensitive information "
                     "such as passphrases)"));
     strUsage += HelpMessageOpt("-rpcwallet=<walletname>",
         _("Send RPC for non-default wallet on RPC server (argument is wallet "
           "filename in bitcoind directory, required if bitcoind runs with "
           "multiple wallets)"));

     return strUsage;
}

std::string HelpMessage()
{
    std::stringstream ss;
    ss << HelpMessageCli();
    ss << HelpMessageGroup(_("Mining options:"));
    ss << HelpMessageOpt( "-blockversion", strprintf(_("Set the block version number. For testing only.  Value must be an integer: %s)"), DEFAULT_NAMED));
    ss << HelpMessageOpt( "-cpus", strprintf(_("Number of cpus to use for mining (default: 1).  Value must be an integer: %s)"), 1));
    ss << HelpMessageOpt( "-duration", strprintf(_("Number of seconds to mine a particular block candidate (default: 30). Value must be an integer: %s)"), DEFAULT_NAMED));
    ss << HelpMessageOpt( "-nblock", strprintf(_("Number of blocks to mine (default: mine forever / -1). Value must be an integer: %s)"), DEFAULT_NAMED));
    return ss.str();
}

inline uint32_t nbits(const UniValue &candidate_props)
{
    uint32_t val;
    std::stringstream ss;
    ss << std::hex << candidate_props["nBits"].get_str();
    ss >> val;
    return val;
}

static CBlockHeader CpuMinerJsonToHeader(const UniValue &candidate_props)
{
    // Does not set hashMerkleRoot (Does not exist in Mining-Candidate params).
    CBlockHeader blockheader;

    // nVersion
    blockheader.nVersion = candidate_props["version"].get_int();

    // hashPrevBlock
    string tmpstr = candidate_props["prevhash"].get_str();
    std::vector<unsigned char> vec = ParseHex(tmpstr);
    std::reverse(vec.begin(), vec.end()); // sent reversed
    blockheader.hashPrevBlock = uint256(vec);

    // nTime:
    blockheader.nTime = candidate_props["time"].get_int();

    // nBits
    blockheader.nBits = nbits(candidate_props);

    return blockheader;
}

static void CalculateNextMerkleRoot(uint256 &merkle_root, const uint256 &merkle_branch)
{
    // Append a branch to the root. Double SHA256 the whole thing:
    uint256 hash;
    CHash256()
        .Write(merkle_root.begin(), merkle_root.size())
        .Write(merkle_branch.begin(), merkle_branch.size())
        .Finalize(hash.begin());
    merkle_root = hash;
}

static uint256 CalculateMerkleRoot(uint256 &coinbase_hash, const std::vector<uint256> &merkleproof)
{
    uint256 merkle_root = coinbase_hash;
    for (unsigned int i = 0; i < merkleproof.size(); i++)
    {
        CalculateNextMerkleRoot(merkle_root, merkleproof[i]);
    }
    return merkle_root;
}

// PLEASE LEAVE FOR FUTURE TROUBLE SHOOTING
void print_coinbase_transaction(ostream& str, vector<unsigned char>& coinbase_bytes)
{
   for(unsigned char ch : coinbase_bytes)
        str << hex << setw(2) << setfill('0') << (int)ch;
    str << ".\n";
}

void Add_space_for_extra_nonce(vector<unsigned char>& coinbase_bytes, size_t offset_extra_nonce)
{
    // Copy the first part of the coinbase transaction into the tmp vector
    vector<unsigned char> tmp(coinbase_bytes.begin(), coinbase_bytes.begin() + offset_extra_nonce);

    // Add space for the extra-nonce into the tmp vector
    for(size_t i=0; i<sizeof(extra_nonce_type); i++)
        tmp.push_back((unsigned char)OP_NOP1);

    // Add on the second part of the coinbase transaction onto the tmp vector
    tmp.insert(tmp.begin() + offset_extra_nonce + sizeof(extra_nonce_type),
                coinbase_bytes.begin() + offset_extra_nonce,
                coinbase_bytes.end());

    // Copy the tmp vector into the original transaction
    coinbase_bytes.assign(tmp.begin(), tmp.end());

    coinbase_bytes[41] += sizeof(extra_nonce_type);
}

// WARNING: This methods "splits" coinbaseBytes and inserts space for an extra-nonce.
static bool CpuMineBlockHasher(CBlockHeader *pblock, vector<unsigned char>& coinbaseBytes, const std::vector<uint256> &merkleproof)
{
    extra_nonce_type nExtraNonce = std::rand();
    uint32_t nNonce = pblock->nNonce;
    arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
    bool found = false;
    int ntries = 10;

    // coinbase data layout
    // 4 bytes - version
    // 1 byte - no of inputs (compact size) [start offset=4]
    // 32 bytes - input tx ID [start offset=5]
    // 4 bytes - input CTxOut index [start offset=37]
    // 1 byte - script length [start offset=41]
    // 3/4 bytes - block height [start offset=42] RegTest: typically looks like {0x02, 0xA&, 0x00}
    // -- extra nonce -- [start offset=45/46]

    size_t bytes_used_for_height = coinbaseBytes[42];
    size_t offset_extra_nonce = 43 + bytes_used_for_height;

    if(coinbaseBytes.size() < offset_extra_nonce + 2) // crude.
    {
        cerr << "Invalid coinbase transaction supplied\n";
        return false;
    }

    //cout << "Original coinbase tx is:\n";
    //print_coinbase_transaction(cout, coinbaseBytes);

    Add_space_for_extra_nonce(coinbaseBytes, offset_extra_nonce);

    //cout << "Expanded coinbase tx is:\n";
    //print_coinbase_transaction(cout, coinbaseBytes);

    while (!found)
    {
        // hashMerkleRoot:
        {
            ++nExtraNonce;
            unsigned char *pbytes = (unsigned char *)coinbaseBytes.data();
            memcpy(pbytes + offset_extra_nonce, &nExtraNonce, sizeof(nExtraNonce));
            uint256 hash;
            CHash256().Write(pbytes, coinbaseBytes.size()).Finalize(hash.begin());

            pblock->hashMerkleRoot = CalculateMerkleRoot(hash, merkleproof);
        }

        //
        // Search
        //
        uint256 hash;
        while (!found)
        {
            // Check if something found
            if (ScanHash(pblock, nNonce, &hash))
            {
                if (UintToArith256(hash) <= hashTarget)
                {
                    // Found a solution
                    pblock->nNonce = nNonce;
                    found = true;
                    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(),
                        hashTarget.GetHex().c_str());
                    break;
                }
                else
                {
                    if (ntries-- < 1)
                    {
                        pblock->nNonce = nNonce; // report the last nonce checked for accounting
                        return false; // Give up leave
                    }
                }
            }
        }
    }

    return found;
}

static double GetDifficulty(uint64_t nBits)
{
    int nShift = (nBits >> 24) & 0xff;

    double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }
    return dDiff;
}

static UniValue CpuMineBlock(unsigned int searchDuration, const UniValue &params, bool &found)
{
    UniValue tmp(UniValue::VOBJ);
    UniValue ret(UniValue::VARR);
    string tmpstr;
    std::vector<uint256> merkleproof;
    CBlockHeader header;
    vector<unsigned char> coinbaseBytes(ParseHex(params["coinbase"].get_str()));

    found = false;

    // re-create merkle branches:
    {
        UniValue uvMerkleproof = params["merkleProof"];
        for (unsigned int i = 0; i < uvMerkleproof.size(); i++)
        {
            tmpstr = uvMerkleproof[i].get_str();
            std::vector<unsigned char> mbr = ParseHex(tmpstr);
            std::reverse(mbr.begin(), mbr.end());
            merkleproof.push_back(uint256(mbr));
        }
    }

    header = CpuMinerJsonToHeader(params);

    // Set the version (only to test):
    {
        int blockversion = gArgs.GetArg("-blockversion", header.nVersion);
        if (blockversion != header.nVersion)
            printf("Force header.nVersion to %d\n", blockversion);
        header.nVersion = blockversion;
    }

    uint32_t startNonce = header.nNonce = std::rand();
    std::string candidateId = params["id"].get_str();

    printf("Mining: id: %s parent: %s bits: %x difficulty: %.8e time: %d\n", candidateId.c_str(),
        header.hashPrevBlock.ToString().c_str(), header.nBits, GetDifficulty(header.nBits), header.nTime);

    int64_t start = GetTime();
    while ((GetTime() < start + searchDuration) && !found)
    {
        // When mining mainnet, you would normally want to advance the time to keep the block time as close to the
        // real time as possible.  However, this CPU miner is only useful on testnet and in testnet the block difficulty
        // resets to 1 after 20 minutes.  This will cause the block's difficulty to mismatch the expected difficulty
        // and the block will be rejected.  So do not advance time (let it be advanced by bitcoind every time we
        // request a new block).
        // header.nTime = (header.nTime < GetTime()) ? GetTime() : header.nTime;

        found = CpuMineBlockHasher(&header, coinbaseBytes, merkleproof);
    }

    // Leave if not found:
    if (!found)
    {
        printf("Checked %d possibilities\n", header.nNonce - startNonce);
        return ret;
    }

    printf("Solution! Checked %d possibilities\n", header.nNonce - startNonce);

    tmpstr = HexStr(coinbaseBytes.begin(), coinbaseBytes.end());
    tmp.push_back(Pair("coinbase", tmpstr));
    tmp.push_back(Pair("id", candidateId));
    tmp.push_back(Pair("time", UniValue(uint64_t(header.nTime)))); // Optional. We have changed so must send.
    tmp.push_back(Pair("nonce", UniValue(uint64_t(header.nNonce))));
    tmp.push_back(Pair("version", UniValue(header.nVersion))); // Optional. We may have changed so sending.
    ret.push_back(tmp);

    return ret;
}

static UniValue RPCSubmitSolution(const UniValue &solution, int &nblocks)
{
    UniValue reply = CallRPC("submitminingsolution", solution);

    const UniValue &error = find_value(reply, "error");

    if (!error.isNull())
    {
        fprintf(stderr, "Block Candidate submission error: %d %s\n", error["code"].get_int(),
            error["message"].get_str().c_str());
        return reply;
    }

    const UniValue &result = find_value(reply, "result");

    if (result.isStr())
    {
        fprintf(stderr, "Block Candidate rejected. Error: %s\n", result.get_str().c_str());
        // Print some debug info if the block is rejected
        UniValue dbg = solution[0].get_obj();
        fprintf(stderr, "id: %d  time: %d  nonce: %d  version: 0x%x\n", (unsigned int)dbg["id"].get_int64(),
            (uint32_t)dbg["time"].get_int64(), (uint32_t)dbg["nonce"].get_int64(), (uint32_t)dbg["version"].get_int());
        fprintf(stderr, "coinbase: %s\n", dbg["coinbase"].get_str().c_str());
    }
    else
    {
        if (result.isTrue())
        {
            printf("Block Candidate accepted.\n");
            if (nblocks > 0)
                nblocks--; // Processed a block
        }
        else
        {
            fprintf(stderr, "Unknown \"submitminingsolution\" Response.\n");
        }
    }

    return reply;
}

int CpuMiner(void)
{
    int searchDuration = gArgs.GetArg("-duration", 30);
    int nblocks = gArgs.GetArg("-nblocks", -1); //-1 mine forever

    UniValue mineresult;
    bool found = false;

    if (0 == nblocks)
    {
        printf("Nothing to do for zero (0) blocks\n");
        return 0;
    }

    while (0 != nblocks)
    {
        UniValue reply;
        UniValue result;
        UniValue nbits;
        string strPrint;
        int nRet = 0;
        try
        {
            // Execute and handle connection failures with -rpcwait
            const bool fWait = true;
            do
            {
                try
                {
                    if (found)
                    {
                        // Submit the solution.
                        // Called here so all exceptions are handled properly below.
                        RPCSubmitSolution(mineresult, nblocks);
                        if (nblocks == 0)
                            return 0; // Done mining exit program
                        found = false; // Mine again
                    }

                    UniValue params(UniValue::VARR);
                    params.push_back(UniValue(true));
                    reply = CallRPC("getminingcandidate", params);

                    // Parse reply
                    result = find_value(reply, "result");
                    const UniValue &error = find_value(reply, "error");

                    if (!error.isNull())
                    {
                        // Error
                        int code = error["code"].get_int();
                        if (fWait && code == RPC_IN_WARMUP)
                            throw CConnectionFailed("server in warmup");
                        strPrint = "error: " + error.write();
                        nRet = abs(code);
                        if (error.isObject())
                        {
                            UniValue errCode = find_value(error, "code");
                            UniValue errMsg = find_value(error, "message");
                            strPrint = errCode.isNull() ? "" : "error code: " + errCode.getValStr() + "\n";

                            if (errMsg.isStr())
                                strPrint += "error message:\n" + errMsg.get_str();
                        }
                    }
                    else
                    {
                        nbits = find_value(result, "nBits");
                        if(nbits.isNull() && !nbits.isStr())
                        {
                            strPrint = "No valid difficulty (nBits) supplied.";
                            return 0;  // exit
                        }

                        // Result
                        if (result.isNull())
                            strPrint = "";
                        else if (result.isStr())
                            strPrint = result.get_str();
                        else
                            strPrint = result.write(2);
                    }
                    // Connection succeeded, no need to retry.
                    break;
                }
                catch (const CConnectionFailed &c)
                {
                    if (fWait)
                    {
                        printf("Warning: %s\n", c.what());
                        MilliSleep(1000);
                    }
                    else
                        throw;
                }
            } while (fWait);
        }
        catch (const boost::thread_interrupted &)
        {
            throw;
        }
        catch (const std::exception &e)
        {
            strPrint = string("error: ") + e.what();
            nRet = EXIT_FAILURE;
        }
        catch (...)
        {
            PrintExceptionContinue(NULL, "CommandLineRPC()");
            throw;
        }

        if (strPrint != "")
        {
            if (nRet != 0)
                fprintf(stderr, "%s\n", strPrint.c_str());
            // Actually do some mining
            if (result.isNull())
            {
                MilliSleep(1000);
            }
            else
            {
                found = false;
                mineresult = CpuMineBlock(searchDuration, result, found);
                if (!found)
                {
                    // printf("Mining did not succeed\n");
                    mineresult.setNull();
                }
                // The result is sent to bitcoind above when the loop gets to it.
                // See:   RPCSubmitSolution(mineresult,nblocks);
                // This is so RPC Exceptions are handled in one place.
            }
        }
    }
    return 0;
}

void static MinerThread()
{
    while (1)
    {
        try
        {
            CpuMiner();
        }
        catch (const std::exception &e)
        {
            PrintExceptionContinue(&e, "CommandLineRPC()");
        }
        catch (...)
        {
            PrintExceptionContinue(NULL, "CommandLineRPC()");
        }
    }
}

int main(int argc, char *argv[])
{
    SetupEnvironment();
    if (!SetupNetworking())
    {
        fprintf(stderr, "Error: Initializing networking failed\n");
        exit(1);
    }

    try
    {
        std::string appname("bitcoin-miner");
        std::string usage = "\n" + _("Usage:") + "\n" + "  " + appname + " [options] " + "\n";
        int ret = AppInitRPC(argc, argv, usage, HelpMessage);
        if (ret != CONTINUE_EXECUTION)
            return ret;
    }
    catch (const std::exception &e)
    {
        PrintExceptionContinue(&e, "AppInitRPC()");
        return EXIT_FAILURE;
    }
    catch (...)
    {
        PrintExceptionContinue(NULL, "AppInitRPC()");
        return EXIT_FAILURE;
    }

    int nThreads = gArgs.GetArg("-cpus", 1);
    boost::thread_group minerThreads;
    for (int i = 0; i < nThreads - 1; i++)
        minerThreads.create_thread(MinerThread);

    int ret = EXIT_FAILURE;
    try
    {
        ret = CpuMiner();
    }
    catch (const std::exception &e)
    {
        PrintExceptionContinue(&e, "CommandLineRPC()");
    }
    catch (...)
    {
        PrintExceptionContinue(NULL, "CommandLineRPC()");
    }
    return ret;
}

max_stars_repo_name: adampaigge/bitcoin-supernova

max_issues_repo_name: adampaigge/bitcoin-supernova

max_forks_repo_name: adampaigge/bitcoin-supernova


text:
// Copyright (c) 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#ifndef NIXPY_ENTITY_H
#define NIXPY_ENTITY_H

#include <boost/python.hpp>

#include <nix.hpp>
#include <accessors.hpp>
#include <docstrings.hpp>

namespace nixpy {

template<typename T>
std::string toStr(T number) {
    std::stringstream s;
    s << number;
    return s.str();
}

/**
 * Exports a specialisation of nix::base::Entity wich can be further used
 * as a subclass.
 *
 * @param type_name          Name of the type used for the specialisation.
 */
template<typename T>
struct PyEntity {

    static void do_export(const std::string& type_name) {
        using namespace boost::python;

        std::string real_name = "__Entity" + type_name;
        class_<nix::base::Entity<T>>(real_name.c_str(), no_init)
            .add_property("id", &nix::base::Entity<T>::id, doc::entity_id)
            .add_property("created_at", &nix::base::Entity<T>::createdAt, doc::entity_crated_at)
            .def("force_created_at", &nix::base::Entity<T>::forceCreatedAt, doc::entity_force_created_at)
            .add_property("updated_at", &nix::base::Entity<T>::updatedAt, doc::entity_updated_at)
            .def("force_updated_at", &nix::base::Entity<T>::forceUpdatedAt, doc::entity_force_updated_at);
    }

};

template<typename T>
struct PyNamedEntity {

    DEF_OPT_SETTER(std::string, nix::base::NamedEntity<T>, definition, definition_setter)

    static void do_export(const std::string& type_name) {
        using namespace boost::python;

        std::string real_name = "__NamedEntity" + type_name;
        PyEntity<T>::do_export(type_name);
        class_<nix::base::NamedEntity<T>, bases<nix::base::Entity<T>>>(real_name.c_str(), no_init)
            .add_property("name",
                          GETTER(std::string, nix::base::NamedEntity<T>, name),
                          doc::entity_name)
            .add_property("type",
                          GETTER(std::string, nix::base::NamedEntity<T>, type),
                          REF_SETTER(std::string, nix::base::NamedEntity<T>, type),
                          doc::entity_type)
            .add_property("definition",
                          OPT_GETTER(std::string, nix::base::NamedEntity<T>, definition),
                          &definition_setter,
                          doc::entity_definition);
    }
};

template<typename T>
struct PyEntityWithMetadata {

    DEF_ENT_GETTER(nix::Section, nix::base::EntityWithMetadata<T>, metadata, metadata_getter)
    DEF_OPT_SETTER(nix::Section, nix::base::EntityWithMetadata<T>, metadata, metadata_setter)

    static void do_export(const std::string& type_name) {
        using namespace boost::python;

        std::string real_name = "__EntityWithMetadata" + type_name;
        PyNamedEntity<T>::do_export(type_name);
        class_<nix::base::EntityWithMetadata<T>, bases<nix::base::NamedEntity<T>>>(real_name.c_str(), no_init)
            .add_property("metadata", &metadata_getter, &metadata_setter, doc::entity_metadata);
    }

};

template<typename T>
struct PyEntityWithSources {

    DEF_ENT_GETTER_BY(nix::Source, nix::base::EntityWithSources<T>, getSource, size_t, get_source_by_pos)
    DEF_ENT_GETTER_BY(nix::Source, nix::base::EntityWithSources<T>, getSource, std::string, get_source_by_id)

    static void do_export(const std::string& type_name) {
        using namespace boost::python;

        // TODO create mixin for all bases of EntityWithSources
        std::string real_name = "__EntityWithSources" + type_name;
        PyEntityWithMetadata<T>::do_export(type_name);
        class_<nix::base::EntityWithSources<T>, bases<nix::base::EntityWithMetadata<T>>>(real_name.c_str(), no_init)
            .def("_source_count", &nix::base::EntityWithSources<T>::sourceCount)
            .def("_has_source_by_id", CHECKER(std::string, nix::base::EntityWithSources<T>, hasSource))
            .def("_get_source_by_id", &get_source_by_id)
            .def("_get_source_by_pos", &get_source_by_pos)
            .def("_add_source_by_id", REF_SETTER(std::string, nix::base::EntityWithSources<T>, addSource))
            .def("_remove_source_by_id", REMOVER(std::string, nix::base::EntityWithSources<T>, removeSource));
    }
};

#if PY_VERSION_HEX >= 0x03000000
#define NIXPY_DO_EXPORT_RETTYPE void *
#define NIXPY_DO_EXPORT_RETVAL  nullptr
#else
#define NIXPY_DO_EXPORT_RETTYPE void
#define NIXPY_DO_EXPORT_RETVAL
#endif

struct PyResult {
    static void do_export();
};

struct PyBlock {
    static void do_export();
};

struct PyFile {
    static void do_export();
};

struct PyProperty {
    static void do_export();
};

struct PySection {
    static void do_export();
};

struct PyValue {
    static void do_export();
};

struct PySource {
    static void do_export();
};

struct PyDataArray {
    static void do_export();
};

struct PyDataSet {
    static NIXPY_DO_EXPORT_RETTYPE do_export();
};

struct PyDimensions {
    static void do_export();
};

struct PyFeature {
    static void do_export();
};

struct PyTag {
    static void do_export();
};

struct PyMultiTag {
    static void do_export();
};

struct PyException {
    static void do_export();
};

struct PyGroup {
    static void do_export();
};
}

#endif

max_stars_repo_name: gicmo/nixpy

max_issues_repo_name: gicmo/nixpy

max_forks_repo_name: gicmo/nixpy


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <boost/math/special_functions/hermite.hpp>
#include <eve/function/hermite.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/platform.hpp>
#include <cmath>

TTS_CASE_TPL("Check eve::hermite return type", EVE_TYPE)
{
  TTS_EXPR_IS(eve::hermite(0, T(0)), T);
}

TTS_CASE_TPL("Check eve::hermite behavior", EVE_TYPE)
{

  auto eve__hermite =  [](auto n, auto x) { return eve::hermite(n, x); };
  auto boost_hermite =  [](auto n, auto x) { return boost::math::hermite(n, x); };
  if constexpr( eve::platform::supports_invalids )
  {
    TTS_ULP_EQUAL(eve__hermite(2u, eve::minf(eve::as<T>())), eve::inf(eve::as<T>()), 0);
    TTS_ULP_EQUAL(eve__hermite(2u, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);
    TTS_ULP_EQUAL(eve__hermite(3u, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
    TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
    TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
  }

  for(unsigned int i=0; i < 10; ++i)
  {
    TTS_ULP_EQUAL(eve__hermite(i, T(10)), T(boost_hermite(i, 10)), 1);
    TTS_ULP_EQUAL(eve__hermite(i, T(5)), T(boost_hermite(i, 5)), 1);
    TTS_ULP_EQUAL(eve__hermite(i, T(2)), T(boost_hermite(i, 2)), 1);
    TTS_ULP_EQUAL(eve__hermite(i, T(1)), T(boost_hermite(i, 1)), 1);
    TTS_ULP_EQUAL(eve__hermite(i, T(0)), T(boost_hermite(i, 0)), 1);
  }
}

max_stars_repo_name: orao/eve

max_issues_repo_name: orao/eve

max_forks_repo_name: orao/eve


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

#define BOOST_TEST_MODULE TestSvmPtr
#include <boost/test/unit_test.hpp>

#include <boost/compute/core.hpp>
#include <boost/compute/svm.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/utility/source.hpp>

#include "check_macros.hpp"
#include "context_setup.hpp"

namespace compute = boost::compute;

BOOST_AUTO_TEST_CASE(empty)
{
}

#ifdef CL_VERSION_2_0
BOOST_AUTO_TEST_CASE(alloc)
{
    compute::svm_ptr<int> ptr = compute::svm_alloc<int>(context, 8);
    compute::svm_free(context, ptr);
}

BOOST_AUTO_TEST_CASE(sum_svm_kernel)
{
    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
        __kernel void sum_svm_mem(__global const int *ptr, __global int *result)
        {
            int sum = 0;
            for(uint i = 0; i < 8; i++){
                sum += ptr[i];
            }
            *result = sum;
        }
    );

    compute::program program =
        compute::program::build_with_source(source, context);

    compute::kernel sum_svm_mem_kernel = program.create_kernel("sum_svm_mem");

    int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    compute::svm_ptr<int> ptr = compute::svm_alloc<int>(context, 8);
    queue.enqueue_svm_memcpy(ptr.get(), data, 8 * sizeof(int));

    compute::vector<int> result(1, context);

    sum_svm_mem_kernel.set_arg(0, ptr);
    sum_svm_mem_kernel.set_arg(1, result);
    queue.enqueue_task(sum_svm_mem_kernel);

    CHECK_RANGE_EQUAL(int, 1, result, (36));

    compute::svm_free(context, ptr);
}
#endif // CL_VERSION_2_0

BOOST_AUTO_TEST_SUITE_END()