text:
#pragma once

#include <crab/common/types.hpp>
#include <crab/common/debug.hpp>
#include <crab/common/stats.hpp>

#include <crab/cfg/cfg.hpp>
#include <crab/iterators/killgen_fixpoint_iterator.hpp>
#include <crab/domains/separate_domains.hpp>
#include <crab/analysis/graphs/cdg.hpp>

#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/range/iterator_range.hpp>

/**
 *  Dataflow analysis that for each block b it computes facts <i,V>
 *  meaning that there exists a path emanating from b that will reach
 *  assertion with id=i and its evaluation depends on the set of
 *  variables V.
 *
 *  These dataflow facts are useful at least for:
 *
 *  - Computing the set of unjustified assumptions when proving a
 *    particular assertion, and
 *
 *  - Performing slicing by havoc'ing statements that cannot affect
 *    any assertion.
 *
 *  TODO:
 *  - Consider only integer instructions ignoring the heap.
 **/

namespace crab {

  namespace analyzer {

    using namespace crab::iterators;
    using namespace crab::domains;
    using namespace crab::cfg;

    // A wrapper to an assert statement
    template<typename CFG>
    struct assert_wrapper: public ikos::writeable {

      typedef typename statement_visitor<typename CFG::number_t,
					 typename CFG::varname_t>::assert_t assert_t;
      typedef typename CFG::basic_block_label_t basic_block_label_t;
      typedef assert_wrapper<CFG> this_type;

      // unique identifier for the assert statement needed for being
      // used as key
      index_t id;
      // basic block where the assert statement is located
      basic_block_label_t bbl;
      // the assert statement
      assert_t* a;

      /// pointers to some global datastructures
      typedef boost::unordered_map<assert_t*, this_type > assert_map_t;
      typedef boost::unordered_map <basic_block_label_t,
				    std::vector<basic_block_label_t> > cdg_t;
      // map assertions to their wrappers
      assert_map_t* assert_map_ptr;
      // control-dependency graph
      const cdg_t* cdg_ptr;

      assert_wrapper (index_t _id, basic_block_label_t _bbl, assert_t* _a,
		      assert_map_t *am, const cdg_t *cdg)
	: id(_id), bbl(_bbl), a(_a), assert_map_ptr(am), cdg_ptr(cdg) {}

      assert_t* get() { return a;}
      const assert_t* get() const { return a;}
      index_t index() const { return id;}
      bool operator==(this_type o) const { return id == o.id;}
      bool operator< (this_type o) const { return id < o.id; }
      void write (crab::crab_os& o) { o << "\"" << *a << "\""; }
    };

    template<typename CFG> class assertion_crawler;

