text:
///////////////////////////////////////////////////////////////
//  Copyright 2021 John Maddock. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#include <iostream>
#include <boost/math/special_functions/relative_difference.hpp>
#include <boost/math/special_functions/next.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/multiprecision/debug_adaptor.hpp>

//[scoped_precision_1

/*`
All our precision changing examples are based around `mpfr_float`.
However, in order to make running this example a little easier to debug,
we'll use `debug_adaptor` throughout so that the values of all variables
can be displayed in your debugger of choice:
*/

using mp_t = boost::multiprecision::debug_adaptor_t<boost::multiprecision::mpfr_float>;

/*`
Our first example will investigate calculating the Bessel J function via it's well known
series representation:

[$../bessel2.svg]

This simple series suffers from catastrophic cancellation error
near the roots of the function, so we'll investigate slowly increasing the precision of
the calculation until we get the result to N-decimal places.  We'll begin by defining
a function to calculate the series for Bessel J, the details of which we'll leave in the
source code:
*/
mp_t calculate_bessel_J_as_series(mp_t x, mp_t v, mp_t* err)
//<-
{
   mp_t sum        = pow(x / 2, v) / tgamma(v + 1);
   mp_t abs_sum    = abs(sum);
   mp_t multiplier = -x * x / 4;
   mp_t divider    = v + 1;
   mp_t term       = sum;
   mp_t eps        = boost::math::tools::epsilon<mp_t>();
   unsigned   m          = 1;

   while (fabs(term / abs_sum) > eps)
   {
      term *= multiplier;
      term /= m;
      term /= divider;
      ++divider;
      ++m;
      sum += term;
      abs_sum += abs(term);
   }
   if (err)
      *err = eps * fabs(abs_sum / sum);
   /*
   std::cout << eps << std::endl;
   if (err)
      std::cout << *err << std::endl;
   std::cout << abs_sum << std::endl;
   std::cout << sum << std::endl;
   */
   return sum;
}
//->

/*`
Next come some simple helper classes, these allow us to modify the current precision and precision-options
via scoped objects which will put everything back as it was at the end.  We'll begin with the class to
modify the working precision:
*/
struct scoped_mpfr_precision
{
   unsigned saved_digits10;
   scoped_mpfr_precision(unsigned digits10) : saved_digits10(mp_t::thread_default_precision())
   {
      mp_t::thread_default_precision(digits10);
   }
   ~scoped_mpfr_precision()
   {
      mp_t::thread_default_precision(saved_digits10);
   }
   void reset(unsigned digits10)
   {
      mp_t::thread_default_precision(digits10);
   }
   void reset()
   {
      mp_t::thread_default_precision(saved_digits10);
   }
};
/*`
And a second class to modify the precision options:
*/
struct scoped_mpfr_precision_options
{
   boost::multiprecision::variable_precision_options saved_options;
   scoped_mpfr_precision_options(boost::multiprecision::variable_precision_options opts) : saved_options(mp_t::thread_default_variable_precision_options())
   {
      mp_t::thread_default_variable_precision_options(opts);
   }
   ~scoped_mpfr_precision_options()
   {
      mp_t::thread_default_variable_precision_options(saved_options);
   }
   void reset(boost::multiprecision::variable_precision_options opts)
   {
      mp_t::thread_default_variable_precision_options(opts);
   }
};
/*`
We can now begin writing a function to calculate J[sub v](z) to a specified precision.
In order to keep the logic as simple as possible, we'll adopt a ['uniform precision computing] approach,
which is to say, within the body of the function, all variables are always at the same working precision.
*/
mp_t Bessel_J_to_precision(mp_t v, mp_t x, unsigned digits10)
{
   //
   // Begin by backing up digits10:
   //
   unsigned saved_digits10 = digits10;
   //
   //
   // Start by defining 2 scoped objects to control precision and associated options.
   // We'll begin by setting the working precision to the required target precision,
   // and since all variables will always be of uniform precision, we can tell the
   // library to ignore all precision control by setting variable_precision_options::assume_uniform_precision:
   //
   scoped_mpfr_precision           scoped(digits10);
   scoped_mpfr_precision_options   scoped_opts(boost::multiprecision::variable_precision_options::assume_uniform_precision);

   mp_t            result;
   mp_t            current_error{1};
   mp_t            target_error {std::pow(10., -static_cast<int>(digits10))};

   while (target_error < current_error)
   {
      //
      // Everything must be of uniform precision in here, including
      // our input values, so we'll begin by setting their precision:
      //
      v.precision(digits10);
      x.precision(digits10);
      //
      // Calculate our approximation and error estimate:
      //
      result = calculate_bessel_J_as_series(x, v, &current_error);
      //
      // If the error from the current approximation is too high we'll need
      // to loop round and try again, in this case we use the simple heuristic
      // of doubling the working precision with each loop.  More refined approaches
      // are certainly available:
      //
      digits10 *= 2;
      scoped.reset(digits10);
   }
   //
   // We now have an accurate result, but it may have too many digits,
   // so lets round the result to the requested precision now:
   //
   result.precision(saved_digits10);
   //
   // To maintain uniform precision during function return, lets
   // reset the default precision now:
   //
   scoped.reset(saved_digits10);
   return result;
}

/*`
So far, this is all well and good, but there is still a potential trap for the unwary here,
when the function returns the variable [/result] may be copied/moved either once or twice
depending on whether the compiler implements the named-return-value optimisation.  And since this
all happens outside the scope of this function, the precision of the returned value may get unexpected
changed - and potentially with different behaviour once optimisations are turned on!

To prevent these kinds of unintended consequences, a function returning a value with specified precision
must either:

* Be called in a /uniform-precision-environment/, with the current working precision, the same as both
the returned value and the variable to which the result will be assigned.
* Be called in an environment that has one of the following set:
   * variable_precision_options::preserve_source_precision
   * variable_precision_options::preserve_component_precision
   * variable_precision_options::preserve_related_precision
   * variable_precision_options::preserve_all_precision

In the case of our example program, we use a /uniform-precision-environment/ and call the function
with the value of `6541389046624379 / 562949953421312` which happens to be near a root of J[sub v](x)
and requires a high-precision calculation to obtain low relative error in the result of
`-9.31614245636402072613249153246313221710284959883647822724e-15`.

You will note in the example we have so far that there are a number of unnecessary temporaries
created: we pass values to our functions by value, and we call the `.precision()` member function
to change the working precision of some variables - something that requires a reallocation internally.
We'll now make our example just a little more efficient, by removing these temporaries, though in the
process, we'll need just a little more control over how mixed-precision arithmetic behaves.

It's tempting to simply define the function that calculates the series to take arguments
by constant reference like so:

*/

mp_t calculate_bessel_J_as_series_2(const mp_t& x, const mp_t& v, mp_t* err)
//<-
{
   mp_t sum        = pow(x / 2, v) / tgamma(v + 1);
   mp_t abs_sum    = abs(sum);
   mp_t multiplier = -x * x / 4;
   mp_t divider    = v + 1;
   mp_t term       = sum;
   mp_t eps        = boost::math::tools::epsilon<mp_t>();
   unsigned   m          = 1;

   while (fabs(term / abs_sum) > eps)
   {
      term *= multiplier;
      term /= m;
      term /= divider;
      ++divider;
      ++m;
      sum += term;
      abs_sum += abs(term);
   }
   if (err)
      *err = eps * fabs(abs_sum / sum);

   return sum;
}
//->

/*`
And to then pass our arguments to it, without first altering their precision to match
the current working default.  However, imagine that `calculate_bessel_J_as_series_2`
calculates x[super 2] internally, what precision is the result?  If it's the same as the
precision of /x/, then our calculation will loose precision, since we really want the result
calculated to the full current working precision, which may be significantly higher than
that of our input variables.  Our new version of Bessel_J_to_precision therefore uses
`variable_precision_options::preserve_target_precision` internally, so that expressions
containing only the low-precision input variables are calculated at the precision of
(at least) the target - which will have been constructed at the current working precision.

Here's our revised code:

*/

mp_t Bessel_J_to_precision_2(const mp_t& v, const mp_t& x, unsigned digits10)
{
   //
   // Begin with 2 scoped objects, one to manage current working precision, one to
   // manage mixed precision arithmetic.  Use of variable_precision_options::preserve_target_precision
   // ensures that expressions containing only low-precision input variables are evaluated at the precision
   // of the variable they are being assigned to (ie current working precision).
   //
   scoped_mpfr_precision scoped(digits10);
   scoped_mpfr_precision_options scoped_opts(boost::multiprecision::variable_precision_options::preserve_target_precision);

   mp_t                    result;
   mp_t            current_error{1};
   mp_t            target_error{std::pow(10., -static_cast<int>(digits10))};

   while (target_error < current_error)
   {
      //
      // The assignment here, rounds the high precision result
      // returned by calculate_bessel_J_as_series_2, to the precision
      // of variable result: ie to the target precision we specified in
      // the function call.  This is only the case because we have
      // variable_precision_options::preserve_target_precision set.
      //
      result = calculate_bessel_J_as_series_2(x, v, &current_error);

      digits10 *= 2;
      scoped.reset(digits10);
   }
   //
   // There may be temporaries created when we return, we must make sure
   // that we reset the working precision and options before we return.
   // In the case of the options, we must preserve the precision of the source
   // object during the return, not only here, but in the calling function too:
   //
   scoped.reset();
   scoped_opts.reset(boost::multiprecision::variable_precision_options::preserve_source_precision);
   return result;
}

/*`
In our final example, we'll look at a (somewhat contrived) case where we reduce the argument
by N * PI, in this case we change the mixed-precision arithmetic options several times,
depending what it is we are trying to achieve at that moment in time:

*/
mp_t reduce_n_pi(const mp_t& arg)
{
   //
   // We begin by estimating how many multiples of PI we will be reducing by,
   // note that this is only an estimate because we're using low precision
   // arithmetic here to get a quick answer:
   //
   unsigned n = static_cast<unsigned>(arg / boost::math::constants::pi<mp_t>());
   //
   // Now that we have an estimate for N, we can up the working precision and obtain
   // a high precision value for PI, best to play safe and preserve the precision of the
   // source here.  Though note that expressions are evaluated at the highest precision
   // of any of their components: in this case that's the current working precision
   // returned by boost::math::constants::pi, and not the precision of arg.
   // However, should this function be called with assume_uniform_precision set
   // then all bets are off unless we do this:
   //
   scoped_mpfr_precision            scope_1(mp_t::thread_default_precision() * 2);
   scoped_mpfr_precision_options    scope_2(boost::multiprecision::variable_precision_options::preserve_source_precision);

   mp_t reduced = arg - n * boost::math::constants::pi<mp_t>();
   //
   // Since N was only an estimate, we may have subtracted one PI too many,
   // correct if that's the case now:
   //
   if (reduced < 0)
      reduced += boost::math::constants::pi<mp_t>();
   //
   // Our variable "reduced" now has the correct answer, but too many digits precision,
   // we can either call its .precision() member function, or assign to a new variable
   // with variable_precision_options::preserve_target_precision set:
   //
   scope_1.reset();
   scope_2.reset(boost::multiprecision::variable_precision_options::preserve_target_precision);
   mp_t result = reduced;
   //
   // As with previous examples, returning the result may create temporaries, so lets
   // make sure that we preserve the precision of result.  Note that this isn't strictly
   // required if the calling context is always of uniform precision, but we can't be sure
   // of our calling context:
   //
   scope_2.reset(boost::multiprecision::variable_precision_options::preserve_source_precision);
   return result;
}

