text:
#include "tokenizer.hpp"
#include "gtest/gtest.h"
#include <cstring>
#include <iostream>
#include <boost/log/trivial.hpp>

class TokenizerTest : public ::testing::Test
{

public:
    virtual void SetUp()
    {
    }

    virtual void TearDown()
    {
    }
};

TEST_F( TokenizerTest, no_quote_no_escape )
{
    std::vector<std::string> tokens = tokenize( "a bb ccc" );
    ASSERT_EQ( 3, tokens.size() ) <<  "3 tokens";
    EXPECT_EQ( "a",   tokens[0] );
    EXPECT_EQ( "bb",  tokens[1] );
    EXPECT_EQ( "ccc", tokens[2] );
}

TEST_F( TokenizerTest, oen_token )
{
    std::vector<std::string> tokens = tokenize( "one" );
    ASSERT_EQ( 1, tokens.size() ) <<  "1 token";
    EXPECT_EQ( "one",   tokens[0] );
}

TEST_F( TokenizerTest, quoted_token )
{
    std::vector<std::string> tokens = tokenize( "\"a bb ccc\" 22 333" );
    ASSERT_EQ( 3, tokens.size() ) <<  "3 token";
    EXPECT_EQ( "a bb ccc", tokens[0] );
    EXPECT_EQ( "22",       tokens[1] );
    EXPECT_EQ( "333",      tokens[2] );
}

TEST_F( TokenizerTest, escaped_token )
{
    std::vector<std::string> tokens = tokenize( "1\\2345 \\ 678" );
    ASSERT_EQ( 2, tokens.size() ) <<  "2 token";
    EXPECT_EQ( "12345", tokens[0] );
    EXPECT_EQ( " 678",  tokens[1] );
}

TEST_F( TokenizerTest, SOA )
{
    const char *ZONE_CONFIG_FULL_SOA =  "example.com.  3600 IN SOA ns01.example.com. hostmaster.example.com. 2017050101 3600 1800 8640000 300";
    std::vector<std::string> tokens = tokenize( ZONE_CONFIG_FULL_SOA );

    ASSERT_EQ( 11, tokens.size() ) <<  "11 token";
    EXPECT_EQ( "example.com.",            tokens[0] );
    EXPECT_EQ( "3600",                    tokens[1] );
    EXPECT_EQ( "IN",                      tokens[2] );
    EXPECT_EQ( "SOA",                     tokens[3] );
    EXPECT_EQ( "ns01.example.com.",       tokens[4] );
    EXPECT_EQ( "hostmaster.example.com.", tokens[5] );
    EXPECT_EQ( "2017050101",              tokens[6] );
    EXPECT_EQ( "3600",                    tokens[7] );
    EXPECT_EQ( "1800",                    tokens[8] );
    EXPECT_EQ( "8640000",                 tokens[9] );
    EXPECT_EQ( "300",                     tokens[10] );
}

TEST_F( TokenizerTest, SOA2 )
{
    const char *ZONE_CONFIG_FULL_SOA =  "siskrn.co.				      3600 IN SOA	siskrn.co. hostmaster.siskrn.co. 1500338838 86400 3600 604800 10800";
    std::vector<std::string> tokens = tokenize( ZONE_CONFIG_FULL_SOA );

    ASSERT_EQ( 11, tokens.size() ) <<  "11 token";
    EXPECT_EQ( "siskrn.co.",            tokens[0] );
    EXPECT_EQ( "3600",                  tokens[1] );
    EXPECT_EQ( "IN",                    tokens[2] );
    EXPECT_EQ( "SOA",                   tokens[3] );
    EXPECT_EQ( "siskrn.co.",            tokens[4] );
    EXPECT_EQ( "hostmaster.siskrn.co.", tokens[5] );
    EXPECT_EQ( "1500338838",            tokens[6] );
    EXPECT_EQ( "86400",                 tokens[7] );
    EXPECT_EQ( "3600",                  tokens[8] );
    EXPECT_EQ( "604800",                tokens[9] );
    EXPECT_EQ( "10800",                 tokens[10] );
}

int main( int argc, char **argv )
{
    ::testing::InitGoogleTest( &argc, argv );
    return RUN_ALL_TESTS();
}

ext: cpp

max_stars_repo_name: sischkg/nxnsattack

max_issues_repo_name: sischkg/dns-fuzz-server

max_forks_repo_name: sischkg/dns-fuzz-server


text: #include <boost/geometry/algorithms/distance.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <iostream>
#include <unordered_map>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <Galois/Galois.h>
#include <Galois/Graph/Graph.h>

//#include <cstring>
#include <string>
#include <fstream>
using namespace std;
using namespace boost;

typedef enum{pi,po,nd,op} node_type;
typedef Galois::InsertBag<GNode> Bag;

struct Node {
 string label_type;//a0,b0...
 node_type type;// pi,po,nd
 bool simplified;
 int fanins; // Not required as of now
 bool fanout; //Not required as of now
 int level;
 };

typedef Galois::Graph::FirstGraph<Node,int,true> Graph;

Graph g;

int node_index = 0;
vector<Graph::GraphNode> gnodes;

vector<string> fields;

bool checkWorkability(Graph::GraphNode gnode){
	int count = 0;
	for (Graph::edge_iterator edge : g.out_edges(gnode)) {
		int edgedata = g.getEdgeData(edge);
	   	if(edgedata == 1|| edgedata ==2)
	   		count++;
	   	}
	if (count > 1)
		return false;
	else
		return true;
}

bool isEqualNodes(Graph::GraphNode gnode1, Graph::GraphNode gnode2){
	int count = 0;

	if(g.getData(gnode1).label_type==g.getData(gnode2).label_type){
		//cout<< "same node"<<endl;
		return true;
	}

	for (Graph::edge_iterator edge1 : g.out_edges(gnode1)){
		for (Graph::edge_iterator edge2 : g.out_edges(gnode2)){
			if(g.getEdgeData(edge1)== 3)
				if(g.getEdgeData(edge2)== 3)
					if(g.getEdgeDst(edge1)==g.getEdgeDst(edge2)){
						count++;
					}
		}
	}
	if(count == 2)
		return true;
	else
		return false;
}

bool find_cut(Graph::GraphNode &top,Graph::GraphNode &child_left,Graph::GraphNode &child_right)
{
	if ( g.getData(top).level != 0 && g.getData(top).level != 1) {
		for (Graph::edge_iterator edge : g.out_edges(top)){
			Graph::GraphNode dst = g.getEdgeDst(edge);
			if(g.getEdgeData(edge) == 3){
				if(child_left==NULL){
					child_left=dst;
				}
				else{
					child_right=dst;
				}
			}
		}
		return true;
	}
	else
		return false;
}

