text:
/**
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Da Zheng (zhengda1936@gmail.com)
 *
 * This file is part of FlashGraph.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unordered_map>
#include <boost/filesystem.hpp>
#include <Rcpp.h>

#include "log.h"
#include "safs_file.h"
#include "matrix/FG_sparse_matrix.h"
#include "matrix/matrix_eigensolver.h"

#include "FGlib.h"
#include "utils.h"
#include "in_mem_storage.h"

#if 0
FG_vector<float>::ptr compute_sstsg(FG_graph::ptr fg, time_t start_time,
		time_t interval, int num_intervals);
FG_vector<float>::ptr compute_betweenness_centrality(FG_graph::ptr fg, vertex_id_t id);
FG_vector<vsize_t>::ptr get_ts_degree(FG_graph::ptr fg, edge_type type,
		time_t start_time, time_t time_interval);
#endif

/*
 * A global configuration of FlashGraphR.
 */
static config_map::ptr configs;

typedef std::unordered_map<std::string, FG_graph::ptr> graph_map_t;
/*
 * This contains all graphs loaded to FlashGraphR. When a graph is loaded
 * to FlashGraphR, it may be in memory and may also be on SAFS.
 */
static graph_map_t graphs;

bool standalone = true;

static FG_graph::ptr get_graph(const std::string &graph_name, bool has_cindex)
{
	// search for the graph in memory.
	graph_map_t::const_iterator it = graphs.find(graph_name);
	if (it != graphs.end())
		return it->second;

	if (standalone)
		return FG_graph::ptr();

	std::string version = itoa(CURR_VERSION);
	std::string graph_file = graph_name + "-v" + version;
	std::string index_file;
	if (has_cindex)
		index_file = graph_name + "-cindex-v" + version;
	else
		index_file = graph_name + "-index-v" + version;
	return FG_graph::create(graph_file, index_file, configs);
}

/**
 * Create a FG_graph for the specified graph.
 */
static FG_graph::ptr R_FG_get_graph(SEXP pgraph)
{
	std::string graph_name = CHAR(STRING_ELT(VECTOR_ELT(pgraph, 0), 0));
	bool has_cindex = INTEGER(VECTOR_ELT(pgraph, 1))[0];
	return get_graph(graph_name, has_cindex);
}

/**
 * Initialize FlashGraphR.
 */
RcppExport SEXP R_FG_init(SEXP pconf)
{
	set_log_level(c_log_level::warning);
	std::string conf_file = CHAR(STRING_ELT(pconf, 0));

	boost::filesystem::path p(conf_file);
	if (boost::filesystem::exists(p)) {
		configs = config_map::create(conf_file);
	}
	else {
		fprintf(stderr, "conf file %s doesn't exist.\n", conf_file.c_str());
		configs = config_map::create();
	}

	Rcpp::LogicalVector res(1);
	try {
		graph_engine::init_flash_graph(configs);
		standalone = false;
		res[0] = true;
	} catch (init_error &e) {
		fprintf(stderr, "init FlashGraphR: %s\n", e.what());
		res[0] = true;
	} catch (std::exception &e) {
		fprintf(stderr, "exception in init: %s\n", e.what());
		res[0] = false;
	}

	if (standalone)
		printf("Run FlashGraphR in standalone mode\n");
	else
		printf("Run FlashGraphR\n");
	return res;
}

/**
 * Destroy FlashGraphR
 */
RcppExport SEXP R_FG_destroy()
{
	graphs.clear();
	graph_engine::destroy_flash_graph();
	return R_NilValue;
}

/*
 * This search in memory first, and then searches in SAFS.
 */
static bool exist_graph(std::string &graph_name)
{
	// Search in memory.
	graph_map_t::const_iterator it = graphs.find(graph_name);
	if (it != graphs.end())
		return true;

	// If FlashGraphR runs in the standalone mode, we can't search in SAFS.
	if (standalone)
		return false;

	std::string version = itoa(CURR_VERSION);
	std::string graph_file_name = graph_name + "-v" + version;
	safs_file graph_file(get_sys_RAID_conf(), graph_file_name);
	if (!graph_file.exist()) {
		fprintf(stderr, "The graph file of %s doesn't exist\n",
				graph_name.c_str());
		return false;
	}

	std::string graph_index_name = graph_name + "-index-v" + version;
	std::string graph_cindex_name = graph_name + "-cindex-v" + version;
	safs_file graph_index_file(get_sys_RAID_conf(), graph_index_name);
	safs_file graph_cindex_file(get_sys_RAID_conf(), graph_cindex_name);
	if (!graph_index_file.exist() && !graph_cindex_file.exist()) {
		fprintf(stderr, "The index file of %s doesn't exist\n",
				graph_name.c_str());
		return false;
	}

	return true;
}

static SEXP get_safs_params()
{
	Rcpp::List ret;
	ret["RAID_block_size"] = params.get_RAID_block_size();
	ret["SA_min_cell_size"] = params.get_SA_min_cell_size();
	ret["IO_dpeth"] = params.get_aio_depth_per_file();
	ret["cache_type"] = params.get_cache_type();
	ret["cache_size"] = params.get_cache_size();
	ret["RAID_mapping"] = params.get_RAID_mapping_option();
	ret["virtual_AIO"] = params.is_use_virt_aio();
	ret["use_flusher"] = params.is_use_flusher();
	ret["NUMA_num_process_threads"] = params.get_numa_num_process_threads();
	ret["num_nodes"] = params.get_num_nodes();
	ret["merge_requests"] = params.is_merge_reqs();
	ret["max_obj_alloc_size"] = params.get_max_obj_alloc_size();
	ret["writable"] = params.is_writable();
	ret["max_num_pending_IOs"] = params.get_max_num_pending_ios();
	ret["huge_page"] = params.is_huge_page_enabled();
	return ret;
}

static SEXP get_fg_params()
{
	Rcpp::List ret;
	ret["prof_file"] = graph_conf.get_prof_file();
	ret["num_threads"] = graph_conf.get_num_threads();
	ret["elevator"] = graph_conf.get_elevator_enabled();
	ret["max_processing_vertices"] = graph_conf.get_max_processing_vertices();
	ret["part_range_size_log"] = graph_conf.get_part_range_size_log();
	ret["preload"] = graph_conf.preload();
	ret["index_file_weight"] = graph_conf.get_index_file_weight();
	ret["in_mem_index"] = graph_conf.use_in_mem_index();
	ret["in_mem_graph"] = graph_conf.use_in_mem_graph();
	ret["serial_run"] = graph_conf.use_serial_run();
	ret["num_vertical_parts"] = graph_conf.get_num_vparts();
	ret["min_vpart_degree"] = graph_conf.get_min_vpart_degree();
	return ret;
}

/**
 * This returns all parameters of SAFS or FlashGraph.
 */
RcppExport SEXP R_FG_get_params(SEXP psys)
{
	std::string sys_name = CHAR(STRING_ELT(psys, 0));
	if (sys_name == "SAFS") {
		if (standalone) {
			fprintf(stderr,
					"Can't get SAFS parameters. FlashGraphR runs in standalone mode\n");
			return R_NilValue;
		}
		else
			return get_safs_params();
	}
	else if (sys_name == "FlashGraph")
		return get_fg_params();
	else {
		fprintf(stderr, "wrong system name\n");
		return R_NilValue;
	}
}

/**
 * This test whether a graph has been loaded to FlashGraphR.
 */
RcppExport SEXP R_FG_exist_graph(SEXP pgraph)
{
	std::string graph_name = CHAR(STRING_ELT(pgraph, 0));
	Rcpp::LogicalVector res(1);
	res[0] = exist_graph(graph_name);
	return res;
}

static bool exist_cindex(const std::string &graph_name)
{
	if (standalone)
		return false;

	std::string cindex_name = graph_name + "-cindex-v" + itoa(CURR_VERSION);
	safs_file cindex_file(get_sys_RAID_conf(), cindex_name);
	return cindex_file.exist();
}

RcppExport SEXP R_FG_exist_cindex(SEXP pgraph)
{
	std::string graph_name = CHAR(STRING_ELT(pgraph, 0));
	Rcpp::LogicalVector res(1);
	res[0] = exist_cindex(graph_name);
	return res;
}

static std::string extract_graph_name(const std::string &file_name)
{
	std::string version = itoa(CURR_VERSION);
	size_t pos = file_name.rfind("-cindex-v" + version);
	if (pos == std::string::npos)
		pos = file_name.rfind("-index-v" + version);
	if (pos == std::string::npos)
		pos = file_name.rfind("-v" + version);
	if (pos == std::string::npos)
		return "";
	else
		return file_name.substr(0, pos);
}

/**
 * This lists all graphs that have been loaded to FlashGraphR.
 */
RcppExport SEXP R_FG_list_graphs()
{
	// Get all graphs in memory.
	std::map<std::string, bool> graph_names;
	for (graph_map_t::const_iterator it = graphs.begin();
			it != graphs.end(); it++) {
		graph_names.insert(std::pair<std::string, bool>(it->first, true));
	}

	// Get all graphs in SAFS.
	if (!standalone) {
		std::set<std::string> files;
		get_all_safs_files(files);

		BOOST_FOREACH(std::string file, files) {
			std::string graph_name = extract_graph_name(file);
			if (!graph_name.empty())
				graph_names.insert(std::pair<std::string, bool>(
							graph_name, false));
		}
	}

	Rcpp::CharacterVector names;
	Rcpp::LogicalVector in_mem;
	typedef std::pair<std::string, bool> graph_value_t;
	BOOST_FOREACH(graph_value_t graph, graph_names) {
		if (graph.second) {
			names.push_back(graph.first);
			in_mem.push_back(graph.second);
		}
		else if (exist_graph(graph.first)) {
			names.push_back(graph.first);
			in_mem.push_back(graph.second);
		}
	}
	return Rcpp::DataFrame::create(Rcpp::Named("name") = names,
			Rcpp::Named("in-mem") = in_mem);
}