/*`
And finally... we need to mention `preserve_component_precision`, `preserve_related_precision` and `preserve_all_precision`.

These form a hierarchy, with each inheriting the properties of those before it.
`preserve_component_precision` is used when dealing with complex or interval numbers, for example if we have:

   mpc_complex val = some_expression;

And `some_expression` contains scalar values of type `mpfr_float`, then the precision of these is ignored unless
we specify at least `preserve_component_precision`.

`preserve_related_precision` we'll somewhat skip over - it extends the range of types whose precision is
considered within an expression to related types - for example all instantiations of `number<mpfr_float_backend<N>, ET>`
when dealing with expression of type `mpfr_float`.  However, such situations are - and should be -  very rare.

The final option - `preserve_all_precision` - is used to preserve the precision of all the types in an expression,
for example:

   // calculate 2^1000 - 1:
   mpz_int i(1);
   i <<= 1000;
   i -= 1;

   mp_t f = i;

The final assignment above will round the value in /i/ to the current working precision, unless `preserve_all_precision`
is set, in which case /f/ will end up with sufficient precision to store /i/ unchanged.

*/

//]

int main()
{
   mp_t::thread_default_precision(50);
   mp_t x{6541389046624379uLL};
   x /= 562949953421312uLL;
   mp_t v{2};
   mp_t err;
   mp_t J = Bessel_J_to_precision(v, x, 50);

   std::cout << std::setprecision(50) << J << std::endl;
   std::cout << J.precision() << std::endl;

   mp_t expected{"-9.31614245636402072613249153246313221710284959883647822724e-15"};
   std::cout << boost::math::relative_difference(expected, J) << std::endl;

   J = Bessel_J_to_precision_2(v, x, 50);
   std::cout << boost::math::relative_difference(expected, J) << std::endl;
   std::cout << J.precision() << std::endl;

   std::cout << reduce_n_pi(boost::math::float_next(boost::math::float_next(5 * boost::math::constants::pi<mp_t>()))) << std::endl;

   return 0;
}


text:
// Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.

#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/list.hpp>
#include <boost/python/overloads.hpp>
#include <boost/python/return_internal_reference.hpp>

#if defined(_AIX) && defined(__EDG_VERSION__) && __EDG_VERSION__ < 245
# include <iostream> // works around a KCC intermediate code generation bug
#endif

using namespace boost::python;

char const* const format = "int(%s); char(%s); string(%s); double(%s); ";

///////////////////////////////////////////////////////////////////////////////
//
//  Overloaded functions
//
///////////////////////////////////////////////////////////////////////////////
object
bar(int a, char b, std::string c, double d)
{
    return format % make_tuple(a, b, c, d);
}

object
bar(int a, char b, std::string c)
{
    return format % make_tuple(a, b, c, 0.0);
}

object
bar(int a, char b)
{
    return format % make_tuple(a, b, "default", 0.0);
}

object
bar(int a)
{
    return format % make_tuple(a, 'D', "default", 0.0);
}

BOOST_PYTHON_FUNCTION_OVERLOADS(bar_stubs, bar, 1, 4)

///////////////////////////////////////////////////////////////////////////////
//
//  Functions with default arguments
//
///////////////////////////////////////////////////////////////////////////////
object
foo(int a, char b = 'D', std::string c = "default", double d = 0.0)
{
    return format % make_tuple(a, b, c, d);
}

BOOST_PYTHON_FUNCTION_OVERLOADS(foo_stubs, foo, 1, 4)

///////////////////////////////////////////////////////////////////////////////
//
//  Overloaded member functions with default arguments
//
///////////////////////////////////////////////////////////////////////////////
struct Y {

    Y() {}

    object
    get_state() const
    {
        return format % make_tuple(a, b, c, d);
    }

    int a; char b; std::string c; double d;
};

struct X {

    X() {}

    X(int a, char b = 'D', std::string c = "constructor", double d = 0.0)
    : state(format % make_tuple(a, b, c, d))
    {}

    X(std::string s, bool b)
    : state("Got exactly two arguments from constructor: string(%s); bool(%s); " % make_tuple(s, b))
    {}

    object
    bar(int a, char b = 'D', std::string c = "default", double d = 0.0) const
    {
        return format % make_tuple(a, b, c, d);
    }

    Y const&
    bar2(int a = 0, char b = 'D', std::string c = "default", double d = 0.0)
    {
        // tests zero arg member function and return_internal_reference policy
        y.a = a;
        y.b = b;
        y.c = c;
        y.d = d;
        return y;
    }

    object
    foo(int a, bool b=false) const
    {
        return "int(%s); bool(%s); " % make_tuple(a, b);
    }

    object
    foo(std::string a, bool b=false) const
    {
        return "string(%s); bool(%s); " % make_tuple(a, b);
    }

    object
    foo(list a, list b, bool c=false) const
    {
        return "list(%s); list(%s); bool(%s); " % make_tuple(a, b, c);
    }

    object
    get_state() const
    {
        return state;
    }

    Y y;
    object state;
};

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_bar_stubs, bar, 1, 4)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_bar_stubs2, bar2, 0, 4)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_foo_2_stubs, foo, 1, 2)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_foo_3_stubs, foo, 2, 3)

///////////////////////////////////////////////////////////////////////////////

BOOST_PYTHON_MODULE(defaults_ext)
{
    def("foo", foo, foo_stubs());
    def("bar", (object(*)(int, char, std::string, double))0, bar_stubs());

    class_<Y>("Y", init<>("doc of Y init")) // this should work
	    .def("get_state", &Y::get_state)
        ;

    class_<X>("X")

        .def(init<int, optional<char, std::string, double> >("doc of init"))
        .def(init<std::string, bool>()[default_call_policies()]) // what's a good policy here?
        .def("get_state", &X::get_state)
        .def("bar", &X::bar, X_bar_stubs())
        .def("bar2", &X::bar2, X_bar_stubs2("doc of X::bar2")[return_internal_reference<>()])
        .def("foo", (object(X::*)(std::string, bool) const)0, X_foo_2_stubs())
        .def("foo", (object(X::*)(int, bool) const)0, X_foo_2_stubs())
        .def("foo", (object(X::*)(list, list, bool) const)0, X_foo_3_stubs())
        ;
}

#include "module_tail.cpp"

ext: cpp


text:
#include "stdafx.h"
#include "CppUnitTest.h"
#include "../SMProxy20/SMProxy2.h"
#include <boost/date_time/gregorian/conversion.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "../SMProxy20/Utils.hpp"
#include <vector>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UnitTest1
{
	TEST_CLASS(UnitTest1)
	{
	public:

		TEST_METHOD(TestMethod1)
		{
			// TODO: 在此输入测试代码
			int a = 1;
			int b = 2;
			int c = Sum(a , b);
			Assert::AreEqual(c, 3);

		}
		TEST_METHOD(TestMethod2)
		{
			// TODO: 在此输入测试代码
			char a[20];
			Hello(20,a);
			Assert::AreEqual(a, "hello world");

		}
		TEST_METHOD(TestMethod3)
		{
			// TODO: 在此输入测试代码
			auto timeTemp = boost::posix_time::second_clock::local_time();
			auto str1 =  Utils::getTimeStr(3);
			auto td = timeTemp.time_of_day();
			auto date = timeTemp.date();
			using std::string;
			using std::to_string;

			tm t = to_tm(date);
			tm t2 = to_tm(td);

			//string YY = std::to_string(t.tm_year + 1900);
			//YY.erase(0, 2);
			string MM = to_string(t.tm_mon + 1);
			if (MM.size() == 1)
			{
				MM.insert(MM.begin(), '0');
			}
			string DD = to_string(t.tm_mday);
			if (DD.size() == 1)
			{
				DD.insert(DD.begin(), '0');
			}
			string HH = to_string(t2.tm_hour);
			if (HH.size() == 1)
			{
				HH.insert(HH.begin(), '0');
			}
			string MI = to_string(t2.tm_min);
			if (MI.size() == 1)
			{
				MI.insert(MI.begin(), '0');
			}
			auto SS = to_string(t2.tm_sec);
			if (SS.size() == 1)
			{
				SS.insert(SS.begin(), '0');
			}
			string str = MM + DD + HH + MI + SS;

			Assert::AreEqual(str1, str);

		}
		TEST_METHOD(TestMethod4)
		{
			// TODO: 在此输入测试代码
			std::vector<int> str;
			str.push_back(1);
			auto iter = str.begin();

			int a = 0;
			if (str.end() == str.end())
			{
				int a = 1;
			}
			Assert::AreEqual(1, a);
		}
	};
}


text:
#include <boost/test/unit_test.hpp>

#include <fc/static_variant.hpp>

BOOST_AUTO_TEST_SUITE(fc_variant_and_log)

BOOST_AUTO_TEST_CASE( types_edge_cases_test )
{

   class sv : public fc::static_variant<>
   {
   public:
      BOOST_ATTRIBUTE_UNUSED typedef fc::static_variant<>::tag_type tag_type;
   };

   BOOST_TEST_MESSAGE( "========== Test empty static_variant ==========" );

   BOOST_CHECK_THROW( fc::static_variant<>(), fc::assert_exception );

   BOOST_TEST_MESSAGE( "========== Test static_variant with tag_type ==========" );

   sv::tag_type init_value = 2;
   fc::static_variant< sv::tag_type, std::string, fc::variant > variant_with_tagtype(init_value);

   BOOST_CHECK_EQUAL( variant_with_tagtype.count(), 3 );
   BOOST_CHECK_EQUAL( variant_with_tagtype.which(), 0 );

   sv::tag_type current_value = variant_with_tagtype.get<sv::tag_type>();
   BOOST_CHECK_EQUAL( current_value, init_value );
   BOOST_CHECK( variant_with_tagtype == init_value );

   for (sv::tag_type i = variant_with_tagtype.count(); i-->0;)
   {
      variant_with_tagtype.set_which(i);
      BOOST_CHECK_EQUAL(variant_with_tagtype.which(), i);
   }

   BOOST_TEST_MESSAGE( "========== Test static_variant with static_variant ==========" );

   using sv_double = fc::static_variant<double>;
   using sv_float = fc::static_variant<float>;
   fc::static_variant< sv_float, std::string, sv_double > variant;
   sv_float variant_float = 1.5f;
   variant = variant_float;
   BOOST_CHECK_EQUAL( variant.which(), 0 );
   BOOST_CHECK_EQUAL( variant.get<sv_float>().get<float>(), 1.5f );

   sv_double variant_double = 1.0;
   variant = variant_double;
   BOOST_CHECK_EQUAL( variant.which() , 2);
   BOOST_CHECK_EQUAL( variant.get<sv_double>().get<double>(), 1.0 );
}

