text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cmath>
#include <boost/algorithm/string.hpp>

//<deque>, <list>, <map>, <set>, <queue>, <stack>, <vector>
//<vector>: .size(), .push_back(), .pop_back()
//int a[7] vs int* p = new int[7]

using namespace std;

vector<double> convertStringVectortoDoubleVector(const vector<string>& stringVector) {
	vector<double> doubleVector(stringVector.size());
	transform(stringVector.begin(), stringVector.end(), doubleVector.begin(), [](const string& val)
		{
			return stod(val);
		});
	return doubleVector;
}

string double_array_to_string(double double_array[], int size_of_array) {
	string s = "";
	for (int i = 0; i < size_of_array; i++) {
		string temp;
		ostringstream convert;
		convert << double_array[i];
		s += convert.str() + ", ";
	}
	s.erase(s.end()-2, s.end());
	return s;
}

void print_double_vector(vector<double>& v) {
	copy(v.begin(), v.end(), std::ostream_iterator<double>(cout, " "));
	cout << "" << endl;
}

void print_int_vector(vector<int>& v) {
	copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, " "));
	cout << "" << endl;
}

void print_array (int arg[], int length) {
	for (int n=0; n<length; ++n)
		cout << arg[n] << ' ';
	cout << '\n';
}

void print_array (double arg[], int length) {
	for (int n=0; n<length; ++n)
		cout << arg[n] << ' ';
	cout << '\n';
}