void parseFileintoGraph(string inFile, unordered_map <string, int> &map){
	ifstream fin;
	Node output;
	fin.open(inFile); // open a file
	if (!fin.good()){
		cout << "file not found\n";

	}
	else
	// read each line of the file
	while (!fin.eof())
	{
	// read an entire line into memory
	string line;
	getline(fin,line);
	trim(line);
	split(fields, line, is_any_of(" "));
	Node n;
	if(fields[0].compare("input") == 0 || fields[0].compare("output") == 0||fields[0].compare("wire") == 0)
	{
		for(unsigned i =1;i<fields.size();i++){
			//add to hash map to index to corresponding node in array
			if(fields[i].size()>1)
			{
				//Add data to each node for level and type of input
				if(fields[0].compare("input") == 0)
				{
					n.type = pi;
					n.level = 0;
					n.label_type = fields[i].substr(0,fields[i].length()-1);

					//nodes[node_index].type = pi;
					//nodes[node_index].level = 0;
					//nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1);
				}
				if(fields[0].compare("output") == 0)
				{
					n.type = po;
					n.level = -1;
					n.label_type = fields[i].substr(0,fields[i].length()-1);

					output.type = op;
					output.level = -2;
					output.label_type = n.label_type+"_out";

					//nodes[node_index].type = po;
					//nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1);
				}
				if(fields[0].compare("wire") == 0)
				{
					n.type = nd;
					n.level = -2;
					n.label_type = fields[i].substr(0,fields[i].length()-1);
					//nodes[node_index].type = nd;
					//nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1);
				}
				cout<<"Check ----> "<< fields[i].substr(0,fields[i].length()-1) <<endl;
				//remove last char b/c its ',' or ';'
				map[fields[i].substr(0,fields[i].length()-1)] = node_index;
				//gnodes[node_index] = g.createNode(nodes[node_index]);
				gnodes.push_back(g.createNode(n));

				g.addNode(gnodes[gnodes.size()-1]);
				//cout << "node index: "<< node_index<<endl;
				node_index++;
				/*For storing output from the output node(No dangling edges on the final node) in the case that it is negated like in OR case*/
				if(fields[0].compare("output") == 0)
				{
					map[output.label_type] = node_index;
					gnodes.push_back(g.createNode(output));
					g.addNode(gnodes[gnodes.size()-1]);

					g.getEdgeData(g.addEdge(gnodes[node_index-1],gnodes[node_index])) = 1;
					node_index++;
				}
			}

		}
	}
	//cout <<"compare assign"<<endl;
	if(fields[0].compare("assign") == 0)
	{
		int level1,level2;
		string f1,f3,f5;
		f1 = fields[1];
		f3 = fields[3];
		f5 = fields[5];
		if(fields[4].compare("|") == 0)
		{	//Edge weight: 2- Negative 1 - Positive
			f3 = f3.substr(0,f3.length());
			f5 = f5.substr(0,f5.length()-1);
			g.getEdgeData(g.addEdge(gnodes[map[f3]]//src
										   ,gnodes[map[f1]])) = 2;//dest

			g.getEdgeData(g.addEdge(gnodes[map[f5]]
										   ,gnodes[map[f1]])) = 2;

			cout << fields[1] << fields[3] << fields[5] << endl;
			g.getEdgeData(g.addEdge(gnodes[map[f1]],gnodes[map[f1+"_out"]])) = 2; //****Hack*** Use edge iterators for identifying final nodes

			level1 = g.getData(gnodes[map[f3]]).level;
			level2 = g.getData(gnodes[map[f5]]).level;
			g.getEdgeData(g.addEdge(gnodes[map[f1]],
					  gnodes[map[f3]])) = 3;//back edges to determine fanins -> wt. = 3
			g.getEdgeData(g.addEdge(gnodes[map[f1]],
					  gnodes[map[f5]])) = 3;//back edges to determins fanins -> wt. = 3
		}

		else
		{	size_t invert = fields[3].find_first_of("~");
			if (invert != string::npos){
				f3 = f3.substr(1,f3.length());
				//addEdge(src,dest)
				//remove the '~' from the start of string
				//map[string] returns node index to find which node
				g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 2;//
				level1 = g.getData(gnodes[map[f3]]).level;
				g.getEdgeData(g.addEdge(gnodes[map[f1]],
							  gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3
			}
			else{
				g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 1;
				level1 = g.getData(gnodes[map[f3]]).level;
				g.getEdgeData(g.addEdge(gnodes[map[f1]],
						  gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3

			}
			invert = fields[5].find_first_of("~");
			if (invert != string::npos){
				f5 = f5.substr(1,f5.length()-2);
				//remove first and last char b/c '~' to start and ';' at th
				//cout <<fields[5] << " substr"<<fields[5].substr(1,fields[5].length()-1)<<" "<<map[fields[5].substr(1,fields[5].length()-1)]<< " "<< nodes[map[fields[5].substr(1,fields[5].length()-1)]].label_type <<endl;
				g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 2;
				level2 = g.getData(gnodes[map[f5]]).level;
				g.getEdgeData(g.addEdge(gnodes[map[f1]],
						  gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3
			}
			else{
				f5 = f5.substr(0,f5.length()-1);
				g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 1;
				level2 = g.getData(gnodes[map[f5]]).level;
				g.getEdgeData(g.addEdge(gnodes[map[f1]],
						  gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3
			}
		}

	if(level1>=level2)
		g.getData(gnodes[map[fields[1]]]).level= level1+1;
	else
		g.getData(gnodes[map[fields[1]]]).level= level2+1;
	}

	}
}

void getChildren(Graph::GraphNode parent, Graph::GraphNode &child1, Graph::GraphNode &child2){
	bool  a = true;
	for (Graph::edge_iterator edge : g.out_edges(parent)){
			if(g.getEdgeData(edge)==3){
				if (a){
					child1 = g.getEdgeDst(edge);
					a = !a;
				}
				else
					child2 = g.getEdgeDst(edge);
			}
		}
}

void make_replacement(Graph::GraphNode node, Graph::GraphNode match_node){
	Graph::GraphNode child1,child2,temp;
	getChildren(node,child1,child2);
	for(Graph::edge_iterator edge : g.out_edges(match_node)){
		temp = g.getEdgeDst(edge);
		if(!((isEqualNodes(child1,temp))||isEqualNodes(child2,temp))){
			g.getEdgeData(g.addEdge(node,temp))=g.getEdgeData(edge);
			g.getEdgeData(g.addEdge(temp,node))=3;//Assigning back edges from the parent nodes of the removed copy node to the original node
		}

	}
	g.removeEdge(child1,g.findEdge(child1,match_node));
	g.removeEdge(child2,g.findEdge(child2,match_node));
	g.removeNode(match_node);
}

bool checkxor(Graph::GraphNode node){
	Graph::GraphNode inode1=NULL,inode2=NULL;
	Graph::GraphNode input1=NULL,input2=NULL,input3=NULL,input4=NULL;
	getChildren(node,inode1,inode2);
	cout<<g.getData(inode1).label_type<<" "<<g.getData(inode2).label_type<<endl;
	getChildren(inode1, input1, input2);
	getChildren(inode2, input3, input4);
	if(g.getEdgeData(g.findEdge(inode1,node))==2 && g.getEdgeData(g.findEdge(inode2,node))==2){
	cout<<"Inside condn inode"<<endl;
	if(isEqualNodes(input1,input3)&&isEqualNodes(input2,input4))
		if(g.getEdgeData(g.findEdge(input1,inode1))!=g.getEdgeData(g.findEdge(input3,inode2))){
			cout << "nequal edges\n";
			if(g.getEdgeData(g.findEdge(input2,inode1))!=g.getEdgeData(g.findEdge(input4,inode2))){
				cout << "true\n";
				return true;
			}
		}
	}
	cout<<"false\n";
	return false;
}
/*
bool checkxnor(Graph::GraphNode node){
	find_cut(node)

}
*/

void convertxor_cost(Graph::GraphNode node){
	int cost=0;
	Graph::GraphNode inode1=NULL,inode2=NULL;
	Graph::GraphNode input1=NULL,input2=NULL,input3=NULL,input4=NULL;
	string child_label,parent_label;
	getChildren(node,inode1,inode2);
	getChildren(inode1, input1, input2);
	getChildren(inode2, input3, input4);
	if(g.getEdgeData(g.findEdge(input1,inode1))==2){
		cout<<"Reassigning edge for "<<g.getData(input1).label_type<<g.getData(inode1).label_type<<endl;
		g.getEdgeData(g.addEdge(input1,inode1))=1;
		cout<<"Changed edge data "<<g.getEdgeData(g.findEdge(input1,inode1))<<endl;
	}
	else
		g.getEdgeData(g.addEdge(input2,inode1))=1;

	if(g.getEdgeData(g.findEdge(input3,inode2))==1)
		g.getEdgeData(g.addEdge(input3,inode2))=2;
	else
		g.getEdgeData(g.addEdge(input4,inode2))=2;

	for (Graph::edge_iterator edge : g.out_edges(node)){
		cout<<"Node: "<<g.getData(node).label_type<<" -> "<<g.getData(g.getEdgeDst(edge)).label_type<<"Weight ="<< g.getEdgeData(edge)<<endl;
		if(g.getEdgeData(edge) == 2)
			g.getEdgeData(edge) = 1;
		else if(g.getEdgeData(edge) == 1)
			g.getEdgeData(edge) = 2;
	}

	/*Compute cost*/
	for (Graph::edge_iterator edge : g.out_edges(input1)){
		Graph::GraphNode dst = g.getEdgeDst(edge);
		if((g.getData(dst).label_type != g.getData(inode1).label_type) &&  (g.getData(dst).label_type != g.getData(inode2).label_type)){
			if(isEqualNodes(dst,inode1)){
				cout<<"Match found: "<< g.getData(dst).label_type <<endl;
				make_replacement(inode1,dst);
				cost++;
			}
			else if(isEqualNodes(dst,inode2)){
				cout<<"Match found: "<< g.getData(dst).label_type <<endl;
				make_replacement(inode2,dst);
				cost++;
			}
		}
	}
}

void printGraph() {
	for ( Graph::GraphNode src : g){
   		//Graph::GraphNode src = *ii;
		cout <<"src: "<< g.getData(src).label_type;
		cout <<" level: "<<g.getData(src).level;

		for (Graph::edge_iterator edge : g.out_edges(src)) {
   			Graph::GraphNode dst = g.getEdgeDst(edge);
     		cout <<" dest: "<< g.getData(dst).label_type;
     		int edgeData = g.getEdgeData(edge);
     		cout << " edge data " << edgeData;
     		//assert(edgeData == 5);
   		}
	   	cout <<endl;
 	}
}

// Populates max_level with the max level of the graph, g.  It also populates levelnodes that lists all nodes for each level.
void groupNodesByLevel(unordered_map<int, vector<string>> & levelnodes, int & max_level) {
	max_level = 0;

	for ( Graph::GraphNode src : g) {
		// if key already exists, append node to the end
		if (levelnodes.count(g.getData(src).level) > 0) { // key exists
			levelnodes[g.getData(src).level].push_back(g.getData(src).label_type);
		}
		else { // key doesn't exist, create vector
			vector<string> v;
			levelnodes[g.getData(src).level] = v;
		}

		if (g.getData(src).level > max_level)
		    max_level = g.getData(src).level;
 	}
}

/* Under constuction
struct Process {
	Bag& result;
	Process(Bag& _result) : result(_result) { }
	void operator()(GNode src, Galois::UserContext<GNode>& ctx) {
		Graph::GraphNode child_left=NULL,child_right=NULL;
		if(find_cut(gnodes[map["s0"]],child_left,child_right)){
			cout<<"Src node:"<<g.getData(gnodes[map["s0"]]).label_type << endl;
			cout<<"Child node 1:"<<g.getData(child_left).label_type << endl;
			cout<<"Child node 2:"<<g.getData(child_right).label_type << endl;
		}

		if(checkxor(gnodes[map["s0"]])){
			convertxor_cost(gnodes[map["s0"]]);
		}
	}
};
*/

int main(int argc, char *argv[]) {
	unordered_map <string, int> map;
	if ( argc != 2 ){
    		cout<<"usage: "<< argv[0] <<" <filename>\n";
		return 0;
	}
  	else
  			parseFileintoGraph(argv[1],map);

	//cout << g.getData(gnodes[0]).label_type << endl;
	// Traverse graph
 	//for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) {
	printGraph();
 	if(checkWorkability(gnodes[map["n15"]]))
 		cout << "1 output"<<endl;
 	else
 		cout <<"more than 1 output"<<endl;

	bool out;

	// Group nodes by level
	unordered_map<int, vector<string>> levelnodes;
	int max_level;
	groupNodesByLevel(levelnodes, max_level);

	// Prints each node by level.
	for(int level = 0 ; level <= max_level ; level++) {
		cout << "Current Level: " << level << endl;
		for( int i = 0 ; i < levelnodes[level].size() ; i++) {
			cout << levelnodes[level][i] << " ";
		}
		cout << endl;
	}

	Graph::GraphNode child_left=NULL,child_right=NULL;
	if(find_cut(gnodes[map["s0"]],child_left,child_right)){
		cout<<"Src node:"<<g.getData(gnodes[map["s0"]]).label_type << endl;
		cout<<"Child node 1:"<<g.getData(child_left).label_type << endl;
		cout<<"Child node 2:"<<g.getData(child_right).label_type << endl;
	}

	if(checkxor(gnodes[map["s0"]])){
		convertxor_cost(gnodes[map["s0"]]);
	}

    /** Shows that it works
		//if(isEqualNodes(gnodes[map["n8"]],gnodes[map["n8"]]))
		//	cout << "equal nodes"<<endl;
		checkxor(gnodes[map["s0"]]);
		checkxor(gnodes[map["n14"]]);
		//checkxor(gnodes[map["s1"]]);
		//checkxor(gnodes[map["s2"]]);

		//checkxnor(gnodes[map["s0"]]);
		if(checkxor(gnodes[map["s0"]])){
			convertxor_cost(gnodes[map["s0"]]);
		}

		printGraph();

		if(checkxor(gnodes[map["n14"]])){
			convertxor_cost(gnodes[map["n14"]]);
		}

		//cout<<"Edge from a0 to n8 "<<g.getEdgeData(g.findEdge(gnodes[map["a0"]],gnodes[map["n8"]]))<<endl;

		printGraph();

		if(checkxor(gnodes[map["s1"]])){
			convertxor_cost(gnodes[map["s1"]]);
		}

		printGraph();
	*/

	return 0;
}


text:
#ifndef META_HS_TOKEN_HPP
#define META_HS_TOKEN_HPP

// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <ast.hpp>
#include <except_keywords.hpp>

#include <boost/metaparse/string.hpp>
#include <boost/metaparse/token.hpp>
#include <boost/metaparse/always_c.hpp>
#include <boost/metaparse/lit_c.hpp>
#include <boost/metaparse/one_of.hpp>
#include <boost/metaparse/last_of.hpp>
#include <boost/metaparse/return_.hpp>
#include <boost/metaparse/int_.hpp>
#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>
#include <boost/metaparse/alphanum.hpp>
#include <boost/metaparse/transform.hpp>
#include <boost/metaparse/letter.hpp>
#include <boost/metaparse/keyword.hpp>
#include <boost/metaparse/optional.hpp>

#include <boost/mpl/lambda.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector.hpp>

namespace token
{
  typedef
    boost::metaparse::token<
      boost::metaparse::always_c<'+',boost::metaparse::string<'.','+','.'> >
    >
    plus;

  typedef
    boost::metaparse::token<
      boost::metaparse::always_c<'-',boost::metaparse::string<'.','-','.'> >
    >
    minus;

  typedef
    boost::metaparse::token<
      boost::metaparse::always_c<'*',boost::metaparse::string<'.','*','.'> >
    >
    mult;

  typedef
    boost::metaparse::token<
      boost::metaparse::always_c<'/',boost::metaparse::string<'.','/','.'> >
    >
    div;

  typedef
    boost::metaparse::token<
      boost::metaparse::one_of<
        boost::metaparse::last_of<
          boost::metaparse::lit_c<'='>,
          boost::metaparse::lit_c<'='>,
          boost::metaparse::return_<
            boost::metaparse::string<'.','=','=','.'>
          >
        >,
        boost::metaparse::last_of<
          boost::metaparse::lit_c<'/'>,
          boost::metaparse::lit_c<'='>,
          boost::metaparse::return_<
            boost::metaparse::string<'.','/','=','.'>
          >
        >,
        boost::metaparse::last_of<
          boost::metaparse::lit_c<'<'>,
          boost::metaparse::one_of<
            boost::metaparse::always_c<
              '=',
              boost::metaparse::string<'.','<','=','.'>
            >,
            boost::metaparse::return_<
              boost::metaparse::string<'.','<','.'>
            >
          >
        >,
        boost::metaparse::last_of<
          boost::metaparse::lit_c<'>'>,
          boost::metaparse::optional<
            boost::metaparse::always_c<
              '=',
              boost::metaparse::string<'.','>','=','.'>
            >,
            boost::metaparse::string<'.','>','.'>
          >
        >
      >
    >
    cmp;

  typedef
    boost::metaparse::token<boost::metaparse::lit_c<'('> >
    open_bracket;

  typedef
    boost::metaparse::token<boost::metaparse::lit_c<')'> >
    close_bracket;

  typedef
    boost::metaparse::token<boost::metaparse::lit_c<'='> >
    define;

  typedef boost::metaparse::token<boost::metaparse::int_> int_;

  typedef
    boost::metaparse::token<
      except_keywords<
        boost::metaparse::foldl_reject_incomplete_start_with_parser<
          boost::metaparse::one_of<
            boost::metaparse::alphanum,
            boost::metaparse::lit_c<'_'>
          >,
          boost::metaparse::transform<
            boost::metaparse::one_of<
              boost::metaparse::letter,
              boost::metaparse::lit_c<'_'>
            >,
            boost::mpl::lambda<
              boost::mpl::push_back<
                boost::metaparse::string<>,
                boost::mpl::_1
              >
            >::type
          >,
          boost::mpl::lambda<
            boost::mpl::push_back<boost::mpl::_1, boost::mpl::_2>
          >::type
        >,
        boost::mpl::vector<
          boost::metaparse::string<'i','f'>,
          boost::metaparse::string<'t','h','e','n'>,
          boost::metaparse::string<'e','l','s','e'>
        >
      >
    >
    name;

  typedef
    boost::metaparse::token<
      boost::metaparse::keyword<boost::metaparse::string<'i','f'> >
    >
    if_;

  typedef
    boost::metaparse::token<
      boost::metaparse::keyword<boost::metaparse::string<'t','h','e','n'> >
    >
    then;

  typedef
    boost::metaparse::token<
      boost::metaparse::keyword<boost::metaparse::string<'e','l','s','e'> >
    >
    else_;
}

#endif


text:
/*
 * Copyright 2013 Andrey Semashev
 *
 * Distributed under the Boost Software License, Version 1.0.
 * See http://www.boost.org/LICENSE_1_0.txt
 */

#ifndef BOOST_WINAPI_TLS_HPP_INCLUDED_
#define BOOST_WINAPI_TLS_HPP_INCLUDED_

#include <boost/winapi/basic_types.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if BOOST_WINAPI_PARTITION_APP_SYSTEM

#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
#if !defined( UNDER_CE )
// Windows CE define TlsAlloc and TlsFree as inline functions in kfuncs.h
BOOST_SYMBOL_IMPORT boost::winapi::DWORD_ WINAPI
TlsAlloc(BOOST_WINAPI_DETAIL_VOID);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI
TlsFree(boost::winapi::DWORD_ dwTlsIndex);
#endif

BOOST_SYMBOL_IMPORT boost::winapi::LPVOID_ WINAPI
TlsGetValue(boost::winapi::DWORD_ dwTlsIndex);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI
TlsSetValue(
    boost::winapi::DWORD_ dwTlsIndex,
    boost::winapi::LPVOID_ lpTlsValue);
} // extern "C"
#endif

namespace boost {
namespace winapi {

using ::TlsAlloc;
using ::TlsFree;
using ::TlsGetValue;
using ::TlsSetValue;

#if defined( BOOST_USE_WINDOWS_H )
const DWORD_ TLS_OUT_OF_INDEXES_ = TLS_OUT_OF_INDEXES;
#else
const DWORD_ TLS_OUT_OF_INDEXES_ = 0xFFFFFFFF;
#endif

const DWORD_ tls_out_of_indexes = TLS_OUT_OF_INDEXES_;

}
}

#endif // BOOST_WINAPI_PARTITION_APP_SYSTEM
#endif // BOOST_WINAPI_TLS_HPP_INCLUDED_

max_stars_repo_name: dilawar/eyesthatblink

max_issues_repo_name: dilawar/eyesthatblink

max_forks_repo_name: dilawar/eyesthatblink


text:
#include <boost/simd/memory/aligned_input_range.hpp>
#include <boost/simd/memory/allocator.hpp>
#include <boost/range/algorithm/copy.hpp>

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

int main()
{
  using boost::simd::pack;
  using boost::simd::allocator;
  using boost::simd::aligned_input_range;

  std::vector<float, allocator<float> > data(16);

  for(std::size_t i=0;i<data.size();++i)
    data[i]  = 1 + i;

  boost::copy( aligned_input_range<4>(data), std::ostream_iterator< pack<float,4> >(std::cout, " "));
  std::cout << std::endl;
}


text:
//
// Copyright (c) 2020 Vinnie Falco (vinnie.falco@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)
//
// Official repository: https://github.com/cppalliance/json
//

#ifndef BOOST_JSON_STATIC_RESOURCE_HPP
#define BOOST_JSON_STATIC_RESOURCE_HPP

#include <boost/json/detail/config.hpp>
#include <boost/json/storage_ptr.hpp>

BOOST_JSON_NS_BEGIN

/** A memory resource using a caller-provided buffer

    This memory resource satisfies allocation requests
    by returning portions of memory from a fixed-size
    buffer specified upon construction. Ownership of
    the buffer is not transferred; the caller is
    responsible for ensuring that the lifetime of the
    buffer extends until the static resource is
    destroyed.
\n

    @par Example
*/
class static_resource final
    : public memory_resource
{
    void* p_;
    std::size_t n_;

public:
    /// Copy constructor (deleted)
    static_resource(
        static_resource const&) = delete;

    /// Copy assignment (deleted)
    static_resource& operator=(
        static_resource const&) = delete;

    /// Destructor
    BOOST_JSON_DECL
    ~static_resource() noexcept;

    /** Constructor

        The resource is constructed to use the specified
        buffer.

        @par Complexity

        Constant.

        @par Exception Safety

        No-throw guarantee.

        @param buffer A pointer to valid storage of at
        least `size` bytes. Ownership is not transferred.

        @param size The number of valid bytes pointed
        to by `buffer`.
    */
    BOOST_JSON_DECL
    static_resource(
        void* buffer,
        std::size_t size) noexcept;

protected:
    /** Allocate memory.
    */
    BOOST_JSON_DECL
    void*
    do_allocate(
        std::size_t n,
        std::size_t align) override;

    /** Deallocate memory.
    */
    BOOST_JSON_DECL
    void
    do_deallocate(
        void* p,
        std::size_t n,
        std::size_t align) override;

    /** Compare for equality.
    */
    BOOST_JSON_DECL
    bool
    do_is_equal(
        memory_resource const& mr
            ) const noexcept override;
};

template<>
struct is_deallocate_trivial<
    static_resource>
{
    static constexpr bool value = true;
};

BOOST_JSON_NS_END

#ifdef BOOST_JSON_HEADER_ONLY
#include <boost/json/impl/static_resource.ipp>
#endif

#endif

max_stars_repo_name: cppalliance-bot/json

max_issues_repo_name: cppalliance-bot/json

max_forks_repo_name: cppalliance-bot/json


text:
#include <cmath>
#include <limits>
#include <stdexcept>
#include <iostream>
#include <boost/filesystem.hpp>
#include <sstream>
#include <cstdlib>
#include <fstream>
#include <cfenv>
#include <X11/xpm.h>
#include <iomanip>
#include <FL/x.H>
#include "utils.hpp"
#include "florb.xpm"

#define CLIPLEFT   (1)  // 0001
#define CLIPRIGHT  (2)  // 0010
#define CLIPBOTTOM (4)  // 0100
#define CLIPTOP    (8)  // 1000

#define CIRCUMFERENCEKM (2*M_PI*6372.7982)

florb::point2d<double> florb::utils::wsg842merc(const florb::point2d<double> &wsg84)
{
    if ((wsg84.x() > 180.0) || (wsg84.x() < -180.0))
        throw std::out_of_range(_("Invalid longitude"));
    if ((wsg84.y() > 90.0) || (wsg84.y() < -90.0))
        throw std::out_of_range(_("Invalid latitude"));

    // Anything above 85 degrees N or S is infinity in the mercator projection,
    // clip here.
    double lat = wsg84.y();
    if (lat > 85.0)
        lat = 85.0;
    else if (lat < -85)
        lat = -85.0;

    // Project to Mercator (360 by 360 square)
    return florb::point2d<double>(
            180.0 + wsg84.x(),
            180.0 - ((180.0/M_PI) * log(tan(M_PI/4.0+lat*(M_PI/180.0)/2.0))));
}

florb::point2d<unsigned long> florb::utils::merc2px(unsigned int z, const florb::point2d<double> &merc)
{
    unsigned long dimxy = dim(z);

    return florb::point2d<unsigned long>(
        (unsigned long)(((double)(dimxy-1)/360.0) * merc.x()),
        (unsigned long)(((double)(dimxy-1)/360.0) * merc.y()));
}

florb::point2d<unsigned long> florb::utils::wsg842px(unsigned int z, const florb::point2d<double> &wsg84)
{
    // Mercator projection
    florb::point2d<double> merc(wsg842merc(wsg84));

    // Unit conversion
    return merc2px(z, merc);
}

florb::point2d<double> florb::utils::px2wsg84(unsigned int z, const florb::point2d<unsigned long> &px)
{
    // Get map dimensions
    unsigned long dimxy = dim(z);

    // Make sure the coordinate is on the map
    if ((px.x() > dimxy) || (px.y() > dimxy))
        throw std::out_of_range(_("Invalid pixel position"));

    // Unit conversion
    florb::point2d<double> mdeg(
            (360.0/((double)dimxy/(double)px.x())),
            (360.0/((double)dimxy/(double)px.y())));

    // Convert mercator to GPS coordinate
    return merc2wsg84(mdeg);
}

florb::point2d<double> florb::utils::merc2wsg84(const florb::point2d<double>& wsg84)
{
    return florb::point2d<double>(
            wsg84.x() - 180.0,
            -((180.0/M_PI) * (2.0 * atan(exp((wsg84.y()-180.0)*M_PI/180.0)) - M_PI/2.0)));
}

florb::point2d<double> florb::utils::px2merc(unsigned int z, const florb::point2d<unsigned long> &px)
{
    unsigned long dimxy = dim(z);

    // Make sure the coordinate is on the map
    if ((px.x() >= dimxy) || (px.y() >= dimxy))
    {
        throw std::out_of_range(_("Invalid pixel position"));
    }

    double x = (px.x() == 0) ? 0.0 : (360.0/((double)(dimxy-1)/(double)px.x()));
    double y = (px.y() == 0) ? 0.0 : (360.0/((double)(dimxy-1)/(double)px.y()));
    return florb::point2d<double>(x,y);
}

unsigned long florb::utils::dim(unsigned int z)
{
    return pow(2.0, z) * 256;
}

double florb::utils::dist(const florb::point2d<double> &p1, const florb::point2d<double> &p2)
{
    if (p1 == p2)
        return 0.0;

    double d2r = (M_PI/180.0);
    double lon1 = p1.x()*d2r;
    double lat1 = p1.y()*d2r;
    double lon2 = p2.x()*d2r;
    double lat2 = p2.y()*d2r;

    double ret = (6378.388 * acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)));

    return (std::isnan(ret) > 0) ? 0.0 : ret;
}

double florb::utils::dist_merc(const florb::point2d<double> &p1, const florb::point2d<double> &p2)
{
    if (p1 == p2)
        return 0.0;

    double dstmerc = sqrt( pow(std::abs(p1.x()-p2.x()), 2.0) + pow(std::abs(p1.y()-p2.y()), 2.0)*0.9444444 );
    return (dstmerc * (CIRCUMFERENCEKM/360.0));
}

double florb::utils::meters_per_pixel(unsigned int z, double lat)
{
    return (CIRCUMFERENCEKM * cos(lat*(M_PI/180.0)) / pow(2.0,(z+8))) * 1000.0;
}

time_t florb::utils::iso8601_2timet(const std::string& iso)
{
    struct tm stm;
    strptime(iso.c_str(), "%FT%T%z", &stm);

    return mktime(&stm);
}

std::string florb::utils::timet2iso8601(time_t t)
{
    char buf[sizeof "2011-10-08T07:07:09Z"];
    strftime(buf, sizeof buf, "%FT%TZ", gmtime(&t));

    return std::string(buf);
}

std::string florb::utils::pathsep()
{
#if defined(WIN32) || defined(_WIN32)
return std::string("\\");
#else
return std::string("/");
#endif
}

std::string florb::utils::userdir()
{
    char *home = getenv("HOME");
    if (!home)
        throw 0;

    return std::string(home);
}

std::string florb::utils::appdir()
{
    std::ostringstream oss;
    oss << userdir();
    oss << pathsep();
    oss << ".florb";

    return oss.str();
}

bool florb::utils::mkdir(const std::string& path)
{
    bool ret = true;

    try {
        boost::filesystem::create_directory(path);
    } catch (...) {
        ret = false;
    }

    return ret;
}

void florb::utils::rm(const std::string& path)
{
    boost::filesystem::remove_all(path);
}

bool florb::utils::exists(const std::string& path)
{
    return boost::filesystem::exists(path);
}

std::string florb::utils::filestem(const std::string& path)
{
    return boost::filesystem::path(path).stem().string();
}

std::string florb::utils::extension(const std::string& path)
{
    return boost::filesystem::path(path).extension().string();
}

void florb::utils::touch(const std::string& path)
{
    std::fstream f(path, std::ios::out|std::ios::app);
	f.close();
}

void florb::utils::set_window_icon(Fl_Window *w)
{
    fl_open_display();
    Pixmap p, mask;
    XpmCreatePixmapFromData(fl_display, DefaultRootWindow(fl_display), const_cast<char**>(florb_xpm), &p, &mask, NULL);
    w->icon((char *)p);
}

std::vector<std::string> florb::utils::str_split(const std::string& str, const std::string& delimiter)
{
    std::size_t offs = 0, p1 = 0, p2 = std::string::npos;
    std::size_t len = str.length();

    std::vector<std::string> ret;
    while ((offs < len) && (p2 = str.find(delimiter, offs)) != std::string::npos)
    {
        std::string token(str.substr(p1, p2-p1));

        if (token.length() > 0)
            ret.push_back(str.substr(p1, p2-p1));

        p1 = p2 + delimiter.length();
        offs = p1;
    }

    if ((p1 != len))
        ret.push_back(str.substr(p1, len-p1));

    return ret;
}

std::size_t florb::utils::str_count(const std::string& str, const std::string& token)
{
    if (token.length() == 0)
        return 0;

    std::size_t ret = 0, offs = 0;

    while ((offs = str.find(token, offs)) != std::string::npos)
    {
        offs += token.length();
        ret++;
    }

    return ret;
}

void florb::utils::str_replace(std::string& str, const std::string& s, const std::string& r)
{
    std::size_t offs = 0;
    while ((offs = str.find(s, 0)) != std::string::npos)
    {
        str.replace(offs, s.length(), r);
    }
}

// Cohen–Sutherland clipping algorithm
bool florb::utils::clipline(
        florb::point2d<double> &p1,
        florb::point2d<double> &p2,
        const florb::point2d<double> &r1,
        const florb::point2d<double> &r2,
        bool &p1clip,
        bool &p2clip)
{
    bool ret = false;
    double xmin, xmax, ymin, ymax;
    p1clip = false;
    p2clip = false;

    if (r1.x() > r2.x())
    {
        xmin = r2.x();
        xmax = r1.x();
    }
    else
    {
        xmin = r1.x();
        xmax = r2.x();
    }

    if (r1.y() > r2.y())
    {
        ymin = r2.y();
        ymax = r1.y();
    }
    else
    {
        ymin = r1.y();
        ymax = r2.y();
    }

    bool overflowa = false;

    // Catch arithmetic overflow when calculating m and n
    double n = 0, m = 0;
    for (;;)
    {
        std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);

        m = (p2.y() - p1.y()) / (p2.x() - p1.x());
        if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)
        {
            overflowa = true;
            break;
        }

        std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);

        n = p1.y() - (m * p1.x());
        if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)
        {
            overflowa = true;
            break;
        }

        break;
    }

    // Max 2 clipping operations per point and one last check operation.
    for (int i=0;i<5;i++)
    {
        // Compute code for both points
        int code1 = 0, code2 = 0;

        if (p1.x() < xmin)
            code1 |= CLIPLEFT;
        if (p1.x() > xmax)
            code1 |= CLIPRIGHT;
        if (p1.y() < ymin)
            code1 |= CLIPTOP;
        if (p1.y() > ymax)
            code1 |= CLIPBOTTOM;

        if (p2.x() < xmin)
            code2 |= CLIPLEFT;
        if (p2.x() > xmax)
            code2 |= CLIPRIGHT;
        if (p2.y() < ymin)
            code2 |= CLIPTOP;
        if (p2.y() > ymax)
            code2 |= CLIPBOTTOM;

        // Both inside, draw line
        if ((code1 | code2) == 0)
        {
            ret = true;
            break;
        }

        // Both top, bottom, left or right outside, line need not be drawn
        if ((code1 & code2) != 0)
        {
            ret = false;
            break;
        }

        // Pick an endpoint for clipping
        florb::point2d<double> &ptmp = (code1 != 0) ? p1 : p2;
        int codetmp;
        if (code1 != 0)
        {
            codetmp = code1;
            p1clip = true;
        }
        else
        {
            codetmp = code2;
            p2clip = true;
        }

        // Clip top
        if (codetmp & CLIPTOP)
        {
            // This is what the following code does with just a little overflow
            // protection:
            // ptmp[0] = (ymin - n) / m;

            double cx;
            for (;!overflowa;)
            {
                std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);
                cx = (ymin - n) / m;

                if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)
                {
                    overflowa = true;
                    break;
                }

                break;
            }

            // In case of an arithmetic exception we assume a vertical line and
            // keep the original x coordinate
            if (!overflowa)
                ptmp[0] = cx;

            ptmp[1] = ymin;
        }
        // Clip Bottom
        else if (codetmp & CLIPBOTTOM)
        {
            // This is what the following code does with just a little overflow
            // protection:
            // ptmp[0] = (ymax - n) / m;

            double cx;
            for (;!overflowa;)
            {
                std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);
                cx = (ymax - n) / m;

                if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)
                {
                    overflowa = true;
                    break;
                }

                break;
            }

            // In case of an arithmetic exception we assume a vertical line and
            // keep the original x coordinate
            if (!overflowa)
                ptmp[0] = cx;

            ptmp[1] = ymax;
        }
        // Clip Left
        else if (codetmp & CLIPLEFT)
        {
            // Vertical line left outside
            if (overflowa)
            {
                ret = false;
                break;
            }

            ptmp[0] = xmin;
            ptmp[1] = m * xmin + n;
        }
        // Clip Right
        else if (codetmp & CLIPRIGHT)
        {
            // Vertical line right outside
            if (overflowa)
            {
                ret = false;
                break;
            }

            ptmp[0] = xmax;
            ptmp[1] = m * xmax + n;
        }
    }

    return ret;
}