BOOST_AUTO_TEST_CASE(mutable_variant_object_test)
{
    // no BOOST_CHECK / BOOST_REQUIRE, just see that this compiles on all supported platforms
    try {
        fc::variant v(42);
        fc::variant_object vo;
        fc::mutable_variant_object mvo;
        fc::variants vs;
        vs.push_back(fc::mutable_variant_object("level", "debug")("color", v));
        vs.push_back(fc::mutable_variant_object()("level", "debug")("color", v));
        vs.push_back(fc::mutable_variant_object("level", "debug")("color", "green"));
        vs.push_back(fc::mutable_variant_object()("level", "debug")("color", "green"));
        vs.push_back(fc::mutable_variant_object("level", "debug")(vo));
        vs.push_back(fc::mutable_variant_object()("level", "debug")(mvo));
        vs.push_back(fc::mutable_variant_object("level", "debug").set("color", v));
        vs.push_back(fc::mutable_variant_object()("level", "debug").set("color", v));
        vs.push_back(fc::mutable_variant_object("level", "debug").set("color", "green"));
        vs.push_back(fc::mutable_variant_object()("level", "debug").set("color", "green"));
    }
    FC_LOG_AND_RETHROW();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: SophiaTX/SophiaTx-Blockchain

max_issues_repo_name: SophiaTX/SophiaTx-Blockchain

max_forks_repo_name: SophiaTX/SophiaTx-Blockchain


text:
/**
* @file    Resource.cpp
* @author  Sebastian Maisch <sebastian.maisch@googlemail.com>
* @date    2014.03.29
*
* @brief   Implementations for the resource class.
*/

#include "Resource.h"
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/filesystem.hpp>
#include "app/ApplicationBase.h"
#include "app/Configuration.h"

namespace cgu {
    /**
     * Constructor.
     * @param resourceId the resource id to use
     * @param app the application object for dependencies
     */
    Resource::Resource(const std::string& resourceId, ApplicationBase* app) :
        application(app),
        id(GetNormalizedResourceId(resourceId))
    {
        boost::split(subresourceIds, id, boost::is_any_of("|"));
        for (auto& sr : subresourceIds) boost::trim(sr);

        if (subresourceIds.size() == 1) {
            boost::split(parameters, subresourceIds[0], boost::is_any_of(","));
            for (auto& param : parameters) {
                boost::trim(param);
                std::string name, value;
                if (parseNamedValue(param, name, value)) {
                    namedParameters.insert(std::make_pair(name, value));
                } else if (parseNamedFlag(param, name)) {
                    namedParameters.insert(std::make_pair(name, ""));
                }
            }
        }
    };

    /** Default copy constructor. */
    Resource::Resource(const Resource&) = default;

    /** Default assignment operator. */
    Resource& Resource::operator=(const Resource&) = default;

    /** Move constructor. */
    Resource::Resource(Resource&& orig) :
        application(std::move(orig.application)),
        id(std::move(orig.id))
    {
        orig.application = nullptr;
    };

    /** Move assignment operator. */
    Resource& Resource::operator=(Resource&& orig)
    {
        if (this != &orig) {
            this->~Resource();
            id = std::move(orig.id);
            application = orig.application;
            orig.application = nullptr;
        }
        return *this;
    };

    Resource::~Resource() = default;

    /**
    * Accessor to the resources id.
    * @return the resources id
    */
    const std::string& Resource::getId() const
    {
        return id;
    };

    std::string Resource::GetNamedParameterString(const std::string& name) const
    {
        auto it = namedParameters.find(name);
        if (it != namedParameters.end()) return it->second;
        return "";
    }

    bool Resource::CheckNamedParameterFlag(const std::string& name) const
    {
        return namedParameters.find(name) != namedParameters.end();
    }

    bool Resource::parseNamedValue(const std::string& str, std::string& name, std::string& value)
    {
        const boost::regex nameValueRegex("^-([\\w-]*)=(.*)$");
        boost::smatch paramMatch;
        if (boost::regex_match(str, paramMatch, nameValueRegex)) {
            name = paramMatch[1].str();
            value = paramMatch[2].str();
            return true;
        }
        return false;
    }

    bool Resource::parseNamedFlag(const std::string& str, std::string& name)
    {
        const boost::regex flagRegex("^-([\\w-]*)$");
        boost::smatch paramMatch;
        if (boost::regex_match(str, paramMatch, flagRegex)) {
            name = paramMatch[1].str();
            return true;
        }
        return false;
    }

    /**
         *  Returns the normalized resource id (no global parameters).
         *  @param the resource id.
         *  @return the normalized resource id.
         */
    std::string Resource::GetNormalizedResourceId(const std::string& resId)
    {
        std::vector<std::string> subresourcesAndGlobalParams;
        boost::split_regex(subresourcesAndGlobalParams, resId, boost::regex("\\|,"));
        for (auto& sr : subresourcesAndGlobalParams) boost::trim(sr);

        SubResourceList subresources;
        boost::split(subresources, subresourcesAndGlobalParams[0], boost::is_any_of("|"));
        for (auto& sr : subresources) {
            boost::trim(sr);
            if (subresourcesAndGlobalParams.size() > 1) sr += "," + subresourcesAndGlobalParams[1];
        }
        return boost::join(subresources, "|");
    }

    /**
     *  Returns the actual location of the resource by looking into all search paths.
     *  @param localFilename the file name local to any resource base directory.
     *  @return the path to the resource.
     */
    std::string Resource::FindResourceLocation(const std::string& localFilename) const
    {
        auto filename = application->GetConfig().resourceBase + "/" + localFilename;
        if (boost::filesystem::exists(filename)) return filename;

        for (const auto& dir : application->GetConfig().resourceDirs) {
            filename = dir + "/" + localFilename;
            if (boost::filesystem::exists(filename)) return filename;
        }

        LOG(ERROR) << L"Cannot find local resource file \"" << localFilename.c_str() << L"\".";
        throw resource_loading_error() << ::boost::errinfo_file_name(localFilename) << resid_info(id)
            << errdesc_info("Cannot find local resource file.");
    }
}


text:
/*
 * Copyright (C) 2016 by Gerrit Daniels <gerrit.daniels@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. 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 OWNER 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.
 */

#ifndef CREATE_REFLECTION_INFO_HPP_
#define CREATE_REFLECTION_INFO_HPP_

#include <boost/mpl/vector.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/push_front.hpp>

namespace reflection {

   class NullType {};

   template <int i_>
   class Int2Type {};

   template <template<int, class> class reflection_info_, int start_, int end_>
   struct create_reflection_info_impl {
      typedef typename reflection_info_<start_, NullType>::present present;

      typedef typename create_reflection_info_impl<reflection_info_, start_ + 1, end_>::result next;

      typedef typename boost::mpl::if_<present, typename boost::mpl::push_front<next, reflection_info_<start_, NullType>>::type, next>::type result;
   };

   template <template<int, class> class reflection_info_, int end_>
   struct create_reflection_info_impl<reflection_info_, end_, end_> {
      typedef boost::mpl::vector<> result;
   };

   template <template<int, class> class reflection_info_, int max_>
   struct create_reflection_info {
      typedef typename create_reflection_info_impl<reflection_info_, 0, max_>::result result;
   };

}

#endif // CREATE_REFLECTION_INFO_HPP_

ext: hpp

max_stars_repo_name: gerritdaniels/reflection

max_issues_repo_name: gerritdaniels/reflection

max_forks_repo_name: gerritdaniels/reflection


text:
/**
 ** Isaac Genome Alignment Software
 ** Copyright (c) 2010-2017 Illumina, Inc.
 ** All rights reserved.
 **
 ** This software is provided under the terms and conditions of the
 ** GNU GENERAL PUBLIC LICENSE Version 3
 **
 ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
 ** along with this program. If not, see
 ** <https://github.com/illumina/licenses/>.
 **
 ** \file .cpp
 **
 ** Command line options for extractNeighbors
 **
 ** \author Roman Petrovski
 **/

#ifndef iSAAC_OPTIONS_EXTRACT_NEIGHBORS_OPTIONS_HH
#define iSAAC_OPTIONS_EXTRACT_NEIGHBORS_OPTIONS_HH

#include <string>
#include <boost/filesystem.hpp>

#include "common/Program.hh"

namespace isaac
{
namespace options
{

class ExtractNeighborsOptions  : public common::Options
{
public:
    unsigned seedLength;
    boost::filesystem::path sortedReferenceMetadata_;
    boost::filesystem::path outputFilePath_;
    boost::filesystem::path highRepeatsFilePath_;

public:
    ExtractNeighborsOptions();

    common::Options::Action parse(int argc, char *argv[]);

private:
    std::string usagePrefix() const {return "extractNeighbors";}
    void postProcess(boost::program_options::variables_map &vm);
    void verifyMandatoryPaths(boost::program_options::variables_map &vm);
};

} // namespace options
} // namespace isaac

#endif // #ifndef iSAAC_OPTIONS_EXTRACT_NEIGHBORS_OPTIONS_HH

ext: hh


text:
#define PY_ARRAY_UNIQUE_SYMBOL pbcvt_ARRAY_API

#include <boost/python.hpp>
#include <pyboostcvconverter/pyboostcvconverter.hpp>
#include <boost/thread/thread.hpp>
#include <boost/chrono/chrono.hpp>
#include <csignal>
#include <iostream>
#include <thread>
#include <future>

#include "pupiltracker/PupilTracker.h"
#include "pupiltracker/cvx.h"
#include "findEyeCenter.h"

volatile unsigned long mainThread;

unsigned long getThreadId(){
	std::string threadId = boost::lexical_cast<std::string>(boost::this_thread::get_id());
	unsigned long threadNumber = 0;
	sscanf(threadId.c_str(), "%lx", &threadNumber);
	return threadNumber;
}

static void handler(int signo) {
	if (signo == 30) {
		if (getThreadId() != mainThread) {
			/* throw boost::thread_interrupted(); */
		}
		std::cout<<getThreadId()<<"\n";
	}
}

namespace pbcvt {

	using namespace boost::python;

	tuple findPupil(cv::Mat face, int ex, int ey, int ew, int eh) {

		cv::Rect eyeROI;
		eyeROI.x = ex;
		eyeROI.y = ey;
		eyeROI.width = ew;
		eyeROI.height = eh;

		cv::Point p = findEyeCenter(face, eyeROI, "");
		tuple ret = make_tuple(p.x,p.y);

		return ret;
	}

	void tryFindPupilEllipse(cv::Mat *eye, cv::RotatedRect *el) {
		cv::Mat1f mat = cv::Mat1f::zeros(1, 5);

		pupiltracker::tracker_log log;

		pupiltracker::TrackerParams pupil_tracker_params;
		pupil_tracker_params.Radius_Min = 20;
		pupil_tracker_params.Radius_Max = 80;
		pupil_tracker_params.CannyThreshold1 = 20;
		pupil_tracker_params.CannyThreshold2 = 40;
		pupil_tracker_params.CannyBlur = 1.6;
		pupil_tracker_params.EarlyRejection = true;
		pupil_tracker_params.EarlyTerminationPercentage = 95;
		pupil_tracker_params.PercentageInliers = 20;
		pupil_tracker_params.InlierIterations = 3;
		pupil_tracker_params.ImageAwareSupport = true;
		pupil_tracker_params.StarburstPoints = 0;
		//pupil_tracker_params.Seed = 0;

		pupiltracker::findPupilEllipse_out pupil_tracker_out;
		bool found = false;
		try {
			found = pupiltracker::findPupilEllipse(pupil_tracker_params, *eye, pupil_tracker_out, log);
		} catch (boost::thread_interrupted &e) {
			printf("INTERRUPTED\n");
		}
		if (found)
			*el = pupil_tracker_out.elPupil;

	}

	tuple findPupilEllipse(cv::Mat eye) {
		sigset_t sigset;
		if (signal(30, handler) == SIG_ERR) {
			fprintf(stderr, "Could not put handle on signal 30: %s\n",strerror(errno));
			return make_tuple(-1);
		}
		if (sigaddset(&sigset, 11) == -1) {
				fprintf(stderr, "Could not add signal 11 to sigset: %s\n",strerror(errno));
				return make_tuple(-1);
		}
		if (sigprocmask(SIG_BLOCK, &sigset, NULL) == -1) {
			fprintf(stderr, "Could not block signals 11 and 30: %s\n",strerror(errno));
			return make_tuple(-1);
		}
		mainThread = getThreadId();
		/* boost::this_thread::disable_interruption di; */

		cv::RotatedRect el = cv::RotatedRect(cv::Point2f(0,0), cv::Size2f(0,0), 0);
		boost::thread track = boost::thread(tryFindPupilEllipse, &eye, &el);
		pthread_t thd = track.native_handle();

		if (track.try_join_for(boost::chrono::milliseconds(100))) {
			printf("TRUE\n");
		} else {
			printf("FALSE\n");
			track.interrupt();
			/* track.detach(); */
			/* pthread_cancel(thd); */
			pthread_kill(thd, 30);
		}

		if (sigprocmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
			fprintf(stderr, "Could not unblock signal 11 and 30: %s\n",strerror(errno));
			return make_tuple(-1);
		}
		return make_tuple(el.center.x, el.center.y, el.size.width/2, el.size.height/2, el.angle);

	}

#if (PY_VERSION_HEX >= 0x03000000)

	static void *init_ar() {
#else
		static void init_ar(){
#endif
		Py_Initialize();

		import_array();
		return NUMPY_IMPORT_ARRAY_RETVAL;
	}

	BOOST_PYTHON_MODULE (pbcvt) {
		//using namespace XM;
		init_ar();

		//initialize converters
		to_python_converter<cv::Mat,pbcvt::matToNDArrayBoostConverter>();
		matFromNDArrayBoostConverter();

		//expose module-level functions
		def("findPupil", findPupil);
		def("findPupilEllipse", findPupilEllipse);

	}

} //end namespace pbcvt

max_stars_repo_name: ostapstephan/SeniorProject

max_issues_repo_name: ostapstephan/SeniorProject

max_forks_repo_name: ostapstephan/SeniorProject


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

#include <SMCE/Sketch.hpp>
#include <boost/python.hpp>

namespace bpy = boost::python;

void export_sketch() {
    bpy::class_<smce::Sketch, boost::noncopyable>{
        "Sketch", "Arduino Sketch", bpy::init<std::string, smce::SketchConfig>{bpy::args("self", "path", "config")}}
        .def(
            "get_source", +[](const smce::Sketch& self) { return self.get_source().string(); }, bpy::arg{"self"})
        .def_readonly("is_compiled", &smce::Sketch::is_compiled)
        .add_property(
            "uuid", +[](const smce::Sketch& self) { return self.get_uuid().to_hex(); });
}

max_stars_repo_name: ItJustWorksTM/pySMCE

max_issues_repo_name: ItJustWorksTM/pySMCE

max_forks_repo_name: ItJustWorksTM/pySMCE


text:
/* ------------------------------------ */
/* HEADER                               */
/*                                      */
/* Mailto: svallero AT to.infn.it       */
/*                                      */
/* ------------------------------------ */

#include "Configurator.h"
#include "FassLog.h"

//#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <sstream>

//#include <unistd.h>
//#include <sys/stat.h>

using namespace std;

/* -------------------------------------------------------------------------- */

bool Configurator::load_configuration(){

    // Cannot use logsystem yet...
    cout << "Loading configuration..." << endl;
    // Declare the supported options.
    po::options_description desc("Allowed options");

    desc.add_options()
    		("help", "produce help message")
                // General
    		("fass.manager_timer", po::value<int>()->default_value(60), "managers period (s)")
     		("fass.one_port", po::value<int>()->default_value(2633), "OpenNebula listen port")
    		("fass.one_endpoint", po::value<string>()->default_value("localhost"), "OpenNebula listen endpoint")
    		("fass.log_level", po::value<int>()->default_value(3), "log level common to all managers")
		// RPC manager
    		("rpcm.listen_port", po::value<int>()->default_value(2634), "listen port")
    		("rpcm.listen_address", po::value<string>()->default_value("127.0.0.1"), "listen address")
    		("rpcm.max_conn", po::value<int>()->default_value(15), "max connections")
    		("rpcm.max_conn_backlog", po::value<int>()->default_value(15), "max connections backlog")
    		("rpcm.keepalive_timeout", po::value<int>()->default_value(15), "keepalive timeout")
    		("rpcm.keepalive_max_conn", po::value<int>()->default_value(30), "keepalive max connections")
    		("rpcm.timeout", po::value<int>()->default_value(15), "timeout")
    		("rpcm.rpc_log", po::value<bool>()->default_value(true), "separate rpc log")
    		("rpcm.message_size", po::value<int>()->default_value(1073741824), "message size")
    		("rpcm.log_call_format", po::value<string>()->default_value("Req:%i UID:%u %m invoked %l"), "log call format")
    		;

    // Read the configuration file
    ifstream settings_file(conf_file.c_str());

    // Clear the map
    vm = po::variables_map();

    try{
        po::store(po::parse_config_file(settings_file , desc), vm);
    } catch(const exception& re){
        cerr << "Error: " << re.what() << endl;
        return false;
    }

    po::notify(vm);

    return true;
}

/* -------------------------------------------------------------------------- */

void Configurator::print_loaded_options(){
        ostringstream os;
        os <<"Reading configuration..." << endl;
        for (po::variables_map::iterator it = vm.begin(); it != vm.end(); it++) {

                string opt_name = it->first;
                os << "> " << opt_name;

                if (((boost::any)it->second.value()).empty()) {
                        os << "(empty)";
                }
                if (vm[opt_name].defaulted() || it->second.defaulted()) {
                        os << "(default)";
                }
                os << "=";

                allowed_types tp = get_option_type(it->second.value());
                switch (tp){
                        case is_string: os << boost::any_cast<string>(vm[opt_name].value());
                        break;
                        case is_int: os << boost::any_cast<int>(vm[opt_name].value());
                        break;
                        case is_double: os << boost::any_cast<double>(vm[opt_name].value());
                        break;
                        case is_bool: os << boost::any_cast<bool>(vm[opt_name].value());
                        break;
                        case is_unkn: os << "UnknownType";
                        break;
                }
                os << endl;

        }
        FassLog::log("CONF",Log::INFO,os);
}

/* -------------------------------------------------------------------------- */

Configurator::allowed_types Configurator::get_option_type(boost::any value){

        const type_info& type = value.type();
        if (type == typeid (string)) return is_string;
        else if (type == typeid (int)) return is_int;
        else if (type == typeid (double)) return is_double;
        else if (type == typeid (bool)) return is_bool;
        else return is_unkn;

}

/* -------------------------------------------------------------------------- */

const char * FassConfigurator::conf_name="fassd.conf";

ext: cc

max_stars_repo_name: svallero/fass

max_issues_repo_name: svallero/fass

max_forks_repo_name: svallero/fass


text:
#ifndef BINDINGS_UTIL_HPP_
#define BINDINGS_UTIL_HPP_

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

#include <vector>

namespace py = boost::python;

namespace imgen { namespace bindings {

template<typename T>
inline py::list vector_to_list(const std::vector<T>& v)
{
    return py::list(py::iterator<std::vector<T> >()(v));
}

template<typename T>
inline std::vector<T> list_to_vector(const py::list& list)
{
    return std::vector<T>(py::stl_input_iterator<T>(list),
                          py::stl_input_iterator<T>());
}

} } // namespace imgen::bindings

#endif // BINDINGS_UTIL_HPP_

max_stars_repo_name: maddisoj/wallgen

max_issues_repo_name: maddisoj/wallgen

max_forks_repo_name: maddisoj/wallgen


text:
/****************************************************************************
 *
 * Copyright 2021 Auterion AG. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * 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.
 *
 ****************************************************************************/

/**
 * @brief Semiglobal planner ROS 2 MapVisualizer class
 * @file semiglobal_planner_visualization.hpp
 * @author Bastian Jäger <bastian@auterion.com>
 */

#pragma once

#include <common.h>

#include <Eigen/Core>
#include <landing_mapper/EuclideanSignedDistanceFields.hpp>

// ROS dependencies
#include <rclcpp/duration.hpp>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <sensor_msgs/point_cloud2_iterator.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <visualization_msgs/msg/marker_array.hpp>

namespace viz {

template <class Derived>
static inline geometry_msgs::msg::Point toPoint(const Eigen::MatrixBase<Derived>& ev3) {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);
    geometry_msgs::msg::Point gmp;
    gmp.x = ev3.x();
    gmp.y = ev3.y();
    gmp.z = ev3.z();
    return gmp;
}

class MapVisualizer {
   public:
    MapVisualizer(rclcpp::Node* node);

    template <class Derived>
    void publishCube(const Eigen::MatrixBase<Derived>& point, std_msgs::msg::ColorRGBA& color,
                     const geometry_msgs::msg::Vector3& scale, const rclcpp::Time& timestamp, bool enabled) const;
    void publishCube(const geometry_msgs::msg::Point& point, std_msgs::msg::ColorRGBA& color,
                     const geometry_msgs::msg::Vector3& scale, const rclcpp::Time& timestamp, bool enabled) const;

    template <class Derived>
    void publishSafeLand(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp, float size,
                         bool enabled) const;
    template <class Derived>
    void publishCloseGround(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp, float size,
                            bool enabled) const;
    template <class Derived>
    void publishGround(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp, float size,
                       bool enabled) const;

    template <typename T>
    void visualizeEsdf(const esdf::EuclideanSignedDistanceFields<T>& esdf, const rclcpp::Time& timestamp,
                       bool enabled = true);

    void prepare_point_cloud_msg(int64_t timestamp_ns, size_t width, size_t height, bool enabled = true);

    template <typename T>
    void add_point_to_point_cloud(const Eigen::Matrix<T, 3, 1>& point, bool enabled = true);
    void visualizePointCloud(bool enabled = true);

    void publishVehicle(double safety_radius, const rclcpp::Time& timestamp, bool enabled = true);

    void publishMarkerArray(const visualization_msgs::msg::MarkerArray& marker_array) {
        marker_pub_->publish(marker_array);
    }

   private:
    rclcpp::Node* _node;

    rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr marker_pub_;
    rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr marker_map_pub_;
    rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr point_cloud_pub_;

    sensor_msgs::msg::PointCloud2::SharedPtr _cloud_ros2_msg;
    std::shared_ptr<sensor_msgs::PointCloud2Iterator<float>> _pc_iter_x;
    std::shared_ptr<sensor_msgs::PointCloud2Iterator<float>> _pc_iter_y;
    std::shared_ptr<sensor_msgs::PointCloud2Iterator<float>> _pc_iter_z;

    std::tuple<float, float, float> HSVtoRGB(std::tuple<float, float, float> hsv);
    int path_length_ = 0;
};

template <class Derived>
void MapVisualizer::publishCube(const Eigen::MatrixBase<Derived>& point, std_msgs::msg::ColorRGBA& color,
                                const geometry_msgs::msg::Vector3& scale, const rclcpp::Time& timestamp,
                                bool enabled) const {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);
    publishCube(toPoint(point), color, scale, timestamp, enabled);
}

template <class Derived>
void MapVisualizer::publishSafeLand(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp, float size,
                                    bool enabled) const {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);

    std_msgs::msg::ColorRGBA color;
    color.a = 0.75;
    color.r = 0.0;
    color.g = 1.0;
    color.b = 0.0;

    geometry_msgs::msg::Vector3 scale;
    scale.x = size;
    scale.y = size;
    scale.z = 0.1;

    publishCube(toPoint(point), color, scale, timestamp, enabled);
}