    // Define the operations of the dataflow analysis
    template<class CFG>
    class assertion_crawler_operations:
      public killgen_operations_api<CFG,
	     separate_killgen_domain<assert_wrapper<CFG>,
				     flat_killgen_domain<typename CFG::variable_t> > > {

      friend class assertion_crawler<CFG>;

    public:

       typedef assert_wrapper<CFG> assert_wrapper_t;
       typedef flat_killgen_domain<typename CFG::variable_t> var_dom_t;
       // -- key type: map an assertion to a set of variables
       typedef separate_killgen_domain<assert_wrapper_t, var_dom_t> separate_domain_t;

    private:

       typedef killgen_operations_api<CFG, separate_domain_t> killgen_operations_api_t;
       typedef typename CFG::basic_block_label_t basic_block_label_t;
       typedef typename CFG::basic_block_t basic_block_t;
       typedef typename CFG::varname_t V;
       typedef typename CFG::number_t N;

       // map each stmt assertion to a unique identifier
       typedef typename assert_wrapper_t::assert_t assert_t;
       typedef boost::unordered_map<assert_t*, assert_wrapper_t > assert_map_t;

       // control-dependency graph
       // map a CFG block to the set of blocks which control-dependent on it.
       typedef boost::unordered_map <basic_block_label_t,
				     std::vector<basic_block_label_t> > cdg_t;

       // set of uses and definitions of an instruction
       typedef crab::cfg::Live<N,V> live_t;

       class transfer_function: public statement_visitor<N,V> {

         typedef typename statement_visitor<N,V>::bin_op_t  bin_op_t;
         typedef typename statement_visitor<N,V>::assign_t  assign_t;
         typedef typename statement_visitor<N,V>::assume_t  assume_t;
         typedef typename statement_visitor<N,V>::select_t  select_t;
         typedef typename statement_visitor<N,V>::assert_t  assert_t;
         typedef typename statement_visitor<N,V>::int_cast_t int_cast_t;
         typedef typename statement_visitor<N,V>::havoc_t   havoc_t;
         typedef typename statement_visitor<N,V>::unreach_t unreach_t;
	 typedef typename statement_visitor<N,V>::bool_bin_op_t bool_bin_op_t;
	 typedef typename statement_visitor<N,V>::bool_assign_cst_t bool_assign_cst_t;
	 typedef typename statement_visitor<N,V>::bool_assign_var_t bool_assign_var_t;
	 typedef typename CFG::variable_t variable_t;

	 // Helper that applies function F to each pair's value of the
	 // separate domain_t.
       	 template<typename F>
       	 struct apply_separate:
	   public std::unary_function<separate_domain_t, separate_domain_t>{
	   typedef apply_separate<F> this_type;
	   typedef std::binary_function<assert_wrapper_t, var_dom_t,
					std::pair<var_dom_t, bool> > function_type;
	   static_assert (std::is_base_of<function_type, F>::value,
			  "Function must be subclass of type F");
       	   F f;

	 public:

       	   apply_separate(F _f): f (_f) {}
	   apply_separate(const this_type& o): f (o.f) {}

       	   separate_domain_t operator()(separate_domain_t inv)
       	   { // XXX: separate_domain_t cannot be modified in-place
	     typedef std::pair<typename separate_domain_t::key_type,
			       typename separate_domain_t::value_type> value_type;

	     if (inv.is_bottom ()) return inv;

       	     std::vector<value_type> kvs;
       	     kvs.reserve (std::distance (inv.begin(), inv.end ()));
       	     for (auto const &kv: inv)
       	       kvs.push_back (value_type(kv.first, kv.second));

       	     for (auto &kv: kvs) {
       	       auto p = f(kv.first, kv.second);
       	       if (p.second) inv.set (kv.first, p.first);
       	     }
       	     return inv;
       	   }
       	 };

	 /** Add data-dependencies **/
       	 class add_data_deps:
       	   public std::binary_function<assert_wrapper_t, var_dom_t,
				       std::pair<var_dom_t,bool> > {
	   var_dom_t uses;
	   var_dom_t defs;

	 public:

       	   add_data_deps(const live_t& l)
	     : uses(var_dom_t::bottom()), defs (var_dom_t::bottom()) {
	     for (auto v: boost::make_iterator_range(l.uses_begin(), l.uses_end()))
	       uses += v;
	     for (auto v: boost::make_iterator_range(l.defs_begin(), l.defs_end()))
	       defs += v;
	   }

	   add_data_deps(const add_data_deps &o): uses (o.uses), defs (o.defs) {}

       	   std::pair<var_dom_t,bool> operator()(assert_wrapper_t /*w*/,var_dom_t d) {
       	     bool change = false;

	     if (defs.is_bottom() && !uses.is_bottom() && !(uses & d).is_bottom ()) {
	       d += uses;
	       change = true;
	     }
       	     if (!(d & defs).is_bottom()) {
       	       d -= defs;
	       d += uses;
       	       change = true;
       	     }
       	     return std::make_pair(d, change);
       	   }
       	 };

	 /** Add control-dependencies **/
       	 class add_control_deps:
       	   public std::binary_function<assert_wrapper_t, var_dom_t,
				       std::pair<var_dom_t,bool> > {
	   const cdg_t &cdg;
	   const std::vector<basic_block_label_t> &roots;

	   var_dom_t uses;

	   // return true if we find a path in cdg from root to target
	   // FIXME: do caching for the queries
	   bool reach (basic_block_label_t root, basic_block_label_t target,
		       boost::unordered_set<basic_block_label_t> &visited) {
	     if (root == target)
	       return true;

	     // break cycles
	     if (visited.find (root) != visited.end ())
	       return false;

	     visited.insert (root);
	     auto it = cdg.find (root);
	     if (it == cdg.end ()) return false;

	     for (auto child: it->second) {
	       if (reach (child, target, visited))
		 return true;
	     }
	     return false;
	   }

	   bool reach (basic_block_label_t target) {
	     boost::unordered_set <basic_block_label_t> visited;
	     for (auto r: roots)
	       if (reach(r, target,visited))
		 return true;
	     return false;
	   }

	 public:

       	   add_control_deps (const cdg_t & _cdg,
			     const std::vector<basic_block_label_t>& _roots,
			     const live_t& l)
	     : cdg(_cdg), roots (_roots), uses(var_dom_t::bottom()) {
	     for (auto v: boost::make_iterator_range(l.uses_begin(), l.uses_end()))
	       uses += v;
	   }

	   add_control_deps (const add_data_deps &o)
	     : cdg (o.cdg), roots (o.roots), uses (o.uses) {}

       	   std::pair<var_dom_t,bool> operator()(assert_wrapper_t w, var_dom_t d) {
       	     bool change = false;
	     if (reach (w.bbl)) {
	       d += uses;
	       change = true;
	     }

       	     return std::make_pair(d, change);
       	   }
       	 };

	 /** Remove data-dependencies **/
       	 class remove_deps:
       	   public std::binary_function<assert_wrapper_t, var_dom_t,
				       std::pair<var_dom_t,bool> > {
	   var_dom_t vars;

	 public:

       	   remove_deps(variable_t v): vars(var_dom_t::bottom()) { vars += v; }

	   remove_deps(const std::vector<variable_t> &vs)
	     : vars(var_dom_t::bottom()) { for (auto v: vs) {vars += v; } }

	   remove_deps(const remove_deps& o): vars (o.vars) {}

       	   std::pair<var_dom_t,bool> operator()(assert_wrapper_t /*w*/, var_dom_t d) {
       	     bool change = false;
       	     if (!(d & vars).is_bottom()) {
       	       d -= vars;
       	       change = true;
       	     }
       	     return std::make_pair(d, change);
       	   }
       	 };

	 typedef apply_separate<add_data_deps> apply_add_data_t;
	 typedef apply_separate<add_control_deps> apply_add_control_t;
	 typedef apply_separate<remove_deps> apply_remove_t;

	 // dataflow solution: map blocks to pairs of assertion id and
	 //                    set of variables.
         separate_domain_t _inv;
	 // map each assertion to a unique identifier
	 assert_map_t &_assert_map;
	 // control-dependence graph
	 const cdg_t &_cdg;
	 // parent basic block (XXX: needed because crab statements do
	 // not have a back pointer to their basic blocks)
	 basic_block_t &_bb;

       public:

         transfer_function (separate_domain_t inv, const cdg_t &g,
			    assert_map_t &am, basic_block_t &bb)
	   : _inv(inv), _assert_map (am), _cdg (g), _bb (bb) { }

	 separate_domain_t inv () {return _inv;}

         void visit(bin_op_t &s){
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps(s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
       	 }

         void visit(assign_t &s) {
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps (s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);

         }

         void visit(assume_t &s) {
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
	   // -- add data dependencies
       	   apply_add_data_t df (add_data_deps (s.get_live ()));
       	   _inv = df(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER data-dep " << _inv << "\n";);

	   // -- add control dependencies
	   for (auto const &pred: boost::make_iterator_range(_bb.prev_blocks ())) {
	     // it->second is the set of basic blocks that control
	     // dependent on s' block
	     auto it = _cdg.find (/*_bb*/ pred);
	     if (it != _cdg.end ()) {
	       auto const &children =  it->second;
	       CRAB_LOG("assertion-crawler-step-control",
			crab::outs () << "{";
			for(auto &c: children) { crab::outs () << c << ";"; }
			crab::outs () << "} control-dependent on " << pred << "\n";);
	       apply_add_control_t cf(add_control_deps(_cdg, children, s.get_live()));
	       _inv = cf(_inv);
	       CRAB_LOG("assertion-crawler-step-control",
			crab::outs () << "\tAFTER control-dep " << _inv << "\n";);
	     }
	   }
         }

         void visit(select_t &s) {
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps (s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
         }

         void visit(assert_t &s) {
	   auto it = _assert_map.find (&s);
	   if (it != _assert_map.end ()) return;

	   var_dom_t vdom = var_dom_t::bottom ();
	   auto const& l = s.get_live ();
	   for (auto v: boost::make_iterator_range(l.uses_begin(), l.uses_end())) {
	     vdom += v;
	   }

	   unsigned id = _assert_map.size ();
	   assert_wrapper_t val(id, _bb.label(), &s, &_assert_map, &_cdg);
	   _assert_map.insert(typename assert_map_t::value_type (&s, val));
	   _inv.set (val, vdom);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n" << "\tAdded " << vdom << "\n";);

       	 }

         void visit(unreach_t&) {
	   _inv = separate_domain_t::bottom();
	 }

         void visit(havoc_t& s) {
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_remove_t f(remove_deps (s.variable ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
	 }

         void visit(int_cast_t &s){
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps (s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
       	 }

         void visit(bool_bin_op_t &s){
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps(s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
       	 }

         void visit(bool_assign_var_t &s){
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps(s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
       	 }

         void visit(bool_assign_cst_t &s){
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "*** " << s << "\n"
	 	                  << "\tBEFORE: " << _inv << "\n");
       	   apply_add_data_t f(add_data_deps(s.get_live ()));
       	   _inv = f(_inv);
	   CRAB_LOG("assertion-crawler-step",
		    crab::outs () << "\tAFTER " << _inv << "\n";);
       	 }

       };

      private:

       // global datastructure for the whole analysis of the CFG
       assert_map_t _assert_map;
       cdg_t _cdg;

      public:

       assertion_crawler_operations(CFG cfg) : killgen_operations_api_t(cfg) { }

       virtual bool is_forward() override { return false;}

       virtual std::string name() override { return "assertion-crawler";}

       virtual void init_fixpoint() override {
	 crab::ScopedCrabStats __st__("Control-Dependency Graph");
	 crab::analyzer::graph_algo::control_dep_graph (this->_cfg, _cdg);
       }

       virtual separate_domain_t entry() override {
	 return separate_domain_t::bottom();
       }

       virtual separate_domain_t merge(separate_domain_t d1, separate_domain_t d2) override {
	 return d1 | d2;
       }

       virtual separate_domain_t
       analyze(basic_block_label_t bb_id, separate_domain_t out) override {
         auto &bb = this->_cfg.get_node(bb_id);
         transfer_function vis(out,_cdg, _assert_map, bb);
	 for (auto &s: boost::make_iterator_range(bb.rbegin(),bb.rend())) {
	   s.accept (&vis);
	 }
         return vis.inv();
       }
     };

     /**
      * The assertion crawler dataflow analysis
      *
      * Compute for each basic block b a set of facts (i,V) such that
      * there exists a path from b that will check assertion i and its
      * evaluation depends on the set of variables V.
      **/
     template<class CFG>
     class assertion_crawler:
       public boost::noncopyable,
       public crab::iterators::
       killgen_fixpoint_iterator<CFG,assertion_crawler_operations<CFG> >{

      public:

       typedef typename CFG::basic_block_label_t basic_block_label_t;
       typedef typename CFG::varname_t varname_t;

      private:

       typedef crab::iterators::
       killgen_fixpoint_iterator<CFG,
				 assertion_crawler_operations<CFG> > fixpo_t;

      public:

       // map assertions to a set of variables
       typedef typename
       assertion_crawler_operations<CFG>::separate_domain_t separate_domain_t;

      private:

       boost::unordered_map<basic_block_label_t, separate_domain_t> m_map;

      public:

       assertion_crawler(CFG cfg): fixpo_t(cfg) {}

       void exec() {
         this->run();
	 for (auto p : boost::make_iterator_range(this->out_begin(), this->out_end())) {
	   m_map.insert(std::make_pair(p.first, p.second));
	 }
         this->release_memory();
       }

       // return the dataflow facts that hold at the exit of block bb
       separate_domain_t& get_assertions(basic_block_label_t bb) {
	 auto it = m_map.find(bb);
	 if (it == m_map.end())
	   CRAB_ERROR("Basic block ", bb, " not found");
	 return it->second;
       }

       // return the dataflow facts of the pre-state at each program point in bb
       void get_assertions(basic_block_label_t b,
			   std::map<typename CFG::statement_t*, separate_domain_t> &res) {
	 auto it = m_map.find(b);
	 if (it != m_map.end()) {
	   if (!it->second.is_bottom()) {
	     auto kv = *(it->second.begin());
	     auto &bb = this->_cfg.get_node(b);
	     typename assertion_crawler_operations<CFG>::transfer_function
	       vis(it->second,
		   *(kv.first.cdg_ptr), *(kv.first.assert_map_ptr),
		   bb);
	     for (auto &s: boost::make_iterator_range(bb.rbegin(),bb.rend())) {
	       // -- post-state
	       // auto out = vis.inv ();
	       // res.insert(std::make_pair(&s,out));
	       // s.accept (&vis);
	       // -- pre-state
	       s.accept (&vis);
	       auto in = vis.inv ();
	       res.insert(std::make_pair(&s,in));
	     }
	   }
	 }
       }

       void write (crab_os &o) {
	 o << "Assertion Crawler Analysis \n";
	 for (auto &kv: m_map) {
	   o << "Block " << kv.first << "\n";
	   #if 1
	   o << "\t" << kv.second << "\n";
	   #else
	   std::map<typename CFG::statement_t*, separate_domain_t> pp_map;
	   get_assertions(kv.first, pp_map);
	   for (auto &kv: pp_map) {
	     o << "\t" << *(kv.first) << " --> " << kv.second << "\n";
	   }
	   #endif
	 }
       }

     };

   template <typename CFG>
   crab_os& operator<<(crab_os& o, assertion_crawler<CFG> &ac) {
     ac.write (o);
     return o;
   }

  } // end namespace
} // end namespace

ext: hpp

max_stars_repo_name: aziem/crab

max_issues_repo_name: aziem/crab

max_forks_repo_name: aziem/crab


text:
#include "potentials.hpp"
#include "metropolis.hpp"
#include "distance.hpp"
#include <cmath>
#include <cassert>
#include <stdexcept>
#include <boost/algorithm/string.hpp>
#include "yaml-cpp/yaml.h"

namespace pauth {

using namespace arma;

double abstract_LJ_full_potential::_U(const metropolis &sim) const {

  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &edge_lengths = sim.edge_lengths();
  const auto N = sim.N();
  double potential = 0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N - 1; ++i) {
    for (auto j = i + 1; j < N; ++j) {

      const double rij2 = sim.m(positions.col(i), positions.col(j),
                                edge_lengths);
      const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
      const double rat2 = (rzero * rzero) / rij2;
      const double rat6 = rat2 * rat2 * rat2;

      potential += 4.0 * get_well_depth(molecular_ids[i], molecular_ids[j]) *
                   (rat6 * rat6 - rat6);
    }
  }

  return potential;
}

double abstract_LJ_full_potential::_delta_U(const metropolis &sim, const size_t j,
                                       arma::vec &rn_j) const {

  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &ro_j = positions.col(j);
  const auto &edge_lengths = sim.edge_lengths();
  const auto N = sim.N();
  double dU = 0;

  #pragma omp parallel for reduction(+:dU)
  for (auto i = size_t{0}; i < N; ++i) {
    if (i == j) continue;

    const auto well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);
    double rij2 = sim.m(positions.col(i), ro_j, edge_lengths);
    double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
    double rat2 = (rzero * rzero) / rij2;
    double rat6 = rat2 * rat2 * rat2;

    const double Uo = 4.0 * well_depth * (rat6 * rat6 - rat6);

    rij2 = sim.m(positions.col(i), rn_j, edge_lengths);
    rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
    rat2 = (rzero * rzero) / rij2;
    rat6 = rat2 * rat2 * rat2;

    const double Un = 4.0 * well_depth * (rat6 * rat6 - rat6);

    dU += Un - Uo;
  }

  return dU;
}

arma::vec abstract_LJ_full_potential::_forceij(const metropolis &sim, const size_t i,
                                          const size_t j) const {
  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &edge_lengths = sim.edge_lengths();
  const auto rij = sim.rij(positions.col(i), positions.col(j), edge_lengths);
  const double _rij2 = dot(rij, rij);
  const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
  const double rat2 = (rzero * rzero) / _rij2;
  const double rat6 = rat2 * rat2 * rat2;
  const double rat8 = rat6 * rat2;
  const double well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);

  return rij / rzero * well_depth * (48.0 * rat8 * rat6 - 24.0 * rat8);
}

double abstract_LJ_cutoff_potential::_U(const metropolis &sim) const {

  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &edge_lengths = sim.edge_lengths();
  const auto N = sim.N();
  double potential = 0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N - 1; ++i) {
    for (auto j = i + 1; j < N; ++j) {

      const double rij2 = sim.m(positions.col(i), positions.col(j),
                                edge_lengths);

      if (rij2 <= _rc2) {

        const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
        const double rz2 = rzero * rzero;
        const double rz4 = rz2 * rz2;
        const double rz8 = rz4 * rz4;

        const double dudr_rc = 6.0 * (rz4 * rz2 * rzero) / (_rc7)-12.0 *
                               (rz8 * rz4 * rzero) / (_rc13);
        const double u_rc = ((rz8 * rz4) / (_rc12) - (rz4 * rz2) / (_rc6));

        const double rat2 = rz2 / rij2;
        const double rat6 = rat2 * rat2 * rat2;

        potential += 4.0 * get_well_depth(molecular_ids[i], molecular_ids[j]) *
                     ((rat6 * rat6 - rat6) - u_rc -
                      (std::sqrt(rij2) - _cutoff) * dudr_rc);
      }
    }
  }

  return potential;
}

double abstract_LJ_cutoff_potential::_delta_U(const metropolis &sim,
                                              const size_t j,
                                              arma::vec &rn_j) const {

  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &ro_j = positions.col(j);
  const auto &edge_lengths = sim.edge_lengths();
  const auto N = sim.N();
  double dU = 0;

  #pragma omp parallel for reduction(+:dU)
  for (auto i = size_t{0}; i < N; ++i) {
    if (i == j) continue;

    const auto rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
    const auto well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);
    const double rz2 = rzero * rzero;
    const double rz4 = rz2 * rz2;
    const double rz8 = rz4 * rz4;

    const double dudr_rc = 6.0 * (rz4 * rz2 * rzero) / (_rc7)-12.0 *
                           (rz8 * rz4 * rzero) / (_rc13);
    const double u_rc = ((rz8 * rz4) / (_rc12) - (rz4 * rz2) / (_rc6));

    double Uo = 0.0;
    double rij2 = sim.m(positions.col(i), ro_j, edge_lengths);

    if (rij2 <= _rc2) {
      const double rat2 = rz2 / rij2;
      const double rat6 = rat2 * rat2 * rat2;

      Uo = 4.0 * well_depth *
           ((rat6 * rat6 - rat6) - u_rc -
            (std::sqrt(rij2) - _cutoff) * dudr_rc);
    }

    double Un = 0.0;
    rij2 = sim.m(positions.col(i), rn_j, edge_lengths);

    if (rij2 <= _rc2) {
      const double rat2 = rz2 / rij2;
      const double rat6 = rat2 * rat2 * rat2;

      Un = 4.0 * well_depth *
           ((rat6 * rat6 - rat6) - u_rc -
            (std::sqrt(rij2) - _cutoff) * dudr_rc);
    }

    dU += Un - Uo;
  }

  return dU;
}

arma::vec abstract_LJ_cutoff_potential::_forceij(const metropolis &sim,
                                                 const size_t i,
                                                 const size_t j) const {

  const auto &molecular_ids = sim.molecular_ids();
  const auto &positions = sim.positions();
  const auto &edge_lengths = sim.edge_lengths();
  const auto _rij = sim.rij(positions.col(i), positions.col(j), edge_lengths);
  const double _rij2 = dot(_rij, _rij);

  if (_rij2 <= _rc2) {

    const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);
    const double rz2 = rzero * rzero;
    const double rz4 = rz2 * rz2;
    const double rz8 = rz4 * rz4;

    const double dudr_rc = 24.0 * (rz4 * rz2 * rzero) / (_rc7)-48.0 *
                           (rz8 * rz4 * rzero) / (_rc13);

    const double rat2 = rz2 / _rij2;
    const double rat6 = rat2 * rat2 * rat2;
    const double rat8 = rat6 * rat2;
    const double well_depth =
        get_well_depth(molecular_ids[i], molecular_ids[j]);

    return _rij / rzero * well_depth *
           (48.0 * rat8 * rat6 - 24.0 * rat8 + dudr_rc / std::sqrt(_rij2));
  }

  return arma::zeros(sim.D());
}

double abstract_spring_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto &molecular_ids = sim.molecular_ids();
  const auto& positions = sim.positions();
  double potential = 0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N; ++i) {
    const double r2 = dot(positions.col(i), positions.col(i));
    potential += 0.5 * get_k(molecular_ids[i]) * r2;
  }