RcppExport SEXP R_FG_set_log_level(SEXP plevel)
{
	std::string level = CHAR(STRING_ELT(plevel, 0));
	if (level == "debug") {
		set_log_level(c_log_level::debug);
	}
	else if (level == "info") {
		set_log_level(c_log_level::info);
	}
	else if (level == "warning") {
		set_log_level(c_log_level::warning);
	}
	else if (level == "error") {
		set_log_level(c_log_level::error);
	}
	else if (level == "fatal") {
		set_log_level(c_log_level::fatal);
	}
	else {
		fprintf(stderr, "unknown level %s\n", level.c_str());
	}
	return R_NilValue;
}

static SEXP create_FGR_obj(const std::string &graph_name)
{
	Rcpp::List ret;
	ret["name"] = Rcpp::String(graph_name);

	Rcpp::LogicalVector cindex(1);
	cindex[0] = exist_cindex(graph_name);
	ret["cindex"] = cindex;

	FG_graph::ptr graph = get_graph(graph_name, cindex[0]);
	if (graph == NULL) {
		fprintf(stderr, "can't create FGR object\n");
		return R_NilValue;
	}
	graph_header header = graph->get_graph_header();
	Rcpp::LogicalVector directed(1);
	directed[0] = header.is_directed_graph();
	ret["directed"] = directed;

	Rcpp::NumericVector vcount(1);
	vcount[0] = header.get_num_vertices();
	ret["vcount"] = vcount;

	Rcpp::NumericVector ecount(1);
	ecount[0] = header.get_num_edges();
	ret["ecount"] = ecount;

	Rcpp::LogicalVector in_mem(1);
	in_mem[0] = graph->get_graph_data() != NULL;
	ret["in.mem"] = in_mem;
	return ret;
}

RcppExport SEXP R_FG_load_graph_adj(SEXP pgraph_name, SEXP pgraph_file,
		SEXP pindex_file)
{
	Rcpp::LogicalVector res(1);
	std::string graph_name = CHAR(STRING_ELT(pgraph_name, 0));
	std::string graph_file = CHAR(STRING_ELT(pgraph_file, 0));
	std::string index_file = CHAR(STRING_ELT(pindex_file, 0));
	FG_graph::ptr fg = FG_graph::create(graph_file, index_file, configs);
	graphs.insert(std::pair<std::string, FG_graph::ptr>(graph_name, fg));
	// Return the FLashGraphR object.
	return create_FGR_obj(graph_name);
}

/*
 * Load a graph from edge lists in a data frame.
 */
RcppExport SEXP R_FG_load_graph_el_df(SEXP pgraph_name, SEXP pedge_lists,
		SEXP pdirected, SEXP pnthreads)
{
	Rcpp::LogicalVector res(1);
	std::string graph_name = CHAR(STRING_ELT(pgraph_name, 0));
	Rcpp::DataFrame edge_lists = Rcpp::DataFrame(pedge_lists);
	bool directed = INTEGER(pdirected)[0];
	int num_threads = INTEGER(pnthreads)[0];

	Rcpp::IntegerVector from = edge_lists["from"];
	Rcpp::IntegerVector to = edge_lists["to"];
	std::vector<vertex_id_t> from_vec(from.begin(), from.end());
	std::vector<vertex_id_t> to_vec(to.begin(), to.end());

	std::pair<in_mem_graph::ptr, vertex_index::ptr> gpair = construct_mem_graph(
		from_vec, to_vec, graph_name, DEFAULT_TYPE, directed, num_threads);
	FG_graph::ptr fg = FG_graph::create(gpair.first, gpair.second, graph_name,
			configs);
	graphs.insert(std::pair<std::string, FG_graph::ptr>(graph_name, fg));
	// Return the FLashGraphR object.
	return create_FGR_obj(graph_name);
}

/*
 * Load a graph from edge lists in a file.
 */
RcppExport SEXP R_FG_load_graph_el(SEXP pgraph_name, SEXP pgraph_file,
		SEXP pdirected, SEXP pnthreads)
{
	Rcpp::LogicalVector res(1);
	std::string graph_name = CHAR(STRING_ELT(pgraph_name, 0));
	std::string graph_file = CHAR(STRING_ELT(pgraph_file, 0));
	bool directed = INTEGER(pdirected)[0];
	int num_threads = INTEGER(pnthreads)[0];

	native_file f(graph_file);
	if (!f.exist()) {
		fprintf(stderr, "%s doesn't exist\n", graph_file.c_str());
		return R_NilValue;
	}

	std::vector<std::string> edge_list_files(1);
	edge_list_files[0] = graph_file;
	std::pair<in_mem_graph::ptr, vertex_index::ptr> gpair = construct_mem_graph(
		edge_list_files, graph_name, DEFAULT_TYPE, directed, num_threads);
	FG_graph::ptr fg = FG_graph::create(gpair.first, gpair.second, graph_name,
			configs);
	graphs.insert(std::pair<std::string, FG_graph::ptr>(graph_name, fg));
	// Return the FLashGraphR object.
	return create_FGR_obj(graph_name);
}

RcppExport SEXP R_FG_get_graph_obj(SEXP pgraph)
{
	std::string graph_name = CHAR(STRING_ELT(pgraph, 0));
	if (!exist_graph(graph_name)) {
		fprintf(stderr, "%s doesn't exist\n", graph_name.c_str());
		return R_NilValue;
	}
	return create_FGR_obj(graph_name);
}

///////////////////////////// graph algorithms ///////////////////////////

RcppExport SEXP R_FG_compute_wcc(SEXP graph)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<vertex_id_t>::ptr fg_vec = compute_wcc(fg);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_scc(SEXP graph)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<vertex_id_t>::ptr fg_vec = compute_scc(fg);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_transitivity(SEXP graph)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<float>::ptr fg_vec = compute_transitivity(fg);
	Rcpp::NumericVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_get_degree(SEXP graph, SEXP ptype)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);

	std::string type_str = CHAR(STRING_ELT(ptype, 0));
	edge_type type = edge_type::NONE;
	if (type_str == "in")
		type = edge_type::IN_EDGE;
	else if (type_str == "out")
		type = edge_type::OUT_EDGE;
	else if (type_str == "both")
		type = edge_type::BOTH_EDGES;

	FG_vector<vsize_t>::ptr fg_vec = get_degree(fg, type);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_pagerank(SEXP graph, SEXP piters, SEXP pdamping)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);

	int num_iters = REAL(piters)[0];
	float damping_factor = REAL(pdamping)[0];

	FG_vector<float>::ptr fg_vec = compute_pagerank2(fg, num_iters, damping_factor);
	Rcpp::NumericVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_undirected_triangles(SEXP graph)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<size_t>::ptr fg_vec = compute_undirected_triangles(fg);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_directed_triangles(SEXP graph, SEXP ptype)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);

	std::string type_str = CHAR(STRING_ELT(ptype, 0));
	directed_triangle_type type = directed_triangle_type::CYCLE;
	if (type_str == "cycle")
		type = directed_triangle_type::CYCLE;
	else
		type = directed_triangle_type::ALL;

	FG_vector<size_t>::ptr fg_vec = compute_directed_triangles_fast(fg, type);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_local_scan(SEXP graph, SEXP order)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<size_t>::ptr fg_vec = compute_local_scan(fg);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_topK_scan(SEXP graph, SEXP order, SEXP K)
{
	size_t topK = REAL(K)[0];
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<std::pair<vertex_id_t, size_t> >::ptr fg_vec
		= compute_topK_scan(fg, topK);
	assert(fg_vec->get_size() == topK);
	Rcpp::IntegerVector vertices(fg_vec->get_size());
	Rcpp::IntegerVector scans(fg_vec->get_size());
	for (size_t i = 0; i < topK; i++) {
		std::pair<vertex_id_t, size_t> pair = fg_vec->get(i);
		vertices[i] = pair.first;
		scans[i] = pair.second;
	}
	return Rcpp::DataFrame::create(Named("vid", vertices), Named("scan", scans));
}

RcppExport SEXP R_FG_compute_kcore(SEXP graph, SEXP _k, SEXP _kmax)
{
	int k = REAL(_k)[0];
	int kmax = REAL(_kmax)[0];
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_vector<size_t>::ptr fg_vec = compute_kcore(fg, k, kmax);
	Rcpp::IntegerVector res(fg_vec->get_size());
	fg_vec->copy_to(res.begin(), fg_vec->get_size());
	return res;
}

RcppExport SEXP R_FG_compute_overlap(SEXP graph, SEXP _vids)
{
	Rcpp::IntegerVector Rvids(_vids);
	std::vector<vertex_id_t> vids(Rvids.begin(), Rvids.end());
	std::vector<std::vector<double> > overlap_matrix;
	size_t num_vertices = vids.size();

	FG_graph::ptr fg = R_FG_get_graph(graph);
	compute_overlap(fg, vids, overlap_matrix);
	assert(overlap_matrix.size() == num_vertices);

	Rcpp::NumericMatrix res(num_vertices, num_vertices);
	for (size_t i = 0; i < num_vertices; i++) {
		assert(overlap_matrix[i].size() == num_vertices);
		for (size_t j = 0; j < num_vertices; j++) {
			res(i, j) = overlap_matrix[i][j];
		}
	}
	return res;
}