template <class Derived>
void MapVisualizer::publishCloseGround(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp,
                                       float size, bool enabled) const {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);

    std_msgs::msg::ColorRGBA color;
    color.a = 0.75;
    color.r = 1.0;
    color.g = 1.0;
    color.b = 0.0;

    geometry_msgs::msg::Vector3 scale;
    scale.x = size;
    scale.y = size;
    scale.z = 0.1;

    publishCube(toPoint(point), color, scale, timestamp, enabled);
}

template <class Derived>
void MapVisualizer::publishGround(const Eigen::MatrixBase<Derived>& point, const rclcpp::Time& timestamp, float size,
                                  bool enabled) const {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);

    std_msgs::msg::ColorRGBA color;
    color.a = 0.75;
    color.r = 1.0;
    color.g = 0.0;
    color.b = 0.0;

    geometry_msgs::msg::Vector3 scale;
    scale.x = size;
    scale.y = size;
    scale.z = 0.1;

    publishCube(toPoint(point), color, scale, timestamp, enabled);
}

template <typename T>
void MapVisualizer::visualizeEsdf(const esdf::EuclideanSignedDistanceFields<T>& esdf, const rclcpp::Time& timestamp,
                                  bool enabled) {
    if (!enabled) {
        return;
    }

    visualization_msgs::msg::MarkerArray marker_array;

    visualization_msgs::msg::Marker map_marker;
    map_marker.header.frame_id = NED_FRAME;
    map_marker.header.stamp = timestamp;
    map_marker.ns = "esdf";
    map_marker.id = 0;
    map_marker.type = visualization_msgs::msg::Marker::CUBE_LIST;
    map_marker.action = visualization_msgs::msg::Marker::DELETE;
    marker_array.markers.push_back(map_marker);

    const esdfvoxelcube::ESDFVoxelCube esdf_map = esdf.getEsdfMap();
    const double cell_size = esdf_map.getBinEdgeWidth();
    map_marker.header.frame_id = NED_FRAME;
    map_marker.header.stamp = timestamp;
    map_marker.ns = "esdf";
    map_marker.id = 0;
    map_marker.type = visualization_msgs::msg::Marker::CUBE_LIST;
    map_marker.action = visualization_msgs::msg::Marker::ADD;
    map_marker.pose.orientation.x = 0.0;
    map_marker.pose.orientation.y = 0.0;
    map_marker.pose.orientation.z = 0.0;
    map_marker.pose.orientation.w = 1.0;
    map_marker.scale.x = cell_size;
    map_marker.scale.y = cell_size;
    map_marker.scale.z = cell_size;
    map_marker.color.a = 0.5;
    map_marker.color.r = 1.0;
    map_marker.color.g = 0.0;
    map_marker.color.b = 0.0;

    const Eigen::Vector3i grid_min = esdf_map.getLowerBoundaryIndices().array();
    const Eigen::Vector3i grid_max = esdf_map.getUpperBoundaryIndices().array();

    // From previous implementation
    // constexpr float distance_max_value = 20.f;
    // constexpr float distance_min_value = -1.f;
    // constexpr float range_max = 320.f;
    // constexpr float range_min = 0.f;

    for (int i = grid_min[0]; i < grid_max[0]; ++i) {
        for (int j = grid_min[1]; j < grid_max[1]; ++j) {
            for (int k = grid_min[2]; k < grid_max[2]; ++k) {
                const Eigen::Vector3i index(i, j, k);
                const esdfvoxelcube::ESDFNode<T>& voxel = esdf_map.getNode(index);
                if (voxel.is_observed && voxel.distance < cell_size) {
                    const Eigen::Matrix<T, 3, 1> voxel_center_pos = esdf_map.getNodeCenter(index);
                    map_marker.points.push_back(toPoint(voxel_center_pos));

                    // const float h = ((range_max - range_min) * (voxel.distance - distance_min_value) /
                    //                 (distance_max_value - distance_min_value)) +
                    //                 range_min;
                    // MA: not entirely sure what this normalization is meant for. Probably not
                    // necessary anymore since we're only displaying voxels that have small
                    // distances. Hence, color by height for now and wrap around every 25m.

                    // TODO make the 25m / 2.0 a parameter somehow. Either dynamic or by ROS parameters
                    const float h = std::abs(std::fmod(voxel_center_pos.z(), 2.0) / 2.0) * 360;

                    std_msgs::msg::ColorRGBA color;
                    color.a = 0.5;
                    std::tie(color.r, color.g, color.b) = HSVtoRGB(std::make_tuple(h, 1.f, 1.f));
                    map_marker.colors.push_back(color);
                }
            }
        }
    }
    marker_array.markers.push_back(map_marker);
    marker_map_pub_->publish(marker_array);
}