max_stars_repo_name: shugaa/florb

max_issues_repo_name: pekdon/florb

max_forks_repo_name: pekdon/florb


text:
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>

using namespace std;

const std::string SEPARATORS = "x";

size_t parse_line(const std::string& line);

int main (int argc, char** argv) {
  std::string line;
  std::getline(std::cin, line);

  size_t surface = 0;
  while(!cin.eof()) {
    surface += parse_line(line);
    std::getline(std::cin, line);
  }

  std::cout << surface << std::endl;
}

size_t parse_line(const std::string& line) {
  std::vector<std::string> strs;
  std::vector<int> values;

  boost::split(strs, line, boost::is_any_of(SEPARATORS));
  if(strs.size() != 3)
    return 0;

  for(auto& str : strs) {
    boost::trim(str);
    values.push_back(std::stoi(str));
  }

  std::sort(values.begin(), values.end());
  return 3 * values[0] * values[1] + 2 * values[1] * values[2] + 2 * values[2] * values[0];
}


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

// Peter Sonneveld and Martin B. van Gijzen, IDR(s): a family of simple and fast algorithms for solving large nonsymmetric linear systems.
// SIAM J. Sci. Comput. Vol. 31, No. 2, pp. 1035-1062 (2008). (copyright SIAM)

#ifndef ITL_IDR_S_INCLUDE
#define ITL_IDR_S_INCLUDE