RcppExport SEXP R_FG_fetch_subgraph(SEXP graph, SEXP pvertices)
{
	Rcpp::IntegerVector vertices(pvertices);
	std::vector<vertex_id_t> vids(vertices.begin(), vertices.end());
	FG_graph::ptr fg = R_FG_get_graph(graph);
	in_mem_subgraph::ptr subg = fetch_subgraph(fg, vids);
	assert(subg->get_num_vertices() == vids.size());
	Rcpp::IntegerVector s_vs(subg->get_num_edges());
	Rcpp::IntegerVector d_vs(subg->get_num_edges());
	size_t num_tot_edges = 0;
	BOOST_FOREACH(vertex_id_t id, vids) {
		const in_mem_vertex &v = subg->get_vertex(id);
		if (v.has_edge_data())
			ABORT_MSG("we can't fetch a subgraph from a graph with attributes");
		if (subg->is_directed()) {
			const in_mem_directed_vertex<> &dv
				= (const in_mem_directed_vertex<> &) v;
			size_t num_edges = dv.get_num_out_edges();
			for (size_t i = 0; i < num_edges; i++) {
				edge<> e = dv.get_out_edge(i);
				s_vs[num_tot_edges] = e.get_from();
				d_vs[num_tot_edges] = e.get_to();
				num_tot_edges++;
			}
		}
		else {
			const in_mem_undirected_vertex<> &un_v
				= (const in_mem_undirected_vertex<> &) v;
			size_t num_edges = un_v.get_num_edges();
			for (size_t i = 0; i < num_edges; i++) {
				edge<> e = un_v.get_edge(i);
				// each edge appears twice in an undirected graph.
				// we only need to store one.
				if (e.get_from() <= e.get_to()) {
					s_vs[num_tot_edges] = e.get_from();
					d_vs[num_tot_edges] = e.get_to();
					num_tot_edges++;
				}
			}
		}
	}
	assert(s_vs.size() == num_tot_edges);
	Rcpp::List ret;
	ret["src"] = s_vs;
	ret["dst"] = d_vs;
	return ret;
}

RcppExport SEXP R_FG_estimate_diameter(SEXP graph, SEXP pdirected)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	bool directed = INTEGER(pdirected)[0];
	int diameter = estimate_diameter(fg, 1, directed);
	Rcpp::IntegerVector ret(1);
	ret[0] = diameter;
	return ret;
}

RcppExport SEXP R_FG_multiply_v(SEXP graph, SEXP pvec, SEXP ptranspose)
{
	bool transpose = INTEGER(ptranspose)[0];
	Rcpp::NumericVector vec(pvec);
	size_t length = vec.size();
	FG_vector<double>::ptr in_vec = FG_vector<double>::create(length);
	for (size_t i = 0; i < length; i++) {
		in_vec->get_data()[i] = vec[i];
	}
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_adj_matrix::ptr matrix = FG_adj_matrix::create(fg);
	if (transpose)
		matrix = matrix->transpose();
	assert(matrix->get_num_rows() == length);
	assert(matrix->get_num_cols() == length);

	FG_vector<double>::ptr out_vec = FG_vector<double>::create(length);
	matrix->multiply<double>(*in_vec, *out_vec);
	Rcpp::NumericVector ret(out_vec->get_data(), out_vec->get_data() + length);
	return ret;
}

#ifdef USE_EIGEN
/*
 * Compute eigen value/vector on an unweighted adjacency matrix.
 */
RcppExport SEXP R_FG_eigen_uw(SEXP graph, SEXP pwhich, SEXP pnev, SEXP pncv)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_adj_matrix::ptr matrix = FG_adj_matrix::create(fg);
	std::string which = CHAR(STRING_ELT(pwhich, 0));
	int nev = INTEGER(pnev)[0];
	int ncv = INTEGER(pncv)[0];
	std::vector<eigen_pair_t> eigen_pairs;
	compute_eigen<FG_adj_matrix>(matrix, ncv, nev, which, eigen_pairs);
	if (eigen_pairs.empty())
		return R_NilValue;

	size_t length = eigen_pairs[0].second->get_size();
	Rcpp::NumericVector eigen_values(nev);
	Rcpp::NumericMatrix eigen_matrix(length, nev);
	for (int i = 0; i < nev; i++) {
		eigen_values[i] = eigen_pairs[i].first;
		for (size_t j = 0; j < length; j++)
			eigen_matrix(j, i) = eigen_pairs[i].second->get(j);
	}
	Rcpp::List ret;
	ret["values"] = eigen_values;
	ret["vectors"] = eigen_matrix;
	return ret;
}

RcppExport SEXP R_FG_SVD_uw(SEXP graph, SEXP pwhich, SEXP pnev, SEXP pncv,
		SEXP ptype)
{
	FG_graph::ptr fg = R_FG_get_graph(graph);
	FG_adj_matrix::ptr matrix = FG_adj_matrix::create(fg);
	std::string which = CHAR(STRING_ELT(pwhich, 0));
	std::string type = CHAR(STRING_ELT(ptype, 0));
	int nev = INTEGER(pnev)[0];
	int ncv = INTEGER(pncv)[0];
	std::vector<eigen_pair_t> eigen_pairs;
	compute_SVD<FG_adj_matrix>(matrix, ncv, nev, which, type, eigen_pairs);
	if (eigen_pairs.empty())
		return R_NilValue;

	size_t length = eigen_pairs[0].second->get_size();
	Rcpp::NumericVector eigen_values(nev);
	Rcpp::NumericMatrix eigen_matrix(length, nev);
	for (int i = 0; i < nev; i++) {
		eigen_values[i] = eigen_pairs[i].first;
		for (size_t j = 0; j < length; j++)
			eigen_matrix(j, i) = eigen_pairs[i].second->get(j);
	}
	Rcpp::List ret;
	ret["values"] = eigen_values;
	ret["vectors"] = eigen_matrix;
	return ret;
}
#endif

max_stars_repo_name: STEMHA/FlashGraph

max_issues_repo_name: Smerity/FlashGraph

max_forks_repo_name: Smerity/FlashGraph


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

#include "log.hpp"

#include <qicore/logmessage.hpp>
#include <queue>

#include <std_msgs/String.h>

#include <boost/algorithm/string.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/foreach.hpp>

#include <ros/console.h>

#define for_each BOOST_FOREACH

namespace naoqi
{
namespace converter
{

/** mutex to change the logs list */
boost::mutex MUTEX_LOGS;
/** list of ogs in which the NAOqi callback will write its logs */
std::queue<rosgraph_msgs::Log> LOGS;
/** Generic Log Level used to store all the correspondences between the libqi and ROS log levels */
class LogLevel
{
public:
  LogLevel(qi::LogLevel qi, rosgraph_msgs::Log::_level_type ros_msg, ros::console::levels::Level ros_console) :
      qi_(qi), ros_msg_(ros_msg), ros_console_(ros_console)
  {
    all_.push_back(*this);
  }

  static const LogLevel& get_from_qi(qi::LogLevel qi)
  {
    for_each(const LogLevel& log_level, all_)
      if (log_level.qi_ == qi)
        return log_level;
  }

  static const LogLevel& get_from_ros_msg(rosgraph_msgs::Log::_level_type ros_msg)
  {
    for_each(const LogLevel& log_level, all_)
      if (log_level.ros_msg_ == ros_msg)
        return log_level;
  }

  static const LogLevel& get_from_ros_console(ros::console::levels::Level ros_console)
  {
    for_each(const LogLevel& log_level, all_)
      if (log_level.ros_console_ == ros_console)
        return log_level;
  }

  qi::LogLevel qi_;
  rosgraph_msgs::Log::_level_type ros_msg_;
  ros::console::levels::Level ros_console_;

private:
  static std::vector<LogLevel> all_;
};

std::vector<LogLevel> LogLevel::all_ = std::vector<LogLevel>();

/** Callback called for each libqi log message
 */
void logCallback(const qi::LogMessage& msg)
{
  // Convert the NAOqi log to a ROS log
  rosgraph_msgs::Log log;

  std::vector<std::string> results;
  boost::split(results, msg.source, boost::is_any_of(":"));
  log.file = results[0];
  log.function = results[1];
  log.line = atoi(results[2].c_str());
  log.level = LogLevel::get_from_qi(msg.level).ros_msg_;
  log.name = msg.category;
  log.msg = msg.message;
  log.header.stamp = ros::Time(msg.timestamp.tv_sec, msg.timestamp.tv_usec);

  // If we are not publishing, the queue will increase, so we have to prevent an explosion
  // We only keep a log if it's within 5 second of the last publish (totally arbitrary)
  boost::mutex::scoped_lock lock( MUTEX_LOGS );
  while (LOGS.size() > 1000)
  {
    LOGS.pop();
  }
  LOGS.push(log);
}

LogConverter::LogConverter( const std::string& name, float frequency, const qi::SessionPtr& session )
  : BaseConverter( name, frequency, session ),
    logger_( session->service("LogManager") ),
    // Default log level is info
    log_level_(qi::LogLevel_Info)
{
  // Define the log equivalents
  LogLevel(qi::LogLevel_Silent, rosgraph_msgs::Log::DEBUG, ros::console::levels::Debug);
  LogLevel(qi::LogLevel_Fatal, rosgraph_msgs::Log::FATAL, ros::console::levels::Fatal);
  LogLevel(qi::LogLevel_Error, rosgraph_msgs::Log::ERROR, ros::console::levels::Error);
  LogLevel(qi::LogLevel_Warning, rosgraph_msgs::Log::WARN, ros::console::levels::Warn);
  LogLevel(qi::LogLevel_Info, rosgraph_msgs::Log::INFO, ros::console::levels::Info);
  LogLevel(qi::LogLevel_Verbose, rosgraph_msgs::Log::DEBUG, ros::console::levels::Debug);
  LogLevel(qi::LogLevel_Debug, rosgraph_msgs::Log::DEBUG, ros::console::levels::Debug);

  listener_ = logger_->getListener();
  set_qi_logger_level();
  listener_->onLogMessage.connect(logCallback);
}

void LogConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

void LogConverter::callAll( const std::vector<message_actions::MessageAction>& actions )
{
  while ( !LOGS.empty() )
  {
    rosgraph_msgs::Log& log_msg = LOGS.front();
    for_each( const message_actions::MessageAction& action, actions)
    {
      callbacks_[action](log_msg);
    }
    {
      boost::mutex::scoped_lock lock( MUTEX_LOGS );
      LOGS.pop();
    }
  }
  set_qi_logger_level();
}

void LogConverter::reset( )
{
}

void LogConverter::set_qi_logger_level( )
{
  // Check that the log level is above or equal to the current one
  std::map<std::string, ros::console::levels::Level> loggers;
  ros::console::get_loggers(loggers);

  std::map<std::string, ros::console::levels::Level>::iterator iter = loggers.find("ros.naoqi_driver");

  if (iter == loggers.end())
    return;

  qi::LogLevel new_level = LogLevel::get_from_ros_console(iter->second).qi_;
  // Only change the log level if it has changed (otherwise, there is a flood of warnings)
  if (new_level == log_level_)
      return;

  log_level_ = new_level;
  qi::log::setLogLevel(log_level_);
}

} // publisher
} //naoqi