  return potential;
}

double abstract_spring_potential::_delta_U(const metropolis &sim,
                                           const size_t j,
                                           arma::vec &rn_j) const {
  const arma::vec &ro_j = sim.positions().col(j);
  return 0.5 * get_k(sim.molecular_ids()[j]) *
         (dot(rn_j, rn_j) - dot(ro_j, ro_j));
}

const_poly_spring_potential::const_poly_spring_potential(
    const std::initializer_list<double> &coeffs)
    : pcoeffs(coeffs) {

  for (size_t i = 1; i < pcoeffs.size(); ++i)
    fcoeffs.push_back(pcoeffs[i] * 2 * i);
}

double const_poly_spring_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto& positions = sim.positions();
  double potential = 0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N; ++i) {
    double Ui = 0.0;
    const double r2 = dot(positions.col(i), positions.col(i));
    for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {
      double x = 1;
      for (auto k = size_t{0}; k < p; ++k)
        x *= r2;
      Ui += pcoeffs[p] * x;
    }
    potential += Ui;
  }

  return potential;
}

double const_poly_spring_potential::_delta_U(const metropolis &sim,
                                             const size_t j,
                                             arma::vec &rn_j) const {
  const arma::vec &ro_j = sim.positions().col(j);

  double Uo = 0.0;
  double r2 = dot(ro_j, ro_j);
  for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {
    double x = 1;
    for (auto k = size_t{0}; k < p; ++k)
      x *= r2;
    Uo += pcoeffs[p] * x;
  }

  double Un = 0.0;
  r2 = dot(rn_j, rn_j);
  for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {
    double x = 1;
    for (auto k = size_t{0}; k < p; ++k)
      x *= r2;
    Un += pcoeffs[p] * x;
  }

  return Un - Uo;
}