#include <boost/numeric/mtl/concept/collection.hpp>
#include <boost/numeric/mtl/vector/dense_vector.hpp>
#include <boost/numeric/mtl/operation/random.hpp>
#include <boost/numeric/mtl/operation/orth.hpp>
#include <boost/numeric/mtl/operation/resource.hpp>
#include <boost/numeric/mtl/matrix/strict_upper.hpp>
#include <boost/numeric/mtl/utility/exception.hpp>
#include <boost/numeric/mtl/utility/irange.hpp>
#include <boost/numeric/linear_algebra/identity.hpp>
#include <boost/numeric/mtl/interface/vpt.hpp>

#include <boost/numeric/itl/krylov/base_solver.hpp>

namespace itl {

/// Induced Dimension Reduction on s dimensions (IDR(s))
template < typename LinearOperator, typename Vector,
	   typename LeftPreconditioner, typename RightPreconditioner,
	   typename Iteration >
int idr_s(const LinearOperator &A, Vector &x, const Vector &b,
	  const LeftPreconditioner &, const RightPreconditioner &,
	  Iteration& iter, size_t s)
{
    mtl::vampir_trace<7010> tracer;
    using mtl::size; using mtl::iall; using mtl::mat::strict_upper;
    typedef typename mtl::Collection<Vector>::value_type Scalar;
    typedef typename mtl::Collection<Vector>::size_type  Size;

    if (size(b) == 0) throw mtl::logic_error("empty rhs vector");
    if (s < 1) s= 1;

    const Scalar                zero= math::zero(Scalar());
    Scalar                      omega(zero);
    Vector                      x0(x), y(resource(x)), v(resource(x)), t(resource(x)), q(resource(x)), r(b - A * x);
    mtl::mat::multi_vector<Vector>   dR(Vector(resource(x), zero), s), dX(Vector(resource(x), zero), s), P(Vector(resource(x), zero), s);
    mtl::dense_vector<Scalar>   m(s), c(s), dm(s);   // replicated in distributed solvers
    mtl::mat::dense2D<Scalar>        M(s, s);             // dito

    random(P);
    P.vector(0)= r;
    orth(P);

    for (size_t k= 0; k < s; k++) {
	v= A * r;
	omega= dot(v, r) / dot(v, v);
	dX.vector(k)= omega * r;
	dR.vector(k)= -omega * v;
	x+= dX.vector(k);
	r+= dR.vector(k);
	if ((++iter).finished(r)) return iter;
	M[iall][k]= trans(P) * dR.vector(k);
    }

    Size oldest= 0;
    m= trans(P) * r;

    while (! iter.finished(r)) {

	for (size_t k= 0; k < s; k++) {
	    c= lu_solve(M, m);
	    q= dR * -c;
	    v= r + q;
	    if (k == 0) {
		t= A * v;
		omega= dot(t, v) / dot(t, t);
		dR.vector(oldest)= q - omega * t;
		dX.vector(oldest)= omega * v - dX * c;
	    } else {
		dX.vector(oldest)= omega * v - dX * c;
		dR.vector(oldest)= A * -dX.vector(oldest);
	    }
	    r+= dR.vector(oldest);
	    x+= dX.vector(oldest);

	    if ((++iter).finished(r))
		return iter;

	    dm= trans(P) * dR.vector(oldest);
	    M[iall][oldest]= dm;
	    m+= dm;
	    oldest= (oldest + 1) % s;
	}
    }
    return iter;
}

/// Solver class for IDR(s) method; right preconditioner ignored (prints warning if not identity)
/** Methods inherited from \ref base_solver. **/
template < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>,
	   typename RightPreconditioner= pc::identity<LinearOperator> >
class idr_s_solver
  : public base_solver< idr_s_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >
{
    typedef base_solver< idr_s_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;
  public:
  public:
    /// Construct solver from a linear operator; generate (left) preconditioner from it
    explicit idr_s_solver(const LinearOperator& A, size_t s= 8) : base(A), s(s), L(A), R(A) {}

    /// Construct solver from a linear operator and left preconditioner
    idr_s_solver(const LinearOperator& A, size_t s, const Preconditioner& L) : base(A), s(s), L(L), R(A) {}

    /// Construct solver from a linear operator and left preconditioner
    idr_s_solver(const LinearOperator& A, size_t s, const Preconditioner& L, const RightPreconditioner& R)
      : base(A), s(s), L(L), R(R) {}

    /// Solve linear system approximately as specified by \p iter
    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
    {
	return idr_s(this->A, x, b, L, R, iter, s);
    }

  private:
    size_t                s;
    Preconditioner        L;
    RightPreconditioner   R;
};

} // namespace itl