template <typename T>
void MapVisualizer::add_point_to_point_cloud(const Eigen::Matrix<T, 3, 1>& point, bool enabled) {
    if (!enabled) {
        return;
    }

    **_pc_iter_x = static_cast<float>(point.x());
    **_pc_iter_y = static_cast<float>(point.y());
    **_pc_iter_z = static_cast<float>(point.z());
    ++(*_pc_iter_x);
    ++(*_pc_iter_y);
    ++(*_pc_iter_z);
}

}  // namespace viz


text:
/*
 * (C) Copyright 2021 Met Office UK
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 */

#include <boost/make_unique.hpp>

#include "eckit/utils/StringTools.h"

#include "ioda/Misc/StringFuncs.h"

#include "ufo/utils/dataextractor/DataExtractor.h"
#include "ufo/utils/dataextractor/DataExtractorCSVBackend.h"
#include "ufo/utils/dataextractor/DataExtractorInput.h"
#include "ufo/utils/dataextractor/DataExtractorNetCDFBackend.h"

/// \brief Boost visitor which allows us to sort a vector.
class SortUpdateVisitor : public boost::static_visitor<void> {
 public:
  explicit SortUpdateVisitor(ufo::RecursiveSplitter &splitter) : splitter(splitter) {}

  template <typename T>
  void operator()(const std::vector<T> &coord) {
    splitter.groupBy(coord);
  }

  void operator()(const std::vector<float> &coord) {
    splitter.sortGroupsBy(
      [&coord](int indexA, int indexB) {
        return coord[static_cast<size_t>(indexA)] < coord[static_cast<size_t>(indexB)];
      });
  }

  ufo::RecursiveSplitter &splitter;
};

/// \brief Boost visitor which allows us to sort a vector.
class SortVisitor : public boost::static_visitor<void> {
 public:
  explicit SortVisitor(const ufo::RecursiveSplitter &splitter) : splitter(splitter) {}

  template <typename T>
  void operator()(std::vector<T> &coord) {
    std::vector<T> newCoord;
    newCoord.reserve(coord.size());
    for (const auto &group : splitter.groups()) {
      for (const auto &index : group) {
        newCoord.push_back(coord[index]);
      }
    }
    // Replace the coordinate with the sorted one.
    coord = std::move(newCoord);
  }

  const ufo::RecursiveSplitter &splitter;
};

namespace ufo {

DataExtractor::DataExtractor(const std::string &filepath, const std::string &group) {
  // Read the data from the file
  load(filepath, group);
  // Start by constraining to the full range of our data
  resetExtract();
  // Initialise splitter for both dimensions
  splitter_.emplace_back(ufo::RecursiveSplitter(static_cast<size_t>(interpolatedArray2D_.rows())));
  splitter_.emplace_back(ufo::RecursiveSplitter(static_cast<size_t>(interpolatedArray2D_.cols())));
}

void DataExtractor::load(const std::string &filepath,
                              const std::string &interpolatedArrayGroup) {
  std::unique_ptr<DataExtractorBackend> backend = createBackendFor(filepath);
  DataExtractorInput input = backend->loadData(interpolatedArrayGroup);
  coord2DimMapping_ = std::move(input.coord2DimMapping);
  dim2CoordMapping_ = std::move(input.dim2CoordMapping);
  coordsVals_ = std::move(input.coordsVals);
  interpolatedArray2D_ = std::move(input.payloadArray);
}

std::unique_ptr<DataExtractorBackend> DataExtractor::createBackendFor(
    const std::string &filepath) {
  const std::string lowercasePath = eckit::StringTools::lower(filepath);
  if (eckit::StringTools::endsWith(lowercasePath, ".nc") ||
      eckit::StringTools::endsWith(lowercasePath, ".nc4"))
    return boost::make_unique<DataExtractorNetCDFBackend>(filepath);
  else if (eckit::StringTools::endsWith(lowercasePath, ".csv"))
    return boost::make_unique<DataExtractorCSVBackend>(filepath);
  else
    throw eckit::BadValue("File '" + filepath + "' has an unrecognized extension. "
                          "The supported extensions are .nc, .nc4 and .csv", Here());
}

void DataExtractor::sort() {
  Eigen::ArrayXXf sortedArray = interpolatedArray2D_;
  nextCoordToExtractBy_ = coordsToExtractBy_.begin();

  for (size_t dim = 0; dim < dim2CoordMapping_.size(); ++dim) {
    // Reorder coordinates
    for (auto &coord : dim2CoordMapping_[dim]) {
      auto &coordVal = coordsVals_[coord];
      SortVisitor visitor(splitter_[dim]);
      boost::apply_visitor(visitor, coordVal);
    }
    // Reorder the array to be interpolated
    if (dim == 0) {
      int ind = -1;
      for (const auto &group : splitter_[dim].groups()) {
        for (const auto &index : group) {
          ind++;
          oops::Log::debug() << "Sort index dim0; index-from: " << ind << " index-to: " <<
            index << std::endl;
          for (Eigen::Index j = 0; j < interpolatedArray2D_.cols(); j++) {
            sortedArray(ind, j) = interpolatedArray2D_(static_cast<Eigen::Index>(index), j);
          }
        }
      }
      // Replace the unsorted array with the sorted one.
      interpolatedArray2D_ = sortedArray;
    } else if (dim == 1) {
      int ind = -1;
      for (const auto &group : splitter_[dim].groups()) {
        for (const auto &index : group) {
          ind++;
          oops::Log::debug() << "Sort index dim1; index-from: " << ind << " index-to: " <<
            index << std::endl;
          for (Eigen::Index i = 0; i < interpolatedArray2D_.rows(); i++) {
            sortedArray(i, ind) = interpolatedArray2D_(i, static_cast<Eigen::Index>(index));
          }
        }
      }
      // Replace the unsorted array with the sorted one.
      interpolatedArray2D_ = sortedArray;
    } else {
        throw eckit::Exception("Unable to reorder the array to be interpolated: "
                               "it has more than 2 dimensions.", Here());
    }
  }
}

void DataExtractor::scheduleSort(const std::string &varName, const InterpMethod &method) {
  // Map any names of the form var@Group to Group/var
  const std::string canonicalVarName = ioda::convertV1PathToV2Path(varName);

  const CoordinateValues &coordVal = coordsVals_.at(canonicalVarName);
  const int dimIndex = coord2DimMapping_.at(canonicalVarName);

  SortUpdateVisitor visitor(splitter_[static_cast<size_t>(dimIndex)]);
  boost::apply_visitor(visitor, coordVal);

  // Update our map between coordinate (variable) and interpolation/extract method
  coordsToExtractBy_.emplace_back(Coordinate{varName, coordVal, method, dimIndex});
}

void DataExtractor::resetExtract() {
  constrainedRanges_[0].begin = 0;
  constrainedRanges_[0].end = static_cast<int>(interpolatedArray2D_.rows());
  constrainedRanges_[1].begin = 0;
  constrainedRanges_[1].end = static_cast<int>(interpolatedArray2D_.cols());
  resultSet_ = false;
  nextCoordToExtractBy_ = coordsToExtractBy_.begin();
}

float DataExtractor::getResult() {
  // Fetch the result
  if (resultSet_) {
    // This was derived from linear interpolation so return it.
    resetExtract();
    return result_;
  }

  int sizeDim0 = constrainedRanges_[0].end - constrainedRanges_[0].begin;
  int sizeDim1 = constrainedRanges_[1].end - constrainedRanges_[1].begin;
  if (sizeDim0 != 1 || sizeDim1 != 1) {
    throw eckit::Exception("Previous calls to extract() have failed to identify "
                           "a single value to return.", Here());
  }
  float res = interpolatedArray2D_(constrainedRanges_[0].begin, constrainedRanges_[1].begin);
  resetExtract();
  return res;
}

}  // namespace ufo