arma::vec const_poly_spring_potential::_forceij(const metropolis &sim, const size_t,
                                                const size_t) const {
  return arma::zeros(sim.D());
}

double const_quad_spring_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto &positions = sim.positions();
  double potential = 0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N; ++i) {
    const double r2 = dot(positions.col(i), positions.col(i));
    potential += a * r2 * r2 + b * r2 + c;
  }

  return potential;
}

double const_quad_spring_potential::_delta_U(const metropolis &sim,
                                             const size_t j,
                                             arma::vec &rn_j) const {
  const arma::vec &ro_j = sim.positions().col(j);
  const double r2o = dot(ro_j, ro_j);
  const double r2n = dot(rn_j, rn_j);

  return a * (r2n*r2n - r2o*r2o) + b * (r2n - r2o);
}

arma::vec abstract_spring_potential::_forceij(const metropolis &sim,
                                                      const size_t,
                                                      const size_t) const {
  return arma::zeros(sim.D());
}

arma::vec const_quad_spring_potential::_forceij(const metropolis &sim, const size_t,
                                                const size_t) const {
  return arma::zeros(sim.D());
}

double twostate_int_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto &positions = sim.positions();

  double potential = 0.0;

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N; ++i) {
    assert(_check_x(positions.col(i)));
    potential += _Ui(positions.col(i));
  }

  #pragma omp parallel for reduction(+:potential)
  for (auto i = size_t{0}; i < N; ++i) {
    for (auto j = size_t{i+1}; j < N; ++j) {
      potential += _Ui(positions.col(i)) * _Ui(positions.col(j));
    }
  }

  return potential;
}