ext: cpp


text:
// Copyright 2014-2015 SDL plc
// 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.
/** \file

    some frequently used string algs.
*/

#ifndef STRING_JG20121212_HPP
#define STRING_JG20121212_HPP
#pragma once

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <algorithm>
#include <fstream>

namespace sdl {
namespace Util {

/**
   \return length of prefix ending with second space or first space -> end of string. 0 if no space found.
*/
inline std::string::size_type len_split2(std::string const& str, char space = ' ') {
  std::string::size_type sp = str.find(space);
  if (sp == std::string::npos) return 0;
  sp = str.find(space, ++sp);
  return sp == std::string::npos ? str.size() : sp;
}

/**
   \return true if str contains space, and if so \out first part before, rest part after.
*/
inline bool split2(std::string const& str, std::string& first, std::string& rest, char space = ' ') {
  using std::string;
  string::size_type sp = str.find(space);
  if (sp == string::npos)
    return false;
  else {
    string::const_iterator begin = str.begin();
    string::const_iterator mid = begin + sp;
    first.assign(begin, mid);
    rest.assign(mid + 1, str.end());
    return true;
  }
}

/**
   \return if trim(str, whitespace) begins with prefix, set str to the trimmed
   string with prefix removed and \return true, else \return false and don't set
   str. close to 'stripPrefix(trim(str), prefix)' but avoids wasted work
   if return value is false.
*/
inline bool stripPrefixTrim(std::string& str, std::string const& prefix,
                            std::string const& whitespace = "\n\r\t ") {
  std::string::size_type b;
  b = str.find_first_not_of(whitespace);
  std::string::iterator nonspaceBegin = str.begin() + b;
  using namespace boost;
  if (boost::algorithm::starts_with(boost::make_iterator_range(nonspaceBegin, str.end()), prefix)) {
    str.erase(str.begin(), nonspaceBegin + prefix.size());
    return true;
  } else
    return false;
}

/**
   \return true and strip prefix if str starts with that, else return false
*/
inline bool stripPrefix(std::string& str, std::string const& prefix) {
  if (boost::algorithm::starts_with(str, prefix)) {
    str.erase(str.begin(), str.begin() + prefix.size());
    return true;
  } else
    return false;
}

/**
   \return str.substr(str.size()-suffix.size()) == suffix

   (without copying)
*/
template <class String>
inline bool endsWith(String const& str, String const& suffix) {
  return boost::algorithm::ends_with(str, suffix);
}

template <class String>
inline bool startsWith(String const& str, String const& prefix) {
  return boost::algorithm::starts_with(str, prefix);
}

inline bool endsWith(std::string const& str, std::string const& suffix) {
  return boost::algorithm::ends_with(str, suffix);
}

inline bool startsWith(std::string const& str, std::string const& prefix) {
  return boost::algorithm::starts_with(str, prefix);
}

inline bool endsWith(std::string const& str, char const* suffix) {
  return boost::algorithm::ends_with(str, suffix);
}

inline bool startsWith(std::string const& str, char const* prefix) {
  return boost::algorithm::starts_with(str, prefix);
}

/**
   \return true and strip suffix if str ends with that, else return false
*/
inline bool stripSuffix(std::string& str, std::string const& suffix) {
  if (endsWith(str, suffix)) {
    str.erase(str.end() - suffix.size(), str.end());
    return true;
  } else
    return false;
}

}}

#endif

ext: hpp

max_stars_repo_name: sdl-research/hyp

max_issues_repo_name: hypergraphs/hyp

max_forks_repo_name: hypergraphs/hyp


text:
#include <iostream>
//
#include <polyvec/api.hpp>
#include <polyvec/core/log.hpp>
#include <polyvec/misc.hpp>
#include <polyvec/io/vtk_curve_writer.hpp>
#include <polyvec/curve-tracer/bezier_merging.hpp>
//
#include <Eigen/Core>
#include <Eigen/Geometry>

NAMESPACE_BEGIN()
NAMESPACE_END()

NAMESPACE_BEGIN(polyvectest)
NAMESPACE_BEGIN(BezierMerging)

int find_affine_transformation(int, char**) {

  // Creat the points and then test the mapping
  Eigen::Matrix<double, 2,3> points0;
  Eigen::Matrix<double, 2,3> points1;
  Eigen::Matrix2d A;
  Eigen::Vector2d b;
  Eigen::Matrix2d Amanu;
  Eigen::Vector2d bmanu;

  points0.col(0) << 2,10;
  points0.col(1) << 5,7;
  points0.col(2) << 4,12;

  //
  // Identity test
  //
  Amanu = Eigen::Matrix2d::Identity();
  bmanu = Eigen::Vector2d::Zero();
  points1 = (Amanu * points0).colwise() + bmanu;

  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);
  assert_break( (A - Amanu).norm() < 1e-12 );
  assert_break( (b - bmanu).norm() < 1e-12 );

  //
  // Translation test
  //
  Amanu = Eigen::Matrix2d::Identity();
  bmanu = Eigen::Vector2d(2, -1.48);
  points1 = (Amanu * points0).colwise() + bmanu;

  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);
  assert_break( (A - Amanu).norm() < 1e-12 );
  assert_break( (b - bmanu).norm() < 1e-12 );

  //
  // A test
  //
  Amanu << 5, 12, -1, 30;
  bmanu = Eigen::Vector2d::Zero();
  points1 = (Amanu * points0).colwise() + bmanu;

  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);
  assert_break( (A - Amanu).norm() < 1e-12 );
  assert_break( (b - bmanu).norm() < 1e-12 );

  //
  // together
  //
  Amanu << 5, 12, -1, 30;
  bmanu << 9, -3;
  points1 = (Amanu * points0).colwise() + bmanu;

  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);
  assert_break( (A - Amanu).norm() < 1e-12 );
  assert_break( (b - bmanu).norm() < 1e-12 );

  return EXIT_FAILURE;
}

NAMESPACE_END(BezierMerging)
NAMESPACE_END(polyvectest)

max_stars_repo_name: ShnitzelKiller/polyfit

max_issues_repo_name: ShnitzelKiller/polyfit

max_forks_repo_name: ShnitzelKiller/polyfit


text:
#include <qlo/objects/obj_defaultbasket.hpp>

#include <ql/currencies/europe.hpp>
#include <ql/experimental/credit/basket.hpp>
#include <boost/make_shared.hpp>

QuantLibAddin::Basket::Basket(
    const boost::shared_ptr<reposit::ValueObject>& properties,
            // BEGIN typemap rp_tm_default
            std::vector< std::string > const &IssuerNames,
            std::vector< boost::shared_ptr< QuantLib::Issuer > > const &Issuers,
            std::vector< QuantLib::Real > const &Notionals,
            QuantLib::Date const &ReferenceDate,
            QuantLib::Real AttachmentRatio,
            QuantLib::Real DettachmentRatio,
            bool Amortizing,
            // END   typemap rp_tm_default
    bool permanent) : reposit::LibraryObject<QuantLib::Basket>(properties, permanent) {

        QL_REQUIRE(IssuerNames.size() == Issuers.size(),
            "Different number of names and issuers.");

        std::vector<QuantLib::DefaultProbKey> contractTriggers(
            IssuerNames.size(),
            QuantLib::NorthAmericaCorpDefaultKey(QuantLib::EURCurrency(),
                QuantLib::SeniorSec,
                QuantLib::Period(),
                1. // amount threshold
            ));

        boost::shared_ptr<QuantLib::Pool> pool(new QuantLib::Pool());
        for(QuantLib::Size i=0; i<IssuerNames.size(); i++)
                pool->add(IssuerNames[i], *Issuers[i], contractTriggers[i]);
        libraryObject_ =
            boost::make_shared<QuantLib::Basket>(
                QuantLib::Basket(ReferenceDate, IssuerNames, Notionals, pool,
                    AttachmentRatio, DettachmentRatio));
}

max_stars_repo_name: eehlers/QuantLibAddin

max_issues_repo_name: eehlers/QuantLibAddin

max_forks_repo_name: eehlers/QuantLibAddin


text:
//
//  OpenNIConnector.cpp
//  gl
//
//  Created by Fabian on 5/5/13.
//
//

#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>

//#include <ni2/OpenNI.h>

#include "core/file_functions.hpp"
#include "gl/Texture.hpp"
#include "gl/Buffer.hpp"
#include <boost/timer/timer.hpp>
#include "OpenNIConnector.h"