max_stars_repo_name: fmahebert/ufo

max_issues_repo_name: fmahebert/ufo

max_forks_repo_name: fmahebert/ufo


text:
// std
#include <iostream>
#include <exception>

// Boost
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/timer/timer.hpp>

// OpenCV
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

// face_seg
#include <face_seg/face_seg.h>
#include <face_seg/utilities.h>

#if WITH_FIND_FACE_LANDMARKS
// sfl
#include <sfl/sequence_face_landmarks.h>
#include <sfl/utilities.h>
#endif	// WITH_FIND_FACE_LANDMARKS

using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::runtime_error;
using namespace boost::program_options;
using namespace boost::filesystem;

const std::string IMAGE_FILTER =
"(.*\\.(bmp|dib|jpeg|jpg|jpe|jp2|png|pbm|pgm|ppm|sr|ras))";

void getImagesFromDir(const std::string& dir_path, std::vector<std::string>& img_paths)
{
    boost::regex filter(IMAGE_FILTER);
    boost::smatch what;
    directory_iterator end_itr; // Default ctor yields past-the-end
    for (directory_iterator it(dir_path); it != end_itr; ++it)
    {
        // Skip if not a file
        if (!boost::filesystem::is_regular_file(it->status())) continue;

        // Get extension
        std::string ext = it->path().extension().string();
        std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);

        // Skip if no match
        if (!boost::regex_match(ext, what, filter)) continue;

        img_paths.push_back(it->path().string());
    }
}

void readImageListFromFile(const std::string& csv_file, std::vector<string>& img_paths)
{
    std::ifstream file(csv_file);
    string img_path;
    while (file.good())
    {
        std::getline(file, img_path, '\n');
        if (img_path.empty()) return;
        img_paths.push_back(img_path);
    }
}

void logError(std::ofstream& log, const string& img_path,
    const string& msg, bool write_to_file = true)
{
    std::cerr << "Error: " << msg << std::endl;
    if (write_to_file)
    {
        log << img_path << ",Error: " << msg << std::endl;
    }
}

int main(int argc, char* argv[])
{
	// Parse command line arguments
    string inputPath;
	string outputPath, modelPath, deployPath, landmarks_path;
    string logPath, cfgPath;
    unsigned int verbose, gpu_device_id;
	bool scale, postprocess, with_gpu;
	try {
		options_description desc("Allowed options");
		desc.add_options()
			("help,h", "display the help message")
            ("verbose,v", value<unsigned int>(&verbose)->default_value(0), "output debug information")
            ("input,i", value<string>(&inputPath)->required(), "path to input directory or image list")
            ("output,o", value<string>(&outputPath)->required(), "output directory")
            ("model,m", value<string>(&modelPath)->required(), "path to network weights model file (.caffemodel)")
            ("deploy,d", value<string>(&deployPath)->required(), "path to deploy prototxt file")
			("scale,s", value<bool>(&scale)->default_value(true), "toggle scale image to network size")
			("postprocess,p", value<bool>(&postprocess)->default_value(false), "toggle segmentation postprocessing")
			("gpu", value<bool>(&with_gpu)->default_value(true), "toggle GPU / CPU")
			("gpu_id", value<unsigned int>(&gpu_device_id)->default_value(0), "GPU's device id")
			("landmarks,l", value<string>(&landmarks_path)->default_value(""), "path to landmarks model for face cropping")
            ("log", value<string>(&logPath)->default_value("face_seg_batch_log.csv"), "log file path")
            ("cfg", value<string>(&cfgPath)->default_value("face_seg_batch.cfg"), "configuration file (.cfg)")
			;
		variables_map vm;
		store(command_line_parser(argc, argv).options(desc).
			positional(positional_options_description().add("input", -1)).run(), vm);

        if (vm.count("help")) {
            cout << "Usage: face_seg_batch [options]" << endl;
            cout << desc << endl;
            exit(0);
        }

        // Read config file
        std::ifstream ifs(vm["cfg"].as<string>());
        store(parse_config_file(ifs, desc), vm);

        notify(vm);

        if (!(is_regular_file(inputPath) || is_directory(inputPath)))
            throw error("input must be a path to input directory or image pairs list!");
        if (!is_directory(outputPath))
            throw error("output must be a path to a directory!");
        if (!is_regular_file(modelPath)) throw error("model must be a path to a file!");
        if (!is_regular_file(deployPath)) throw error("deploy must be a path to a file!");
		if (!landmarks_path.empty() && !is_regular_file(landmarks_path))
			throw error("landmarks must be a path to a file!");
	}
	catch (const error& e) {
        cerr << "Error while parsing command-line arguments: " << e.what() << endl;
        cerr << "Use --help to display a list of options." << endl;
		exit(1);
	}

	try
	{
        // Initialize log file
        std::ofstream log;
        if (verbose > 0)
            log.open(logPath);

		// Initialize face segmentation
		face_seg::FaceSeg fs(deployPath, modelPath, with_gpu, gpu_device_id, scale, postprocess);

#if WITH_FIND_FACE_LANDMARKS
		// Initialize sequence face landmarks
		std::shared_ptr<sfl::SequenceFaceLandmarks> _sfl;
		if (!landmarks_path.empty())
			_sfl = sfl::SequenceFaceLandmarks::create(landmarks_path);
#endif	// WITH_FIND_FACE_LANDMARKS

		// Initialize timer
		boost::timer::cpu_timer timer;
		float seg_delta_time = 0.0f, lms_delta_time = 0.0f;

        // Parse images
        std::vector<string> img_paths;
        if (is_directory(inputPath))
            getImagesFromDir(inputPath, img_paths);
        else readImageListFromFile(inputPath, img_paths);

        // For each image
        string prev_src_path, prev_tgt_path;
        cv::Mat source_img, target_img, rendered_img;
        for (const string& img_path : img_paths)
        {
            // Check if output image already exists
            path outputName = (path(img_path).stem() += ".png");
            string currOutputPath = (path(outputPath) /= outputName).string();
            if (is_regular_file(currOutputPath))
            {
                std::cout << "Skipping: " << outputName << std::endl;
                continue;
            }
            std::cout << "Face segmenting: " << outputName << std::endl;

			// Read source image
            cv::Mat source_img = cv::imread(img_path);

#if WITH_FIND_FACE_LANDMARKS
			// Crop source image
			if (_sfl != nullptr)
			{
				// Start measuring time
				timer.start();

				_sfl->clear();
				const sfl::Frame& lmsFrame = _sfl->addFrame(source_img);
				if (lmsFrame.faces.empty())
				{
					logError(log, img_path, "Failed to find a face in the image!", verbose);
					continue;
				}
				const sfl::Face* face = lmsFrame.getFace(sfl::getMainFaceID(_sfl->getSequence()));
				cv::Rect bbox = sfl::getFaceBBoxFromLandmarks(face->landmarks, source_img.size(), true);
				source_img = source_img(bbox).clone();

				// Stop measuring time
				timer.stop();

				// Print current timing statistics
				lms_delta_time += (timer.elapsed().wall*1.0e-9 - lms_delta_time)*0.1f;
				std::cout << "Landmarks timing = " << lms_delta_time << "s (" <<
					(1.0f / lms_delta_time) << " fps)" << std::endl;
			}
#endif	// WITH_FIND_FACE_LANDMARKS

			// Start measuring time
			timer.start();

			// Do face segmentation
			cv::Mat seg = fs.process(source_img);
			if (seg.empty())
			{
				logError(log, img_path, "Face segmentation failed!", verbose);
				continue;
			}

			// Stop measuring time
			timer.stop();

            // Write output to file
            std::cout << "Writing " << outputName << " to output directory." << std::endl;
            cv::imwrite(currOutputPath, seg);

			// Print current timing
			seg_delta_time += (timer.elapsed().wall*1.0e-9 - seg_delta_time)*0.1f;
			std::cout << "Segmentation timing = " << seg_delta_time << "s (" <<
				(1.0f / seg_delta_time) << " fps)" << std::endl;

            // Debug
            if (verbose > 0)
            {
                // Write rendered image
				cv::Mat debug_render_img = source_img.clone();
				face_seg::renderSegmentationBlend(debug_render_img, seg);
                string debug_render_path = (path(outputPath) /=
                    (path(currOutputPath).stem() += "_debug.jpg")).string();
                cv::imwrite(debug_render_path, debug_render_img);
            }
        }
	}
	catch (std::exception& e)
	{
		cerr << e.what() << endl;
		return 1;
	}

	return 0;
}


text:
#include <igl/boundary_facets.h>
#include <igl/colon.h>
#include <igl/cotmatrix.h>
#include <igl/jet.h>
#include <igl/min_quad_with_fixed.h>
#include <igl/readOFF.h>
#include <igl/setdiff.h>
#include <igl/slice.h>
#include <igl/slice_into.h>
#include <igl/unique.h>
#include <igl/opengl/glfw/Viewer.h>
#include <Eigen/Sparse>
#include <iostream>
#include "tutorial_shared_path.h"