#endif // ITL_IDR_S_INCLUDE


text:
#ifndef BOOST_ADAPTBX_GRAPH_MAXIMUM_CLIQUE_RASCAL_H
#define BOOST_ADAPTBX_GRAPH_MAXIMUM_CLIQUE_RASCAL_H

#include <boost_adaptbx/graph/vertex_map.hpp>

#include <boost/graph/sequential_vertex_coloring.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>

#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>

#include <vector>
#include <set>
#include <stack>
#include <algorithm>
#include <iterator>

namespace boost_adaptbx
{
namespace graph
{

template< typename VertexDescriptor, typename SizeType >
class rascal_state
{
public:
  typedef VertexDescriptor vertex_descriptor_type;
  typedef SizeType size_type;
  typedef std::set< vertex_descriptor_type > vertex_group_type;
  typedef std::vector< vertex_group_type > vertex_partition_type;

  typedef typename vertex_partition_type::const_iterator const_partition_iterator;

private:
  vertex_partition_type m_partition;
  size_type m_upper_bound_kwp;

public:
  rascal_state()
    : m_upper_bound_kwp( 0 )
  {};

  rascal_state(size_type const& upper_bound_kwp)
    : m_partition( upper_bound_kwp ), m_upper_bound_kwp( upper_bound_kwp )
  {};

  rascal_state(vertex_partition_type const& partition, size_type const& upper_bound_kwp)
    : m_partition( partition ), m_upper_bound_kwp( upper_bound_kwp )
  {};

  size_type& upper_bound_kwp()
  {
    return m_upper_bound_kwp;
  }

  size_type const& upper_bound_kwp() const
  {
    return m_upper_bound_kwp;
  }

  size_type upper_bound_ka() const
  {
    return m_partition.size();
  }

  size_type upper_bound() const
  {
    return std::min( upper_bound_kwp(), upper_bound_ka() );
  }

  vertex_partition_type& partition()
  {
    return m_partition;
  }

  vertex_partition_type const& partition() const
  {
    return m_partition;
  }
};

struct size_sort_predicate
{
  template< typename Container >
  bool operator ()(Container const& left, Container const& right) const
  {
    return left.size() > right.size();
  }
};

struct initial_partition_by_vertex_coloring
{
  template< typename VertexListGraph >
  rascal_state<
    typename boost::graph_traits< VertexListGraph >::vertex_descriptor,
    typename boost::graph_traits< VertexListGraph >::vertices_size_type
    >
  operator ()(VertexListGraph const& g) const
  {
    typedef boost::graph_traits< VertexListGraph > graph_traits;
    typedef typename graph_traits::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits::vertex_iterator vertex_iterator;
    typedef typename graph_traits::vertices_size_type vertices_size_type;

    typedef vertex_map::generic_vertex_map< VertexListGraph, vertices_size_type >
      color_map_type;
    typedef typename color_map_type::property_map_type color_property_map_type;

    typedef rascal_state< vertex_descriptor, vertices_size_type > state_type;
    typedef typename state_type::vertex_group_type vertex_group_type;
    typedef typename state_type::vertex_partition_type vertex_partition_type;

    color_map_type color_map( g );
    color_property_map_type color_property_map( color_map.get() );
    vertices_size_type color_count = boost::sequential_vertex_coloring(
      g,
      color_property_map
      );

    state_type result( color_count );

    vertex_iterator v, vend;
    vertex_partition_type& partition = result.partition();

    for( boost::tie( v, vend ) = boost::vertices( g ); v != vend; ++v )
    {
      vertex_descriptor const& vertex = *v;
      partition[ boost::get( color_property_map, vertex ) ].insert( vertex );
    }

    std::stable_sort( partition.begin(), partition.end(), size_sort_predicate() );
    return result;
  }
};

template< typename Descriptor >
class partial_graph_selection_predicate
{
public:
  typedef std::set< Descriptor > descriptor_set_type;
  typedef boost::shared_ptr< descriptor_set_type > descriptor_set_ptr_type;

private:
  descriptor_set_ptr_type m_descriptor_set_ptr;

public:
  partial_graph_selection_predicate()
    : m_descriptor_set_ptr( new descriptor_set_type() )
  {};

  partial_graph_selection_predicate(descriptor_set_ptr_type const& ptr)
    : m_descriptor_set_ptr( ptr )
  {};

  template< typename InputIterator >
  partial_graph_selection_predicate(InputIterator begin, InputIterator end)
    : m_descriptor_set_ptr( new descriptor_set_type( begin, end ) )
  {}

  bool operator ()(Descriptor const& desc) const
  {
    return m_descriptor_set_ptr->find( desc ) != m_descriptor_set_ptr->end();
  }

  descriptor_set_type& selection() const
  {
    return *m_descriptor_set_ptr;
  }
};

template< typename Graph1, typename Graph2, typename InputIterator >
void
selected_subgraph(Graph1 const& graph, Graph2& subgraph, InputIterator begin, InputIterator end)
{
  typedef Graph1 graph_type;
  typedef boost::graph_traits< graph_type > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits::vertex_iterator vertex_iterator;
  typedef typename graph_traits::edge_descriptor edge_descriptor;
  typedef typename graph_traits::out_edge_iterator out_edge_iterator;
  typedef typename graph_traits::vertices_size_type vertices_size_type;

  typedef partial_graph_selection_predicate< vertex_descriptor > vertex_predicate_type;
  typedef typename vertex_predicate_type::descriptor_set_type vertex_descriptor_set_type;
  typedef partial_graph_selection_predicate< edge_descriptor > edge_predicate_type;
  typedef typename edge_predicate_type::descriptor_set_type edge_descriptor_set_type;

  typedef boost::filtered_graph< graph_type, edge_predicate_type, vertex_predicate_type >
    filtered_graph_type;
  typedef vertex_map::index_map< filtered_graph_type > index_map_type;

  vertex_predicate_type keep_vertices_pred( begin, end );
  vertex_descriptor_set_type const& keep_vertices_set = keep_vertices_pred.selection();

  edge_predicate_type keep_edges_pred;
  edge_descriptor_set_type& keep_edges_set = keep_edges_pred.selection();

  for (
    typename vertex_descriptor_set_type::const_iterator it = keep_vertices_set.begin();
    it != keep_vertices_set.end();
    ++it
    )
  {
    out_edge_iterator e, eend;

    for( boost::tie( e, eend ) = boost::out_edges( *it, graph ); e != eend; ++e )
    {
      if ( keep_vertices_set.find( boost::target( *e, graph ) ) != keep_vertices_set.end() )
      {
        keep_edges_set.insert( *e );
      }
    }
  }

  filtered_graph_type filtgraph(
    graph,
    keep_edges_pred,
    keep_vertices_pred
    );

  index_map_type index_map( filtgraph );

  boost::copy_graph(
    filtgraph,
    subgraph,
    boost::vertex_index_map( index_map.get() )
    );
}

struct upper_bound_by_chromatic_number
{
  template< typename VertexListGraph, typename Partition >
  typename boost::graph_traits< VertexListGraph >::vertices_size_type
  operator ()(VertexListGraph const& graph, Partition const& partition) const
  {
    typedef VertexListGraph graph_type;
    typedef boost::graph_traits< graph_type > graph_traits;
    typedef typename graph_traits::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits::vertices_size_type vertices_size_type;

    typedef vertex_map::generic_vertex_map< VertexListGraph, vertices_size_type >
      color_map_type;

    std::vector< vertex_descriptor > vertices;

    for (
      typename Partition::const_iterator it = partition.begin();
      it != partition.end();
      ++it
      )
    {
      std::copy( it->begin(), it->end(), std::back_inserter( vertices ) );
    }

    graph_type subgraph;
    selected_subgraph( graph, subgraph, vertices.begin(), vertices.end() );

    color_map_type color_map( graph );
    return boost::sequential_vertex_coloring( subgraph, color_map.get() );
  }

};

struct empty_size_predicate
{
  template< typename Container >
  bool operator ()(Container const& con) const
  {
    return con.empty();
  }
};

template< typename VertexListGraph, typename Partition, typename SizeType >
void
move_vertices_from_excess_partitions_if_possible(
  VertexListGraph const& graph,
  Partition& partition,
  SizeType lower_bound
  )
{
  typedef VertexListGraph graph_type;
  typedef boost::graph_traits< graph_type > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits::vertex_iterator vertex_iterator;
  typedef typename graph_traits::edge_descriptor edge_descriptor;
  typedef typename graph_traits::adjacency_iterator adjacency_iterator;
  typedef typename graph_traits::vertices_size_type vertices_size_type;
  typedef typename Partition::value_type vertex_group_type;
  typedef typename Partition::iterator partition_iterator;
  typedef typename vertex_group_type::iterator vertex_group_iterator;

  typedef std::set< vertex_descriptor > vertex_descriptor_set;

  partition_iterator divisor = partition.begin() + std::min( lower_bound, partition.size() );

  for ( partition_iterator pit_e = divisor; pit_e != partition.end(); ++pit_e )
  {
    vertex_group_iterator next = pit_e->begin();

    for ( vertex_group_iterator vgit = next; vgit != pit_e->end(); vgit = next )
    {
      ++next;
      adjacency_iterator v, vend;
      boost::tie( v, vend ) = boost::adjacent_vertices( *vgit, graph );
      vertex_descriptor_set neighbours( v, vend );

      for ( partition_iterator pit_m = partition.begin(); pit_m != divisor; ++pit_m )
      {
        vertex_descriptor_set intersect;
        std::set_intersection(
          neighbours.begin(),
          neighbours.end(),
          pit_m->begin(),
          pit_m->end(),
          std::inserter( intersect, intersect.end() )
          );

        if ( intersect.empty() )
        {
          pit_m->insert( *vgit );
          pit_e->erase( vgit );
          break;
        }
      }
    }
  }

  partition.erase(
    std::remove_if( divisor, partition.end(), empty_size_predicate() ),
    partition.end()
    );
  std::stable_sort( partition.begin(), partition.end(), size_sort_predicate() );
}

template<
  typename AdjacencyGraph,
  typename InitialPartition,
  typename UpperBound,
  typename UserCallback
  >
void
maximum_clique_rascal(
  AdjacencyGraph const& graph,
  InitialPartition const& initial_partition,
  UpperBound const& upper_bound,
  UserCallback callback,
  typename boost::graph_traits< AdjacencyGraph >::vertices_size_type lower_bound = 1
  )
{
  typedef boost::graph_traits< AdjacencyGraph > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits::vertices_size_type vertices_size_type;
  typedef typename graph_traits::adjacency_iterator adjacency_iterator;
  typedef rascal_state< vertex_descriptor, vertices_size_type > state_type;
  typedef typename state_type::vertex_group_type vertex_group_type;

  vertices_size_type max_clique_size = lower_bound + 1;
  std::vector< vertex_descriptor > branch_points;
  std::stack< state_type > states;
  states.push( initial_partition( graph ) );
  branch_points.push_back( graph_traits::null_vertex() );

  while ( true )
  {
    state_type& state = states.top();

    if (
      !state.partition().empty()
      && ( max_clique_size <= branch_points.size() + state.upper_bound() )
      )
    {
      typename vertex_group_type::iterator selit = state.partition().back().begin();
      vertex_descriptor selected = *selit;
      state.partition().back().erase( selit );
      branch_points.push_back( selected );
      max_clique_size = std::max( max_clique_size, branch_points.size() );

      adjacency_iterator v, vend;
      boost::tie( v, vend ) = boost::adjacent_vertices( selected, graph );
      std::set< vertex_descriptor > adjacents( v, vend );
      states.push( state_type() );
      state_type& next = states.top();

      for (
        typename state_type::const_partition_iterator pit = state.partition().begin();
        pit != state.partition().end() - 1;
        ++pit
        )
      {
        vertex_group_type igroup;
        std::set_intersection(
          adjacents.begin(),
          adjacents.end(),
          pit->begin(),
          pit->end(),
          std::inserter( igroup, igroup.end() )
          );

        if ( ! igroup.empty() )
        {
          next.partition().push_back( igroup );
        }
      }

      if ( state.partition().back().empty() )
      {
        state.partition().pop_back();
      }

      std::stable_sort(
        next.partition().begin(),
        next.partition().end(),
        size_sort_predicate()
        );
      move_vertices_from_excess_partitions_if_possible(
        graph,
        next.partition(),
        max_clique_size - branch_points.size()
        );
      next.upper_bound_kwp() = upper_bound( graph, next.partition() );
    }

    else
    {
      if ( max_clique_size <= branch_points.size() )
      {
        callback( branch_points.begin() + 1, branch_points.end() );
      }

      do
      {
        states.pop();
        branch_points.pop_back();
      }
      while (
        !states.empty()
        && !( max_clique_size <= branch_points.size() + states.top().upper_bound() )
        );

      if ( !states.empty() )
      {
        state_type& top = states.top();
        top.upper_bound_kwp() =  upper_bound( graph, top.partition() );
      }

      else
      {
        break;
      }
    }
  }
}

} // namespace graph
} // namespace boost_adaptbx