//Ignore threshold_adjust and pair_check for now
string query_distance(const char* libfile, const char* values, int threshold_adjust_counts=100, float threshold=0.4) {

	bool threshold_adjust = threshold_adjust_counts == -1 ? false:true;

	//Splitting template distance values into vector
	string dist_str(values);
	vector<string> dist_split_str;
	boost::split(dist_split_str, dist_str, boost::algorithm::is_any_of(","));
	vector<double> dists = convertStringVectortoDoubleVector(dist_split_str);

	int num_dists = dists.size();

	//RMSD values and AA identities for every IP in library file
	vector<int> aas;
	vector<double> rmsds;

	//Keep track of lowest 100 RMSDs
	vector<double> thresholds;

	string line;
	ifstream infile;
	infile.open(libfile);
	while (!infile.eof()) {
		getline(infile, line);
		vector<std::string> split1;
		boost::split(split1, line, boost::algorithm::is_any_of(";"));
		if (split1.size() > 1) {
			string lib_dists_str(split1.at(0));
			vector<std::string> split2;
			boost::split(split2, lib_dists_str, boost::algorithm::is_any_of(","));
			vector<double> lib_dists = convertStringVectortoDoubleVector(split2);

			float rmsd = 0;
			for (int i = 0; i < num_dists; i++) {
				rmsd += (lib_dists.at(i) - dists.at(i)) * (lib_dists.at(i) - dists.at(i));
			}
			rmsd = sqrt(rmsd/(num_dists-1));
			rmsds.push_back(rmsd);

			if (threshold_adjust) {
				if (thresholds.size() < threshold_adjust_counts) {
					thresholds.push_back(rmsd);
					push_heap(thresholds.begin(), thresholds.end());

				} else if (rmsd < thresholds.front()) {
					pop_heap (thresholds.begin(), thresholds.end());
					thresholds.pop_back();

					thresholds.push_back(rmsd);
					push_heap(thresholds.begin(), thresholds.end());
				}
			}

			int aa = stoi(split1.at(1));
			aas.push_back(aa);
		}
		cout << "\n";
	}

	const float ip_probs[20] = {0.064, 0.018, 0.038, 0.043, 0.065, 0.052, 0.025, 0.084, 0.04, 0.127, 0.024, 0.033, 0.038, 0.029, 0.052, 0.044, 0.05, 0.095, 0.025, 0.055};
	infile.close();

	threshold = threshold_adjust ? thresholds.front(): threshold;
	cout << "Using threshold " << threshold << endl;

	int match_counts[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	double match_probs[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

	//Tally up matches within RMSD threshold
	for (unsigned int i = 0; i < aas.size(); i++)
		if (rmsds[i] < threshold) match_counts[aas[i]] += 1;

	int match_total = 0;
	for (int i = 0; i < 20; i++) {
		if (match_counts[i] == 0) match_counts[i] += 1;
		match_total += match_counts[i];
	}

	for (int i = 0; i < 20; i++)
		match_probs[i] = match_counts[i]/match_total;

	double energies[20];
	for (int i = 0; i < 20; i++) {
		if (abs(match_probs[i] - ip_probs[i]) < 0.0001 || match_probs[i] == 0.0) {
			energies[i] = 0.0;
		} else {
			energies[i] = -1.0*log10(match_probs[i] / ip_probs[i]);
		}
	}

	return double_array_to_string(energies, 20);
}

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(statium_cpp)
{
	def("query_distance", query_distance);
}

max_stars_repo_name: skoppula/statium

max_issues_repo_name: hardhary/statium

max_forks_repo_name: hardhary/statium


text:
/*
 [auto_generated]
 libs/numeric/odeint/test/prepare_stepper_testing.hpp

 [begin_description]
 This file defines some helper functions for the stepper tests.
 [end_description]

 Copyright 2009-2012 Karsten Ahnert
 Copyright 2009-2012 Mario Mulansky

 Distributed under the Boost Software License, Version 1.0.
 (See accompanying file LICENSE_1_0.txt or
 copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef PREPARE_STEPPER_TESTING_HPP_
#define PREPARE_STEPPER_TESTING_HPP_

#include <boost/array.hpp>
#include <vector>
#include <boost/fusion/sequence.hpp>

#include <boost/mpl/vector.hpp>

#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>
#include <boost/numeric/odeint/algebra/array_algebra.hpp>

#include "vector_space_1d.hpp"

namespace mpl = boost::mpl;
namespace fusion = boost::fusion;

using namespace boost::numeric::odeint;

/* the state types that will be tested */
typedef std::vector< double > vector_type;
typedef vector_space_1d< double > vector_space_type;
typedef boost::array< double , 1 > array_type;

typedef mpl::vector< vector_type , vector_space_type , array_type >::type container_types;

/* choose the right algebra */
template< class State > struct algebra_dispatcher { typedef range_algebra type; };
template<> struct algebra_dispatcher< array_type > { typedef array_algebra type; };
template<> struct algebra_dispatcher< vector_space_type > { typedef vector_space_algebra type; };
template<> struct algebra_dispatcher< double > { typedef vector_space_algebra type; };

/*
typedef mpl::vector
<
    mpl::vector< float , boost::array< float , 1 > , boost::array< float , 1 > , constant_system_standard , stepper_type > ,
    mpl::vector< float , boost::array< float , 1 > , std::vector< float > , constant_system_standard , stepper_type >
    > types_and_systems_matrix;

struct check_stepper
{
    template< class Vector >
    void operator()( Vector )
    {
        typedef typename mpl::at_c< Vector , 0 >::type value_type;
        typedef typename mpl::at_c< Vector , 1 >::type deriv_type;
        typedef typename mpl::at_c< Vector , 2 >::type state_type;
        typedef typename mpl::at_c< Vector , 3 >::type system_type;
    }
};
*/

#endif /* PREPARE_STEPPER_TESTING_HPP_ */

ext: hpp

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#include "glog/logging.h"
#include "python_support.h"
#include <boost/python.hpp>

using namespace boost::python;
using namespace google::protobuf;
using namespace std;

DEFINE_double(crawler_runtime, -1, "Amount of time to run, in seconds.");
DEFINE_bool(crawler_triggers, false, "Use trigger-based crawler (t/f).");

namespace piccolo {

Kernel* kernel() { return the_kernel; }

double crawler_runtime() {
  return FLAGS_crawler_runtime;
}

bool crawler_triggers() {
  return FLAGS_crawler_triggers;
}

int PythonSharder::operator()(const string& k, int shards) {
  PyObjectPtr result = PyEval_CallFunction(c_, "(si)", k.c_str(), shards);
  if (PyErr_Occurred()) {
    PyErr_Print();
    exit(1);
  }

  long r = PyInt_AsLong(result);
//  Py_DecRef(result);
  return r;
}

void PythonAccumulate::Accumulate(PyObjectPtr* a, const PyObjectPtr& b) {
  PyObjectPtr result = PyEval_CallFunction(c_, "OO", *a, b);
  if (PyErr_Occurred()) {
    PyErr_Print();
    exit(1);
  }

  *a = result;
}

template<class K, class V>
PythonTrigger<K, V>::PythonTrigger(ShardedTable* thistable, const string& codeshort, const string& codelong) {
  Init(thistable);
  params_.put("python_code_short", codeshort);
  params_.put("python_code_long", codelong);
  //trigid = thistable->register_trigger(this);
}

template<class K, class V>
void PythonTrigger<K, V>::Init(ShardedTable* thistable) {
  try {
    object sys_module = import("sys");
    object sys_ns = sys_module.attr("__dict__");
    crawl_module_ = import("crawler");
    crawl_ns_ = crawl_module_.attr("__dict__");
  } catch (error_already_set& e) {
    PyErr_Print();
    exit(1);
  }
}

template<class K, class V>
bool PythonTrigger<K, V>::LongFire(const K k, bool lastrun) {
  string python_code = params_.get<string> ("python_code_long");
  PyObject *key, *callable;
  callable = PyObject_GetAttrString(crawl_module_.ptr(), python_code.c_str());
  key = PyString_FromString(k.c_str());

  // Make sure all the callfunctionobjarg arguments are fine
  if (key == NULL || callable == NULL) {
    LOG(ERROR) << "Failed to launch trigger " << python_code << "!";
    if (key == NULL) LOG(ERROR) << "[FAIL] key was null";
    if (callable == NULL) LOG(ERROR) << "[FAIL] callable was null";
    return true;
  }

  Py_INCREF(callable);
  Py_INCREF(key);

  V dummyv;
  bool rv = PythonTrigger<K, V>::CallPythonTrigger(callable, key, &dummyv, dummyv, true, lastrun); //hijack "isNew" for "lastrun"

  Py_DECREF(key);
  Py_DECREF(callable);

  //LOG(INFO) << "returning " << (rv?"TRUE":"FALSE") << " from trigger";
  return rv;
}

template<class K, class V>
bool PythonTrigger<K, V>::ProcessPyRetval(PyObjectPtr retval) {
  if (NULL == retval) {
    PyErr_Print();
    LOG(FATAL) << "Attempting to flush and die because Trigger/Accumulator returned non-bool/non-int.";
  }
  if (!PyBool_Check(retval) && !PyInt_Check(retval)) {
    PyErr_SetString(PyExc_RuntimeError,"Trigger returned neither bool nor int!");
    PyErr_Print();
    LOG(FATAL) << "Python trigger returned invalid value";
  }
  return (retval == Py_True)?true:((retval == Py_False)?false:(bool)PyInt_AsLong(retval));
}

template<class K, class V>
bool PythonTrigger<K, V>::Accumulate(V* value, const V& newvalue) {
  string python_code = params_.get<string> ("python_code_short");
  PyObject *callable;
  callable = PyObject_GetAttrString(crawl_module_.ptr(), python_code.c_str());

  // Make sure all the callfunctionobjarg arguments are fine
  if (callable == NULL) {
    LOG(ERROR) << "Failed to launch trigger " << python_code << "!";
    LOG(ERROR) << "[FAIL] callable was null";
    return false;
  }

  Py_INCREF(callable);

  bool rv = PythonTrigger<K, V>::CallPythonTrigger(callable, NULL, value, newvalue, false, false);

  Py_DECREF(callable);

  //LOG(INFO) << "returning " << (rv?"TRUE":"FALSE") << " from trigger-connected accumulator";
  return rv;
}

template<class K, class V>
bool PythonTrigger<K, V>::CallPythonTrigger(PyObjectPtr callable, PyObjectPtr key, V* value, const V& newvalue, bool isTrigger, bool isNewOrLast) {
  LOG(FATAL) << "No such CallPythonTrigger for this key/value pair type!";
  exit(1);
}

template<>
bool PythonTrigger<string, int64_t>::CallPythonTrigger(PyObjectPtr callable, PyObjectPtr key, int64_t* value, const int64_t& update, bool isTrigger, bool isLast) {
  PyObjectPtr retval;
  PyGILState_STATE gstate;

  //LOG(ERROR) << "Handling Python trigger call type " << isTrigger << " on string:int64_t table";
  //Handle LongTriggers
  if (isTrigger) {
    PyObject* lastrun_obj = PyBool_FromLong((long)isLast);
    if (lastrun_obj == NULL) {
      LOG(ERROR) << "Failed to bootstrap <int,int> trigger (trigger) launch";
      return true;
    }
    try {

      gstate = PyGILState_Ensure();
      retval = PyObject_CallFunctionObjArgs(callable, key, lastrun_obj, NULL);

    } catch (error_already_set& e) {
      PyErr_Print();
      PyGILState_Release(gstate);
      LOG(FATAL) << "Fatal Python error aborted Oolong";
    }
    if (PyErr_Occurred()) {
      PyErr_Print();
      LOG(FATAL) << "Fatal Python error aborted Oolong";
    }
    PyGILState_Release(gstate);
    return ProcessPyRetval(retval);
  }

  PyObject* cur_obj = PyLong_FromLongLong(*value);
  PyObject* upd_obj = PyLong_FromLongLong(update);

  if (cur_obj == NULL || upd_obj == NULL) {
    LOG(ERROR) << "Failed to bootstrap <int,int> trigger (accumulator) launch";
    return true;
  }
  try {

    gstate = PyGILState_Ensure();
    retval = PyEval_CallFunction(
               callable, "OO", cur_obj, upd_obj);

  } catch (error_already_set& e) {
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Fatal Python error aborted Oolong";
  }
  if (PyErr_Occurred()) {
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Fatal Python error aborted Oolong";
  }

  if (retval == NULL || !PyTuple_Check(retval) || 2 != PyTuple_GET_SIZE(retval)) {
    PyErr_SetString(PyExc_RuntimeError,"Accum/Trigger must return 2-item tuple");
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Python accum/trigger returned invalid value";
  }

  *value = PyLong_AsLongLong(PyTuple_GetItem(retval,0));

  PyGILState_Release(gstate);
  return ProcessPyRetval(PyTuple_GetItem(retval,1));
}

template<>
bool PythonTrigger<string, string>::CallPythonTrigger(PyObjectPtr callable, PyObjectPtr key, string* value, const string& update, bool isTrigger, bool isLast) {
  PyObjectPtr retval;
  PyGILState_STATE gstate;

  //LOG(ERROR) << "Handling Python trigger call type " << isTrigger << " on string:string table";
  //Handle LongTriggers
  if (isTrigger) {
    PyObject* lastrun_obj = PyBool_FromLong((long)isLast);
    if (lastrun_obj == NULL) {
      LOG(ERROR) << "Failed to bootstrap <int,int> trigger (trigger) launch";
      return true;
    }
    try {

      gstate = PyGILState_Ensure();
      retval = PyObject_CallFunctionObjArgs(callable, key, lastrun_obj, NULL);

    } catch (error_already_set& e) {
      PyErr_Print();
      PyGILState_Release(gstate);
      LOG(FATAL) << "Fatal Python error aborted Oolong";
    }
    if (PyErr_Occurred()) {
      PyErr_Print();
      PyGILState_Release(gstate);
      LOG(FATAL) << "Fatal Python error aborted Oolong";
    }

    PyGILState_Release(gstate);
    return ProcessPyRetval(retval);
  }

  PyObject* cur_obj = PyString_FromStringAndSize(value->c_str(),value->length());
  PyObject* upd_obj = PyString_FromStringAndSize(update.c_str(),update.length());

  if (cur_obj == NULL || upd_obj == NULL) {
    LOG(ERROR) << "Failed to bootstrap <string,string> trigger (accumulator) launch";
    return true;
  }
  try {

    gstate = PyGILState_Ensure();
    retval = PyObject_CallFunctionObjArgs(
               callable, cur_obj, upd_obj, NULL);

  } catch (error_already_set& e) {
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Fatal Python error aborted Oolong";
  }

  if (PyErr_Occurred()) {
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Fatal Python error aborted Oolong";
  }

  if (retval == NULL || !PyTuple_Check(retval) || 2 != PyTuple_GET_SIZE(retval)) {
    PyErr_SetString(PyExc_RuntimeError,"Accum/Trigger must return 2-item tuple");
    PyErr_Print();
    PyGILState_Release(gstate);
    LOG(FATAL) << "Python accum/trigger returned invalid value";
  }

  *value = PyString_AsString(PyTuple_GetItem(retval,0));

  PyGILState_Release(gstate);
  return ProcessPyRetval(PyTuple_GetItem(retval,1));
}

class PythonKernel: public Kernel {
public:
  bool is_swapaccum(void) { return false; }
  virtual ~PythonKernel() {}
  PythonKernel() {
    try {
      object sys_module = import("sys");
      object sys_ns = sys_module.attr("__dict__");
      exec("path += ['src/examples/crawler']", sys_ns, sys_ns);
      exec("path += ['bin/release/examples/']", sys_ns, sys_ns);
      exec("path += ['bin/debug/examples/']", sys_ns, sys_ns);

      crawl_module_ = import("crawler");
      crawl_ns_ = crawl_module_.attr("__dict__");
    } catch (error_already_set e) {
      PyErr_Print();
      exit(1);
    }
  }

  void run_python_code() {
    if (!PyEval_ThreadsInitialized()) {
      PyEval_InitThreads();
      PyEval_ReleaseLock(); //cf. SO question 5140998 answer #1
      LOG(INFO) << "Initializing Python C threading safety support";
    } else {
      LOG(INFO) << "Python C threading safety support already initialized";
    }

    the_kernel = this;
    string python_code = get_arg<string> ("python_code");
    LOG(INFO) << "Executing python code: " << python_code;
    try {
      exec(StringPrintf("%s\n", python_code.c_str()).c_str(), crawl_ns_, crawl_ns_);
    } catch (error_already_set e) {
      PyErr_Print();
      exit(1);
    }
  }

  void swap_python_accumulator() {
    LOG(FATAL) << "Swapping accumulators in Python not yet implemented.";
//    the_kernel = this;
//    string python_code = get_arg<string> ("python_accumulator");
//    LOG(INFO) << "Swapping python accumulator: " << python_code;
//    try {
//    } catch (error_already_set e) {
//      PyErr_Print();
//      exit(1);
//    }
  }

private:
  object crawl_module_;
  object crawl_ns_;
};
REGISTER_KERNEL(PythonKernel)
;
REGISTER_METHOD(PythonKernel, run_python_code)
;
REGISTER_METHOD(PythonKernel, swap_python_accumulator)
;

template class PythonTrigger<string, string>;
template class PythonTrigger<string, int64_t>;

} //End namespace piccolo

ext: cc

max_stars_repo_name: ShufengGong/piccolo

max_issues_repo_name: ShufengGong/piccolo

max_forks_repo_name: ShufengGong/piccolo


text:
#include <iostream>
#include <utility>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/graph_utility.hpp>

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

using namespace boost;
namespace py = boost::python;
namespace np = boost::python::numpy;

typedef adjacency_list<vecS, vecS, undirectedS> Graph;
typedef property_map<Graph, vertex_index_t>::type IndexMap;
typedef graph_traits<Graph>::vertex_iterator VertexIter;
typedef std::vector<int> IntVec;
typedef std::map<IntVec, int> VecIntMap;

enum class RemovalStrategy { random, targeted};

void print_vector(IntVec& vec_to_print) {
    for (IntVec::iterator it=vec_to_print.begin(); it!=vec_to_print.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << std::endl;
}

void populate_index_labels(Graph& g, IntVec& index_labels) {
    for (auto v : boost::make_iterator_range(vertices(g))) {
       index_labels[v] = v;
    }
}

void generate_random_sequence(Graph& g, IntVec& removal_sequence, int N) {
    populate_index_labels(g, removal_sequence);
    std::random_shuffle (removal_sequence.begin(), removal_sequence.end());
}

void generate_targeted_sequence(Graph& g, const IntVec& node_degrees, IntVec& removal_sequence, int N) {
    populate_index_labels(g, removal_sequence);

    IntVec random_sequence(N);
    generate_random_sequence(g, random_sequence, N);

    std::sort(
        removal_sequence.begin(),
        removal_sequence.end(),
        [node_degrees, random_sequence](int a, int b) {
            return (node_degrees[a] > node_degrees[b]) || (node_degrees[a] == node_degrees[b] && random_sequence[a] > random_sequence[b]);
        }
    );
}

void generate_removal_sequence(RemovalStrategy strat, Graph& g, const IntVec& node_degrees, IntVec& removal_sequence, int N) {
    switch(strat) {
        case RemovalStrategy::random: return generate_random_sequence(g,removal_sequence, N);
        case RemovalStrategy::targeted: return generate_targeted_sequence(g, node_degrees, removal_sequence, N);
    }
}

bool should_cache_ncc(RemovalStrategy strat) {
    switch(strat) {
        case RemovalStrategy::random: return false;
        case RemovalStrategy::targeted: return true;
    }
}

double compute_critical_fraction(RemovalStrategy strat, Graph& g, const IntVec& node_degrees, VecIntMap& ncc_cache, int N, unsigned base_graph_hash, int sim_num, int random_seed) {
    int crit_removed = 0;
    std::srand (unsigned ( (base_graph_hash * sim_num * random_seed) ) );
    IntVec component(N);
    IntVec removal_sequence(N);
    generate_removal_sequence(strat, g, node_degrees, removal_sequence, N);

    for(int i=0; i<N-1; ++i) {
        int node_to_remove = removal_sequence[i];

        clear_vertex(node_to_remove, g);
        int nodes_removed = i+1;

        int num = -1;
        if(should_cache_ncc(strat)) {
            IntVec seq_so_far = IntVec(removal_sequence.begin(), removal_sequence.begin() + i + 1);

            auto search = ncc_cache.find(seq_so_far);
            if (search != ncc_cache.end()) {
                num = search->second;
            } else {
                num = connected_components(g, &component[0]) - nodes_removed;
                ncc_cache.insert(std::make_pair(seq_so_far, num));
            }
        }
        else {
            num = connected_components(g, &component[0]) - nodes_removed;
        }

        if (num > 1) {
            crit_removed = nodes_removed;
            break;
        }
        if (i == N-2) {
            crit_removed = N;
            break;
        }
    }

    double p = ((double) crit_removed) / ((double) N);
    return p;
}

double exp_critical_fraction(RemovalStrategy strat, int N, int M, np::ndarray const& edge_list, int num_sims, unsigned base_graph_hash, int random_seed) {
    int* input_ptr = reinterpret_cast<int*>(edge_list.get_data());

    Graph g;
    int first_node, second_node;
    int input_size = M * 2;

    for (int i = 0; i < input_size-1; i+=2) {
        first_node = *(input_ptr + i);
        second_node = *(input_ptr + i + 1);
        add_edge(first_node, second_node, g);
    }

    IntVec node_degrees(N);
    for (auto v : boost::make_iterator_range(vertices(g))) {
        node_degrees[v] = out_degree(v, g);
    }

    double cf_sum = 0;

    VecIntMap ncc_cache;
    for (int sim_num = 0; sim_num < num_sims; ++sim_num) {
        Graph g_copy;
        copy_graph(g, g_copy);
        double cf = compute_critical_fraction(strat, g_copy, node_degrees, ncc_cache, N, base_graph_hash, sim_num, random_seed);
        cf_sum += cf;
    }

    double exp_cf = cf_sum / ((double) num_sims);
    return exp_cf;
}

double critical_fraction_random(int N, int M, np::ndarray const& edge_list, int num_sims, unsigned base_graph_hash, int random_seed)
{
    return exp_critical_fraction(RemovalStrategy::random, N, M, edge_list, num_sims, base_graph_hash, random_seed);
}

double critical_fraction_targeted(int N, int M, np::ndarray const& edge_list, int num_sims, unsigned base_graph_hash, int random_seed)
{
    return exp_critical_fraction(RemovalStrategy::targeted, N, M, edge_list, num_sims, base_graph_hash, random_seed);
}

BOOST_PYTHON_MODULE(objective_functions_ext)
{
    Py_Initialize();
    np::initialize();

    def("critical_fraction_random", critical_fraction_random);
    def("critical_fraction_targeted", critical_fraction_targeted);
}

ext: cpp

max_stars_repo_name: VictorDarvariu/graph-construction-rl

max_issues_repo_name: VictorDarvariu/graph-construction-rl

max_forks_repo_name: VictorDarvariu/graph-construction-rl


text:
#include <CGAL/Surface_mesh_segmentation/internal/Expectation_maximization.h>

#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
/**
 * Generates sample points using a few gauissians.
 * Then applies gmm fitting on these generated points.
 * Provides a heuristic score for each gmm fitting result.
 *
 */
int main(void)
{
    boost::mt19937 engine;
    engine.seed(1340818006);

    // generate random data using gauissians below
    std::vector< boost::normal_distribution<double> > distributions;
    distributions.push_back(boost::normal_distribution<double>(0.1, 0.05));
    distributions.push_back(boost::normal_distribution<double>(0.4, 0.1));
    distributions.push_back(boost::normal_distribution<double>(0.55, 0.05));
    distributions.push_back(boost::normal_distribution<double>(0.7, 0.1));
    distributions.push_back(boost::normal_distribution<double>(0.9, 0.05));
    distributions.push_back(boost::normal_distribution<double>(1.0, 0.05));

    std::vector<double> data;
    for(std::vector< boost::normal_distribution<double> >::iterator it = distributions.begin();
      it != distributions.end(); ++it)
    {
        boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > var_nor(engine, *it);

        for(std::size_t i = 0; i < 300; ++i) { data.push_back(var_nor()); }
    }

    // calculate closest center (using above gauissians) for each generated points
    // we will compare it with gmm fitting results
    // also we might want to compute mixing coef for each center and select centers according to mixing_coef * prob(data)
    std::vector<std::size_t> data_centers;
    for(std::vector<double>::iterator it = data.begin(); it != data.end(); ++it)
    {
        std::size_t center_id = (std::numeric_limits<std::size_t>::max)(), center_counter = 0;;
        double min_distance = (std::numeric_limits<double>::max)();
        for(std::vector< boost::normal_distribution<double> >::iterator dis_it = distributions.begin();
          dis_it != distributions.end(); ++dis_it, ++center_counter)
        {
            double distance = std::abs(*it - dis_it->mean());
            if(min_distance > distance)
            {
                min_distance = distance;
                center_id = center_counter;
            }
        }
        data_centers.push_back(center_id);
    }

    // apply gmm fitting clustering
    typedef CGAL::internal::Expectation_maximization E_M;
    std::vector<E_M> gmm_fitters;
    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::PLUS_INITIALIZATION));
    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::RANDOM_INITIALIZATION));
    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::K_MEANS_INITIALIZATION));

    std::vector< std::vector<std::size_t> > calculated_centers(gmm_fitters.size());
    std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();
    for(std::vector<E_M>::iterator it = gmm_fitters.begin(); it != gmm_fitters.end(); ++it, ++calc_centers_it)
    {
        it->fill_with_center_ids(*calc_centers_it);
    }

    std::cout << "Compare results of EM with 'expected' (but be aware, it is not optimal result in terms of likelihood)" << std::endl;
    std::cout << "Another words a clustering which has higher likelihood can result in worse score in here" << std::endl;
    for(std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();
        calc_centers_it != calculated_centers.end(); ++calc_centers_it)
    {
        std::size_t true_count = 0;
        std::vector<std::size_t>::iterator calculated_it = calc_centers_it->begin();
        for(std::vector<std::size_t>::iterator it = data_centers.begin(); it != data_centers.end(); ++it, ++calculated_it)
        {
            if( (*it) == (*calculated_it) ) { ++true_count; }
        }
        double app_fit = static_cast<double>(true_count) / data_centers.size();
        std::cout << "[0,1]: " << app_fit << std::endl;
        if(app_fit < 0.7) {
            std::cerr << "There might be a problem if above printed comparison is too low." << std::endl;
            return EXIT_FAILURE;
        }
    }
}