double twostate_int_potential::_delta_U(const metropolis &sim, const size_t j,
                                        arma::vec &rn_j) const {

  const auto N = sim.N();
  const auto &positions = sim.positions();

  double dUi = _Ui(rn_j) - _Ui(positions.col(j));

  double U2 = 0.0;
  #pragma omp parallel for reduction(+:U2)
  for (auto i = size_t{0}; i < N; ++i) {
    if (i == j) continue;
    U2 += _Ui(positions.col(i));
  }

  return dUi + dUi * U2;

}

arma::vec twostate_int_potential::_forceij(const metropolis &sim, const size_t,
                                           const size_t) const {
  return arma::zeros(sim.D());
}

abstract_LJ_lookup_potential::abstract_LJ_lookup_potential(const char *fname) {
  vector<string> molecular_strs;
  const auto well_params = YAML::LoadFile(fname);

  for (const auto &well_param : well_params) {
    auto molecular_pair_str = well_param.first.as<string>();
    boost::split(molecular_strs, molecular_pair_str, boost::is_any_of(","));
    for (auto &molecular_str : molecular_strs) boost::trim(molecular_str);
    if (molecular_names_to_ids.count(molecular_strs[0]) &&
        molecular_names_to_ids.count(molecular_strs[1])) {
      unordered_pair<molecular_id> key {
        molecular_names_to_ids.at(molecular_strs[0]),
        molecular_names_to_ids.at(molecular_strs[1])
      };
      _well_depth_map[key] = well_param.second["epsilon"].as<double>();
      _rzero_map[key] = well_param.second["sigma"].as<double>();
    }
    else throw runtime_error(string("Molecular pair ") +
                             well_param.first.as<string>() +
                             string(" not found."));
  }
}

double abstract_LJ_lookup_potential::_get_well_depth(const molecular_id id1,
                                                     const molecular_id id2) const {
  unordered_pair<molecular_id> key { id1, id2 };
  return _well_depth_map.at(key);
}

double abstract_LJ_lookup_potential::_get_rzero(const molecular_id id1,
                                                const molecular_id id2) const {
  unordered_pair<molecular_id> key { id1, id2 };
  return _rzero_map.at(key);
}

double dipole_electric_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto &positions = sim.positions();
  double sum = 0.0;

  #pragma omp parallel for reduction(+:sum)
  for (auto i = size_t{0}; i < N; ++i) {
    auto& positionsi = positions.col(i);
    for (auto& kv : _efield)
      sum += -(positionsi(kv.first) * kv.second(positionsi));
  }

  return sum;

}

double dipole_electric_potential::_delta_U(const metropolis &sim,
  const size_t j, arma::vec &dx) const {

  auto& positionsj = sim.positions().col(j);

  double sum = 0.0;
  for (auto& kv : _efield)
    sum += -(dx(kv.first) * kv.second(positionsj));

  return sum;

}

arma::vec dipole_electric_potential::_forceij(const metropolis &sim,
    const size_t, const size_t) const { return arma::zeros(sim.D()); }

double abstract_dipole_strain_potential::_U(const metropolis &sim) const {

  const auto N = sim.N();
  const auto &positions = sim.positions();
  const auto &ids = sim.molecular_ids();
  double sum = 0.0;

  #pragma omp parallel for reduction(+:sum)
  for (auto i = size_t{0}; i < N; ++i) {

    auto& xsi = positions.col(i);
    auto pi = p(xsi);

    // Ui = 1/2 * p . X p
    sum += arma::dot(pi, inv_chi(xsi, ids[i]) * pi);

  }

  return 0.5 * sum;

}

double abstract_dipole_strain_potential::_delta_U(const metropolis &sim,
    const size_t j, arma::vec &dx) const {

  auto& xs = sim.positions().col(j);
  const auto id = sim.molecular_ids()[j];
  auto xs_new = xs + dx;

  auto pi = p(xs);
  auto pnew = p(xs_new);

  return 0.5 * (arma::dot(pi, inv_chi(xs, id) * pi) -
                arma::dot(pnew, inv_chi(xs_new, id) * pnew));

}

arma::vec abstract_dipole_strain_potential::_forceij
  (const metropolis &sim, const size_t, const size_t) const {
  return arma::zeros(sim.D());
}

// definitions for pure virtual destructors
abstract_potential::~abstract_potential() {}
abstract_LJ_potential::~abstract_LJ_potential() {}
abstract_LJ_full_potential::~abstract_LJ_full_potential() {}
abstract_LJ_lookup_potential::~abstract_LJ_lookup_potential() {}
abstract_LJ_cutoff_potential::~abstract_LJ_cutoff_potential() {}
abstract_spring_potential::~abstract_spring_potential() {}
abstract_dipole_strain_potential::~abstract_dipole_strain_potential() {}
abstract_dipole_strain_2d_potential::~abstract_dipole_strain_2d_potential() {}
abstract_dipole_strain_3d_potential::~abstract_dipole_strain_3d_potential() {}
abstract_dipole_strain_linear_potential::~abstract_dipole_strain_linear_potential() {}

} // namespace pauth

ext: cpp

max_stars_repo_name: grasingerm/port-authority

max_issues_repo_name: grasingerm/port-authority

max_forks_repo_name: grasingerm/port-authority


text:
#ifndef SODES_BOOSTODEINT_HPP
#define SODES_BOOSTODEINT_HPP

#include <Eigen/Core>
#include <boost/numeric/odeint.hpp>
#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>
#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>

#include <tuple>
#include <functional>
#include <vector>
#include <utility>
#include <stdexcept>

#include "math_types.hpp"

namespace sodes::detail::odeint {

using namespace boost::numeric::odeint;
using namespace Eigen;
using namespace std;

using namespace sodes::math_types;

typedef eigen_array_1d state_type;

struct Observer
{
    vector<state_type>& m_states;
    vector<double>& m_times;

    Observer(vector<state_type>& states, vector<double>& times)
        : m_states(states), m_times(times) {}