#endif // BOOST_ADAPTBX_GRAPH_MAXIMUM_CLIQUE_RASCAL_H


text:
//  Force boost_utility library to be included.
#ifndef BOOST_UTILITY_H_
#define BOOST_UTILITY_H_
#include <boost_preprocessor.hpp>  //  Force boost_preprocessor library to be included.
#endif  //  BOOST_UTILITY_H_

max_stars_repo_name: lupyuen/send-altitude-cocoos

max_issues_repo_name: lupyuen/send-altitude-cocoos

max_forks_repo_name: lupyuen/send-altitude-cocoos


text:
#ifndef CANNON_CONTROL_AFFINE_CONTROLLER_H
#define CANNON_CONTROL_AFFINE_CONTROLLER_H

/*!
 * \file cannon/control/affine_controller.hpp
 * \brief File containing AffineController class definition.
 */

/*!
 * \namespace cannon::control
 * \brief Namespace containing control-relevant classes and functions.
 */

#include <Eigen/Dense>

#include <cannon/ml/adam.hpp>

using namespace Eigen;

using namespace cannon::ml;

namespace cannon {
  namespace control {

    /*!
     * \brief Class representing an affine-controller.
     *
     * An affine controller is one with a term linear in the state and a
     * constant offset; this controller is explicitly multidimensional and
     * designed to be updated by gradient descent.
     *
     * \sa cannon::ml::AdamOptimizer
     */
    class AffineController {
      public:
        AffineController() = delete;

        /*!
         * Constructor taking the state dimension and action (control) dimension.
         *
         * \param state_dim Dimensionality of state space
         * \param action_dim Dimensionality of action (control) space
         * \param learning_rate Learning rate for gradient-based updating of the controller
         * \param use_adam Whether to use the Adam optimizer. If false,
         * stochastic gradient descent is used
         *
         */
        AffineController(unsigned int state_dim, unsigned int action_dim,
            double learning_rate=1e-4, bool use_adam=true) :
        state_dim_(state_dim), action_dim_(action_dim),
        learning_rate_(learning_rate), initial_learning_rate_(learning_rate),
        use_adam_(use_adam), K_opt_(action_dim, state_dim,learning_rate),
        k_opt_(action_dim, 1, learning_rate) {
          K_ = MatrixXd::Zero(action_dim_, state_dim_);
          k_ = VectorXd::Zero(action_dim_);
        }

        /*!
         * Computes the action (control) applied by this controller for the input state.
         *
         * \param state The state to compute an action for
         *
         * \returns The action applied by this controller
         */
        VectorXd get_action(const VectorXd& state) const;

        /*!
         * Returns the vector offset and linear terms defining this controller.
         * These are the k and K vector and matrix, respectively, in control
         * literature.
         *
         * \returns k and K, the constant and linear terms for this controller.
         */
        std::pair<VectorXd, MatrixXd> get_mats() const;

        /*!
         * Applies the input gradient to this controller, updating the k and K parameters.
         *
         * \param k_gradient The gradient to apply to the vector offset for this controller.
         * \param K_gradient The gradient to apply to the linear term of this controller.
         */
        void apply_gradient(const VectorXd& k_gradient, const MatrixXd& K_gradient);

        /*!
         * Set the control offset vector.
         *
         * \param k New control offset vector, which should be of the correct
         * dimension.
         */
        void set_k(const VectorXd& k);

        /*!
         * Set the control gain matrix.
         *
         * \param K New control gain matrix, which should be of the correct
         * dimension.
         */
        void set_K(const MatrixXd& K);

      private:
        // Parameters
        unsigned int state_dim_; //!< Dimensionality of state space
        unsigned int action_dim_; //!< Dimensionality of action space
        double learning_rate_; //!< Current learning rate for updates
        double initial_learning_rate_; //!< Initial learning rate
        bool use_adam_; //!< Whether to use AdamOptimizer for updating

        /*!
         * \rst
         * .. todo:: Make learning rate decay parameter for AffineController
         * \endrst
         */
        double decay_ = 0.1; //!< Learning rate decay

        unsigned int overall_t_ = 0; //!< Number of updates applied to this controller

        // Matrices
        MatrixXd K_; //!< Linear term for this controller
        VectorXd k_; //!< Constant offset for this controller

        // Optimizers
        AdamOptimizer K_opt_; //!< Optimizer for the K matrix of this controller
        AdamOptimizer k_opt_; //!< Optimizer for the k matrix of this controller
    };

  } // namespace control
} // namespace cannon

#endif /* ifndef CANNON_CONTROL_AFFINE_CONTROLLER_H */

max_stars_repo_name: cannontwo/cannon

max_issues_repo_name: cannontwo/cannon

max_forks_repo_name: cannontwo/cannon


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

#ifndef COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_HPP_
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_HPP_

#if __cplusplus
extern "C" {
#endif

// The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from
// demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_EXPORT __attribute__((dllexport))
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_IMPORT __attribute__((dllimport))
#else
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_EXPORT __declspec(dllexport)
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_IMPORT __declspec(dllimport)
#endif
#ifdef COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_BUILDING_DLL
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC \
  COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_EXPORT
#else
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC \
  COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_IMPORT
#endif
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC_TYPE \
  COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_LOCAL
#else
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_EXPORT \
  __attribute__((visibility("default")))
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_IMPORT
#if __GNUC__ >= 4
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC \
  __attribute__((visibility("default")))
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_LOCAL __attribute__((visibility("hidden")))
#else
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_LOCAL
#endif
#define COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC_TYPE
#endif

#if __cplusplus
}  // extern "
#endif

// HEaders in ROS
#include <pcl/PCLPointCloud2.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/crop_hull.h>
#include <pcl/filters/passthrough.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>

#include <boost/circular_buffer.hpp>
#include <boost/optional.hpp>
#include <data_buffer/data_buffer_base.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs_data_buffer/pose_stamped_data_buffer.hpp>
#include <grid_map_core/GridMap.hpp>
#include <grid_map_core/iterators/GridMapIterator.hpp>
#include <grid_map_msgs/msg/grid_map.hpp>
#include <grid_map_ros/grid_map_ros.hpp>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/laser_scan.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>

namespace robotx_costmap_calculator
{
class CostmapCalculatorComponent : public rclcpp::Node
{
public:
  COSTMAP_CALCULATOR_COSTMAP_CALCULATOR_COMPONENT_PUBLIC
  explicit CostmapCalculatorComponent(const rclcpp::NodeOptions & options);

private:
  rclcpp::Publisher<grid_map_msgs::msg::GridMap>::SharedPtr grid_map_pub_;
  rclcpp::Publisher<grid_map_msgs::msg::GridMap>::SharedPtr combine_grid_map_pub_;
  rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr pointcloud_sub_;
  rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr laserscan_sub_;
  rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr pose_sub_;
  void initGridMap();
  void pointCloudCallback(const sensor_msgs::msg::PointCloud2::SharedPtr cloud);
  void scanCallback(const sensor_msgs::msg::LaserScan::SharedPtr scan);
  void poseCallback(const geometry_msgs::msg::PoseStamped::SharedPtr pose);
  boost::circular_buffer<grid_map::GridMap> map_data_;
  boost::circular_buffer<sensor_msgs::msg::PointCloud2> cloud_buffer_;
  boost::circular_buffer<sensor_msgs::msg::LaserScan> scan_buffer_;
  grid_map::GridMap combine_map;
  grid_map::GridMap map;
  void TransformScan(
    const sensor_msgs::msg::LaserScan & scan, const geometry_msgs::msg::PoseStamped & pose);
  grid_map::Matrix getScanToGridMap(
    const sensor_msgs::msg::LaserScan & scan, const std::string & scan_layer_name);
  grid_map::Matrix getPointCloudToGridMap(
    const sensor_msgs::msg::PointCloud2 & cloud, const std::string & grid_map_layer_name);
  std::string points_raw_topic_;
  grid_map::Matrix grid_map_data_;
  std::string laserscan_raw_topic_;
  std::string output_topic_;
  std::string current_pose_topic;
  geometry_msgs::msg::PoseStamped pose_data;
  geometry_msgs::msg::PoseStamped new_pose;
  geometry_msgs::msg::PoseStamped interpolation_pose;
  double update_rate_;
  double resolution_;
  double laser_resolution_;
  rclcpp::Time timestamp_;
  int num_grids_;
  int laser_num_grids_;
  double range_max_;
  float point_late;
  double scan_late;
  float currentpoint_downlate;
  std_msgs::msg::Header header;
  sensor_msgs::msg::Image img_msg;
  std::string visualize_frame_id_;
  std::shared_ptr<data_buffer::PoseStampedDataBuffer> data_buffer;
};
}  // namespace robotx_costmap_calculator

#endif  //ROBOTX_COSTMAP_CALCULATOR_COSTMAP_COMPONENT_HPP_


text:
//           Copyright Matthew Pulver 2018 - 2019.
// Distributed under the Boost Software License, Version 1.0.
//      (See accompanying file LICENSE_1_0.txt or copy at
//           https://www.boost.org/LICENSE_1_0.txt)

// THIS IS NOT MEANT TO BE COMPILED - ONLY FOR INCLUSION IN DOCUMENTATION.

#include <boost/math/differentiation/autodiff.hpp>

namespace boost {
namespace math {
namespace differentiation {

// Function returning a single variable of differentiation. Recommended: Use auto for type.
template <typename RealType, size_t Order, size_t... Orders>
autodiff_fvar<RealType, Order, Orders...> make_fvar(RealType const& ca);

// Function returning multiple independent variables of differentiation in a std::tuple.
template<typename RealType, size_t... Orders, typename... RealTypes>
auto make_ftuple(RealTypes const&... ca);

// Type of combined autodiff types. Recommended: Use auto for return type (C++14).
template <typename RealType, typename... RealTypes>
using promote = typename detail::promote_args_n<RealType, RealTypes...>::type;

namespace detail {

// Single autodiff variable. Use make_fvar() or make_ftuple() to instantiate.
template <typename RealType, size_t Order>
class fvar {
 public:
  // Query return value of function to get the derivatives.
  template <typename... Orders>
  get_type_at<RealType, sizeof...(Orders) - 1> derivative(Orders... orders) const;

  // All of the arithmetic and comparison operators are overloaded.
  template <typename RealType2, size_t Order2>
  fvar& operator+=(fvar<RealType2, Order2> const&);

  fvar& operator+=(root_type const&);