int main(int argc, char *argv[])
{
  using namespace Eigen;
  using namespace std;
  MatrixXd V;
  MatrixXi F;
  igl::readOFF(TUTORIAL_SHARED_PATH "/camelhead.off",V,F);
  // Find boundary edges
  MatrixXi E;
  igl::boundary_facets(F,E);
  // Find boundary vertices
  VectorXi b,IA,IC;
  igl::unique(E,b,IA,IC);
  // List of all vertex indices
  VectorXi all,in;
  igl::colon<int>(0,V.rows()-1,all);
  // List of interior indices
  igl::setdiff(all,b,in,IA);

  // Construct and slice up Laplacian
  SparseMatrix<double> L,L_in_in,L_in_b;
  igl::cotmatrix(V,F,L);
  igl::slice(L,in,in,L_in_in);
  igl::slice(L,in,b,L_in_b);

  // Dirichlet boundary conditions from z-coordinate
  VectorXd bc;
  VectorXd Z = V.col(2);
  igl::slice(Z,b,bc);

  // Solve PDE
  SimplicialLLT<SparseMatrix<double > > solver(-L_in_in);
  VectorXd Z_in = solver.solve(L_in_b*bc);
  // slice into solution
  igl::slice_into(Z_in,in,Z);

  // Alternative, short hand
  igl::min_quad_with_fixed_data<double> mqwf;
  // Linear term is 0
  VectorXd B = VectorXd::Zero(V.rows(),1);
  // Empty constraints
  VectorXd Beq;
  SparseMatrix<double> Aeq;
  // Our cotmatrix is _negative_ definite, so flip sign
  igl::min_quad_with_fixed_precompute((-L).eval(),b,Aeq,true,mqwf);
  igl::min_quad_with_fixed_solve(mqwf,B,bc,Beq,Z);

  // Pseudo-color based on solution
  MatrixXd C;
  igl::jet(Z,true,C);

  // Plot the mesh with pseudocolors
  igl::opengl::glfw::Viewer viewer;
  viewer.data().set_mesh(V, F);
  viewer.data().show_lines = false;
  viewer.data().set_colors(C);
  viewer.launch();
}


text:
#pragma once
#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>
#include <eosio/chain/abi_serializer.hpp>
#include <fc/variant_object.hpp>

#define UNIT_TEST_ENV

// Note: cannot check nested mvo
#define CHECK_EQUAL_OBJECTS(left, right) { \
    auto l = fc::variant(left); \
    auto r = fc::variant(right); \
    BOOST_TEST_CHECK(l.is_object()); \
    BOOST_TEST_CHECK(r.is_object()); \
    if (l.is_object() && r.is_object()) { \
        BOOST_CHECK_EQUAL_COLLECTIONS(l.get_object().begin(), l.get_object().end(), r.get_object().begin(), r.get_object().end()); }}

#define CHECK_MATCHING_OBJECT(check, reference) { \
    auto a = fc::variant(reference); \
    auto b = fc::variant(check); \
    BOOST_TEST_CHECK(a.is_object()); \
    BOOST_TEST_CHECK(b.is_object()); \
    if (a.is_object() && b.is_object()) { \
        auto filtered = ::eosio::testing::filter_fields(a.get_object(), b.get_object()); \
        BOOST_CHECK_EQUAL_COLLECTIONS(a.get_object().begin(), a.get_object().end(), filtered.begin(), filtered.end()); }}

namespace eosio { namespace testing {

uint64_t hash64(const std::string& arg);

// TODO: maybe use native db struct
struct permission {
    name        perm_name;
    name        parent;
    authority   required_auth;
};

struct contract_error_messages {
protected:
    const string amsg(const string& x) { return base_tester::wasm_assert_msg(x); }
};

class golos_tester : public tester {
protected:
    const name _code;     // shortcut to main tested contract account name

    cyberway::chaindb::chaindb_controller& _chaindb;
    std::map<account_name, abi_serializer> _abis;

public:
    golos_tester(name code, bool push_genesis = true)
    : tester(base_tester::default_config("_GOLOSTEST_"), push_genesis)
    , _code(code)
    , _chaindb(control->chaindb()) {
    }
    ~golos_tester() {
    }

    void install_contract(account_name acc, const std::vector<uint8_t>& wasm, const std::vector<char>& abi, bool produce = true, const private_key_type* signer = nullptr);

    std::vector<permission> get_account_permissions(account_name a);

    action_result push_and_check_action(account_name, action_name, account_name, const variant_object&);
    action_result push_action(account_name code, action_name name, account_name signer, const variant_object& data);
    action_result push_action_msig_tx(account_name code, action_name name,
        std::vector<permission_level> perms, std::vector<account_name> signers, const variant_object& data, bool produce=true);
    action_result push_tx(signed_transaction&& tx, bool produce_and_check=true);
    void delegate_authority(account_name from, std::vector<account_name> to,
        account_name code, action_name type, permission_name req,
        permission_name parent = N(active), permission_name prov = config::eosio_code_name);

    fc::variant get_chaindb_struct(name code, uint64_t scope, name tbl, uint64_t id, const std::string& n) const;
    fc::variant get_chaindb_singleton(name code, uint64_t scope, name tbl, const std::string& n) const;
    std::vector<fc::variant> get_all_chaindb_rows(name code, uint64_t scope, name tbl, bool strict) const;
    signed_block_ptr wait_block(const uint32_t n);
};

}} // eosio::tesing

FC_REFLECT(eosio::testing::permission, (perm_name)(parent)(required_auth))


text:
// Copyright 2015-2019 Carnegie Mellon University.  See LICENSE file for terms.

#include <boost/format.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/filtered_graph.hpp>

#include <rose.h>

#include "misc.hpp"
#include "masm.hpp"
#include "pdg.hpp"
#include "usage.hpp"
#include "method.hpp"
#include "cdg.hpp"
#include "ooanalyzer.hpp"