    void operator()(const state_type& x, const double& t)
    {
        m_states.push_back(x);
        m_times.push_back(t);
    }
};

template<typename Stepper>
pair<vector<double>, vector<state_type>> _integrate_const_stepper(
    const function<state_type(eigen_array_1d_constref, eigen_array_1d_ref, const double&)>& f,
    const tuple<double, double>& t_span,
    const double& dt,
    state_type& y0,
    Stepper stepper)
{
    // Containers to store solution
    vector<state_type> states;
    vector<double> times;

    // Integrate over time
    auto[t_init, t_final] = t_span;
    auto observer = Observer(states, times);
    integrate_const(
        stepper,
        f,
        y0,
        t_init,
        t_final,
        dt,
        observer);

    auto solution_pair = make_pair(times, states);

    return solution_pair;
}
}  // namespace sodes::detail::odeint

namespace sodes::odeint {

using namespace std;
using namespace Eigen;
using namespace sodes::math_types;

pair<vector<double>, vector<ArrayXd>> solve_ivp_const(
    const function<ArrayXd(eigen_array_1d_constref, eigen_array_1d_ref, const double&)>& f,
    const tuple<double, double>& t_span,
    const double& dt,
    ArrayXd& y0,
    const string& method = "runge_kutta4")
{
    using namespace sodes::detail::odeint;

    if (method == "runge_kutta4") {
        typedef runge_kutta4<state_type, double, state_type, double, vector_space_algebra> stepper;
        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());
    }
//    else if (method == "runge_kutta_dopri5") {
//        typedef runge_kutta_dopri5<state_type, double, state_type, double, vector_space_algebra> stepper;
//        auto dense_output = make_dense_output<stepper>(1e-6, 1e-6);
//        return _integrate_const_stepper<dense_output>(f, t_span, dt, y0, dense_output);
//    }
    else if (method == "runge_kutta_cash_karp54") {
        typedef runge_kutta_cash_karp54<state_type, double, state_type, double, vector_space_algebra> stepper;
        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());
    }
    else if (method == "runge_kutta_fehlberg78") {
        typedef runge_kutta_fehlberg78<state_type, double, state_type, double, vector_space_algebra> stepper;
        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());
    }
    else if (method == "modified_midpoint") {
        typedef modified_midpoint<state_type, double, state_type, double, vector_space_algebra> stepper;
        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());
    }
    else if (method == "euler") {
        typedef euler<state_type, double, state_type, double, vector_space_algebra> stepper;
        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());
    }
    else {
        throw invalid_argument("Unavailable integration method from Boost::odeint");
    }
}
}  // namespace sodes::odeint

#endif //SODES_BOOSTODEINT_HPP

max_stars_repo_name: volpatto/pysodes

max_issues_repo_name: volpatto/pysodes

max_forks_repo_name: volpatto/pysodes


text:
#include "share.h"

#include <stdexcept>
#include <tuple>
#include <set>
#include <string>

#include <univalue.h>
#include <libdevcore/logger.h>
#include <libdevcore/common.h>
#include <libdevcore/addr_store.h>
#include "tracker.h"
#include "data.h"
#include "share_builder.h"

using namespace std;

#include <boost/format.hpp>