  // ...
};

// Standard math functions are overloaded and called via argument-dependent lookup (ADL).
template <typename RealType, size_t Order>
fvar<RealType, Order> floor(fvar<RealType, Order> const&);

template <typename RealType, size_t Order>
fvar<RealType, Order> exp(fvar<RealType, Order> const&);

// ...

}  // namespace detail

}  // namespace differentiation
}  // namespace math
}  // namespace boost
/**/

max_stars_repo_name: pulver/autodiff

max_issues_repo_name: pulver/autodiff

max_forks_repo_name: pulver/autodiff


text:
#include <gtest/gtest.h>
#include <ros/package.h>

#include "mwoibn/eigen_utils/eigen_utils.h"
#include <Eigen/Core>

#include <iostream>
#include <fstream>

bool skipLine(std::ifstream* myfile, int skip)
{
  std::string line;
  try
  {
    for (int i = 0; i < skip; i++)
      getline(*myfile, line);
  }
  catch (const std::exception& exc)
  {
    ADD_FAILURE() << exc.what(); // add proper throws
  }
  return true;
}

Eigen::MatrixXd readMatrix(std::ifstream* myfile, int rows, int cols)
{

  std::string line;

  std::vector<double> data;
  std::vector<double> new_data;
  for (int i = 0; i < rows; i++)
  {
    getline(*myfile, line);
    std::istringstream is(line);
    new_data = std::vector<double>(std::istream_iterator<double>(is),
                                   std::istream_iterator<double>());
    data.insert(data.end(), new_data.begin(), new_data.end());
  }

  Eigen::Map<
      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
      J(&data[0], rows,
        cols); // requires c++11, "cannot-appear-in-a-constant-expression"

  return J;
}

::testing::AssertionResult compareMatrices(Eigen::MatrixXd m1,
                                           Eigen::MatrixXd m2, double eps)
{

  if (!m1.rows() == m2.rows())
    return ::testing::AssertionFailure()
           << " matrices has diffrenet row numbers"
           << "m1: " << m1.rows() << ", m2: " << m2.rows();
  if (!m1.cols() == m2.cols())
    return ::testing::AssertionFailure()
           << " matrices has diffrenet columns numbers"
           << "m1: " << m1.cols() << ", m2: " << m2.cols();

  for (int i = 0; i < m1.rows(); i++)
  {
    for (int j = 0; j < m1.cols(); j++)
    {
      if (fabs(m1(i, j) - m2(i, j)) > eps)
        return ::testing::AssertionFailure() << "row " << i << ", columns " << j
                                             << ", value a " << m1(i, j)
                                             << ", value b " << m2(i, j);
    }
  }

  return ::testing::AssertionSuccess();
}

// Check if class initialization works correctly

// Check all class methods, orientation is not fully supported therefore it is
// not checked during tests
TEST(EigenUtilsTest, methods)
{

  // READ FILE
  std::string path = ros::package::getPath("eigen_utils");
  std::string file_name = path + "/test/resources/eigen_test.txt";
  std::ifstream myfile(file_name);
  if (!myfile.is_open())
    FAIL() << "couldn't open the file, abort";

  // Prepare variables
  float eps = 0.0001;
  Eigen::MatrixXd J_test;
  Eigen::MatrixXd J;

  // READ TEST MATRICES
  Eigen::MatrixXd m_square;
  Eigen::MatrixXd m_nonsquare;

  try
  {
    // read square matrix
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    m_square = readMatrix(&myfile, 3, 3);

    // read non-sqaure
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    m_nonsquare = readMatrix(&myfile, 5, 9);
  }
  catch (const std::exception& exc)
  {
    ADD_FAILURE() << exc.what();
  }
  catch (...)
  {
    ADD_FAILURE()
        << "Unknown exception, while getting PointHandling information";
  }

  // CHECK_METHODS
  try
  {
    // FIRST MATRIX TEST: pseudoInverse for square matrix with too low damping
    // Skip to first line
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    // Read first matrix
    J = readMatrix(&myfile, 3, 3);
    // Compute test matrix
    J_test = mwoibn::eigen_utils::pseudoInverse(m_square, 1e-18);
    // Test first matrix
    EXPECT_TRUE(compareMatrices(J, J_test, 1));

    // SECOND MATRIX TEST: pseudoInverse for square matrix with correct damping
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    J = readMatrix(&myfile, 3, 3);
    J_test = mwoibn::eigen_utils::pseudoInverse(m_square, 1e-8);
    EXPECT_TRUE(compareMatrices(J, J_test, eps));

    // THIRD MATRIX TEST: pseudoInverse for non-square matrix with defult
    // damping
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    J = readMatrix(&myfile, 9, 5);
    J_test = Eigen::MatrixXd::Zero(9, 5);
    J_test = mwoibn::eigen_utils::pseudoInverse(m_nonsquare);
    EXPECT_TRUE(compareMatrices(J, J_test, eps));

    // FOURTH MATRIX TEST: agumented Null Space Projection Matrix
    Eigen::MatrixXd P;
    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    Eigen::MatrixXd P0 = readMatrix(&myfile, 9, 9);

    if (!skipLine(&myfile, 1))
      FAIL() << "couldn't continue, file finished prematurely";
    J = readMatrix(&myfile, 9, 5);
    J_test = Eigen::MatrixXd::Zero(9, 5);
    J_test = mwoibn::eigen_utils::agumentedNullSpaceProjection(m_nonsquare, P0, P);
    EXPECT_TRUE(compareMatrices(J, J_test, eps));
  }
  catch (const std::exception& exc)
  {
    ADD_FAILURE() << exc.what();
  }
  catch (...)
  {
    ADD_FAILURE()
        << "Unknown exception, while getting PointHandling information";
  }
}

int main(int argc, char** argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: ADVRHumanoids/DrivingFramework

max_issues_repo_name: ADVRHumanoids/DrivingFramework

max_forks_repo_name: ADVRHumanoids/DrivingFramework


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "kudu/server/rpcz-path-handler.h"

#include <memory>
#include <sstream>
#include <string>
#include <unordered_map>

#include <boost/bind.hpp> // IWYU pragma: keep

#include "kudu/gutil/map-util.h"
#include "kudu/gutil/strings/numbers.h"
#include "kudu/rpc/messenger.h"
#include "kudu/rpc/rpc_introspection.pb.h"
#include "kudu/rpc/rpcz_store.h"
#include "kudu/server/webserver.h"
#include "kudu/util/jsonwriter.h"
#include "kudu/util/web_callback_registry.h"

using kudu::rpc::DumpConnectionsRequestPB;
using kudu::rpc::DumpConnectionsResponsePB;
using kudu::rpc::DumpRpczStoreRequestPB;
using kudu::rpc::DumpRpczStoreResponsePB;
using kudu::rpc::Messenger;
using std::ostringstream;
using std::shared_ptr;
using std::string;

namespace kudu {

namespace {

void RpczPathHandler(const shared_ptr<Messenger>& messenger,
                     const Webserver::WebRequest& req,
                     Webserver::PrerenderedWebResponse* resp) {
  DumpConnectionsResponsePB running_rpcs;
  {
    DumpConnectionsRequestPB dump_req;

    string arg = FindWithDefault(req.parsed_args, "include_traces", "false");
    dump_req.set_include_traces(ParseLeadingBoolValue(arg.c_str(), false));

    messenger->DumpConnections(dump_req, &running_rpcs);
  }
  DumpRpczStoreResponsePB sampled_rpcs;
  {
    DumpRpczStoreRequestPB dump_req;
    messenger->rpcz_store()->DumpPB(dump_req, &sampled_rpcs);
  }

  JsonWriter writer(&resp->output, JsonWriter::PRETTY);
  writer.StartObject();
  writer.String("running");
  writer.Protobuf(running_rpcs);
  writer.String("sampled");
  writer.Protobuf(sampled_rpcs);
  writer.EndObject();

}

} // anonymous namespace

void AddRpczPathHandlers(const shared_ptr<Messenger>& messenger, Webserver* webserver) {
  webserver->RegisterPrerenderedPathHandler("/rpcz", "RPCs",
                                            boost::bind(RpczPathHandler, messenger, _1, _2),
                                            false, true);
}

} // namespace kudu

ext: cc

max_stars_repo_name: shirodkara/kudu

max_issues_repo_name: shirodkara/kudu

max_forks_repo_name: shirodkara/kudu


text:
#include <gtl_poly_serialize.h>

#include <fstream>
#include <iostream>

#include <boost/serialization/vector.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/tracking.hpp>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

// it seems that the serialize stuff doesn't like having both types of polygon declared.
// because of this, it's especially important to keep the boost::geometry and boost::polygon stuff separate.
namespace boost{
    namespace serialization{

        // serialization for Point
        template<class Archive>
        void save(Archive &ar, const Point &p, unsigned int version)
        {
            ar & gtl::x(p);
            ar & gtl::y(p);
        }

        template<class Archive>
        void load(Archive & ar, Point &p, unsigned int version)
        {
            int x,y;

            ar & x;
            ar & y;

            p = Point(x,y);
        }

        // Serialization for Polygon_NoHoles
        template<class Archive>
        void save(Archive & ar, const Polygon_NoHoles &poly, unsigned int version)
        {
            ar & poly.size();
            for(const Point &pt : poly) {
                ar & pt;
            }
        }

        template<class Archive>
        void load(Archive & ar, Polygon_NoHoles &poly, unsigned int version)
        {
            int numpts;
            ar & numpts;

            std::vector<Point> pts;
            for(int i=0; i<numpts; i++) {
                Point pt;
                ar & pt;
                pts.push_back(pt);
            }
            gtl::set_points(poly, pts.begin(), pts.end());
        }

        // Serialization for Polygon_Holes
        template<class Archive>
        void save(Archive & ar, const Polygon_Holes &poly, unsigned int version)
        {
            ar & poly.size();
            for(Point pt : poly) {
                ar & pt;
            }

            ar & poly.size_holes();
            for(auto i=poly.begin_holes(); i!=poly.end_holes(); ++i) {
                ar & (*i);
            }
        }

        template<class Archive>
        void load(Archive & ar, Polygon_Holes &poly, unsigned int version)
        {
            int numpts;
            ar & numpts;

            std::vector<Point> pts;
            for(int i=0; i<numpts; i++) {
                Point pt;
                ar & pt;
                pts.push_back(pt);
            }
            gtl::set_points(poly, pts.begin(), pts.end());

            int numholes;
            ar & numholes;

            std::vector<Polygon_NoHoles> holes;
            for(int i=0; i<numholes; i++) {
                Polygon_NoHoles hole;
                ar & hole;
                holes.push_back(hole);
            }
            gtl::set_holes(poly, holes.begin(), holes.end());
        }

// not actually necessary since polyset is a vector.
#if 0
        template<class Archive>
        void save(Archive & ar, const PolygonSet &ps, unsigned int version)
        {
            ar & ps.size();
            for (const Polygon_Holes &poly : ps) {
                ar & poly;
            }
        }

        template<class Archive>
        void load(Archive & ar, PolygonSet &ps, unsigned int version)
        {
            int numpoly;
            ar & numpoly;

            ps.clear();
            for(int i=0; i<numpoly; i++) {
                Polygon_Holes poly;
                ar & poly;
                ps.push_back(poly);
            }
        }
#endif
        /*
        template<class Archive>
        void save(Archive & ar, const Point &p, unsigned int version)
        {
            // ar & ...
        }

        template<class Archive>
        void load(Archive & ar, Point &t, unsigned int version)
        {
            // ar & ...
        }
        */

    }
}

BOOST_SERIALIZATION_SPLIT_FREE(Point)
BOOST_SERIALIZATION_SPLIT_FREE(Polygon_NoHoles)
BOOST_SERIALIZATION_SPLIT_FREE(Polygon_Holes)

// polyset is a vector, this isn't needed.
// BOOST_SERIALIZATION_SPLIT_FREE(PolygonSet)

void write_polys(std::string filename, const Polygon_Holes &poly)
{
    const PolygonSet polys{poly};

    write_polys(filename, polys);
}

void write_polys(std::string filename, const PolygonSet &polys)
{
    std::ofstream ofs(filename);
    boost::archive::text_oarchive oa(ofs);

    oa << polys;
}

void read_polys(std::string filename, PolygonSet &polys)
{
    polys.clear();

    std::ifstream ifs(filename);
    boost::archive::text_iarchive ia(ifs);
    ia >> polys;
}


text:
#include "Carpenter.h"
#include <boost/locale/message.hpp>
#include <Core/orders/OrderCombined.h>

bool Carpenter::CanPeformOrder(POrder p)
{
	if(p->GetId() == Order::Idfor<OrderCombined>())
	{
		auto ord = std::static_pointer_cast<OrderCombined>(p);
		return ord->need_to_perform == GetId();
	}
	return false;
}

std::string Carpenter::Name()
{
	return boost::locale::translate("Carpenter");
}

std::string Carpenter::Description()
{
	return "some description";
}

void Carpenter::Perform(const GameObjectParams& params, PGameObject performer)
{
}

PProfession Carpenter::Clone()
{
	return std::make_shared<Carpenter>(*this);
}

float Carpenter::GetBaseCost() const
{
	return 10;
}

max_stars_repo_name: ishellstrike/MinecraftLike

max_issues_repo_name: ishellstrike/MinecraftLike

max_forks_repo_name: ishellstrike/MinecraftLike


text:
#include <slas/dbus/object.h>

#include <cstring>
#include <boost/log/trivial.hpp>

namespace dbus
{

Object::~Object()
{
}

DBusHandlerResult Object::MessageHandler(DBusConnection *connection, DBusMessage *message)
{
  BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Function call";

  const char *interface = dbus_message_get_interface(message);
  BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Interface: " << interface;

  if (strcmp(interface, DBUS_INTERFACE_INTROSPECTABLE) == 0)
  {
    BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Introspection function called";

    const char *xml = GetXmlInterface();
    BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: XML introspection: " << xml;

    DBusMessage *reply_msg = dbus_message_new_method_return(message);

    DBusMessageIter args;
    dbus_message_iter_init_append(reply_msg, &args);
    dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &xml);

    BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Sending reply";
    dbus_connection_send(connection, reply_msg, NULL);

    BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Connection flushing";
    dbus_connection_flush(connection);

    BOOST_LOG_TRIVIAL(debug) << "dbus::Object::MessageHandler: Done. Returning DBUS_HANDLER_RESULT_HANDLED";

    return DBUS_HANDLER_RESULT_HANDLED;
  }

  return OwnMessageHandler(connection, message);
}

}