namespace pharos {

template<> char const* EnumStrings<AllocType>::data[] = {
  "Unknown",
  "Stack",
  "Heap",
  "Global",
  "Param",
};
template std::string Enum2Str<AllocType>(AllocType);

using Rose::BinaryAnalysis::SymbolicExpr::OP_ITE;

// A hacked up routine to pick the correct object pointer from an ITE expression.  There's much
// better ways to implement this, but none that will be as easy for demonstrating that this is
// not a major architectural problem with the ITE expressions.  More NEWWAY fixes are required.
// Additionally, this function is currently only used in this file, but it might be useful
// elsewhere as well.
SymbolicValuePtr pick_this_ptr(SymbolicValuePtr& sv) {
  InternalNodePtr in = sv->get_expression()->isInteriorNode();
  if (in && in->getOperator() == OP_ITE) {
    // For right now, make a complete copy of the symbolic value, maintaining definers and so
    // forth.  Set the expression to just the half that we're interested in.
    SymbolicValuePtr newsv = sv->scopy();
    newsv->set_expression(in->child(1));
    return newsv;
  }
  else {
    return sv;
  }
}

ThisPtrUsage::ThisPtrUsage(const FunctionDescriptor* f, SymbolicValuePtr tptr,
                           const ThisCallMethod* tcm, SgAsmInstruction* call_insn) : fd(f) {
  assert(tptr);
  this_ptr = tptr;

  assert(fd != NULL);

  // We don't know anything about our allocation yet.
  alloc_type = AllocUnknown;
  alloc_size = 0;
  alloc_insn = NULL;

  add_method(tcm, call_insn);
  analyze_alloc();
}

// Analyze the allocation type and location of this-pointers.
void ThisPtrUsage::analyze_alloc() {
  // Set the allocation type to unknown by default.
  alloc_type = AllocUnknown;

  // Use the type returned from get_memory_type() to determine our allocation type.  Perhaps in
  // the future thse can be fully combined, but this was what was required to support non-zero
  // ESP initialization.
  MemoryType type = this_ptr->get_memory_type();
  if (type == StackMemLocalVariable) {
    alloc_type = AllocLocalStack;
  }
  else if (type == StackMemParameter) {
    alloc_type = AllocParameter;
  }
  else if (type == UnknownMem) {
    // This code is really a function of get_memory_type() still being broken.
    // If we're not a constant address (global), skip this function.
    if (!this_ptr->is_number() || this_ptr->get_width() > 64) return;
    // This is a bit hackish, but also reject obviously invalid constants.
    size_t num = this_ptr->get_number();
    // Here's a place where we're having the age old debate about how to tell what is an
    // address with absolutely no context.  Cory still likes consistency.  Others have
    // suggested that we should be using the memory map despite all of it's flaws...
    // if (!ds->memory_in_image(num)) return;
    if (num < 0x10000 || num > 0x7FFFFFFF) return;
    // Otherwise, we look like a legit global address?
    alloc_type = AllocGlobal;
  }
  else {
    return;
  }

  // It's not actually clear why we're looking for the allocation instruction.  Perhaps we
  // should quit doing this and just use the tests above.  At least for now though, looking for
  // the common pattern allows us to detect some unusual situations.  Wes' previous logic also
  // filtered by requiring LEA instructions, so we're preserving that limit.

  // This code previously relied on the first-creator-of-read feature of modifiers, which we're
  // retiring.  Even though it's not clear that this code is required, I've updated it to use
  // latest definers in place of modifiers, only we haven't switch to just using the _latest_
  // definers yet so it needed some additional filtering to determine which definer to use.
  const PDG* pdg = fd->get_pdg();
  // Shouldn't happen.
  if (!pdg) return;
  const DUAnalysis& du = pdg->get_usedef();

  // This is hackish too.  We need it for debugging so that we have some way of reporting which
  // instructions are involved in the confusion.
  SgAsmInstruction* first_insn = NULL;
  for (SgAsmInstruction *ginsn : this_ptr->get_defining_instructions()) {
    // For debugging so that we have an address.
    if (first_insn == NULL) first_insn = ginsn;

    SgAsmX86Instruction *insn = isSgAsmX86Instruction(ginsn);
    if (insn == NULL) continue;

    // Since definers isn't the "latest" definer just yet, filter our subsequent analysis to
    // the one that wrote the this-ptr value.  This is hackish and wrong because we shouldn't
    // have to filter.  But maybe once we can upgrade , this code can go away...
    auto writes = du.get_writes(insn);
    bool found_write = false;
    for (const AbstractAccess& aa : writes) {
      if (aa.value->get_expression()->isEquivalentTo(this_ptr->get_expression())) {
        found_write = true;
        break;
      }
    }
    // If this instruction didn't write the this-ptr, it's not the one that we're looking for.
    if (!found_write) continue;
    // If we're here, this should be the instruction that defined the this-pointer.

    // If we're a local variable and we've found an LEA instruction, that's probably the one
    // we're looking for.
    if (alloc_type == AllocLocalStack && insn->get_kind() == x86_lea) {
      alloc_insn = ginsn;
      GDEBUG << "Stack allocated object: " << *(this_ptr->get_expression()) << " at "
             << debug_instruction(alloc_insn) << LEND;
      return;
    }
    // For global variables, the typical cases are move or push instructions.
    else if (alloc_type == AllocGlobal &&
             (insn->get_kind() == x86_mov || insn->get_kind() == x86_push)) {
      alloc_insn = ginsn;
      GDEBUG << "Global static object: " << *(this_ptr->get_expression()) << " at "
             << debug_instruction(alloc_insn) << LEND;
      return;
    }
    // For passed parameters, we should probably be looking for the instruction that reads the
    // undefined this-pointer value.  This code was sufficient at the time...
    else if (alloc_type == AllocParameter) {
      GDEBUG << "Passed object: " << *(this_ptr->get_expression()) << LEND;
      return;
    }
  }

  if (first_insn == NULL) {
    GDEBUG << "No allocation instruction found for " << *(this_ptr->get_expression())
           << " alloc_type=" << Enum2Str(alloc_type) << LEND;
  }
  else {
    GDEBUG << "No allocation instruction found for " << *(this_ptr->get_expression())
           << " alloc_type=" << Enum2Str(alloc_type) << " at " << debug_instruction(first_insn) << LEND;
  }

  // Based on evaluation of the test suite, if we've reached this point, something's gone
  // wrong, and it's very unclear if we're really the allocation type we thought we were.
  // Perhaps it's better to be cautious and retract our allocation type claims.  We could also
  // choose to return the best guess of our type here, by removing this line.
  //alloc_type = AllocUnknown;
  return;
}

ObjectUse::ObjectUse(OOAnalyzer& ooa, const FunctionDescriptor* f) {
  fd = f;
  assert(fd != NULL);
  analyze_object_uses(ooa);
}

using VertexFound = std::runtime_error;

// Use a fancy std bidirectional thingie instead?
using InsnVertexMap = std::map<SgAsmInstruction*, CFGVertex>;
using VertexInsnMap = std::map<CFGVertex, SgAsmInstruction*>;

class CallOrderVisitor: public boost::default_bfs_visitor {
 public:
  InsnVertexMap call2vertex;
  VertexInsnMap vertex2call;
  // The current start vertex (so we don't match ourself).
  CFGVertex current;
  CallOrderVisitor() { }
  template < typename Graph >
  void discover_vertex(CFGVertex v, const Graph & g UNUSED) const {
    // Don't match ourself.
    if (v == current) {
      //const SgAsmInstruction* i = vertex2call.at(v);
      //OINFO << "Instruction " << addr_str(i->get_address()) << " ignored." << LEND;
      return;
    }
    // But if we match one of the other call instructions, we're done, so throw!
    if (vertex2call.find(v) != vertex2call.end()) {
      const SgAsmInstruction* call_insn = vertex2call.at(v);
      const SgAsmInstruction* curr_insn = vertex2call.at(current);
      GDEBUG << "Address " << addr_str(curr_insn->get_address())
             << " was disproven by address " << addr_str(call_insn->get_address()) << LEND;
      throw VertexFound("found");
    }
  }
  // Add an instruction to the bidirectional map.
  void add(SgAsmInstruction* i, CFGVertex v) {
    call2vertex[i] = v;
    vertex2call[v] = i;
  }
};

class NonReturningCFGFilter {
 public:
  std::set<CFGEdge> non_returning_edges;
  template <typename Graph>
  void add_vertex(Graph& cfg, CFGVertex v) {
    for (const CFGEdge& e: cfg_out_edges(cfg, v)) {
      non_returning_edges.insert(e);
    }
  }
  bool operator()(const CFGEdge& e) const {
    return(non_returning_edges.find(e) == non_returning_edges.end());
  }
};

void ObjectUse::update_ctor_dtor(OOAnalyzer& ooa) const {
  // For each this-pointer... (since there can be multiple objects in a single function)
  for (const ThisPtrUsage& tpu : boost::adaptors::values(references)) {
    // A this-pointer usage (tpu) describes a particular object instance, including which
    // methods are called using the this pointer.
    tpu.update_ctor_dtor(ooa);
  }
}

// A new Prolog mode method to update the constructor/destructor booleans in the ThisCallMethod
// based on whether there are other function calls that come before or after the method.
void ThisPtrUsage::update_ctor_dtor(OOAnalyzer& ooa) const {
  // =====================================================================================
  // Step 1. The key of the method evidence map is the call instruction that called the
  // method on the this-pointer.  Look through the CFG finding the vertex numbers for each of
  // the calls and add them to the CallOrderVisitor.

  NonReturningCFGFilter nrf;
  CallOrderVisitor cov;

  // How many more vertices do we need to find?
  size_t remaining = method_evidence.size();
  // If there are no method calls to find, we're done.
  if (remaining == 0) return;

  // Get the control flow graph.
  CFG const & cfg = fd->get_rose_cfg();

  // For each vertex in the control flow graph.
  for (const CFGVertex& vertex : cfg_vertices(cfg)) {
    // Get the last instruction in the basic block.
    SgAsmBlock *bb = get(boost::vertex_name, cfg, vertex);
    const SgAsmInstruction* lastinsn = last_insn_in_block(bb);
    const SgAsmX86Instruction* lastxinsn = isSgAsmX86Instruction(lastinsn);

    // If the instruction is a call
    if (lastxinsn && insn_is_call(lastxinsn)) {
      // Get the call descriptor
      const CallDescriptor* cd = fd->ds.get_call(lastinsn->get_address());
      // If the call never returns, add it to the list of non-returning vertices.
      if (cd && cd->get_never_returns()) {
        //OINFO << "Adding vertex to non-returning hash list..." << LEND;
        nrf.add_vertex(cfg, vertex);
      }
    }

    // See if it's one of the methods that we're looking for.
    for (const MethodEvidenceMap::value_type& mpair : method_evidence) {
      SgAsmInstruction* callinsn = mpair.first;
      if (lastinsn == callinsn) {
        //OINFO << "Adding insn to map: " << addr_str(callinsn->get_address()) << LEND;
        // Add the vertex to the vector of interesting call vertices.
        cov.add(callinsn, vertex);
        // We've found another...
        remaining--;
        // There's no point in looking through more method evidence since we found it.
        break;
      }
    }

    // If we've found them all we're done.
    if (remaining == 0) break;
  }

  // If we didn't find them all, that's very unexpected.
  if (remaining != 0) {
    GERROR << "We did not find all the CFG vertices in " << fd->address_string() << LEND;
  }

  // =====================================================================================
  // Step 2. For each method called update the constructor/destructor facts.

  // For each call instruction...
  for (const MethodEvidenceMap::value_type& mpair : method_evidence) {
    SgAsmInstruction* callinsn = mpair.first;
    CFGVertex s = cov.call2vertex[callinsn];
    //OINFO << "Considering call insn: " << addr_str(callinsn->get_address()) << LEND;
    // For each method called by that instruction... (usually just one)
    for (const ThisCallMethod* tcm : mpair.second) {
      // Convert const tcm to non-const wtcm, so we can update the properties.
      ThisCallMethod* wtcm = ooa.get_method_rw(tcm->get_address());

      //OINFO << "Considering method: " << wtcm->address_string() << LEND;
      // If we still think that we're possibly a constructor...
      if (wtcm->no_calls_before) {
        //OINFO << "Method " << wtcm->address_string() << " is a possible constructor." << LEND;
        try {
          // Mark our starting vertex and then do a breadth first search for one of the other
          // calls.  Reverse the graph because we want to search backwards in the CFG.
          cov.current = s;
          boost::filtered_graph<CFG, NonReturningCFGFilter> filtered_graph(cfg, nrf);
          auto reversed_graph = boost::make_reverse_graph(filtered_graph);
          boost::breadth_first_search(reversed_graph, s, visitor(cov));
        }
        // If the search threw VertexFound, there's another call before this method, so we're
        // not a constructor.   Update the ThisCallMethod to reflect this.
        catch (VertexFound&) {
          GINFO << "Method " << wtcm->address_string() << " is NOT a constructor because "
                << "of the call at " << addr_str(callinsn->get_address()) << LEND;
          // Mark the method as not a constructor.
          wtcm->no_calls_before = false;
        }
      }

      // If we still think that we're possibly a destructor...
      if (wtcm->no_calls_after) {
        //OINFO << "Method " << wtcm->address_string() << " is a possible destructor." << LEND;
        try {
          // Mark our starting vertex and then do a breadth first search for one of the other
          cov.current = s;
          boost::filtered_graph<CFG, NonReturningCFGFilter> filtered_graph(cfg, nrf);
          boost::breadth_first_search(filtered_graph, s, visitor(cov));
        }
        // If the search threw VertexFound, there's another call after this method, so we're
        // not a destructor.   Update the ThisCallMethod to reflect this.
        catch (VertexFound&) {
          GINFO << "Method " << wtcm->address_string() << " is NOT a destructor because "
                << "of the call at " << addr_str(callinsn->get_address()) << LEND;
          // Mark the method as not a destructor.
          wtcm->no_calls_after = false;
        }
      }
    }
  }
}

// Analyze the function and populate the references member with information about each
// this-pointer use in the function.  We were filtering based on which methods were known to be
// object oriented by calling follow thunks, but that's heavily dependent on the order in which
// the functions are analyzed.
void ObjectUse::analyze_object_uses(OOAnalyzer const & ooa) {
  for (CallDescriptor* cd : fd->get_outgoing_calls()) {
    // The the value in the this-pointer location (ECX) before the call.
    SymbolicValuePtr this_ptr = get_this_ptr_for_call(cd);
    GDEBUG << "This-Ptr for call at " << cd->address_string() <<  " is " << *this_ptr << LEND;
    // We're only interested in valid pointers.
    if (!(this_ptr->is_valid())) continue;
    // If the symbolic value is an ITE expression, pick the meaningful one.
    this_ptr = pick_this_ptr(this_ptr);
    GDEBUG << "Updated This-Ptr for call at " << cd->address_string()
           <<  " is " << *this_ptr << LEND;
    // Get the string representation of the this-pointer.
    SVHash hash = this_ptr->get_hash();

    // Go through each of the possible targets looking for OO methods.
    for (rose_addr_t target : cd->get_targets()) {
      // If we're not an OO method, we're not interested.
      // We can't tell properly right now anyway because we're being called from visit()!!!
      const ThisCallMethod* tcm = ooa.follow_thunks(target);
      if (tcm == nullptr) continue;

      // Do we already have any entry for this this-pointer?
      ThisPtrUsageMap::iterator finder = references.find(hash);
      // If we don't create a new entry for the this-pointer.
      if (finder == references.end()) {
        GDEBUG << "Adding ref this_ptr=" << *this_ptr << LEND;
        references.insert(ThisPtrUsageMap::value_type(hash,
          ThisPtrUsage(fd, this_ptr, tcm, cd->get_insn())));
      }
      // Otherwise, add this method to the existing list of methods.
      else {
        GDEBUG << "Adding method this_ptr=" << *this_ptr << LEND;
        finder->second.add_method(tcm, cd->get_insn());
      }
    }
  }
}

} // namespace pharos

/* Local Variables:   */
/* mode: c++          */
/* fill-column:    95 */
/* comment-column: 0  */
/* End:               */

max_stars_repo_name: JanWielemaker/pharos

max_issues_repo_name: sei-ccohen/pharos

max_forks_repo_name: sei-ccohen/pharos


text:
/*
 * This file is part of the Sequoia MSO Solver.
 *
 * Copyright 2012 Alexander Langer, Theoretical Computer Science,
 *                                  RWTH Aachen University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @author Alexander Langer
 */
#include "apply_dynstep_assignments.h"
#include "lightweight_apply.h"

#include <algorithm>
#include <boost/scoped_ptr.hpp>
#ifdef HAVE_TBB
#include <tbb/parallel_do.h>
#endif

namespace sequoia {

template <typename ApplyGame, typename Solver>
void
ApplyDynStepAssignment<ApplyGame, Solver>::operator()(const SequoiaTable::const_iterator::value_type &entry) {
    const Assignment_f *child_alpha = entry.first;
    const GameVoidPtrMap *inmap = entry.second;
    ApplyGame apply(_solver, _node, _terminal_symbol, _game_info, child_alpha);
    apply.init();
    DPRINTLN("Start iterating over sets");
    GameVoidPtrMap::const_iterator git = inmap->begin();
    GameVoidPtrMap::const_iterator gitend = inmap->end();
#ifdef HAVE_TBB
    tbb::parallel_do(git, gitend, lightweight_apply(&apply));
#else
    std::for_each(git, gitend, lightweight_apply(&apply));
#endif
    _solver->log_games_completed(apply.count());
}

} // namespace

max_stars_repo_name: sequoia-mso/sequoia-core

max_issues_repo_name: sequoia-mso/sequoia-core

max_forks_repo_name: sequoia-mso/sequoia-core