#define CheckShareRequirement(field_name)               \
    if (!field_name)                                     \
        throw std::runtime_error(#field_name " == NULL");

void Share::init()
{
    CheckShareRequirement(min_header);
    CheckShareRequirement(share_data);
    CheckShareRequirement(share_info);
    CheckShareRequirement(ref_merkle_link);
    CheckShareRequirement(hash_link);
    CheckShareRequirement(merkle_link);

    bool segwit_activated = shares::is_segwit_activated(VERSION, net);
    if (segwit_activated && !segwit_data)
        throw std::runtime_error("Segwit activated, but segwit_data == nullptr!");

    if (!(coinbase->size() >= 2 && coinbase->size() <= 100))
    {
        throw std::runtime_error((boost::format("bad coinbase size! %1% bytes.") % coinbase->size()).str());
    }

    if ((*merkle_link)->branch.size() > 16)
    {
        throw std::runtime_error("Merkle branch too long#1!");
    }

    if (segwit_activated)
        if ((*segwit_data)->txid_merkle_link.branch.size() > 16)
            throw std::runtime_error("Merkle branch too long#1!");

    assert(hash_link->get()->extra_data.empty());

    new_script = coind::data::pubkey_hash_to_script2((*share_data)->pubkey_hash);

    if (net->net_name == "bitcoin" && *absheight > 3927800 && *desired_version == 16)
    {
        throw std::runtime_error("This is not a hardfork-supporting share!");
    }

//TODO: check txs
//    std::set<int32_t> n;
//    for share_count, tx_count in self.iter_transaction_hash_refs():
//      assert share_count < 110
//      if share_count == 0:
//          n.add(tx_count)
//    assert n == set(range(len(self.share_info['new_transaction_hashes'])))

    std::vector<unsigned char> hash_link_data;
    {
        auto ref_hash = shares::get_ref_hash(net, *share_info->get(), *ref_merkle_link->get());
        hash_link_data = ref_hash.data;

        IntType(64) _last_txout_nonce(last_txout_nonce);
        PackStream packed_last_txout_nonce;
        packed_last_txout_nonce << _last_txout_nonce;
        hash_link_data.insert(hash_link_data.begin(), packed_last_txout_nonce.data.begin(), packed_last_txout_nonce.data.end());

        IntType(32) _z(0);
        PackStream packed_z;
        packed_z << _z;
        hash_link_data.insert(hash_link_data.begin(), packed_z.data.begin(), packed_z.data.end());
    }

    gentx_hash = shares::check_hash_link(hash_link, hash_link_data, std::string(net->gentx_before_refhash.begin(),net->gentx_before_refhash.end()));
    auto merkle_root = coind::data::check_merkle_link(gentx_hash, segwit_activated ? (*segwit_data)->txid_merkle_link : *merkle_link->get());
    header.set_value(coind::data::types::BlockHeaderType(*min_header->get(), merkle_root));

    coind::data::stream::BlockHeaderType_stream header_stream(*header.get());
    PackStream packed_block_header;
    packed_block_header << header_stream;

    pow_hash = net->parent->POW_FUNC(packed_block_header);

    PackStream packed_block_header2;
    packed_block_header2 << header_stream;
    hash = coind::data::hash256(packed_block_header2);

    if (target > net->MAX_TARGET)
    {
        throw std::runtime_error("Share target invalid!"); //TODO: remake for c2pool::p2p::exception_from_peer
    }

    if (pow_hash > target)
    {
        throw std::runtime_error("Share PoW indalid!"); //TODO: remake for c2pool::p2p::exception_from_peer
    }
}
#undef CheckShareRequirement

void Share::check(std::shared_ptr<ShareTracker> _tracker, std::map<uint256, coind::data::tx_type> other_txs)
{
    if (*timestamp > (c2pool::dev::timestamp() + 600))
    {
        throw std::invalid_argument(
                (boost::format{"Share timestamp is %1% seconds in the future! Check your system clock."} %
                 (*timestamp - c2pool::dev::timestamp())).str());
    }

    std::map<uint64_t, uint256> counts;

    if (!previous_hash->IsNull())
    {
        auto previous_share = _tracker->get(*previous_hash);
        if (_tracker->get_height(*previous_hash) >= net->CHAIN_LENGTH)
        {
            //tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10
            counts = _tracker->get_desired_version_counts(
                    _tracker->get_nth_parent_hash(previous_share->hash, net->CHAIN_LENGTH * 9 / 10),
                    net->CHAIN_LENGTH / 10);

            //TODO: python check for version
//            if type(self) is type(previous_share):
//                pass
//              elif type(self) is type(previous_share).SUCCESSOR:
//                  # switch only valid if 60% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
//                  if counts.get(self.VERSION, 0) < sum(counts.itervalues())*60//100:
//                      raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
//              else:
//                  raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
        }
        //elif type(self) is type(previous_share).SUCCESSOR:
        //      raise p2p.PeerMisbehavingError('switch without enough history')
    }

    std::vector<uint256> other_tx_hashes;
    for (auto v: (*share_info)->transaction_hash_refs)
    {
        auto share_count = std::get<0>(v);
        auto tx_count = std::get<1>(v);

        other_tx_hashes.push_back(_tracker->get(_tracker->get_nth_parent_hash(hash,
                                                                              share_count))->share_info->get()->new_transaction_hashes[tx_count]);
    }

    // TODO: Check type in python???
    //if other_txs is not None and not isinstance(other_txs, dict): other_txs = dict((bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)), tx) for tx in other_txs)

    auto gentx_F = GenerateShareTransaction(_tracker);
    gentx_F.set_share_data(*share_data->get());
    gentx_F.set_block_target(FloatingInteger(header->bits).target()); //TODO: check
    gentx_F.set_desired_timestamp(*timestamp);
    gentx_F.set_desired_target(FloatingInteger((*share_info)->bits).target()); //TODO: check
    gentx_F.set_ref_merkle_link(*ref_merkle_link->get());
    {
        std::vector<std::tuple<uint256, std::optional<int32_t>>> _desired_other_transaction_hashes_and_fees;
        for (auto v: other_tx_hashes)
        {
            std::optional<int32_t> temp_value{};
            _desired_other_transaction_hashes_and_fees.emplace_back(v, temp_value);
        }
        gentx_F.set_desired_other_transaction_hashes_and_fees(_desired_other_transaction_hashes_and_fees);
    }
    gentx_F.set_known_txs(other_txs);
    gentx_F.set_last_txout_nonce(last_txout_nonce);
    if (segwit_data)
    {
        gentx_F.set_segwit_data(*segwit_data->get());
    }

    auto gentx = gentx_F(VERSION);

    //TODO: just check
//    assert other_tx_hashes2 == other_tx_hashes
//    if share_info != self.share_info:
//        raise ValueError('share_info invalid')
//    if bitcoin_data.get_txid(gentx) != self.gentx_hash:
//        raise ValueError('''gentx doesn't match hash_link''')
//    if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link: # the other hash commitments are checked in the share_info assertion
//        raise ValueError('merkle_link and other_tx_hashes do not match')

    //TODO: wanna for upd protocol version???
    // update_min_protocol_version(counts, self)

    //TODO: Нужно ли это делать в c2pool???
//    self.gentx_size = len(bitcoin_data.tx_id_type.pack(gentx))

    //    self.gentx_weight = len(bitcoin_data.tx_type.pack(gentx)) + 3*self.gentx_size
    {
        PackStream weight_stream;
        coind::data::stream::TransactionType_stream tx_type_data = gentx->gentx;
        weight_stream << tx_type_data;

        gentx_weight = weight_stream.size();
    }

//
//    type(self).gentx_size   = self.gentx_size # saving this share's gentx size as a class variable is an ugly hack, and you're welcome to hate me for doing it. But it works.
//            type(self).gentx_weight = self.gentx_weight

//TODO: При получении блока, нужно ли это?
// return gentx # only used by as_block
}

std::shared_ptr<Share> load_share(PackStream &stream, std::shared_ptr<c2pool::Network> net, addr_type peer_addr)
{
	PackedShareData packed_share;
	stream >> packed_share;

	PackStream _stream(packed_share.contents.value);

	ShareDirector director(net);
	switch (packed_share.type.value)
	{
		case 17:
			return director.make_share(packed_share.type.value, peer_addr, _stream);
		case 32:
			return director.make_preSegwitShare(packed_share.type.value, peer_addr, _stream);
		default:
			if (packed_share.type.value < 17)
				throw std::runtime_error("sent an obsolete share");
			else
				throw std::runtime_error((boost::format("unkown share type: %1") % packed_share.type.value).str());
			break;
	}
}

max_issues_repo_name: frstrtr/cpool

max_forks_repo_name: frstrtr/cpool


text:
#ifndef CSV_FILTER_RECORDFILTERBOX_H
#define CSV_FILTER_RECORDFILTERBOX_H

#include <boost/shared_ptr.hpp>

#include <QWidget>
#include <QtCore/qnamespace.h>

#include <QHBoxLayout>

#include "../../model/filter/node.hpp"

namespace CSMWorld
{
    class Data;
}

namespace CSVFilter
{
    class EditWidget;

    class RecordFilterBox : public QWidget
    {
            Q_OBJECT

            EditWidget *mEdit;

        public:

            RecordFilterBox (CSMWorld::Data& data, QWidget *parent = 0);

            void setFilter (const std::string& filter);

            void useFilterRequest(const std::string& idOfFilter);

            void createFilterRequest(std::vector<std::pair<std::string, std::vector<std::string> > >& filterSource,
                                     Qt::DropAction action);

        signals:

            void filterChanged (boost::shared_ptr<CSMFilter::Node> filter);
    };

}

#endif

max_stars_repo_name: Bodillium/openmw

max_issues_repo_name: Bodillium/openmw

max_forks_repo_name: Bodillium/openmw


text:
#ifndef BOOST_GIL_TIFF_TILED_READ_MACROS_HPP
#define BOOST_GIL_TIFF_TILED_READ_MACROS_HPP

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/tiff_read.hpp>

#include "paths.hpp"

typedef boost::gil::tiff_tag tag_t;

#define GENERATE_TILE_STRIP_COMPARISON_BIT_ALIGNED_RGB(z, n, data)\
    BOOST_AUTO_TEST_CASE( BOOST_PP_CAT( \
                                BOOST_PP_CAT( \
                                    BOOST_PP_CAT( \
                                        BOOST_PP_CAT( \
                                            BOOST_PP_CAT( read_tile_and_compare_with_ \
                                                        , BOOST_PP_TUPLE_ELEM(2,0,data) \
                                                        ) \
                                                , BOOST_PP_TUPLE_ELEM(2,1,data) \
                                                ) \
                                            ,_strip_ \
                                            ) \
                                        ,n \
                                        ) \
                                      , bit_bit_aligned \
                                      ) \
                        )\
    { \
      using namespace std; \
      using namespace boost; \
      using namespace gil; \
      string filename_strip( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2,0,data)) + "-strip-" + BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2,1,data)) + "-" ); \
      string filename_tile ( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2,0,data)) + "-tile-"  + BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2,1,data)) + "-" ); \
      string padding(""); \
      if(BOOST_PP_LESS(n, 10)==1) \
        padding = "0"; \
      filename_strip = filename_strip + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      filename_tile  = filename_tile  + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      bit_aligned_image3_type< n, n, n, rgb_layout_t >::type img_strip, img_tile; \
      read_image( filename_strip, img_strip, tag_t() ); \
      read_image( filename_tile,  img_tile,  tag_t() ); \
      BOOST_CHECK_EQUAL( equal_pixels( const_view(img_strip), const_view(img_tile) ), true); \
    } \