max_stars_repo_name: chyla/slas

max_issues_repo_name: chyla/slas

max_forks_repo_name: chyla/slas


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   default_attribute_names.cpp
 * \author Andrey Semashev
 * \date   13.07.2012
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/libs/log/doc/log.html.
 */

#include <boost/shared_ptr.hpp>
#include <boost/log/detail/default_attribute_names.hpp>
#include <boost/log/detail/singleton.hpp>
#include <boost/log/detail/header.hpp>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

namespace default_attribute_names {

BOOST_LOG_ANONYMOUS_NAMESPACE {

    class names :
        public lazy_singleton< names, shared_ptr< names > >
    {
    private:
        typedef lazy_singleton< names, shared_ptr< names > > base_type;

#if !defined(BOOST_LOG_BROKEN_FRIEND_TEMPLATE_INSTANTIATIONS)
        friend class lazy_singleton< names, shared_ptr< names > >;
#else
        friend class base_type;
#endif

    public:
        const attribute_name severity;
        const attribute_name channel;
        const attribute_name message;
        const attribute_name line_id;
        const attribute_name timestamp;
        const attribute_name process_id;
        const attribute_name thread_id;

    private:
        names() :
            severity("Severity"),
            channel("Channel"),
            message("Message"),
            line_id("LineID"),
            timestamp("TimeStamp"),
            process_id("ProcessID"),
            thread_id("ThreadID")
        {
        }

        static void init_instance()
        {
            get_instance().reset(new names());
        }

    public:
        static names& get()
        {
            return *base_type::get();
        }
    };

} // namespace

BOOST_LOG_API attribute_name severity()
{
    return names::get().severity;
}

BOOST_LOG_API attribute_name channel()
{
    return names::get().channel;
}

BOOST_LOG_API attribute_name message()
{
    return names::get().message;
}

BOOST_LOG_API attribute_name line_id()
{
    return names::get().line_id;
}

BOOST_LOG_API attribute_name timestamp()
{
    return names::get().timestamp;
}

BOOST_LOG_API attribute_name process_id()
{
    return names::get().process_id;
}

BOOST_LOG_API attribute_name thread_id()
{
    return names::get().thread_id;
}

} // namespace default_attribute_names

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

max_issues_repo_name: graehl/boost

max_forks_repo_name: graehl/boost


text:
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES)

#include <boost/proto/transform/detail/preprocessed/default_function_impl.hpp>

#elif !defined(BOOST_PP_IS_ITERATING)

#define BOOST_PROTO_DEF_FUN_INVOKE_ARG(Z, M, DATA)                             \
  BOOST_PROTO_DEFAULT_EVAL(Z, BOOST_PP_ADD(M, 2), DATA)

#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve : 2, line : 0, output                             \
                    : "preprocessed/default_function_impl.hpp")
#endif

///////////////////////////////////////////////////////////////////////////////
/// \file default_function_impl.hpp
/// Contains definition of the default_function_impl, the implementation of the
/// _default transform for function-like nodes.
//
//  Copyright 2008 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve : 1)
#endif

#define BOOST_PP_ITERATION_PARAMS_1                                            \
  (3, (3, BOOST_PROTO_MAX_ARITY,                                               \
       <boost / proto / transform / detail / default_function_impl.hpp>))
#include BOOST_PP_ITERATE()

#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(output : null)
#endif

#undef BOOST_PROTO_DEF_FUN_INVOKE_ARG

#else

#define N BOOST_PP_ITERATION()

template <typename Grammar, typename Expr, typename State, typename Data>
struct default_function_impl<Grammar, Expr, State, Data, N>
    : transform_impl<Expr, State, Data> {
  BOOST_PP_REPEAT(N, BOOST_PROTO_DEFAULT_EVAL_TYPE, Expr)

  typedef typename proto::detail::result_of_fixup<r0>::type function_type;

  typedef typename BOOST_PROTO_RESULT_OF<function_type(
      BOOST_PP_ENUM_SHIFTED_PARAMS(N, r))>::type result_type;

  result_type operator()(typename default_function_impl::expr_param e,
                         typename default_function_impl::state_param s,
                         typename default_function_impl::data_param d) const {
    return this->invoke(e, s, d, is_member_function_pointer<function_type>());
  }

private:
  result_type invoke(typename default_function_impl::expr_param e,
                     typename default_function_impl::state_param s,
                     typename default_function_impl::data_param d,
                     mpl::false_) const {
    return BOOST_PROTO_DEFAULT_EVAL(~, 0, e)(
        BOOST_PP_ENUM_SHIFTED(N, BOOST_PROTO_DEFAULT_EVAL, e));
  }

  result_type invoke(typename default_function_impl::expr_param e,
                     typename default_function_impl::state_param s,
                     typename default_function_impl::data_param d,
                     mpl::true_) const {
    BOOST_PROTO_USE_GET_POINTER();
    typedef typename detail::class_member_traits<function_type>::class_type
        class_type;
    return (
        BOOST_PROTO_GET_POINTER(class_type, (BOOST_PROTO_DEFAULT_EVAL(~, 1, e)))
            ->*BOOST_PROTO_DEFAULT_EVAL(~, 0, e))(
        BOOST_PP_ENUM(BOOST_PP_SUB(N, 2), BOOST_PROTO_DEF_FUN_INVOKE_ARG, e));
  }
};

#undef N

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include <boost/date_time/posix_time/ptime.hpp>

#include <goby/middleware/marshalling/protobuf.h>
// this space intentionally left blank
#include <goby/time/convert.h>
#include <goby/zeromq/application/single_thread.h>

#include "config.pb.h"
#include "goby3-course/groups.h"
#include "goby3-course/messages/health_status.pb.h"

using goby::glog;
namespace si = boost::units::si;
using ApplicationBase = goby::zeromq::SingleThreadApplication<goby3_course::config::Subscriber>;

namespace goby3_course
{
namespace apps
{
class Subscriber : public ApplicationBase
{
  public:
    Subscriber();
};
} // namespace apps
} // namespace goby3_course

int main(int argc, char* argv[])
{
    return goby::run<goby3_course::apps::Subscriber>(
        goby::middleware::ProtobufConfigurator<goby3_course::config::Subscriber>(argc, argv));
}

goby3_course::apps::Subscriber::Subscriber()
{
    auto on_health_status = [](const goby3_course::protobuf::HealthStatus& health_status_msg) {
        glog.is_verbose() &&
            glog << "Received HealthStatus: " << health_status_msg.ShortDebugString() << std::endl;
        auto timestamp =
            goby::time::convert<boost::posix_time::ptime>(health_status_msg.timestamp_with_units());
        glog.is_verbose() && glog << "Timestamp as date: "
                                  << boost::posix_time::to_simple_string(timestamp) << std::endl;

        auto microseconds_latency =
            std::chrono::microseconds(goby::time::SystemClock::now() -
                                      goby::time::convert<goby::time::SystemClock::time_point>(
                                          health_status_msg.timestamp_with_units()));
        glog.is_verbose() && glog << "Latency (microsec): " << microseconds_latency.count()
                                  << std::endl;
        // do whatever you need to with the message in real code ...
    };

    auto on_subscribed = [](const goby::middleware::intervehicle::protobuf::Subscription& sub,
                            const goby::middleware::intervehicle::protobuf::AckData& ack) {
        glog.is_verbose() && glog << "Received acknowledgment: " << ack.ShortDebugString()
                                  << " for subscription: " << sub.ShortDebugString() << std::endl;
    };

    goby::middleware::protobuf::TransporterConfig subscriber_cfg;
    subscriber_cfg.mutable_intervehicle()->add_publisher_id(1);
    auto& buffer_cfg = *subscriber_cfg.mutable_intervehicle()->mutable_buffer();
    buffer_cfg.set_ttl_with_units(5 * boost::units::si::seconds);
    goby::middleware::Subscriber<goby3_course::protobuf::HealthStatus> health_status_subscriber(
        subscriber_cfg, on_subscribed);
    intervehicle()
        .subscribe<goby3_course::groups::health_status, goby3_course::protobuf::HealthStatus>(
            on_health_status, health_status_subscriber);
}


text:
#include <boost/test/unit_test.hpp>
#include "Component.h"
#include "ComponentMapper.h"
#include "Entity.h"
#include "World.h"

#include <vector>

using namespace hecate;
using namespace std;

class C1 : public Component {
public:
	C1() {
		setType(this);
	}
};
class C2 : public Component {
public:
	C2() {
		setType(this);
	}
};

BOOST_AUTO_TEST_SUITE(ComponentMapper_Test)

BOOST_AUTO_TEST_CASE(ComponentMapper_Constructor_Case) {
	World w;
	Entity *e1 = w.createEntity(), *e2 = w.createEntity();
	C1 *c1 = new C1();
	C2 *c2 = new C2();
	e1->addComponent(c1);
	e1->addComponent(c2);
	e2->addComponent(new C1());
	ComponentMapper<C1> cm1(C1(), &w);
	ComponentMapper<C2> cm2(C2(), &w);
	Component *c1a = e1->getComponent(C1());

	// Check that c1 is correctly returned
	BOOST_CHECK(c1 == cm1.get(*e1));
	// Check that e1 & e2's c1 are not equal
	BOOST_CHECK(cm1.get(*e1) != cm1.get(*e2));
	// e2 doesn't have a c2
	BOOST_CHECK(cm2.get(*e2) == NULL);
	// e2 doesn't have a c2, but e1 does
	BOOST_CHECK(cm2.get(*e1) != cm2.get(*e2));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: losinggeneration/hecate

max_issues_repo_name: losinggeneration/hecate

max_forks_repo_name: losinggeneration/hecate


text: #include <boost/log/utility/type_dispatch/static_type_dispatcher.hpp>