using namespace std;

inline float raw_depth_to_meters(int raw_depth)
{
    if (raw_depth < 2047)
    {
        return 1.0 / (raw_depth * -0.0030711016 + 3.3309495161);
    }
    return 0;
}

namespace kinski{ namespace gl{

    struct OpenNIConnector::Obj
    {
        xn::Context m_context;
        xn::ScriptNode m_scriptNode;
        xn::DepthGenerator m_depthGenerator;
        xn::UserGenerator m_userGenerator;
        xn::Player m_player;
        std::vector<uint8_t> m_pixel_buffer;
        std::vector<float> m_histogram_buffer;

        std::vector<glm::vec4> m_point_buffer;

        Obj(){}

        ~Obj()
        {
            m_scriptNode.Release();
            m_depthGenerator.Release();
            m_userGenerator.Release();
            m_player.Release();
            m_context.Release();
        }

        static void XN_CALLBACK_TYPE new_user(xn::UserGenerator& /*generator*/, XnUserID nId,
                                              void* cookie);
        static void XN_CALLBACK_TYPE lost_user(xn::UserGenerator& /*generator*/, XnUserID nId,
                                               void* cookie);
        static void XN_CALLBACK_TYPE calibration_start(xn::SkeletonCapability& /*capability*/,
                                                       XnUserID nId, void* cookie);
        static void XN_CALLBACK_TYPE calibration_complete(xn::SkeletonCapability& /*capability*/,
                                                          XnUserID nId, XnCalibrationStatus eStatus,
                                                   void* cookie);
        static void XN_CALLBACK_TYPE pose_detected(xn::PoseDetectionCapability& /*capability*/,
                                                   const XnChar* strPose, XnUserID nId, void* cookie);
    };

    OpenNIConnector::OpenNIConnector():
    m_new_frame(false),
    m_depth_texture(640, 480, gl::Texture::Format()),
    m_running(false),
    m_live_input(Property_<bool>::create("Live input", false)),
    m_config_path(Property_<string>::create("Config path", "ni_config.xml")),
    m_oni_path(Property_<string>::create("Oni path", ""))
    {
        set_name("OpenNIConnector");
        register_property(m_live_input);
        register_property(m_config_path);
        register_property(m_oni_path);

        m_user_colors.resize(50);
        for (int i= 0; i < m_user_colors.size(); ++i)
        {m_user_colors[i] = gl::Color(glm::vec3(random(0.f, 1.f), .2f, random(0.f, 1.f)), 1.f);}
        m_user_colors.push_back(gl::Color(1));
    }

    OpenNIConnector::~OpenNIConnector()
    {
        stop();
    }

    void OpenNIConnector::init()
    {
        LOG_DEBUG<<"initializing OpenNI ...";
        m_obj.reset(new Obj);
        XnStatus ni_status = XN_STATUS_OK;

        // hook up a attached camera
        if(*m_live_input)
        {
            xn::EnumerationErrors errors;
            try
            {
                ni_status = m_obj->m_context.InitFromXmlFile(fs::search_file(*m_config_path).c_str(),
                                                             m_obj->m_scriptNode, &errors);
            } catch (fs::FileNotFoundException &e){LOG_ERROR<<e.what();}

            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
        }
        // load oni file
        else
        {
            if(m_oni_path->value().empty()){throw OpenNIException("empty .oni path");};

            m_obj->m_context.Init();
            try
            {
                ni_status = m_obj->m_context.OpenFileRecording(fs::search_file(*m_oni_path).c_str(),
                                                               m_obj->m_player);
            }catch (fs::FileNotFoundException &e){LOG_ERROR<<e.what();}
            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
        }

        // create a depth generator
        ni_status = m_obj->m_context.FindExistingNode(XN_NODE_TYPE_DEPTH, m_obj->m_depthGenerator);
        if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
        m_obj->m_depthGenerator.StartGenerating();
        LOG_DEBUG<<"created depth node";

        // create a user generator
        if(false)
        {
            ni_status = m_obj->m_context.FindExistingNode(XN_NODE_TYPE_USER, m_obj->m_userGenerator);
            if (ni_status != XN_STATUS_OK)
            {
                ni_status = m_obj->m_userGenerator.Create(m_obj->m_context);
                if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
            }
            LOG_DEBUG<<"created user node";

            if (!m_obj->m_userGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
            {
                LOG_WARNING<<"Supplied user generator doesn't support skeleton";
            }
            XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete;
            ni_status = m_obj->m_userGenerator.RegisterUserCallbacks(Obj::new_user, Obj::lost_user,
                                                                     m_obj.get(), hUserCallbacks);
            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}

            ni_status = m_obj->m_userGenerator.GetSkeletonCap().RegisterToCalibrationStart(Obj::calibration_start,
                                                                                m_obj.get(),
                                                                                hCalibrationStart);
            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
            ni_status = m_obj->m_userGenerator.GetSkeletonCap().RegisterToCalibrationComplete(Obj::calibration_complete,
                                                                                m_obj.get(),
                                                                                hCalibrationComplete);
            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}

            ni_status = m_obj->m_userGenerator.StartGenerating();;
            if(ni_status != XN_STATUS_OK){throw OpenNIException(xnGetStatusString(ni_status));}
        }

        XnFieldOfView fov;
        m_obj->m_depthGenerator.GetFieldOfView(fov);
        LOG_DEBUG<<"Sensor fov: H: "<<glm::degrees(fov.fHFOV)<<" -- V: "<<glm::degrees(fov.fVFOV);
        LOG_DEBUG<<"init complete";
    }

    // Callback: New user was detected
    void XN_CALLBACK_TYPE OpenNIConnector::Obj::new_user(xn::UserGenerator& /*generator*/,
                                                         XnUserID nId, void* cookie)
    {
        Obj *myObj = static_cast<Obj*>(cookie);
        char str_pose[20];
        LOG_DEBUG<<"New User "<<nId;

        // New user found
        if (false)//g_bNeedPose)
        {
            myObj->m_userGenerator.GetPoseDetectionCap().StartPoseDetection(str_pose, nId);
        }
        else
        {
            myObj->m_userGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
        }
    }

    // Callback: An existing user was lost
    void XN_CALLBACK_TYPE OpenNIConnector::Obj::lost_user(xn::UserGenerator& /*generator*/,
                                                          XnUserID nId, void* cookie)
    {
        //Obj *myObj = static_cast<Obj*>(cookie);
        LOG_DEBUG<<"Lost user "<<nId;
    }

    void XN_CALLBACK_TYPE
    OpenNIConnector::Obj::pose_detected(xn::PoseDetectionCapability& /*capability*/,
                                        const XnChar* strPose, XnUserID nId, void* cookie)
    {
        Obj *myObj = static_cast<Obj*>(cookie);
        LOG_DEBUG<<"Pose "<<strPose<<" detected for user "<<nId;
        myObj->m_userGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
        myObj->m_userGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
    }
    // Callback: Started calibration
    void XN_CALLBACK_TYPE
    OpenNIConnector::Obj::calibration_start(xn::SkeletonCapability& /*capability*/, XnUserID nId,
                                            void* /*pCookie*/)
    {
        LOG_DEBUG<<"Calibration started for user "<<nId;
    }

    // Callback: Finished calibration
    void XN_CALLBACK_TYPE
    OpenNIConnector::Obj::calibration_complete(xn::SkeletonCapability& /*capability*/,
                                               XnUserID nId, XnCalibrationStatus eStatus,
                                               void* cookie)
    {
        Obj *myObj = static_cast<Obj*>(cookie);
        if (eStatus == XN_CALIBRATION_STATUS_OK)
        {
            // Calibration succeeded
            LOG_DEBUG<<"Calibration complete, start tracking user "<<nId;
            myObj->m_userGenerator.GetSkeletonCap().StartTracking(nId);
        }
        else
        {
            char str_pose[20];

            // Calibration failed
            LOG_DEBUG<<"Calibration failed for user "<<nId;
            if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
            {
                LOG_DEBUG<<"Manual abort occured, stop attempting to calibrate!";
                return;
            }
            if (false)//g_bNeedPose)
            {
                myObj->m_userGenerator.GetPoseDetectionCap().StartPoseDetection(str_pose, nId);
            }
            else
            {
                myObj->m_userGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
            }
        }
    }

    void OpenNIConnector::updateProperty(const Property::ConstPtr &theProperty)
    {
        if(theProperty == m_live_input)
        {
            stop();
            if(*m_live_input) start();
        }
        else if(theProperty == m_oni_path)
        {
            if(!*m_live_input)
            {
                stop();
                start();
            }
        }
    }

    void OpenNIConnector::start()
    {
        if(m_running) return;
        m_thread = std::thread(std::bind(&OpenNIConnector::run, this));
        m_running = true;
    }

    void OpenNIConnector::stop()
    {
        m_running = false;

        if(m_thread.joinable())
        {
            try{m_thread.join();}
            catch(std::exception &e){LOG_ERROR<<e.what();}
        }
    }