max_stars_repo_name: ffteja/cgal

max_issues_repo_name: ffteja/cgal

max_forks_repo_name: ffteja/cgal


text:
/*
 * RTQL8, Copyright (c) 2011, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author(s): Sumit Jain <sumit@cc.gatech.edu>, Yuting Ye <yuting.ye@gmail.com>
 *
 * Geoorgia Tech Graphics Lab
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "GLFuncs.h"
#include "utils/LoadOpengl.h"
#include <string>
#include <iostream>
#include <Eigen/Eigen>
#include <cstdio>

using namespace std;
using namespace Eigen;

namespace yui{

    void drawStringOnScreen(float x, float y, const std::string& s)
    { // draws text on the screen
        GLint oldMode;
        glGetIntegerv(GL_MATRIX_MODE, &oldMode);
        glMatrixMode( GL_PROJECTION );

        glPushMatrix();
        glLoadIdentity();
        gluOrtho2D( 0.0, 1.0, 0.0, 1.0 );

        glMatrixMode( GL_MODELVIEW );
        glPushMatrix();
        glLoadIdentity();
        glRasterPos2f(x, y);
        unsigned int length = s.length();
        for (unsigned int c=0; c < length; c++)
            glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, s.at(c) );
        glPopMatrix();

        glMatrixMode( GL_PROJECTION );
        glPopMatrix();
        glMatrixMode(oldMode);
    }

    // draw a 3D arrow starting from pt along dir, the arrowhead is on the other end
    void drawArrow3D(const Vector3d& pt, const Vector3d& dir, const double length, const double thickness, const double arrowThickness){
        Vector3d normDir = dir;
        normDir.normalize();

        double arrowLength;
        if(arrowThickness == -1)
            arrowLength = 4*thickness;
        else arrowLength = 2*arrowThickness;

        // draw the arrow body as a cylinder
        GLUquadricObj *c;
        c = gluNewQuadric();
        gluQuadricDrawStyle(c, GLU_FILL);
        gluQuadricNormals(c, GLU_SMOOTH);

        glPushMatrix();
        glTranslatef(pt[0], pt[1], pt[2]);
        glRotated(acos(normDir[2])*180/M_PI, -normDir[1], normDir[0], 0);
        gluCylinder(c, thickness, thickness, length-arrowLength, 16, 16);

        // draw the arrowhed as a cone
        glPushMatrix();
        glTranslatef(0, 0, length-arrowLength);
        gluCylinder(c, arrowLength*0.5, 0.0, arrowLength, 10, 10);
        glPopMatrix();

        glPopMatrix();

        gluDeleteQuadric(c);
    }

    // draw a 2D arrow starting from pt along vec, the arrow head is on the other end
    void drawArrow2D(const Vector2d& pt, const Vector2d& vec, double thickness)
    {
        // draw the arrow body as a thick line
        glLineWidth(thickness);
        glBegin(GL_LINES);
        glVertex2f(pt[0],pt[1]);
        glVertex2f(pt[0]+vec[0],pt[1]+vec[1]);
        glEnd();

        // draw arrowhead as a triangle
        double theta = atan2(vec[1],vec[0]);
        glPushMatrix();
        glTranslatef(pt[0]+vec[0],pt[1]+vec[1],0.0);
        glRotatef(theta*180.0/M_PI,0.0,0.0,1.0);
        glTranslatef(thickness,0.0,0.0);
        glBegin(GL_TRIANGLES);
        glVertex2f(0.0,thickness);
        glVertex2f(2*thickness,0.0);
        glVertex2f(0.0,-thickness);
        glEnd();
        glPopMatrix();
    }

    void drawProgressBar(int currFrame, int totalFrame)
    {
        GLint oldMode;
        glGetIntegerv(GL_MATRIX_MODE, &oldMode);
        glMatrixMode( GL_PROJECTION );

        glPushMatrix();
        glLoadIdentity();
        gluOrtho2D( 0.0, 1.0, 0.0, 1.0 );

        glMatrixMode( GL_MODELVIEW );
        glPushMatrix();
        glLoadIdentity();

        glPolygonMode(GL_FRONT, GL_LINE);
        glColor4d(0.0,0.0,0.0,0.5);
        glBegin(GL_QUADS);
        glVertex2f(0.15f,0.02f);
        glVertex2f(0.85f,0.02f);
        glVertex2f(0.85f,0.08f);
        glVertex2f(0.15f,0.08f);
        glEnd();

        float portion = (float)currFrame/totalFrame;
        float end = 0.15f+portion*0.7f;
        glPolygonMode(GL_FRONT, GL_FILL);
        glColor4d(0.3,0.3,0.3,0.5);
        glBegin(GL_QUADS);
        glVertex2f(0.15f,0.02f);
        glVertex2f(end, 0.02f);
        glVertex2f(end, 0.08f);
        glVertex2f(0.15f,0.08f);
        glEnd();

        glPopMatrix();

        glMatrixMode( GL_PROJECTION );
        glPopMatrix();
        glMatrixMode(oldMode);
    }

    bool screenShot(int w, int h, char *fname, bool _antialias) {
        // make sure OpenGL context is current
        //make_current();

        // read the pixels
        int numPixels = w*h;
        unsigned char *pixels = new unsigned char[numPixels*3*sizeof(unsigned char)];
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        if(_antialias) glReadBuffer(GL_ACCUM);
        else glReadBuffer(GL_FRONT);
        glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);

        // swap red and blue, because TGA format is stupid
        int i;
        for (i=0; i < numPixels; i++) {
            pixels[i * 3 + 0] ^= pixels[i * 3 + 2];
            pixels[i * 3 + 2] ^= pixels[i * 3 + 0];
            pixels[i * 3 + 0] ^= pixels[i * 3 + 2];
        }

        // get file name
        //#if USEFLTK
        //	if (fname == NULL) {
        //		fname = (char *)fltk::file_chooser("L", "*.tga", NULL);
        //	}
        //#endif
        if (fname == NULL)
            return false;

        // open the file
        FILE *fptr;
        fptr = fopen(fname, "wb");
        if (fptr == NULL) {
            //    PrintOnScreen("Failed to open this file");
            return false;
        }

        // create tga header
        putc(0,fptr);
        putc(0,fptr);
        putc(2,fptr);                         // uncompressed RGB
        putc(0,fptr); putc(0,fptr);
        putc(0,fptr); putc(0,fptr);
        putc(0,fptr);
        putc(0,fptr); putc(0,fptr);           // X origin
        putc(0,fptr); putc(0,fptr);           // y origin
        putc((w & 0x00FF),fptr);
        putc((w & 0xFF00) / 256,fptr);
        putc((h & 0x00FF),fptr);
        putc((h & 0xFF00) / 256,fptr);
        putc(24,fptr);                        // 24 bit bitmap
        putc(0,fptr);

        // write the data
        fwrite(pixels, w*h*3*sizeof(char), 1, fptr);
        fclose(fptr);

        delete []pixels;

        cout << fname << " generated" << endl;
        return true;
    }
} // namespace yui


text:
#include "average_case_error.hpp"

#include <boost/multiprecision/cpp_int.hpp>
#include <cudd_helpers.hpp>

using abo::util::NumberRepresentation;
using boost::multiprecision::cpp_dec_float_100;
using boost::multiprecision::uint256_t;

namespace abo::error_metrics {

cpp_dec_float_100 average_value(const std::vector<BDD>& f)
{

    uint256_t sum = 0;
    const uint256_t one = 1;

    int max_support_size = 0;
    for (const auto& bdd : f)
    {
        max_support_size = std::max(max_support_size, bdd.SupportSize());
    }

    for (unsigned int i = 0; i < f.size(); i++)
    {
        // TODO: CountMinterms returns a double, might loose precision
        double minterms = f[i].CountMinterm(max_support_size);
        sum += (one << i) * uint256_t(minterms);
    }

    return cpp_dec_float_100(sum) /
           cpp_dec_float_100(one << max_support_size);
}

cpp_dec_float_100 mean_squared_value(const std::vector<BDD>& f)
{

    uint256_t sum = 0;
    const uint256_t one = 1;

    int max_support_size = 0;
    for (const auto& bdd : f)
    {
        max_support_size = std::max(max_support_size, bdd.SupportSize());
    }

    for (unsigned int i = 0; i < f.size(); i++)
    {
        for (unsigned int b = i; b < f.size(); b++)
        {
            // cudd handles the case i = b efficiently
            BDD both = f[i] & f[b];
            double minterms = both.CountMinterm(max_support_size);
            // most terms (except for i == b), appear twice when factoring the square
            uint256_t doubling_factor = i == b ? 1 : 2;
            sum += (one << i) * (one << b) * uint256_t(minterms) *
                   doubling_factor;
        }
    }

    return cpp_dec_float_100(sum) /
           cpp_dec_float_100(one << max_support_size);
}

cpp_dec_float_100
average_case_error(const Cudd& mgr, const std::vector<BDD>& f,
                   const std::vector<BDD>& f_hat,
                   const util::NumberRepresentation num_rep)
{

    std::vector<BDD> absolute_difference =
        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);
    return average_value(absolute_difference);
}

cpp_dec_float_100
mean_squared_error(const Cudd& mgr, const std::vector<BDD>& f,
                   const std::vector<BDD>& f_hat,
                   const util::NumberRepresentation num_rep)
{

    std::vector<BDD> absolute_difference =
        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);
    return mean_squared_value(absolute_difference);
}

cpp_dec_float_100 average_case_error_add(const Cudd& mgr,
                                        const std::vector<BDD>& f,
                                        const std::vector<BDD>& f_hat,
                                        const NumberRepresentation num_rep)
{

    ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);
    std::vector<std::pair<double, unsigned long>> terminal_values =
        abo::util::add_terminal_values(diff);

    uint256_t sum = 0;
    uint256_t path_sum = 0;
    for (auto p : terminal_values)
    {
        sum += uint256_t(p.first) * p.second;
        path_sum += p.second;
    }
    return cpp_dec_float_100(sum) /
           cpp_dec_float_100(path_sum);
}

cpp_dec_float_100 mean_squared_error_add(const Cudd& mgr,
                                        const std::vector<BDD>& f,
                                        const std::vector<BDD>& f_hat,
                                        const NumberRepresentation num_rep)
{

    ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);
    std::vector<std::pair<double, unsigned long>> terminal_values =
        abo::util::add_terminal_values(diff);

    uint256_t sum = 0;
    uint256_t path_sum = 0;
    for (auto p : terminal_values)
    {
        uint256_t value(p.first);
        sum += value * value * p.second;
        path_sum += p.second;
    }
    return cpp_dec_float_100(sum) /
           cpp_dec_float_100(path_sum);
}

} // namespace abo::error_metrics

max_stars_repo_name: keszocze/abo

max_issues_repo_name: keszocze/abo

max_forks_repo_name: keszocze/abo


text:
/*=============================================================================
    Copyright (c) 2003 Joel de Guzman
    Copyright (c) 2004 Peder Holt

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_AS_FUSION_ITERATOR_HPP)
#define FUSION_SEQUENCE_AS_FUSION_ITERATOR_HPP

#include <boost/spirit/fusion/iterator/is_iterator.hpp>
#include <boost/spirit/fusion/iterator/type_sequence_iterator.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace fusion
{
    //  Test T. If it is a fusion iterator, return a reference to it.
    //  else, assume it is an mpl iterator.

    namespace as_fusion_iterator_detail {
        template <typename T>
        static T const&
        convert(T const& x, mpl::true_)
        {
            return x;
        }

        template <typename T>
        static type_sequence_iterator<T>
        convert(T const& x, mpl::false_)
        {
            return type_sequence_iterator<T>();
        }
    }

    template <typename T>
    struct as_fusion_iterator
    {
        typedef typename
            mpl::if_<
                fusion::is_iterator<T>
              , T
              , type_sequence_iterator<T>
            >::type
        type;

        static typename
            mpl::if_<
                fusion::is_iterator<T>
              , T const&
              , type_sequence_iterator<T>
            >::type
        convert(T const& x);
    };

    template <typename T>
    typename
        mpl::if_<
            fusion::is_iterator<T>
          , T const&
          , type_sequence_iterator<T>
        >::type
    as_fusion_iterator<T>::convert(T const& x)
    {
        return as_fusion_iterator_detail::convert(x, fusion::is_iterator<T>());
    }

}}

#endif

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
// Copyright 2015-2018 Hans Dembinski
//
// 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)

//[ guide_histogram_projection

#include <boost/histogram.hpp>
#include <cassert>
#include <iostream>
#include <sstream>

int main() {
  using namespace boost::histogram;
  using namespace literals; // enables _c suffix

  // make a 2d histogram
  auto h = make_histogram(axis::regular<>(3, -1.0, 1.0), axis::integer<>(0, 2));

  h(-0.9, 0);
  h(0.9, 1);
  h(0.1, 0);

  auto hr0 = algorithm::project(h, 0_c); // keep only first axis
  auto hr1 = algorithm::project(h, 1_c); // keep only second axis

  // reduce does not remove counts; returned histograms are summed over
  // the removed axes, so h, hr0, and hr1 have same number of total counts;
  // we compute the sum of counts with the sum algorithm
  assert(algorithm::sum(h) == 3 && algorithm::sum(hr0) == 3 && algorithm::sum(hr1) == 3);

  std::ostringstream os1;
  for (auto x : indexed(h))
    os1 << "(" << x.index(0) << ", " << x.index(1) << "): " << *x << "\n";
  std::cout << os1.str() << std::flush;
  assert(os1.str() == "(0, 0): 1\n"
                      "(1, 0): 1\n"
                      "(2, 0): 0\n"
                      "(0, 1): 0\n"
                      "(1, 1): 0\n"
                      "(2, 1): 1\n");

  std::ostringstream os2;
  for (auto x : indexed(hr0)) os2 << "(" << x.index(0) << ", -): " << *x << "\n";
  std::cout << os2.str() << std::flush;
  assert(os2.str() == "(0, -): 1\n"
                      "(1, -): 1\n"
                      "(2, -): 1\n");

  std::ostringstream os3;
  for (auto x : indexed(hr1)) os3 << "(- ," << x.index(0) << "): " << *x << "\n";
  std::cout << os3.str() << std::flush;
  assert(os3.str() == "(- ,0): 2\n"
                      "(- ,1): 1\n");
}

//]

max_stars_repo_name: henryiii/histogram

max_issues_repo_name: henryiii/histogram

max_forks_repo_name: henryiii/histogram


text:
// Example ntrip server using boost asio, based off of boost http server example
// See http://www.boost.org/LICENSE_1_0.txt

#include "request_handler.h"
#include <algorithm>
#include <fstream>
#include <sstream>
#include <string>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>

#include "glog/logging.h"
#include "mime_types.h"
#include "reply.h"
#include "request.h"

namespace ntrip {

request_handler::request_handler(const std::string& doc_root)
    : doc_root_(doc_root) {}

void request_handler::handle_source_table_request(reply& rep) {
  rep.status = reply::source_table_ok;
  // Thu, 04 April 2019 19:31:18 UTC
  std::stringstream content_ss;
  content_ss << "STR;Polaris;PointOneNavigation;RTCM "
                "3.3;1010(1),1012(1),1006(30);2;GPS+GLO;PointOne;USA;32.56;-"
                "127.63;1;0;P1;none;N;N;4096;;\r\n";
  content_ss << "ENDSOURCETABLE\r\n";
  content_ss << "\r\n";

  std::stringstream date_ss;
  boost::posix_time::ptime t =
      boost::posix_time::microsec_clock::universal_time();
  date_ss << boost::posix_time::to_iso_extended_string(t) << "Z\n";

  rep.content = content_ss.str();
  rep.headers.resize(4);
  rep.headers[0].name = "Server";
  rep.headers[0].value = "PointOne Navigation Polaris NTRIP Proxy Example";
  rep.headers[1].name = "Date";
  rep.headers[1].value = date_ss.str();
  rep.headers[2].name = "Content-Length";
  rep.headers[2].value = boost::lexical_cast<std::string>(rep.content.size());
  rep.headers[3].name = "Content-Type";
  rep.headers[3].value = "text/plain";
}

void request_handler::handle_mountpoint_request(const std::string& mount_point,
                                                const std::string& ntrip_gga,
                                                reply& rep) {
  rep = reply::stock_reply(reply::icy_ok);
  rep.mount_point = mount_point;
  rep.ntrip_gga = ntrip_gga;
}

void request_handler::handle_normal_http_request(const request& req,
                                                 reply& rep) {
  // Decode url to path.
  std::string request_path;
  if (!url_decode(req.uri, request_path)) {
    LOG(INFO) << "Bad request";
    rep = reply::stock_reply(reply::bad_request);
    return;
  }

  // Request path must be absolute and not contain "..".
  if (request_path.empty() || request_path[0] != '/' ||
      request_path.find("..") != std::string::npos) {
    LOG(INFO) << "Bad request: " << request_path;
    rep = reply::stock_reply(reply::bad_request);
    return;
  }
  // If path ends in slash (i.e. is a directory) then add "index.html".
  if (request_path[request_path.size() - 1] == '/') {
    request_path += "index.html";
  }

  // Determine the file extension.
  std::size_t last_slash_pos = request_path.find_last_of("/");
  std::size_t last_dot_pos = request_path.find_last_of(".");
  std::string extension;
  if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) {
    extension = request_path.substr(last_dot_pos + 1);
  }

  // Open the file to send back.
  std::string full_path = doc_root_ + request_path;
  std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
  if (!is) {
    LOG(INFO) << full_path;
    rep = reply::stock_reply(reply::not_found);
    return;
  }

  // Fill out the reply to be sent to the client.
  rep.status = reply::ok;
  char buf[512];
  while (is.read(buf, sizeof(buf)).gcount() > 0)
    rep.content.append(buf, is.gcount());
  rep.headers.resize(2);
  rep.headers[0].name = "Content-Length";
  rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
  rep.headers[1].name = "Content-Type";
  rep.headers[1].value = extension_to_type(extension);
}

void request_handler::handle_request(const request& req, reply& rep) {
  bool ntrip_user_agent = false;
  std::string ntrip_gga;
  for (const auto& header : req.headers) {
    std::string data = header.name;
    std::transform(data.begin(), data.end(), data.begin(), ::tolower);
    std::string value = header.value;
    std::transform(value.begin(), value.end(), value.begin(), ::tolower);
    if (data == "user-agent" && boost::istarts_with(value, "ntrip")) {
      LOG(INFO) << value;
      ntrip_user_agent = true;
    }
    if (data == "ntrip-gga") {
      ntrip_gga = header.value;
    }
  }

  VLOG(2) << "Ntrip user agent: " << ntrip_user_agent;
  VLOG(2) << req.uri;

  // The ntrip user agent makes this respond with NTRIP standard responses
  // that dont have the normal HTTP codes (as expected by receviers)
  if (!ntrip_user_agent) {
    handle_normal_http_request(req, rep);
  } else if (mountpoints_.find(req.uri) != mountpoints_.end()) {
    handle_mountpoint_request(req.uri, ntrip_gga, rep);
  } else {
    handle_source_table_request(rep);
  }
}

bool request_handler::url_decode(const std::string& in, std::string& out) {
  out.clear();
  out.reserve(in.size());
  for (std::size_t i = 0; i < in.size(); ++i) {
    if (in[i] == '%') {
      if (i + 3 <= in.size()) {
        int value = 0;
        std::istringstream is(in.substr(i + 1, 2));
        if (is >> std::hex >> value) {
          out += static_cast<char>(value);
          i += 2;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else if (in[i] == '+') {
      out += ' ';
    } else {
      out += in[i];
    }
  }
  return true;
}

}  // namespace ntrip


text:
#ifndef ORDER_DECODER_HPP
#define ORDER_DECODER_HPP

#include <map>
#include <memory>
#include "../typedefs.hpp"
#include "game_order.hpp"
#include <regex>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include "../get_regex_function.hpp"

using namespace std;

class OrderDecoder{
public:
    void decode(string orders){
	int i =10;

    std::vector<std::string> vec;
	while(orders.size()>0){
	string order = orders.substr(orders.find("<order>")+7, orders.find("</order>")-7);
	vec.push_back(order);
    orders = orders.substr(orders.find("</order>")+8);
		}
	for(auto order : vec){
		//cout<<endl <<order;

		string s1 = getRegex(order, "(?<=<move>)(.*)(?=</move>)");
		string s2 = getRegex(order, "(?<=<build>)(.*)(?=</build>)");
		string s3 = getRegex(order, "(?<=<create>)(.*)(?=</create>)");
		if(s1.length()>0){
			cout<<endl<<s1;

			shared_ptr<MoveOrder> ptr  = make_shared<MoveOrder>(s1);
			move_orders_.push_back(ptr);
			}
		if(s2.length()>0){

			cout<<endl<<s2;

			shared_ptr<CreateShipOrder> ptr  = make_shared<CreateShipOrder>(s2);
			create_ship_orders_.push_back(ptr);
			}
		if(s3.length()>0){

			cout<<endl<<s3;

			shared_ptr<BuildOrder> ptr  = make_shared<BuildOrder>(s3);
			build_orders_.push_back(ptr);

			}

		}
	}

	void clear(){
		move_orders_.clear();
		create_ship_orders_.clear();
		build_orders_.clear();
		}
	vector<shared_ptr<MoveOrder>> move_orders_;
	vector<shared_ptr<CreateShipOrder>> create_ship_orders_;
	vector<shared_ptr<BuildOrder>> build_orders_;
};

#endif //ORDER_DECODER_HPP