// Special case for minisblack images
#define GENERATE_TILE_STRIP_COMPARISON_BIT_ALIGNED_MINISBLACK(z, n, data)\
    BOOST_AUTO_TEST_CASE( BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(read_tile_and_compare_with_,data),_strip_),n), bit_bit_aligned) )\
    { \
      using namespace std; \
      using namespace boost; \
      using namespace gil; \
      string filename_strip( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(data) + "-strip-" ); \
      string filename_tile ( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(data) + "-tile-"  ); \
      string padding(""); \
      if(BOOST_PP_LESS(n, 10)==1) \
        padding = "0"; \
      filename_strip = filename_strip + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      filename_tile  = filename_tile  + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      bit_aligned_image1_type< n, gray_layout_t >::type img_strip, img_tile; \
      read_image( filename_strip, img_strip, tag_t() ); \
      read_image( filename_tile,  img_tile,  tag_t() ); \
      BOOST_CHECK_EQUAL( equal_pixels( const_view(img_strip), const_view(img_tile) ), true); \
    } \

// Special case for palette images
#define GENERATE_TILE_STRIP_COMPARISON_PALETTE(z, n, data)\
    BOOST_AUTO_TEST_CASE( BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(read_tile_and_compare_with_,data),_strip_),n), bit) )\
    { \
      using namespace std; \
      using namespace boost; \
      using namespace gil; \
      string filename_strip( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(data) + "-strip-" ); \
      string filename_tile ( tiff_in_GM + "tiger-" + BOOST_PP_STRINGIZE(data) + "-tile-"  ); \
      string padding(""); \
      if(BOOST_PP_LESS(n, 10)==1) \
        padding = "0"; \
      filename_strip = filename_strip + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      filename_tile  = filename_tile  + padding + BOOST_PP_STRINGIZE(n) + ".tif"; \
      rgb16_image_t img_strip, img_tile; \
      read_image( filename_strip, img_strip, tag_t() ); \
      read_image( filename_tile,  img_tile,  tag_t() ); \
      BOOST_CHECK_EQUAL( equal_pixels( const_view(img_strip), const_view(img_tile) ), true); \
    } \

#endif // BOOST_GIL_TIFF_TILED_READ_MACROS_HPP

max_stars_repo_name: smart-make/boost

max_issues_repo_name: smart-make/boost

max_forks_repo_name: smart-make/boost


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_anonymous_semaphoreA
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include "doc_anonymous_semaphore_shared_data.hpp"

using namespace boost::interprocess;

int main ()
{
   try{
      //Erase previous shared memory
      shared_memory_object::remove("shared_memory");

      //Create a shared memory object.
      shared_memory_object shm
         (create_only                  //only create
         ,"shared_memory"              //name
         ,read_write  //read-write mode
         );

      //Set size
      shm.truncate(sizeof(shared_memory_buffer));

      //Map the whole shared memory in this process
      mapped_region region
         (shm                       //What to map
         ,read_write //Map it as read-write
         );

      //Get the address of the mapped region
      void * addr       = region.get_address();

      //Construct the shared structure in memory
      shared_memory_buffer * data = new (addr) shared_memory_buffer;

      const int NumMsg = 100;

      //Insert data in the array
      for(int i = 0; i < NumMsg; ++i){
         data->nempty.wait();
         data->mutex.wait();
         data->items[i % shared_memory_buffer::NumItems] = i;
         data->mutex.post();
         data->nstored.post();
      }
   }
   catch(interprocess_exception &ex){
      shared_memory_object::remove("shared_memory");
      std::cout << ex.what() << std::endl;
      return 1;
   }

   //Erase shared memory
   shared_memory_object::remove("shared_memory");

   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>


text:
/*
 * Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under 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 <cetty/service/pool/WatermarkConnectionPool.h>

#include <boost/bind.hpp>
#include <cetty/channel/ChannelFuture.h>

namespace cetty {
namespace service {
namespace pool {

WatermarkConnectionPool::WatermarkConnectionPool(const Connections& connections)
    : ConnectionPool(connections),
      lowWatermark_(1),
      highWatermark_(0xffff) {
}

WatermarkConnectionPool::WatermarkConnectionPool(const Connections& connections,
        int lowWatermark,
        int highWatermark)
    : ConnectionPool(connections),
      lowWatermark_(lowWatermark),
      highWatermark_(highWatermark) {
}

WatermarkConnectionPool::WatermarkConnectionPool(const Connections& connections,
        const EventLoopPtr& eventLoop)
    : ConnectionPool(connections, eventLoop),
      lowWatermark_(1),
      highWatermark_(0xffff) {
}

WatermarkConnectionPool::WatermarkConnectionPool(const Connections& connections,
        const EventLoopPtr& eventLoop,
        int lowWatermark,
        int highWatermark)
    : ConnectionPool(connections, eventLoop),
      lowWatermark_(lowWatermark),
      highWatermark_(highWatermark) {
}

WatermarkConnectionPool::~WatermarkConnectionPool() {
}

void WatermarkConnectionPool::start() {
    ChannelFuturePtr future =
        bootstrap_.connect(connections_[0].host, connections_[0].port);

    future->addListener(boost::bind(
                            &ConnectionPool::connectedCallback,
                            this,
                            _1));
}

}
}
}


text:
// Warning! This file is autogenerated.
#ifndef BOOST_TEXT_DATA_LKT_HPP
#define BOOST_TEXT_DATA_LKT_HPP

#include <boost/text/string_view.hpp>

namespace boost { namespace text { namespace data { namespace lkt {

inline string_view standard_collation_tailoring()
{
    return string_view(
u8R"(
&C<č<<<Č
&G<ǧ<<<Ǧ
&H<ȟ<<<Ȟ
&S<š<<<Š
&Z<ž<<<Ž
  )");
}

}}}}

#endif

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


text:
/*=============================================================================
    Copyright (c) 2001-2014 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_X3_ANY_CHAR_APRIL_16_2006_1051AM)
#define BOOST_SPIRIT_X3_ANY_CHAR_APRIL_16_2006_1051AM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/x3/char/literal_char.hpp>

namespace boost { namespace spirit { namespace x3
{
    template <typename Encoding>
    struct any_char : char_parser<any_char<Encoding>>
    {
        typedef typename Encoding::char_type char_type;
        typedef Encoding encoding;
        typedef char_type attribute_type;
        static bool const has_attribute = true;

        template <typename Char, typename Context>
        bool test(Char ch_, Context const&) const
        {
            return ((sizeof(Char) <= sizeof(char_type)) || encoding::ischar(ch_));
        }

        template <typename Char>
        literal_char<Encoding>
        operator()(Char ch) const
        {
            return literal_char<Encoding>(ch);
        }
    };
}}}

#endif