    void OpenNIConnector::run()
    {
        m_running = true;
        try{init();}
        catch(OpenNIException &e){LOG_ERROR<<e.what(); m_running = false;}

        // measure elapsed time with these
        xn::SceneMetaData sceneMD;
        xn::DepthMetaData depthMD;

        while(m_running)
        {
            // Read next available data
            m_obj->m_context.WaitOneUpdateAll(m_obj->m_depthGenerator);

            // Process the data
            m_obj->m_depthGenerator.GetMetaData(depthMD);
//            m_obj->m_userGenerator.GetUserPixels(0, sceneMD);
//
//            XnPoint3D user_center;
//            XnUInt16 num_users = m_obj->m_userGenerator.GetNumberOfUsers();
//            uint32_t user_ids[num_users];
//            m_obj->m_userGenerator.GetUsers(user_ids, num_users);

            //locked scope
            {
                std::unique_lock<std::mutex> lock(m_mutex);
                update_depth_texture(depthMD, sceneMD);
//
//                m_user_list.clear();
//
//                for (int i = 0; i < num_users; ++i)
//                {
//                    m_obj->m_userGenerator.GetCoM(user_ids[i], user_center);
//                    glm::vec3 p = glm::make_vec3((float*)&user_center);
//                    // zombie filter
//                    if(p != glm::vec3(0))
//                    {
//                        m_user_list.push_back(User(user_ids[i], p));
//                    }
//                }
                m_new_frame = true;
            }
        }
        m_user_list.clear();
        m_obj->m_pixel_buffer.clear();
        m_running = false;
    }

    OpenNIConnector::UserList OpenNIConnector::get_user_positions() const
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_new_frame = false;
        return m_user_list;
    }

    gl::Texture OpenNIConnector::get_depth_texture()
    {
//        // needs OpenGL -> can only be called from main thread
//        // TODO: move or keep !?
//        std::unique_lock<std::mutex> lock(m_mutex);
//        m_new_frame = false;
//        if(m_obj && !m_obj->m_pixel_buffer.empty())
//            m_depth_texture.update(&m_obj->m_pixel_buffer[0], GL_UNSIGNED_BYTE, GL_RGB, 640, 480, true);
//        return m_depth_texture;

        m_depth_texture_raw.update((void*)m_depth_data, GL_UNSIGNED_SHORT, GL_RED, 640, 480, true);
        return m_depth_texture_raw;
    }

    void OpenNIConnector::update_depth_buffer(gl::Buffer the_vertex_buf) const
    {
        // needs OpenGL -> can only be called from main thread
        std::unique_lock<std::mutex> lock(m_mutex);
        m_new_frame = false;
        if(m_obj && !m_obj->m_point_buffer.empty())
        {
            the_vertex_buf.set_data(m_obj->m_point_buffer);
        }
    }

    void OpenNIConnector::update_depth_texture(const xn::DepthMetaData& dmd, const xn::SceneMetaData& smd)
    {
        unsigned int nZRes = dmd.ZRes();
        m_obj->m_histogram_buffer.resize(nZRes);
        std::fill(m_obj->m_histogram_buffer.begin(), m_obj->m_histogram_buffer.end(), 0);
        float* pDepthHist = &m_obj->m_histogram_buffer[0];

        unsigned int nValue = 0;
        unsigned int nHistValue = 0;
        unsigned int nIndex = 0;
        unsigned int nX = 0;
        unsigned int nY = 0;
        unsigned int nNumberOfPoints = 0;
        XnUInt16 x_res = dmd.XRes();
        XnUInt16 y_res = dmd.YRes();

        m_obj->m_pixel_buffer.resize(x_res * y_res * 3);
        unsigned char* pDestImage = &m_obj->m_pixel_buffer[0];

        const XnDepthPixel* pDepth = dmd.Data();
        const XnLabel* pLabels = smd.Data();

        // make raw depth image available for gpu processing
        if(true)
        {
            m_depth_data = static_cast<const uint16_t*>(dmd.Data());
            return;
        }

        // Calculate the accumulative histogram
        for (nY=0; nY<y_res; nY++)
        {
            for (nX=0; nX<x_res; nX++)
            {
                nValue = *pDepth;

                if (nValue != 0)
                {
                    pDepthHist[nValue]++;
                    nNumberOfPoints++;
                }
                pDepth++;
            }
        }

        for (nIndex=1; nIndex<nZRes; nIndex++)
        {
            pDepthHist[nIndex] += pDepthHist[nIndex-1];
        }
        if (nNumberOfPoints)
        {
            for (nIndex=1; nIndex<nZRes; nIndex++)
            {
                pDepthHist[nIndex] = (unsigned int)(256 * (1.0f - (pDepthHist[nIndex] / nNumberOfPoints)));
            }
        }

        pDepth = dmd.Data();

        if (false)//g_bDrawPixels)
        {
            XnUInt32 nIndex = 0;
            int num_colors = m_user_colors.size() - 1;

            // Prepare the texture map
            for (nY=0; nY<y_res; nY++)
            {
                for (nX = 0; nX < x_res; nX++, nIndex++)
                {
                    pDestImage[0] = 0;
                    pDestImage[1] = 0;
                    pDestImage[2] = 0;
                    if (/*g_bDrawBackground*/true || *pLabels != 0)
                    {
                        nValue = *pDepth;
                        XnLabel label = *pLabels;
                        XnUInt32 nColorID = label % num_colors;
                        if (label == 0)
                        {
                            nColorID = num_colors;
                        }

                        if (nValue != 0)
                        {
                            nHistValue = pDepthHist[nValue];
                            pDestImage[0] = nHistValue * m_user_colors[nColorID][0];
                            pDestImage[1] = nHistValue * m_user_colors[nColorID][1];
                            pDestImage[2] = nHistValue * m_user_colors[nColorID][2];
                        }
                    }
                    pDepth++;
                    pLabels++;
                    pDestImage+=3;
                }
            }
        }
        else
        {
            std::fill(m_obj->m_pixel_buffer.begin(), m_obj->m_pixel_buffer.end(), 0);
        }

        if(false)
        {
            // point buffer
            int w = 640, h = 480;

            m_obj->m_point_buffer.resize(w * h);

            // reset pointer
            pDepth = dmd.Data();

            XnPoint3D p2d, p3d;
            for (int i = 0; i < h; i++)
                for (int j = 0; j < w; j++)
                {
                    p2d.X = j;
                    p2d.Y = i;
                    p2d.Z = pDepth[i * w + j];
                    m_obj->m_depthGenerator.ConvertProjectiveToRealWorld(1, &p2d, &p3d);

                    m_obj->m_point_buffer[i * w + j] = glm::vec4(p3d.X, p3d.Y, -p3d.Z, 1.f);

                    //                m_obj->m_point_buffer[i * w + j] = glm::vec4(j, i, pDepth[i * w + j], 1.f);
                }
        }

    }

}}

max_stars_repo_name: crocdialer/KinskiGL

max_issues_repo_name: crocdialer/KinskiGL

max_forks_repo_name: crocdialer/KinskiGL


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman
    Copyright (c) 2011 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(FUSION_FIND_IF_05052005_1108)
#define FUSION_FIND_IF_05052005_1108

#include <boost/fusion/algorithm/query/detail/find_if.hpp>
#include <boost/fusion/algorithm/query/detail/segmented_find_if.hpp>
#include <boost/fusion/algorithm/query/find_if_fwd.hpp>
#include <boost/fusion/iterator/value_of.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/is_segmented.hpp>
#include <boost/mpl/bind.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/quote.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
namespace fusion {
namespace result_of {
template <typename Sequence, typename Pred>
struct find_if
    : mpl::if_<
          traits::is_segmented<Sequence>,
          detail::result_of_segmented_find_if<Sequence, Pred>,
          detail::result_of_find_if<
              Sequence,
              mpl::bind1<typename mpl::lambda<Pred>::type,
                         mpl::bind1<mpl::quote1<value_of>, mpl::_1>>>>::type {};
} // namespace result_of

template <typename Pred, typename Sequence>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline
    typename lazy_disable_if<is_const<Sequence>,
                             result_of::find_if<Sequence, Pred>>::type
    find_if(Sequence &seq) {
  typedef typename result_of::find_if<Sequence, Pred>::filter filter;
  return filter::call(seq);
}

template <typename Pred, typename Sequence>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline
    typename result_of::find_if<Sequence const, Pred>::type const
    find_if(Sequence const &seq) {
  typedef typename result_of::find_if<Sequence const, Pred>::filter filter;
  return filter::call(seq);
}
} // namespace fusion
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/maybe.hpp>
using namespace boost::hana;

int main() {
    //! [main]
    BOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {
        return x + 1; // next letter
    };

    BOOST_HANA_CONSTEXPR_ASSERT(ap(just(f), just('x')) == just(f('x')));
    BOOST_HANA_CONSTANT_ASSERT(ap(nothing, just('x')) == nothing);
    BOOST_HANA_CONSTANT_ASSERT(ap(just(f), nothing) == nothing);
    BOOST_HANA_CONSTANT_ASSERT(ap(nothing, nothing) == nothing);
    //! [main]
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/filesystem.hpp>
#include "GameConfigHead.h"

namespace game{
namespace config{

	namespace bp=boost::program_options;
	namespace bf=boost::filesystem;
	namespace bpt=boost::property_tree;

	inline void parse_item(ConfigMap & cm,bpt::ptree & pt){
		using namespace bpt;
		std::string type=pt.get<std::string>("<xmlattr>.type","None");
		std::string tag=pt.get<std::string>("<xmlattr>.tag","None");
		if (tag=="None"){
			std::cerr<<"在配置文件中没有标识符"<<std::endl;
			std::exit(0);
		}
		if (type=="string"){
			cm.insert(ConfigPair(tag,pt.get_value<std::string>()));
		}else if (type=="int"){
			cm.insert(ConfigPair(tag,pt.get_value<int>()));
		}else if (type=="bool"){
			cm.insert(ConfigPair(tag,pt.get_value<bool>()));
		}
	}

	std::string parse_cmd(int argc,char * argv []){

		using namespace bp;

		variables_map vm;
		options_description opts("Magic-Cubes游戏");
		opts.add_options()
			("version,v","显示版本")
			("help,h","显示帮助")
			("file,f",value<std::string>()
				->default_value("../res/config.xml")
				->implicit_value("../res/config.xml")
				,"指定配置文件");

		store(parse_command_line(argc,argv,opts),vm);

		if (vm.count("help")){
			std::cout<<opts<<std::endl;
			std::exit(0);
		}

		if (vm.count("version")){
			std::cout<<"Version:1.0"<<std::endl;
			std::exit(0);
		}

		return vm["file"].as<std::string>();

	}

	void parse_config_file(std::string filename,ConfigMap & cm){
		using namespace bpt;

		ptree pt;
		read_xml(filename,pt);
		ptree  child=pt.get_child("GameConfig");
		ptree::iterator it=child.begin();
		for (;it!=child.end();++it){
			if ((*it).first=="Item"){
				ptree & ip=(*it).second;
				parse_item(cm,ip);
			}
		}

	}

}
}

max_stars_repo_name: lihaolang/magic-cubes

max_issues_repo_name: lihaolang/magic-cubes

max_forks_repo_name: lihaolang/magic-cubes


text:
#define PY_ARRAY_UNIQUE_SYMBOL superimg_PyArray_API
#define NO_IMPORT_ARRAY

#include <string>
#include <cmath>

#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include <boost/array.hpp>

#include <boost/accumulators/accumulators.hpp>

#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/median.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>
#include <boost/accumulators/statistics/tail_quantile.hpp>

#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>

#include "seglib/cgp2d/cgp2d.hxx"
#include "seglib/cgp2d/cgp2d_python.hxx"
#include "seglib/distances/distance.hxx"

namespace python = boost::python;

namespace cgp2d {

    // tgrid and input image type
    typedef Cgp<CoordinateType,LabelType> CgpType;
    typedef CgpType::TopologicalGridType TopologicalGridType;

    void mergeFeatures(
        vigra::NumpyArray<1,LabelType>          labeling,
        const size_t                            numberOfLabels,
        vigra::NumpyArray<1,float>              weights,
        vigra::NumpyArray<2,float>              features,
        vigra::NumpyArray<2,float>              mergedFeatures,
        vigra::NumpyArray<1,float>              weightBuffer
    ){
        CGP_ASSERT_OP(labeling.shape(0),==,features.shape(0));
        CGP_ASSERT_OP(labeling.shape(0),==,mergedFeatures.shape(0));
        CGP_ASSERT_OP(features.shape(1),==,mergedFeatures.shape(1));
        CGP_ASSERT_OP(weightBuffer.shape(0),==,features.shape(0));

        // initalize with zeros
        std::fill(mergedFeatures.begin(),mergedFeatures.begin()+numberOfLabels,0.0);
        std::fill(weightBuffer.begin(),weightBuffer.begin()+numberOfLabels,0.0);

        const size_t nItems = labeling.shape(0);
        const size_t nFeatures = features.shape(1);

        // accumulate
        for(size_t i=0;i<nItems;++i){

            // get the label
            const size_t label = labeling(i);
            // get the weight
            const float weight = weights(i);
            // accumulate features
            for(size_t f=0;f<nFeatures;++f){
                mergedFeatures(label,f)+=weight*features(i,f);
            }
            // accumulate weights
            weightBuffer(i)+=weight;
        }
        // normalize

        for(size_t label=0;label<numberOfLabels;++label){
            const float weight=weights(label);
            for(size_t f=0;f<nFeatures;++f){
                mergedFeatures(label,f)/=weight;
            }
        }

    }

    float withinClusterDist(
        vigra::NumpyArray<1,LabelType>          labeling,
        const size_t                            numberOfLabels,
        vigra::NumpyArray<1,float>              weights,
        vigra::NumpyArray<2,float>              features,
        vigra::NumpyArray<2,float>              mergedFeatures
    ){
        CGP_ASSERT_OP(labeling.shape(0),==,features.shape(0));
        CGP_ASSERT_OP(labeling.shape(0),==,mergedFeatures.shape(0));
        CGP_ASSERT_OP(features.shape(1),==,mergedFeatures.shape(1));

        const size_t nItems = labeling.shape(0);
        const size_t nFeatures = features.shape(1);

        float totalD = 0.0;

        for(size_t i=0;i<nItems;++i){

            // get the label
            const size_t label = labeling(i);

            // compute the distance between the feature of the item (superpixel)
            // and the feature of the cluster (cluster of superpixel / "HyperRegion")
            vigra::MultiArrayView<1,float> a=features.bindInner(i);
            vigra::MultiArrayView<1,float> b=mergedFeatures.bindInner(label);
            const  float d = distances::Distance<float>::klDivergenz(a.begin(),a.end(),b.begin(),b.end());
            // get the weight of the item (superpixel size)
            const float weight=weights(i);

            totalD += weight*d;

            //weightBuffer(l)+=weight
        }
        return totalD;
    }

    float betweenClusterDist(
        const Cgp<CoordinateType,LabelType> &   cgp,
        vigra::NumpyArray<1,LabelType>          labeling,
        const size_t                            numberOfLabels,
        vigra::NumpyArray<2,float>              mergedFeatures
    ){

        float totalD=0.0f;

        std::set<size_t> used;
        const size_t nBoundaries = cgp.numCells(1);
        for(size_t b=0;b<nBoundaries;++b){
            const size_t r1 = cgp.bound<1>(b,0)-1;
            const size_t r2 = cgp.bound<1>(b,1)-1;

            size_t l1 =labeling(r1);
            size_t l2 =labeling(r2);

            // active boundarie ?
            if(l1!=l2){

                if(l2<l1){
                    std::swap(l1,l2);
                }
                const size_t key = l1+ l2*numberOfLabels;
                if(used.find(key)==used.end()){
                    used.insert(key);
                    vigra::MultiArrayView<1,float> a=mergedFeatures.bindInner(l1);
                    vigra::MultiArrayView<1,float> b=mergedFeatures.bindInner(l2);
                    const float d = distances::Distance<float>::klDivergenz(a.begin(),a.end(),b.begin(),b.end());
                    totalD+=d;
                }
            }
        }
        return totalD;
    }

    void export_merge(){

        python::def("_mergeFeatures",vigra::registerConverters(&mergeFeatures),
            (
                python::arg("labeling"),
                python::arg("numberOfLabels"),
                python::arg("weights"),
                python::arg("features"),
                python::arg("mergedFeatures"),
                python::arg("weightBuffer")
            )
        );

        python::def("_withinClusterDist",vigra::registerConverters(&withinClusterDist),
            (
                python::arg("labeling"),
                python::arg("numberOfLabels"),
                python::arg("weights"),
                python::arg("features"),
                python::arg("mergedFeatures")
            )
        );

        python::def("_betweenClusterDist",vigra::registerConverters(&betweenClusterDist),
            (
                python::arg("cgp"),
                python::arg("labeling"),
                python::arg("numberOfLabels"),
                python::arg("mergedFeatures")
            )
        );

    }

}

ext: cxx

max_stars_repo_name: DerThorsten/seglib

max_issues_repo_name: DerThorsten/seglib

max_forks_repo_name: DerThorsten/seglib


text:
//// Commented out since we *dont* use embedded python
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        :
// Author      : Avi
// Revision    : $Revision: #10 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <stdexcept>
//#include <boost/python.hpp>
//#include <boost/detail/lightweight_test.hpp>
//#include "boost/filesystem/operations.hpp"
//#include "boost/filesystem/path.hpp"
//#include <iostream>
//
//namespace fs     = boost::filesystem;
//namespace python = boost::python;
//
//// init_defs is defined in BOOST_PYTHON_MODULE(_defs) in file EcfDefsExt.cpp
//// However we need definition here. Hence expanded the pertinent contents of
//// BOOST_PYTHON_MODULE
//extern "C" __attribute__ ((visibility("default"))) void initecflow();
//
//void exec_test()
//{
//	std::cout << "registering extension module ecflow..." << std::endl;
//
//	// Register the module with the interpreter
//	if (PyImport_AppendInittab((char*)"_defs", initecflow) == -1)
//		throw std::runtime_error("Failed to add _defs to the interpreter's built in modules");
//
//	std::cout << "defining Defs..." << std::endl;
//
//	// Retrieve the main module
//	python::object main = python::import("__main__");
//
//	// Retrieve the main module's namespace
//	python::object global(main.attr("__dict__"));
//
//	// Define Defs in Python.
//	python::object result = python::exec(
//	                                     "from ecflow import *\n"
//	                                     "file = 'embedded.def'\n"
//	                                     "defs = Defs(file)\n"
//	                                     "suite = Suite('s1')\n"
//	                                     "family = Family('f1')\n"
//	                                     "for i in [ '_1', '_2', '_3' ]: family.add_task( Task( 't' + i) ) \n"
//	                                     "defs.add_suite(suite);  \n"
//	                                     "suite.add_family(family)\n"
//	                                     "defs.save_as_defs("embedded.def")\n",
// 	                                     global, global);
//
//	// Check it worked by looking for the presence of embedded.def file
// 	BOOST_TEST(fs::exists("embedded.def") );
// 	fs::remove("embedded.def");
//
//	std::cout << "success!" << std::endl;
//}
//
//int main(int argc, char **argv)
//{
//	// Initialize the interpreter
//	Py_Initialize();
//
//	if ( python::handle_exception(exec_test) )
//	{
//		if (PyErr_Occurred())
//		{
// 			PyErr_Print();
//		}
//		else
//		{
//			BOOST_ERROR("A C++ exception was thrown  for which "
//			            "there was no exception translator registered.");
//		}
//	}
//
//	// Boost.Python doesn't support Py_Finalize yet, so don't call it!
//	return boost::report_errors();
//}

max_stars_repo_name: ecmwf/ecflow

max_issues_repo_name: CoollRock/ecflow

max_forks_repo_name: CoollRock/ecflow


text:
// Copyright (c) 2013 The Claire Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <claire/common/logging/Logger.h>

#include <stdio.h>
#include <signal.h>

#include <boost/bind.hpp>

#include <claire/common/logging/LogFile.h>

namespace claire {

Logger::Logger()
    : running_(false),
      thread_(boost::bind(&Logger::ThreadMain, this), "Logger"),
      mutex_(),
      condition_(mutex_),
      latch_(1),
      current_buffer_(new Buffer),
      next_buffer_(new Buffer),
      buffers_()
{
    current_buffer_->bzero();
    next_buffer_->bzero();
    buffers_.reserve(16);
}

void Logger::Append(const char* data, size_t length)
{
    MutexLock lock(mutex_);
    if (current_buffer_->avail() > length)
    {
        current_buffer_->Append(data, length);
    }
    else
    {
        buffers_.push_back(current_buffer_.release());
        if (next_buffer_)
        {
            current_buffer_ = boost::ptr_container::move(next_buffer_);
        }
        else
        {
            current_buffer_.reset(new Buffer);
        }

        current_buffer_->Append(data, length);
        condition_.Notify();
    }
}

void Logger::ThreadMain()
{
    // first ignore unuse signals
    {
        sigset_t mask;
        sigemptyset(&mask);
        sigaddset(&mask, SIGHUP);
        sigaddset(&mask, SIGPIPE);
        sigaddset(&mask, SIGUSR1);
        sigaddset(&mask, SIGUSR2);
        sigprocmask(SIG_BLOCK, &mask, NULL);
    }

    assert(running_ = true);
    latch_.CountDown();

    LogFile output(false);

    BufferPtr buffer1(new Buffer);
    BufferPtr buffer2(new Buffer);

    buffer1->bzero();
    buffer2->bzero();

    decltype(buffers_) buffers_to_write;
    buffers_to_write.reserve(16);

    while (running_)
    {
        assert(buffer1 && buffer1->length() == 0);
        assert(buffer2 && buffer2->length() == 0);
        assert(buffers_to_write.empty());

        {
            MutexLock lock(mutex_);
            if (buffers_.empty())
            {
                condition_.WaitForSeconds(FLAGS_logbufsecs);
            }
            buffers_.push_back(current_buffer_.release());
            buffers_to_write.swap(buffers_);

            current_buffer_ = boost::ptr_container::move(buffer1);
            if (!next_buffer_)
            {
                next_buffer_ = boost::ptr_container::move(buffer2);
            }
        }

        assert(!buffers_to_write.empty());

        if (buffers_to_write.size() > 25)
        {
            char buf[256];
            snprintf(buf, sizeof buf, "Dropped log messages at %s, %zd larger buffers\n",
                     Timestamp::Now().ToFormattedString().c_str(),
                     buffers_to_write.size()-2);
            fputs(buf, stderr);
            output.Append(buf, static_cast<int>(strlen(buf)));
            buffers_to_write.erase(buffers_to_write.begin()+2, buffers_to_write.end());
            //FIXME: add over load callback?
        }

        for (size_t i = 0;i < buffers_to_write.size();i++)
        {
            // here, use writev can not make it fast!
            output.Append(buffers_to_write[i].data(), buffers_to_write[i].length());
        }

        if (buffers_to_write.size() > 2)
        {
            // drop non-bzero-ed buffers, avoid trashing
            buffers_to_write.resize(2);
        }

        if (!buffer1)
        {
            assert(!buffers_to_write.empty());
            buffer1 = buffers_to_write.pop_back();
            buffer1->Reset();
        }

        if (!buffer2)
        {
            assert(!buffers_to_write.empty());
            buffer2 = buffers_to_write.pop_back();
            buffer2->Reset();
        }

        buffers_to_write.clear();
        output.Flush();
    }

    output.Flush();
}

} // namespace claire

ext: cc

max_stars_repo_name: byzhang/claire-common

max_issues_repo_name: byzhang/claire-common

max_forks_repo_name: byzhang/claire-common


text:
// generate by pypp <https://github.com/mugwort-rc/pypp>
// original source code: SPK_StaticEmitter.h

#include <Extensions/Emitters/SPK_StaticEmitter.h>
#include <boost/python.hpp>

class StaticEmitterWrapper :
    public SPK::StaticEmitter,
    public boost::python::wrapper<SPK::StaticEmitter>
{
public:
    std::string getClassName () const {
        if ( auto getClassName = this->get_override("getClassName") ) {
            return getClassName();
        } else {
            return StaticEmitter::getClassName();
        }
    }
};

void init_SPK_StaticEmitter_h() {
    boost::python::class_<StaticEmitterWrapper, boost::python::bases<SPK::Emitter>, std::shared_ptr<SPK::StaticEmitter>>("StaticEmitter")
        .def("getClassName", &SPK::StaticEmitter::getClassName)
        .def("create", &SPK::StaticEmitter::create,
			":brief: Creates and registers a new StaticEmitter\n"
			":return: A new registered StaticEmitter\n",
			boost::python::return_value_policy<boost::python::reference_existing_object>())
        .staticmethod("create")
        ;
}

max_stars_repo_name: chromia/pyspk

max_issues_repo_name: chromia/pyspk

max_forks_repo_name: chromia/pyspk


text:
#pragma once
#include <iostream>
#include <string>

#include "ros/ros.h"

#include <image_geometry/pinhole_camera_model.h>
#include <image_transport/image_transport.h>

#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/circular_buffer.hpp>

#include <std_srvs/SetBool.h>

#include "sub8_msgs/BMatrix.h"
#include "sub8_msgs/VisionRequest2D.h"

using namespace boost::accumulators;

class Sub8StartGateDetector
{
public:
  Sub8StartGateDetector();
  ~Sub8StartGateDetector();

  // 76 inches x 39.5 inches
  // 1.9304 x 1.0033
  const double START_GATE_WIDTH = 1.9304;  // Meters
  const double START_GATE_HEIGHT = 1.0033;
  const double START_GATE_SIZE_TOLERANCE = 10000;

  void imageCallback(const sensor_msgs::ImageConstPtr &msg, const sensor_msgs::CameraInfoConstPtr &info_msg);
  bool requestStartGatePosition2d(sub8_msgs::VisionRequest2D::Request &req, sub8_msgs::VisionRequest2D::Response &resp);
  bool requestStartGateEnable(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
  bool requestStartGateDistance(sub8_msgs::BMatrix::Request &req, sub8_msgs::BMatrix::Response &resp);
  void findGate(const sensor_msgs::ImageConstPtr &image_msg);

  double getGateDistance();

  ros::NodeHandle nh_;
  bool running_;

  image_transport::ImageTransport image_transport_;
  image_transport::CameraSubscriber image_sub_;

  image_geometry::PinholeCameraModel cam_model_;
  ros::Time image_time_;

  int rows_;
  int cols_;

  boost::circular_buffer<std::vector<std::vector<cv::Point2f>>> gate_line_buffer_;
  accumulator_set<int, features<tag::mean, tag::variance>> accX_;
  accumulator_set<int, features<tag::mean, tag::variance>> accY_;
  accumulator_set<int, features<tag::mean, tag::variance>> accSizeX_;
  accumulator_set<int, features<tag::mean, tag::variance>> accSizeY_;

  ros::ServiceServer service_enable_;
  ros::ServiceServer service_2d_;
  ros::ServiceServer service_distance_;

  image_transport::Publisher pubImage_;
};

max_stars_repo_name: DSsoto/SubjuGator

max_issues_repo_name: DSsoto/SubjuGator

max_forks_repo_name: DSsoto/SubjuGator


text:
#pragma once

#include <memory>
#include <apptronik_system/system.hpp>
#include <HipInterface/HipInterface.hpp>
#include <apptronik_srvs/UInt16.h>
#include <Eigen/Dense>

/**  A clean and empty example Nodelet Controller for you to copy and customize. */
namespace hip_nodelet
{
  using namespace apptronik_system;

  /**  An empty Nodelet controller that does nothing. */
  class HipNodelet: public nodelet::Nodelet
  {
  public:
    boost::shared_ptr<SystemLoop> m_sys;
    boost::shared_ptr<boost::thread> m_system_thread;

    // States
    unsigned int m_fault_status;
    Eigen::VectorXd jPos;
    Eigen::VectorXd jVel;
    Eigen::VectorXd jTrq;

    std::vector<double*> jPosList;
    std::vector<double*> jVelList;
    std::vector<double*> jTrqList;

    // Commands
    Eigen::VectorXd jTrqCmd;
    Eigen::VectorXd jPosCmd;
    Eigen::VectorXd jVelCmd;

    std::vector<double*> jPosCmdList;
    std::vector<double*> jVelCmdList;
    std::vector<double*> jTrqCmdList;

    int numJoint;
    std::map<std::string, int> jNameIdxMap;
    std::vector<std::string> slaveNames;
    std::string medullaName;
    std::shared_ptr<HipInterface> Interface;
    std::shared_ptr<HipSensorData> SensorData;
    std::shared_ptr<HipCommand> CommandData;

    HipNodelet();
    ~HipNodelet();
    void onInit();
    void systemThread();
    void loop(const double& time, const dBitset& fault_bitmap );
    void _CallFloat32Service(const ros::NodeHandle & nh,
                             const std::string & slave_name,
                             const std::string & parameter_name,
                             const std::string & service_name);

    void _CallInt16Service(const ros::NodeHandle & nh,
                           const std::string & slave_name,
                           const std::string & parameter_name,
                           const std::string & service_name);
    void _CopyData();
    void _CopyCommand();
    void _ClearFaults(std::vector<std::string> slave_names);
  };
}

max_stars_repo_name: junhyeokahn/DracoNodelet

max_issues_repo_name: junhyeokahn/DracoNodelet

max_forks_repo_name: junhyeokahn/DracoNodelet