text:
#include "compiler/steps.hpp"
#include "compiler/exceptions.hpp"
#include "shared/optional_apply.hpp"
#include "vm/instruction_pointer.hpp"

#include <boost/variant/apply_visitor.hpp>

#include <utility>
#include <tuple>
#include <sstream>

namespace perseus
{
  namespace detail
  {
    namespace clean = perseus::detail::ast::clean;
    namespace parser = perseus::detail::ast::parser;
    namespace art = perseus::detail::ast;

    using namespace std::string_literals;

    /// tag: any type allowed
    struct tag_any_type
    {
    };
    /// tag: any type except type_id::void_ allowed (for variable type deduction)
    struct tag_not_void
    {
    };
    /// Requirements for traversed expressions - must they be pure, according to the function? what type is expected?
    struct expectations
    {
      /// requirements on the type - none, not void, or must be a given type.
      typedef boost::variant<
        tag_any_type,
        tag_not_void,
        // specific type expected
        type_id
      > expected_type;

      expectations( bool pure, expected_type&& type )
        : pure( pure )
        , type( std::move( type ) )
      {
      }

      /// whether the expression must be pure (if false, it may be either)
      bool pure = true;
      expected_type type{ tag_any_type{} };

      bool is_purity_accepted( const bool actual_pure ) const
      {
        return actual_pure || !pure;
      }
      bool is_type_accepted( type_id actual_type ) const
      {
        /// visitor checking whether the type is valid
        struct type_check
        {
          const type_id& actual;
          bool operator()( const tag_any_type& ) const
          {
            return true;
          }
          bool operator()( const tag_not_void& ) const
          {
            return actual != type_id::void_;
          }
          bool operator()( const type_id& expected ) const
          {
            return actual == expected;
          }
        };
        return boost::apply_visitor( type_check{ actual_type }, type );
      }
    };

    struct variable
    {
      int offset;
      type_id type;
    };

    using scope = std::map< std::string, variable >;

    struct context
    {
      /// change expectations
      context expect( expectations::expected_type type ) const
      {
        return context{ expectations{ expected.pure, std::move( type ) }, functions, return_type, stack_size, variables };
      }
      context push( int bytes ) const
      {
        return context{ expected, functions, return_type, stack_size + bytes, variables };
      }
      const expectations expected;
      function_manager& functions;
      /// return type of current function, for return expressions
      const type_id return_type;
      int stack_size;
      scope variables;
    };

    /// @throws semantic_error on unknown signature
    static function_manager::function_pointer find_function( const context& context, const function_signature& signature, const file_position& pos )
    {
      function_manager::function_pointer function;
      if( !context.functions.get_function( signature, function ) )
      {
        function_manager::function_map::const_iterator begin, end;
        std::tie( begin, end ) = context.functions.get_functions( signature.name );
        std::stringstream error;
        error << "Could not find " << signature << "!";
        if( begin != end )
        {
          error << " Candidates:";
          while( begin != end )
          {
            error << "\n  " << begin->first;
            ++begin;
          }
        }
        throw semantic_error( error.str(), pos );
      }
      return function;
    }

    static void check_function( const context& context, function_manager::function_pointer function, const file_position& pos )
    {
      if( !context.expected.is_type_accepted( function->second.return_type ) )
      {
        std::stringstream error;
        error << function->first << " returns incorrect type " << get_name( function->second.return_type ) << "!";
        throw type_error{ error.str(), pos };
      }
      if( !context.expected.is_purity_accepted( function->second.pure ) )
      {
        std::stringstream error;
        error << "Can't call impure function " << function->first << " from pure function!";
        throw semantic_error{ error.str(), pos };
      }
    }

    static clean::expression convert( parser::expression&& exp, const context& context );
    static clean::expression convert( parser::operand&& op, const context& context );

    //    Block Member conversion (expression/variable declaration)

    struct convert_block_member
    {
      clean::block_member operator()( parser::expression& exp ) const
      {
        return convert( std::move( exp ), static_cast< const perseus::detail::context& >( context ) );
      }
      clean::block_member operator()( parser::explicit_variable_declaration& dec ) const
      {
        check_declaration_valid( dec.variable );
        type_id type = get_type( dec.type );
        // declared variable not yet visible in initial value expression
        clean::expression initial_value = convert( std::move( dec.initial_value ), context.expect( type ) );
        add_variable_to_context( std::move( dec.variable ), type );
        return clean::variable_declaration{ std::move( initial_value ) };
      }
      clean::block_member operator()( parser::deduced_variable_declaration& dec ) const
      {
        check_declaration_valid( dec.variable );
        clean::expression initial_value = convert( std::move( dec.initial_value ), context.expect( tag_not_void{} ) );
        add_variable_to_context( std::move( dec.variable ), initial_value.type );
        return clean::variable_declaration{ std::move( initial_value ) };
      }

      context& context;

    private:
      void check_declaration_valid( const file_position& pos ) const
      {
        if( !context.expected.is_type_accepted( type_id::void_ ) )
        {
          throw semantic_error{ "Variable declaration not valid here!", pos };
        }
      }
      void add_variable_to_context( std::string&& name, type_id type ) const
      {
        context.variables[ std::move( name ) ] = { context.stack_size, type };
        context.stack_size += get_size( type );
      }
    };

    static clean::block_member convert( parser::block_member&& member, context& context )
    {
      // this should really be std::move( member ), but apply_visitor does not support rvalues
      // see https://svn.boost.org/trac/boost/ticket/6971
      return boost::apply_visitor( convert_block_member{ context }, member );
    }

    //    Operand conversion (constants, variables, control structures etc.)

    struct convert_operand
    {
      //    Constants

      clean::expression operator()( const std::int32_t& i ) const
      {
        // TODO: track position
        if( !context.expected.is_type_accepted( type_id::i32 ) )
        {
          throw type_error{ "i32 type not valid here!", { 0, 0 } };
        }
        return { type_id::i32, { 0, 0 }, i };
      }
      clean::expression operator()( const bool& b ) const
      {
        // TODO: track position
        if( !context.expected.is_type_accepted( type_id::bool_ ) )
        {
          throw type_error{ "bool type not valid here!",{ 0, 0 } };
        }
        return{ type_id::bool_, { 0, 0 }, b };
      }
      clean::expression operator()( const ast::void_expression& ) const
      {
        // TODO: track position
        if( !context.expected.is_type_accepted( type_id::void_ ) )
        {
          throw type_error{ "void type not valid here!",{ 0, 0 } };
        }
        return{ type_id::void_, { 0, 0 }, ast::void_expression{} };
      }
      clean::expression operator()( const ast::string_literal& lit ) const
      {
        // TODO: string support
        throw semantic_error( "Strings not yet supported!"s, lit );
      }

      //    Variable references

      clean::expression operator()( const ast::identifier& identifier ) const
      {
        // TODO: first class functions
        auto it = context.variables.find( identifier );
        if( it == context.variables.end() )
        {
          throw semantic_error( "No such variable: "s + identifier, identifier );
        }
        if( !context.expected.is_type_accepted( it->second.type ) )
        {
          throw type_error{ "Variable "s + identifier + " has incorrect type "s + get_name( it->second.type ), identifier };
        }
        return clean::expression{ it->second.type, identifier, clean::local_variable_reference{ it->second.offset - context.stack_size } };
      }

      //    Unary Operation

      clean::expression operator()( parser::unary_operation& op ) const
      {
        file_position pos = std::move( static_cast< file_position& >( op.operation ) );
        clean::expression operand = convert( std::move( op.operand ), context.expect( tag_not_void{} ) );
        function_signature signature{ std::move( static_cast< std::string& >( op.operation ) ), { operand.type } };
        auto function = find_function( context, signature, pos );
        check_function( context, function, pos );
        return{ function->second.return_type, std::move( pos ), clean::call_expression{ function, { std::move( operand ) } } };
      }

      //    If Expression

      clean::expression operator()( parser::if_expression& exp ) const
      {
        clean::expression condition = convert( std::move( exp.condition ), context.expect( type_id::bool_ ) );
        clean::expression then_expression = convert( std::move( exp.then_expression ), context );
        clean::expression else_expression = convert( std::move( exp.else_expression ), context );
        if( then_expression.type != else_expression.type )
        {
          throw type_error( "\"if\" branch types do not match: then branch returns "s + get_name( then_expression.type ) + ", else branch returns "s + get_name( else_expression.type ) + "!"s, condition.position );
        }
        return{ then_expression.type, condition.position, clean::if_expression{ std::move( condition ), std::move( then_expression ), std::move( else_expression ) } };
      }

      //    While Expression

      clean::expression operator()( parser::while_expression& exp ) const
      {
        clean::expression condition = convert( std::move( exp.condition ), context.expect( type_id::bool_ ) );
        if( !context.expected.is_type_accepted( type_id::void_ ) )
        {
          throw type_error{ "Can't use while expression, void type illegal here!"s, condition.position };
        }
        clean::expression body = convert( std::move( exp.body ), context.expect( tag_any_type{} ) );
        return{ type_id::void_, condition.position, clean::while_expression{ std::move( condition ), std::move( body ) } };
      }

      //    Return Expression

      clean::expression operator()( parser::return_expression& exp ) const
      {
        clean::expression return_value = convert( std::move( exp.value ), context.expect( context.return_type ) );
        return{ context.return_type, return_value.position, clean::return_expression{ std::move( return_value ) } };
      }

      //    Block Expression

      clean::expression operator()( parser::block_expression& block ) const
      {
        std::vector< clean::block_member > members;
        // TODO: track position
        file_position pos{ 0, 0 };
        // use the same context for all members since its stack size and variables change
        perseus::detail::context member_context = context.expect( tag_any_type{} );
        for( auto it = block.body.begin(); it != block.body.end(); )
        {
          parser::block_member& member = *it;
          bool first = it == block.body.begin();
          ++it;
          // type only matters for last member
          if( it == block.body.end() )
          {
            perseus::detail::context type_context = member_context.expect( context.expected.type );
            members.emplace_back( convert( std::move( member ), type_context ) );
          }
          else
          {
            members.emplace_back( convert( std::move( member ), member_context ) );
          }
        }
        if( members.empty() )
        {
          if( !context.expected.is_type_accepted( type_id::void_ ) )
          {
            // TODO: track position
            throw type_error( "Block can't be empty, void type illegal here!", pos );
          }
          return{ type_id::void_, pos, clean::block_expression{ std::move( members ) } };
        }
        struct block_type
        {
          type_id operator()( const clean::variable_declaration& ) const
          {
            return type_id::void_;
          }
          type_id operator()( const clean::expression& exp ) const
          {
            return exp.type;
          }
        };
        type_id type = boost::apply_visitor( block_type{}, members.back() );
        return{ type, pos, clean::block_expression{ std::move( members ) } };
      }

      //    Expression

      clean::expression operator()( parser::expression& exp ) const
      {
        return convert( std::move( exp ), context );
      }

      const context& context;
    };

    static clean::expression convert( parser::operand&& op, const context& context )
    {
      // this should really be std::move( op ), but apply_visitor does not support rvalues
      // see https://svn.boost.org/trac/boost/ticket/6971
      return boost::apply_visitor( convert_operand{ context }, op );
    }

    //    Operation conversion

    static clean::expression generate_call( const context& context, const std::string& name, std::vector< clean::expression >&& arguments, file_position position )
    {
      function_signature signature{ std::move( name ),{} };
      signature.parameters.reserve( arguments.size() );
      for( const clean::expression& argument : arguments )
      {
        signature.parameters.push_back( argument.type );
      }
      auto function = find_function( context, signature, position );
      check_function( context, function, position );
      return{ function->second.return_type, std::move( position ), clean::call_expression{ function, std::move( arguments ) } };
    }

    struct convert_operation
    {

      clean::expression operator()( parser::binary_operation& bin ) const
      {
        return generate_call(
          context,
          // name
          std::move( static_cast< std::string& >( bin.operation ) ),
          // arguments
          { std::move( lhs ), convert( std::move( bin.operand ), context.expect( tag_not_void{} ) ) },
          // position
          std::move( static_cast< file_position& >( bin.operation ) )
          );
      }
      clean::expression operator()( parser::index_expression& exp ) const
      {
        return generate_call(
          context,
          "[]"s,
          { std::move( lhs ), convert( std::move( exp.index ), context.expect( tag_not_void{} ) ) },
          lhs.position
          );
      }
      clean::expression operator()( parser::call_expression& exp ) const
      {
        throw std::logic_error( "Should have been handled separately!" );
      }

      clean::expression lhs;
      const context& context;
    };

    static clean::expression convert( parser::expression&& exp, const context& context )
    {
      // TODO FIXME: support more than 2 operands, i.e. handle precedence & associativity
      if( exp.tail.empty() )
      {
        // simple operand

        return convert( std::move( exp.head ), context );
      }
      else if( exp.tail.size() == 1 )
      {
        // binary expression, including call & index

        parser::operation& operation = exp.tail.front();
        parser::call_expression* call_exp = boost::get< parser::call_expression >( &operation );
        if( call_exp )
        {
          // since we have no first class functions yet, we need to handle this separately
          ast::identifier* function_name = boost::get< ast::identifier >( &exp.head );
          if( !function_name )
          {
            throw semantic_error{ "Functions must be referred to by identifier! (No first-class functions yet.)"s, {0,0} };
          }

          function_signature signature{ std::move( static_cast< std::string& >( *function_name ) ),{} };
          signature.parameters.reserve( call_exp->arguments.size() );
          for( const parser::expression& argument : call_exp->arguments )
          {
            // this expression tree is unusable due to invalid local variable stack offsets, but we need to create it to determinate the type
            // the offsets are off by the size of the function's return value, for which memory is allocated on the stack prior to the call
            // but since we need the parameter types to determine the return type, some duplicate work is required
            // (luckily function call arguments are typically rather simple, so this isn't totally terrible)
            clean::expression exp = convert( parser::expression( argument ), context.expect( tag_not_void{} ) );
            signature.parameters.push_back( exp.type );
          }
          file_position& position = *function_name;
          auto function = find_function( context, signature, position );
          check_function( context, function, position );

          std::vector< clean::expression > arguments;
          arguments.reserve( call_exp->arguments.size() );
          // stack grows due to multiple arguments being pushed
          int stack_offset = get_size( function->second.return_type );
          for( auto& arg : call_exp->arguments )
          {
            clean::expression exp = convert( std::move( arg ), context.expect( tag_not_void{} ).push( stack_offset ) );
            stack_offset += get_size( exp.type );
            arguments.emplace_back( std::move( exp ) );
          }
          return{ function->second.return_type, std::move( position ), clean::call_expression{ function, std::move( arguments ) } };
        }
        else
        {
          clean::expression lhs = convert( std::move( exp.head ), context.expect( tag_not_void{} ) );
          const perseus::detail::context convert_context = context.push( get_size( lhs.type ) );
          // this should really be std::move( exp.tail.front() ), but apply_visitor does not support rvalues
          // see https://svn.boost.org/trac/boost/ticket/6971
          return boost::apply_visitor( convert_operation{ std::move( lhs ), convert_context }, exp.tail.front() );
        }
      }
      else
      {
        // n-ary expression (n > 2)

        throw semantic_error{ "Sorry, but for now operator precedence must be explicitly defined using parens."s, { 0, 0 } };
      }
    }

    clean::file simplify_and_annotate( parser::file&& file, function_manager& functions )
    {
      ast::clean::file result;
      result.functions.reserve( file.functions.size() );
      for( auto& function : file.functions )
      {
        scope initial_scope;
        {
          int offset = -static_cast< int >( sizeof( instruction_pointer::value_type ) ); // return address
          for( auto it = function.arguments.rbegin(); it != function.arguments.rend(); ++it )
          {
            auto& arg = *it;
            type_id type = get_type( arg.type );
            offset -= get_size( type );
            initial_scope.emplace( scope::value_type{ std::move( arg.name ), variable{ offset, type } } );
          }
        }
        // set up context: expected return type, purity
        type_id return_type = function.manager_entry->second.return_type;
        expectations expected{ function.manager_entry->second.pure, return_type };
        context initial_context{ expected, functions, return_type, 0, std::move( initial_scope ) };
        result.functions.emplace_back(
          clean::function_definition{ convert( std::move( function.body ), static_cast< const context& >( initial_context ) ), function.manager_entry }
        );
      }
      return result;
    }
  }
}

max_stars_repo_name: mrwonko/perseus

max_issues_repo_name: mrwonko/perseus

max_forks_repo_name: mrwonko/perseus


text:
#pragma once

#ifdef USEWINSDK

#include <Windows.h>
#include <boost/optional.hpp>

namespace chatterino {

boost::optional<UINT> getWindowDpi(HWND hwnd);

}  // namespace chatterino

#endif

ext: hpp


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_COMPONENTS_CLIENT_BASE_OCT_31_2008_0424PM)
#define HPX_COMPONENTS_CLIENT_BASE_OCT_31_2008_0424PM

#include <hpx/hpx_fwd.hpp>

#include <hpx/runtime/components/stubs/runtime_support.hpp>
#include <hpx/runtime/naming/name.hpp>
#include <hpx/runtime/components/component_type.hpp>
#include <hpx/runtime/components/stubs/stub_base.hpp>
#include <hpx/util/always_void.hpp>
#include <hpx/util/move.hpp>
#include <hpx/util/safe_bool.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/traits/is_future.hpp>
#include <hpx/traits/acquire_future.hpp>
#include <hpx/runtime/agas/interface.hpp>

#include <utility>
#include <boost/utility/enable_if.hpp>
#include <boost/preprocessor/enum_params.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/type_traits/is_base_of.hpp>

///////////////////////////////////////////////////////////////////////////////
// Client objects are equivalent to futures
namespace hpx { namespace components
{
    template <typename Derived, typename Stub>
    class client_base;
}}

namespace hpx { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable = void>
    struct is_client
      : boost::mpl::false_
    {};

    template <typename Derived>
    struct is_client<Derived,
        typename util::always_void<typename Derived::stub_argument_type>::type
    > : boost::is_base_of<
            components::client_base<
                Derived, typename Derived::stub_argument_type
            >,
            Derived>
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename Derived>
    struct is_future<Derived,
        typename boost::enable_if<is_client<Derived> >::type>
      : boost::mpl::true_
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename Derived>
    struct future_traits<Derived,
        typename boost::enable_if<is_client<Derived> >::type>
    {
        typedef naming::id_type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename Derived>
    struct future_access<Derived,
        typename boost::enable_if<is_client<Derived> >::type>
    {
        BOOST_FORCEINLINE static
        typename lcos::detail::shared_state_ptr<naming::id_type>::type const&
        get_shared_state(Derived const& client)
        {
            return client.share().shared_state_;
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename Derived>
    struct acquire_future_impl<Derived,
        typename boost::enable_if<is_client<Derived> >::type>
    {
        typedef Derived type;

        template <typename T_>
        BOOST_FORCEINLINE
        Derived operator()(T_ && value) const
        {
            return std::forward<T_>(value);
        }
    };
}}

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace components
{
    namespace detail
    {
        BOOST_MPL_HAS_XXX_TRAIT_DEF(server_component_type)

        // Wrap a give type such that it is usable as a stub_base.
        // The main template is chosen whenever the argument Stub is not a (or
        // not derived from) a stub_base. In this case Stub should be a server
        // side component implementation type.
        template <typename Stub, typename Enable = void>
        struct make_stub
        {
            typedef components::stub_base<Stub> type;
            typedef typename components::stub_base<Stub>::server_component_type
                server_component_type;
        };

        // This specialization is chosen whenever the argument Stub is a (or
        // derived from a) stub_base.
        template <typename Stub>
        struct make_stub<Stub, typename util::always_void<
            typename Stub::server_component_type>::type>
        {
            typedef Stub type;
            typedef typename Stub::server_component_type server_component_type;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename Derived>
        struct client_unwrapper
        {
            typedef shared_future<naming::id_type> result_type;

            BOOST_FORCEINLINE result_type
            operator()(future<Derived> f) const
            {
                return f.get().share();
            }
        };
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Derived, typename Stub>
    class client_base : public detail::make_stub<Stub>::type
    {
    protected:
        typedef typename detail::make_stub<Stub>::type stub_type;
        typedef shared_future<naming::id_type> future_type;

    public:
        typedef Stub stub_argument_type;
        typedef typename detail::make_stub<Stub>::server_component_type
            server_component_type;

        client_base()
          : gid_()
        {}

        explicit client_base(naming::id_type const& gid)
          : gid_(lcos::make_ready_future(gid))
        {}
        explicit client_base(naming::id_type && gid)
          : gid_(lcos::make_ready_future(std::move(gid)))
        {}

        explicit client_base(future_type const& gid)
          : gid_(gid)
        {}
        explicit client_base(future_type && gid)
          : gid_(std::move(gid))
        {}
        explicit client_base(future<naming::id_type> && gid)
          : gid_(gid.share())
        {}

        explicit client_base(client_base const& rhs)
          : gid_(rhs.gid_)
        {}
        explicit client_base(client_base && rhs)
          : gid_(std::move(rhs.gid_))
        {}

        // A future to a client_base can be unwrapped to represent the
        // client_base directly as a client_base holds another future to the
        // id of the referenced object.
        client_base(future<Derived> && d)
          : gid_(d.then(detail::client_unwrapper<Derived>()))
        {}

        // copy assignment and move assignment
        client_base& operator=(naming::id_type const & gid)
        {
            gid_ = lcos::make_ready_future(gid);
            return *this;
        }
        client_base& operator=(naming::id_type && gid)
        {
            gid_ = lcos::make_ready_future(std::move(gid));
            return *this;
        }

        client_base& operator=(future_type const & gid)
        {
            gid_ = gid;
            return *this;
        }
        client_base& operator=(future_type && gid)
        {
            gid_ = std::move(gid);
            return *this;
        }
        client_base& operator=(future<naming::id_type> && gid)
        {
            gid_ = gid.share();
            return *this;
        }

        client_base& operator=(client_base const & rhs)
        {
            gid_ = rhs.gid_;
            return *this;
        }
        client_base& operator=(client_base && rhs)
        {
            gid_ = std::move(rhs.gid_);
            return *this;
        }

        bool valid() const
        {
            return gid_.valid();
        }

        // check whether the embedded future is valid
        operator typename util::safe_bool<client_base>::result_type() const
        {
            return util::safe_bool<client_base>()(valid());
        }

        ///////////////////////////////////////////////////////////////////////
        /// Create a new instance of an object on the locality as
        /// given by the parameter \a targetgid
        static Derived create(naming::id_type const& targetgid)
        {
            return Derived(stub_type::create_async(targetgid));
        }

        static Derived create_colocated(naming::id_type const& id)
        {
            return Derived(stub_type::create_colocated_async(id));
        }

#define HPX_CLIENT_BASE_CREATE(Z, N, D)                                       \
        template <BOOST_PP_ENUM_PARAMS(N, typename Arg)>                      \
        static Derived create(naming::id_type const& targetgid,               \
            HPX_ENUM_FWD_ARGS(N, Arg, arg))                                   \
        {                                                                     \
            return Derived(stub_type::create_async(targetgid,                 \
                HPX_ENUM_FORWARD_ARGS(N , Arg, arg)));                        \
        }                                                                     \
                                                                              \
        template <BOOST_PP_ENUM_PARAMS(N, typename Arg)>                      \
        static Derived create_colocated(naming::id_type const& id,            \
            HPX_ENUM_FWD_ARGS(N, Arg, arg))                                   \
        {                                                                     \
            return Derived(stub_type::create_colocated_async(id,              \
                HPX_ENUM_FORWARD_ARGS(N , Arg, arg)));                        \
        }                                                                     \
    /**/

        BOOST_PP_REPEAT_FROM_TO(
            1
          , HPX_ACTION_ARGUMENT_LIMIT
          , HPX_CLIENT_BASE_CREATE
          , _
        )

#undef HPX_CLIENT_BASE_CREATE

        void free()
        {
            gid_ = future_type();
        }

        ///////////////////////////////////////////////////////////////////////
        naming::id_type const & get_gid() const
        {
            return gid_.get();
        }

        naming::gid_type const & get_raw_gid() const
        {
            return gid_.get().get_gid();
        }

        ///////////////////////////////////////////////////////////////////////
        future_type detach()
        {
            shared_future<naming::id_type> g;
            std::swap(gid_, g);
            return g;
        }

        future_type const& share() const
        {
            return gid_;
        }

        void reset(id_type const& id)
        {
            gid_ = make_ready_future(id);
        }

        void reset(id_type && id)
        {
            gid_ = make_ready_future(std::move(id));
        }

        void reset(future_type && rhs)
        {
            gid_ = std::move(rhs);
        }

        ///////////////////////////////////////////////////////////////////////
        // Interface mimicking future
        bool is_ready() const
        {
            return gid_.is_ready();
        }

        ///////////////////////////////////////////////////////////////////////
    protected:
        static void register_as_helper(shared_future<naming::id_type> f,
            std::string const& symbolic_name)
        {
            hpx::agas::register_name(symbolic_name, f.get());
        }

    public:
        // Register our id with AGAS using the given name
        future<void> register_as(std::string const& symbolic_name)
        {
            using util::placeholders::_1;
            return gid_.then(util::bind(
                &client_base::register_as_helper, _1, symbolic_name));
        }

        // Retrieve the id associated with the given name and use it to
        // initialize this client_base instance.
        //
        // F is expected to reset the underlying client_base, it is passed the
        // future<id_type> returned from on_symbol_namespace_event()
        template <typename F>
        future<void> connect_to(std::string const& symbolic_name, F && f)
        {
            return agas::on_symbol_namespace_event(
                symbolic_name, agas::symbol_ns_bind, true)
                    .then(std::forward<F>(f));
        }

    protected:
        void connect_to_helper(future<naming::id_type> f)
        {
            gid_ = f.share();
        }

    public:
        future<void> connect_to(std::string const& symbolic_name)
        {
            using util::placeholders::_1;
            return connect_to(symbolic_name,
                util::bind(&client_base::connect_to_helper, this, _1));
        }

//     protected:
//         template <typename F>
//         static typename lcos::detail::future_then_result<client_base, F>::cont_result
//         on_ready(future_type fut, F && f)
//         {
//             return f(Derived(fut));
//         }
//
//     public:
//         template <typename F>
//         typename lcos::detail::future_then_result<client_base, F>::type
//         then(F && f)
//         {
//             typedef typename util::decay<F>::type func_type;
//             return gid_.then(util::bind(
//                 util::one_shot(&client_base::on_ready<func_type>),
//                 std::forward<F>(f)));
//         }

    private:
        friend class boost::serialization::access;

        template <typename Archive>
        void serialize(Archive & ar, unsigned)
        {
            ar & gid_;
        }

    protected:
        future_type gid_;
    };
}}

#endif


text:
//  (C) Copyright Tony Lewis 2016.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  Description : checks that datasets over tuples are supported
//  see issue https://svn.boost.org/trac/boost/ticket/12241
// ***************************************************************************

#define BOOST_TEST_MODULE boost_test_tuple_prob

#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>

#include <tuple>
#include <vector>
#include <iostream>

const std::vector< std::tuple<int, int>> values = {
        std::tuple<int, int>{  1, 11 },
        std::tuple<int, int>{  2, 12 },
        std::tuple<int, int>{  3, 13 },
};

BOOST_DATA_TEST_CASE( test1, boost::unit_test::data::make( values ), var1, var2 ) {
        std::cout << var1 << ", " << var2 << "\n";
}

ext: cpp


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_DIMENSIONLESS_TYPE_HPP
#define BOOST_UNITS_DIMENSIONLESS_TYPE_HPP

///
/// \file
/// \brief Dimension lists in which all exponents resolve to zero reduce to @c dimensionless_type.
///

#include <boost/mpl/long.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/arithmetic.hpp>

#include <boost/units/config.hpp>

namespace boost {

namespace units {

namespace detail {

struct dimension_list_tag;

}

/// Dimension lists in which all exponents resolve to zero reduce to @c dimensionless_type.
struct dimensionless_type
{
    typedef dimensionless_type          type;
    typedef detail::dimension_list_tag  tag;
    typedef mpl::long_<0>               size;
};

} // namespace units

} // namespace boost

#if BOOST_UNITS_HAS_BOOST_TYPEOF

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TYPE(boost::units::dimensionless_type)

#endif

#endif // BOOST_UNITS_DIMENSIONLESS_TYPE_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


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

#include <exception>
#include <cstdlib>
#include <iostream>
#include <string>

#include <boost/thread.hpp>

#include "producer.hpp"

int main(int argc, char* argv[])
{
	std::string hostname = (argc >= 2) ? argv[1] : "localhost";
	std::string port = (argc >= 3) ? argv[2] : "9092";

	boost::asio::io_service io_service;
	std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(io_service));
	boost::thread bt(boost::bind(&boost::asio::io_service::run, &io_service));

	kafkaconnect::producer producer(io_service);
	producer.connect(hostname, port);

	while(!producer.is_connected())
	{
		boost::this_thread::sleep(boost::posix_time::seconds(1));
	}

	std::vector<std::string> messages;
	messages.push_back("So long and thanks for all the fish");
	messages.push_back("Time is an illusion. Lunchtime doubly so.");
	producer.send(messages, "test");

	work.reset();
	io_service.stop();

	return EXIT_SUCCESS;
}

max_stars_repo_name: JerryYuYG/kafka

max_issues_repo_name: JerryYuYG/kafka

max_forks_repo_name: JerryYuYG/kafka


text:
/*
 *
 * Author : Anishka Gupta
 * Created on July 7, 2017
 *
 */

#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <boost/tokenizer.hpp>

#include "parser.hpp"
#include "PorterStemmer/porter2_stemmer.h"

namespace wunner
{

  Parser::Parser()
  {
      std::ifstream fin(STOPPER);
      if (fin) {
          std::string stop_word;
          while (!fin.eof()) {
              getline(fin, stop_word);
              stop_words.insert(stop_word);
          }
      } else {
          std::cerr << "WARNING: Couldn't find list of stop words to filter out!";
      }
  }

  void Parser::tokenizer(std::string const & document)
  {
      boost::char_separator<char> sep(",.@|-\"\"\'\' \n");
      std::ifstream fin(document);
      if (fin) {
          std::stringstream buf;
          buf << fin.rdbuf();
          std::string doc = buf.str();
          boost::tokenizer<boost::char_separator<char>> tokens(doc, sep);
          for (auto it = tokens.begin(); it != tokens.end(); ++it) {
              parsed_doc.push_back(*it);
          }
          fin.close();
      } else {
          // Do nothing, skip that file
          std::cerr << "Document " << document << " not found!" << std::endl;
      }
  }

  void Parser::query_tokenizer(std::string const & query)
  {
      boost::char_separator<char> sep(",.@|-\"\"\'\' \n");
      boost::tokenizer<boost::char_separator<char>> tokens(query, sep);
      for (auto it = tokens.begin(); it != tokens.end(); ++it) {
          parsed_doc.push_back(*it);
      }
  }

  void Parser::normalizer()
  {
      for (auto & word : parsed_doc) {
           std::transform(word.begin(), word.end(), word.begin(), ::tolower);
      }
  }

  void Parser::stop_words_removal()
  {
      parsed_doc.erase(std::remove_if(parsed_doc.begin(), parsed_doc.end(),
                                         [&](std::string const & w) {
                                             if (stop_words.find(w) == stop_words.end()) {
                                                 return false;
                                             } else {
                                                 return true;
                                             }
                                     }), parsed_doc.end());
  }

  void Parser::stemmer()
  {
      std::unordered_map<std::string, std::string> yet_stemmed;
      for (auto & word : parsed_doc) {
          if (yet_stemmed.find(word) == yet_stemmed.end()) {
              std::string orig_word = word;
              Porter2Stemmer::stem(word);
              yet_stemmed[orig_word] = word;
          } else {
              word = yet_stemmed[word];
          }
      }
  }

  std::vector<std::string> Parser::get_parsed_document(std::string const & document)
  {
      parsed_doc.clear();
      tokenizer(document);
      normalizer();
      stop_words_removal();
      stemmer();
      return parsed_doc;
  }

  const std::vector<std::string> & Parser::get_parsed_query(std::string const & query)
  {
      query_tokenizer(query);
      normalizer();
      stop_words_removal();
      stemmer();
      return parsed_doc;
  }

}


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/append.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/concat.hpp>
#include <boost/hana/empty.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/tuple.hpp>

#include <string>
namespace hana = boost::hana;
using namespace std::string_literals;

BOOST_HANA_CONSTANT_CHECK(hana::empty<hana::tuple_tag>() == hana::make_tuple());

static_assert(hana::append(hana::make_tuple(1, '2', 3.3), nullptr)
                        == hana::make_tuple(1, '2', 3.3, nullptr), "");

int main() {
    BOOST_HANA_RUNTIME_CHECK(
        hana::concat(hana::make_tuple(1, '2', 3.3), hana::make_tuple("abcdef"s)) ==
        hana::make_tuple(1, '2', 3.3, "abcdef"s)
    );
}


text:
#include <boost/parameter.hpp>
#include <cassert>
BOOST_PARAMETER_NAME(name)
BOOST_PARAMETER_NAME(index)

template <class Name, class Index>
int deduce_arg_types_impl(Name& name, Index& index)
{
    Name& n2 = name;  // we know the types
    Index& i2 = index;
    return index;
}

template <class ArgumentPack>
int deduce_arg_types(ArgumentPack const& args)
{
    return deduce_arg_types_impl(args[_name], args[_index|42]);
}
int a1 = deduce_arg_types((_name = "foo"));
int a2 = deduce_arg_types((_name = "foo", _index = 3));

int main()
{
    assert(a1 == 42);
    assert(a2 == 3);
}


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2006-2013
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_slist_code
#include <boost/intrusive/slist.hpp>
#include <vector>

using namespace boost::intrusive;

                  //This is a base hook
class MyClass : public slist_base_hook<>
{
   int int_;

   public:
   //This is a member hook
   slist_member_hook<> member_hook_;

   MyClass(int i)
      :  int_(i)
   {}
   //<-
   int get_int() const { return int_; }
   //->
};

//Define an slist that will store MyClass using the public base hook
typedef slist<MyClass> BaseList;

//Define an slist that will store MyClass using the public member hook
typedef member_hook<MyClass, slist_member_hook<>, &MyClass::member_hook_> MemberOption;
typedef slist<MyClass, MemberOption> MemberList;

int main()
{
   typedef std::vector<MyClass>::iterator VectIt;
   typedef std::vector<MyClass>::reverse_iterator VectRit;

   //Create several MyClass objects, each one with a different value
   std::vector<MyClass> values;
   for(int i = 0; i < 100; ++i)  values.push_back(MyClass(i));

   BaseList baselist;
   MemberList memberlist;

   //Now insert them in the reverse order in the base hook list
   for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it)
      baselist.push_front(*it);

   //Now insert them in the same order as in vector in the member hook list
   for(BaseList::iterator it(baselist.begin()), itend(baselist.end())
      ; it != itend; ++it){
      memberlist.push_front(*it);
   }

   //Now test lists
   {
      BaseList::iterator bit(baselist.begin());
      MemberList::iterator mit(memberlist.begin());
      VectRit rit(values.rbegin()), ritend(values.rend());
      VectIt  it(values.begin()), itend(values.end());

      //Test the objects inserted in the base hook list
      for(; rit != ritend; ++rit, ++bit)
         if(&*bit != &*rit)   return 1;

      //Test the objects inserted in the member hook list
      for(; it != itend; ++it, ++mit)
         if(&*mit != &*it)    return 1;
   }

   return 0;
}
//]


text:
#ifndef AVECADO_HPP
#define AVECADO_HPP

#include "tile.hpp"
#include "post_processor.hpp"

#include <memory>
#include <boost/optional.hpp>
#include <mapnik/map.hpp>
#include <mapnik/image_scaling.hpp>

// forward declaration of mapnik's raster image type
namespace mapnik { class image_32; }

namespace avecado {

/**
 * make_vector_tile adds geometry from a mapnik query to a vector
 * tile object.
 *
 * Arguments:
 *
 *   tile
 *     The vector tile to which geometry from the query will be
 *     added.
 *
 *   path_multiplier
 *     Multiplier for pixel coordinates within the vector tile. If
 *     this is set to 1, then coordinates will correspond to integer
 *     pixels. However, a larger number (e.g: 16) is recommended to
 *     improve the visual appearance of vector tiles, especially when
 *     over-zoomed.
 *
 *   map
 *     The mapnik object which contains the settings for the queries
 *     and styles used to build the vector tile.
 *
 *   buffer_size
 *     The size of the buffer in pixels which adds a "border" around
 *     the vector tile for which data is extracted, but is not
 *     intended to be part of the visible area. This exists to handle
 *     the rendering of objects whose visual effects extend beyond
 *     their geometric extent (e.g: lines rendered with a width, but
 *     the geometry has zero width).
 *
 *   scale_factor
 *     Scale factor by which to increase the pixel sizes of rendered items.
 *
 *   offset_x & offset_y
 *     Offset in pixels to add to transformed coordinates. This can be
 *     used to shift the origin of the vector tile to a different
 *     position.
 *
 *   tolerance
 *     If a geometry path has successive points which are closer than
 *     this tolerance in both the x and y directions, then the point
 *     will be dropped. Note that the units are pixels multiplied by
 *     the `path_multiplier`.
 *
 *   image_format
 *     File format used when encoding raster features in the tile
 *     object.
 *
 *   scaling_method
 *     Which method to use when scaling pixels from raster sources.
 *
 *   scale_denominator
 *     Scale denominator to use when rendering features. If <= 0, then
 *     mapnik will choose an appropriate scale based on the request
 *     size.
 *
 *   post_processor
 *     An optional `post_processor` object to handle geometry
 *     operations ("izers") before the tile is serialised.
 *
 * Returns true if the renderer painted, which means that it added
 * some geometry to the vector tile. Returns false if no geometry
 * was added. This can be used to detect empty tiles, which can be
 * used to accelerate hierarchical rendering of tiles by pruning
 * empty branches.
 *
 * Throws an exception if an unrecoverable error was encountered
 * while building the vector tile.
 */
bool make_vector_tile(tile &tile,
                      unsigned int path_multiplier,
                      mapnik::Map const& map,
                      int buffer_size,
                      double scale_factor,
                      unsigned int offset_x,
                      unsigned int offset_y,
                      unsigned int tolerance,
                      const std::string &image_format,
                      mapnik::scaling_method_e scaling_method,
                      double scale_denominator,
                      boost::optional<const post_processor &> post_processor);

/* Render a vector tile to a raster image.
 *
 * This function takes a vector tile as data, and renders to the
 * referenced raster image using the other parameters given.
 *
 * Arguments:
 *
 *   image:
 *     The raster image type to render into. Any content already
 *     rendered to this object will likely be overwritten.
 *
 *   tile:
 *     Vector tile object, containing the data about the features
 *     which will be rendered. Note that the tile object may cover
 *     a larger extent than needs to be rendered (a.k.a. overzoom)
 *
 *   map:
 *     The Mapnik object encapsulating the style with which to
 *     render the map.
 *
 *   z, x & y:
 *     Tile coordinates of the region to be rendered to the image.
 *
 *   scale_factor:
 *     Scale factor to use when rendering.
 *
 *   buffer_size:
 *     Buffer size to use around the rendered image. Setting
 *     this will not cause additional tiles to be fetched and
 *     setting it to anything larger than the greatest
 *     buffer_size of the underlying vector tiles will not
 *     normally have an effect. (TODO: check this is what's
 *     actually happening.)
 */
bool render_vector_tile(mapnik::image_32 &image,
                        tile &tile,
                        mapnik::Map const &map,
                        double scale_factor,
                        unsigned int buffer_size);

} // namespace avecado

#endif /* AVECADO_HPP */

max_stars_repo_name: zerebubuth/avecado

max_issues_repo_name: zerebubuth/avecado

max_forks_repo_name: zerebubuth/avecado


text:
// #pragma GCC optimize ("O0")

#include "fileLog.hpp"

#include <chrono>
#include <ctime>

#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/log/trivial.hpp>

#ifdef ENABLE_MONGODB
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>

using bsoncxx::builder::basic::kvp;

#endif

namespace sinks = boost::log::sinks;

string FileLog::path_log;

void FileLog::consume(
	boost::log::record_view																	const&	rec,
	sinks::basic_formatted_sink_backend<char, sinks::synchronized_feeding>::string_type		const&	log_string)
{
	string mess = log_string.c_str();
	boost::erase_all(mess, "\n");
	if (mess == "")
		return;

	int logLevel = 2;
	auto attrs = rec.attribute_values();
	auto sev = attrs[boost::log::trivial::severity].get();
	switch (sev)
	{
		case boost::log::trivial::trace:			logLevel = 5;			break;
		case boost::log::trivial::debug:			logLevel = 4;			break;
		case boost::log::trivial::info:				logLevel = 3;			break;
		case boost::log::trivial::warning:			logLevel = 2;			break;
		case boost::log::trivial::error:			logLevel = 1;			break;
		case boost::log::trivial::fatal:			logLevel = 0;			break;
	}

	std::ofstream logStream(FileLog::path_log, std::ofstream::app);

	if (!logStream)
		return;

	std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

	bsoncxx::builder::basic::document doc = {};
	doc.append(kvp("label", 		"message"));
// 	doc.append(kvp("timestamp", 	std::put_time(std::localtime( &now ),"%F %X")));
	doc.append(kvp("level", 		logLevel));
	doc.append(kvp("str", 			mess));

	logStream << bsoncxx::to_json(doc) << std::endl;
}

void addFileLog()
{
	// Construct the sink
	using LogSink = sinks::synchronous_sink<FileLog>;

	boost::shared_ptr<LogSink> logSink = boost::make_shared<LogSink>();

	// Register the sink in the logging core
	boost::log::core::get()->add_sink(logSink);
}

max_stars_repo_name: GnssTao/ginan


text:
// Copyright (C) 2009-2020 Christian@Schladetsch.com
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MONOTONIC_STACK_HPP
#define BOOST_MONOTONIC_STACK_HPP

#include <typeinfo>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility/iter_range.hpp>

#include <boost/monotonic/detail/prefix.hpp>
#include <boost/monotonic/storage.hpp>
#include <boost/monotonic/containers/vector.hpp>

// warning C4345: behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized
#pragma warning(disable:4345)

namespace boost
{
    namespace monotonic
    {
        struct null_pointer {};

        /// a first-class fixed-size stack object
        template <size_t InlineSize>
        struct fixed_stack
        {
            typedef fixed_stack<InlineSize> this_type;

        private:
            fixed_storage<InlineSize> store;

            template <class>
            struct element;

            /// an entry on the stack
            struct element_base
            {
                element_base *previous;
                size_t cursor;
                bool is_pod;
                element_base(bool ip = false)
                    : is_pod(ip) { }
                template <class T>
                bool is_type() const
                {
                    return get_type() == typeid(T);
                }
                template <class T>
                T &get()
                {
                    if (get_type() != typeid(T))
                        throw std::bad_get();
                    return *static_get<element<T> &>(*this).get_pointer();
                }
                template <class T>
                const T &get() const
                {
                    if (get_type() != typeid(T))
                        throw std::bad_get();
                    return *static_get<const element<T> &>(*this).get_pointer();
                }

                virtual void destroy() {}
                virtual const std::type_info &get_type() const = 0;
            };
            struct impl
            {
                /// a class-type element
                template <class T, bool>
                struct element : element_base
                {
                    typedef T type;
                    typedef type *pointer;

                private:
                    pointer ptr;
                    char value[sizeof(T)];

                public:
                    element()
                        : ptr(reinterpret_cast<T *>(value))
                    {
                    }
                    const std::type_info &get_type() const
                    {
                        return typeid(T);
                    }
                    pointer get_pointer()
                    {
                        return ptr;
                    }
                    void destroy()
                    {
                        destroy(ptr, boost::has_trivial_destructor<type>());
                    }
                    void destroy(pointer ptr, const boost::false_type& )
                    {
                        (*ptr).~type();
                    }

                    void destroy(pointer, const boost::true_type& )
                    {
                    }
                };

                /// a pod-type element
                template <class T>
                struct element<T, true> : element_base
                {
                    typedef T type;
                    type val;
                    element()
                        : element_base(true)
                    {
                    }
                    type *get_pointer()
                    {
                        return &val;
                    }
                    const std::type_info &get_type() const
                    {
                        return typeid(T);
                    }
                };
            };

            /// an element of a given type on the stack
            template <class T>
            struct element
                : impl::element<T, boost::is_pod<T>::value>
            {
            };

            element_base *previous;

        public:
            typedef element_base value_type;
            typedef element_base &reference;
            typedef element_base const &const_reference;
            typedef size_t size_type;

            struct const_iterator : boost::iterator<forward_traversal_tag, element_base>
            {
                typedef element_base value_type;
                element_base *current;

                const_iterator(element_base *elem = 0)
                    : current(elem) { }

                const value_type &operator*() const
                {
                    return *current;
                }
                const value_type *operator->() const
                {
                    return current;
                }
                const_iterator &operator++()
                {
                    current = current->previous;
                    return *this;
                }
                const_iterator operator++(int)
                {
                    const_iterator tmp = *this;
                    ++(*this);
                    return tmp;
                }
                friend bool operator==(const_iterator left, const_iterator right)
                {
                    return left.current == right.current;
                }
                friend bool operator!=(const_iterator left, const_iterator right)
                {
                    return left.current != right.current;
                }
            };

            struct iterator : const_iterator
            {
                iterator(element_base *elem = 0)
                    : const_iterator(elem) { }

                value_type &operator*()
                {
                    return *current;
                }
                value_type *operator->()
                {
                    return current;
                }
                iterator &operator++()
                {
                    const_iterator::operator++(0);
                    return *this;
                }
                iterator operator++(int)
                {
                    iterator tmp = *this;
                    const_iterator::operator++(0);
                    return tmp;
                }
            };

        public:
            fixed_stack()
                : previous(0)
            {
            }
            ~fixed_stack()
            {
                clear();
            }

            size_t size() const
            {
                size_t len = 0;
                const_iterator F = begin(), L = end();
                for (; F != L; ++F)
                    ++len;
                return len;
            }
            const_iterator begin() const
            {
                return const_iterator(previous);
            }
            const_iterator end() const
            {
                return const_iterator(0);
            }
            iterator begin()
            {
                return iterator(previous);
            }
            iterator end()
            {
                return iterator(0);
            }

            template <class T>
            T &push()
            {
                element<T> &elem = push_element<T>();
                if (!is_pod<T>::value)
                    new (elem.get_pointer()) T();
                return *elem.get_pointer();
            }

            template <class T, class A0>
            T &push(A0 a0)
            {
                element<T> &elem = push_element<T>();
                new (elem.get_pointer()) T(a0);
                return *elem.get_pointer();
            }

            template <class T, class A0, class A1>
            T &push(A0 a0, A1 a1)
            {
                element<T> &elem = push_element<T>();
                new (elem.get_pointer()) T(a0, a1);
                return *elem.get_pointer();
            }

            template <class T, size_t N>
            array<T, N> &push_array()
            {
                return push<array<T, N> >();
            }

            void pop()
            {
                BOOST_ASSERT(previous);
                element_base *elem = previous;
                previous = elem->previous;
                size_t cursor = elem->cursor;
                if (!elem->is_pod)    // avoid empty virtual call for pods
                    elem->destroy();
                store.set_cursor(cursor);
            }

            size_t top() const
            {
                return store.get_cursor();
            }

            void clear()
            {
                while (previous != 0)
                {
                    pop();
                }
            }

        private:
            template <class T>
            element<T> &push_element()
            {
                size_t cursor = store.get_cursor();
                element<T> &elem = store.create<element<T> >();
                elem.previous = previous;
                elem.cursor = cursor;
                previous = &elem;
                return elem;
            }
        };

        /// a growable stack
        template <size_t Size, size_t Inc, class Al>
        struct stack
        {
            fixed_stack<Size> fixed;

        private:
            storage<Size, Inc, Al> storage;

        public:
            stack()
            {
            }
            ~stack()
            {
                clear();
            }

            void clear()
            {

            }
            size_t top() const
            {
                return 0;
            }
            size_t size() const
            {
                return 0;
            }
            template <class T>
            T &push()
            {
                return fixed.push<T>();
            }
        };

    } // namespace monotonic

} // namespace boost

#include <boost/monotonic/detail/postfix.hpp>

#endif // BOOST_MONOTONIC_STACK_HPP

//EOF

max_stars_repo_name: cschladetsch/Monotonic

max_issues_repo_name: cschladetsch/Monotonic

max_forks_repo_name: cschladetsch/Monotonic


text:
#include <cmath>
#include <cstdio>

#include <iostream>
#include <Eigen/Dense>

#if defined(_OPENMP)
#include <omp.h>
#endif

#include "linalg.h"

#include "wf_vector.h"

double WFVectorSN::A(const int i, const int j, const bool exact) {
  const int delta_ij = (i == j);

  const double x_i = pixels[i].x;
  const double y_i = pixels[i].y;
  const double z_i = pixels[i].z;
  const double N_ii = pixels[i].N;

  const double dx = x_i - pixels[j].x;
  const double dy = y_i - pixels[j].y;
  const double dz = z_i - pixels[j].z;

  const double x_perp_2 = dx*dx + dy*dy;
  const double x_para_2 = dz*dz;
  double S_ij;
  if (exact) {
    S_ij = signal_covar_exact(x_perp_2, x_para_2, s_params);
  }
  else {
    S_ij = signal_covar(x_perp_2, x_para_2, s_params);
  }

  const double A_ij = S_ij + N_ii * delta_ij;
  return A_ij;
}

void WFVectorSN::preconditioner_solve(const double* const b, double* const x) {
  const double var_s = s_params->var_s;
  for (int i = 0; i < n; ++i) {
    // no coord lookup for diagonal. Apc_ii = var_s + N_i
    double Apc_ii = var_s + pixels[i].N;
    x[i] = b[i] / Apc_ii;
  }
}

void WFVectorSN::A_product(const double* const a, double* const b) {
  int i, j;
#if defined(_OPENMP)
  #pragma omp parallel for private(i, j)
#endif
  for (i = 0; i < n; ++i) {
    b[i] = 0.0;
    const double x_i = pixels[i].x;
    const double y_i = pixels[i].y;
    const double z_i = pixels[i].z;
    const double N_ii = pixels[i].N;
    for (j = 0; j < n; ++j) {
      const int delta_ij = (i == j);
      const double dx = x_i - pixels[j].x;
      const double dy = y_i - pixels[j].y;
      const double dz = z_i - pixels[j].z;
      const double x_perp_2 = (dx*dx + dy*dy);
      const double x_para_2 = dz*dz;
      const double S_ij = signal_covar(x_perp_2, x_para_2, s_params);
      const double A_ij = S_ij + N_ii * delta_ij;
      b[i] += A_ij * a[j];
    }
  }
}

void WFVectorSN::A_residual(const double* const x, double* const r) {
  int i, j;
#if defined(_OPENMP)
  #pragma omp parallel for private(i, j)
#endif
  for (i = 0; i < n; ++i) {
    double sum_Ax_i = 0.0;
    const double x_i = pixels[i].x;
    const double y_i = pixels[i].y;
    const double z_i = pixels[i].z;
    const double N_ii = pixels[i].N;
    const double d_i = pixels[i].d;

    for (j = 0; j < n; ++j) {
      const int delta_ij = (i == j);
      const double dx = x_i - pixels[j].x;
      const double dy = y_i - pixels[j].y;
      const double dz = z_i - pixels[j].z;
      const double x_perp_2 = (dx*dx + dy*dy);
      const double x_para_2 = dz*dz;
      const double S_ij = signal_covar(x_perp_2, x_para_2, s_params);
      const double A_ij = S_ij + N_ii * delta_ij;
      sum_Ax_i += A_ij * x[j];
    }
    // r_i = b_i - sum_j A_ij x_j
    r[i] = d_i - sum_Ax_i;
  }
}

double WFVectorSN::norm_b() {
  double sum_b2 = 0.0;
  for (int i = 0; i < n; ++i) {
    const double bi = pixels[i].d;
    sum_b2 += bi * bi;
  }
  return sqrt(sum_b2);
}

PCGResult WFVectorSN::solve_pcg(const PCGParams& pcg_params,
    double* const x) {
  const double norm_b_val = norm_b();
  PCGResult res = pcg_solve(pcg_params, norm_b_val, this_A_product,
      this_A_residual, this_pc_solve, x);

  return res;
}

void WFVectorSN::solve_cf(double* const x, const bool verbose, const bool exact) {
  using namespace Eigen;
  if (verbose) { puts("Filling A matrix."); }

  // init A = (S + N)
  MatrixXd sn(n, n);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      sn(i, j) = A(i, j, exact);
    }
  }

  if (verbose) { puts("Filling b vector."); }

  // init b = d
  VectorXd b(n);
  for (int i = 0; i < n; ++i) {
    b(i) = pixels[i].d;
  }

  if (verbose) { puts("Calling eigen solve."); }

  // solve
  VectorXd vec_x(n);
  vec_x = sn.ldlt().solve(b);

  if (verbose) { puts("Copying back."); }

  // write back to our format.
  for (int i = 0; i < n; ++i) {
    x[i] = vec_x(i);
  }
}

double WFVectorW::A(const int i, const int j, const bool exact) {
  const int delta_ij = (i == j);

  const double x_i = pixels[i].x;
  const double y_i = pixels[i].y;
  const double z_i = pixels[i].z;
  const double w_i = pixels[i].w;

  const double dx = x_i - pixels[j].x;
  const double dy = y_i - pixels[j].y;
  const double dz = z_i - pixels[j].z;
  const double w_j = pixels[j].w;

  const double x_perp_2 = (dx*dx + dy*dy);
  const double x_para_2 = dz*dz;

  double S_ij;
  if (exact) {
    S_ij = signal_covar_exact(x_perp_2, x_para_2, s_params);
  }
  else {
    S_ij = signal_covar(x_perp_2, x_para_2, s_params);
  }

  const double A_ij = w_i * S_ij * w_j + delta_ij;
  return A_ij;
}

void WFVectorW::preconditioner_solve(const double* const b, double* const x) {
  const double var_s = s_params->var_s;

  for (int i = 0; i < n; ++i) {
    // no coord lookup for diagonal. Apc_ii = var_s + N_i
    double wi = pixels[i].w;
    double Apc_ii = wi * wi * var_s + 1.0;
    x[i] = b[i] / Apc_ii;
  }
}

void WFVectorW::A_product(const double* const a, double* const b) {
  int i, j;
#if defined(_OPENMP)
  #pragma omp parallel for private(i, j)
#endif
  for (i = 0; i < n; ++i) {
    b[i] = 0.0;
    const double x_i = pixels[i].x;
    const double y_i = pixels[i].y;
    const double z_i = pixels[i].z;
    const double w_i = pixels[i].w;
    for (j = 0; j < n; ++j) {
      const int delta_ij = (i == j);
      const double w_j = pixels[j].w;
      const double dx = x_i - pixels[j].x;
      const double dy = y_i - pixels[j].y;
      const double dz = z_i - pixels[j].z;
      const double x_perp_2 = (dx*dx + dy*dy);
      const double x_para_2 = dz*dz;
      const double S_ij = signal_covar(x_perp_2, x_para_2, s_params);
      const double A_ij = w_i * S_ij * w_j + delta_ij;
      b[i] += A_ij * a[j];
    }
  }
}

void WFVectorW::A_residual(const double* const x, double* const r) {
  int i, j;
#if defined(_OPENMP)
  #pragma omp parallel for private(i, j)
#endif
  for (i = 0; i < n; ++i) {
    double sum_Ax_i = 0.0;
    const double x_i = pixels[i].x;
    const double y_i = pixels[i].y;
    const double z_i = pixels[i].z;
    const double w_i = pixels[i].w;

    for (j = 0; j < n; ++j) {
      const int delta_ij = (i == j);
      const double w_j = pixels[j].w;
      const double dx = x_i - pixels[j].x;
      const double dy = y_i - pixels[j].y;
      const double dz = z_i - pixels[j].z;
      const double x_perp_2 = (dx*dx + dy*dy);
      const double x_para_2 = dz*dz;
      const double S_ij = signal_covar(x_perp_2, x_para_2, s_params);
      const double A_ij = w_i * S_ij * w_j + delta_ij;
      sum_Ax_i += A_ij * x[j];
    }

    // r_i = b_i - sum_j A_ij x_j
    const double wd_i = pixels[i].wd;
    r[i] = wd_i - sum_Ax_i;
  }
}

double WFVectorW::norm_b() {
  double sum_b2 = 0.0;
  for (int i = 0; i < n; ++i) {
    const double bi = pixels[i].wd;
    sum_b2 += bi * bi;
  }
  return sqrt(sum_b2);
}

PCGResult WFVectorW::solve_pcg(const PCGParams& pcg_params, double* const x) {
  const double norm_b_val = norm_b();
  PCGResult res = pcg_solve(pcg_params, norm_b_val, this_A_product,
      this_A_residual, this_pc_solve, x);

  // Don't forget the last multiply!
  for (int i = 0; i < n; ++i) {
    x[i] *= pixels[i].w;
  }

  return res;
}

void WFVectorW::solve_cf(double* const x, const bool verbose,
    const bool exact) {
  using namespace Eigen;

  if (verbose) {
    puts("Filling A matrix.");
  }

  // init A = (S + N)
  MatrixXd sn(n, n);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      sn(i, j) = A(i, j, exact);
    }
  }

  if (verbose) {
    puts("Filling b vector.");
  }

  // init b = d
  VectorXd b(n);
  for (int i = 0; i < n; ++i) {
    b(i) = pixels[i].wd;
  }

  if (verbose) {
    puts("Calling eigen solve.");
  }

  // solve
  VectorXd vec_x(n);
  vec_x = sn.ldlt().solve(b);

  if (verbose) {
    puts("Copying back.");
  }

  // write back to our format
  // Don't forget the last multiply!
  for (int i = 0; i < n; ++i) {
    x[i] = pixels[i].w * vec_x(i);
  }
}

ext: cc

max_stars_repo_name: caseywstark/dachshund

max_issues_repo_name: caseywstark/dachshund

max_forks_repo_name: caseywstark/dachshund


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2014-2017,  Regents of the University of California,
 *                           Arizona Board of Regents,
 *                           Colorado State University,
 *                           University Pierre & Marie Curie, Sorbonne University,
 *                           Washington University in St. Louis,
 *                           Beijing Institute of Technology,
 *                           The University of Memphis.
 *
 * This file is part of NFD (Named Data Networking Forwarding Daemon).
 * See AUTHORS.md for complete list of NFD authors and contributors.
 *
 * NFD is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef NFD_TESTS_DAEMON_FACE_TEST_IP_HPP
#define NFD_TESTS_DAEMON_FACE_TEST_IP_HPP

#include "core/common.hpp"

#include <boost/asio/ip/address.hpp>
#include <ndn-cxx/net/network-address.hpp>

namespace nfd {
namespace face {
namespace tests {

enum class AddressFamily {
  V4 = static_cast<int>(ndn::net::AddressFamily::V4),
  V6 = static_cast<int>(ndn::net::AddressFamily::V6),
  Any
};

std::ostream&
operator<<(std::ostream& os, AddressFamily family);

enum class AddressScope {
  Loopback  = static_cast<int>(ndn::net::AddressScope::HOST),
  LinkLocal = static_cast<int>(ndn::net::AddressScope::LINK),
  Global    = static_cast<int>(ndn::net::AddressScope::GLOBAL),
  Any
};

std::ostream&
operator<<(std::ostream& os, AddressScope scope);

enum class MulticastInterface {
  No,
  Yes,
  Any
};

std::ostream&
operator<<(std::ostream& os, MulticastInterface mcast);

/** \brief Derives IP address type from AddressFamily
 */
template<AddressFamily AF>
struct IpAddressFromFamily;

template<>
struct IpAddressFromFamily<AddressFamily::V4>
{
  using type = boost::asio::ip::address_v4;
};

template<>
struct IpAddressFromFamily<AddressFamily::V6>
{
  using type = boost::asio::ip::address_v6;
};

/** \brief Get an IP address from any available network interface
 *  \param family the desired address family
 *  \param scope the desired address scope
 *  \param mcast specifies if the address can, must, or must not be chosen from a multicast-capable interface
 *  \return an IP address, either boost::asio::ip::address_v4 or boost::asio::ip::address_v6
 *  \retval unspecified address, if no appropriate address is available
 */
boost::asio::ip::address
getTestIp(AddressFamily family = AddressFamily::Any,
          AddressScope scope = AddressScope::Any,
          MulticastInterface mcast = MulticastInterface::Any);

/** \brief Skip the rest of the test case if \p address is unavailable
 *
 *  This macro can be used in conjunction with nfd::tests::getTestIp in a test case. Example:
 *  \code
 *  BOOST_AUTO_TEST_CASE(TestCase)
 *  {
 *    auto ip = getTestIp(AddressFamily::V4);
 *    SKIP_IF_IP_UNAVAILABLE(ip);
 *    // Test something that requires an IPv4 address.
 *  }
 *  \endcode
 */
#define SKIP_IF_IP_UNAVAILABLE(address) \
  do { \
    if ((address).is_unspecified()) { \
      BOOST_WARN_MESSAGE(false, "skipping assertions that require a valid IP address"); \
      return; \
    } \
  } while (false)

} // namespace tests
} // namespace face
} // namespace nfd

#endif // NFD_TESTS_DAEMON_FACE_TEST_IP_HPP

max_stars_repo_name: NDNLink/NDN-Chord

max_issues_repo_name: NDNLink/NDN-Chord

max_forks_repo_name: NDNLink/NDN-Chord


text:
#pragma once

#include <Configuration.h>
#include <Eigen/Dense>

class AtlasStateProvider;
class RobotSystem;
class BasicAccumulation;
class AtlasSensorData;

class AtlasStateEstimator {
   public:
    AtlasStateEstimator(RobotSystem* robot);
    ~AtlasStateEstimator();

    void Initialization(AtlasSensorData*);
    void Update(AtlasSensorData*);

   protected:
    double initial_height_;
    int fixed_foot_;
    Eigen::Vector3d foot_pos_;
    AtlasStateProvider* sp_;
    RobotSystem* robot_;

    Eigen::VectorXd curr_config_;
    Eigen::VectorXd curr_qdot_;
    Eigen::Vector3d global_body_euler_zyx_;
    Eigen::Quaternion<double> global_body_quat_;
    Eigen::Vector3d global_body_euler_zyx_dot_;

    BasicAccumulation* ori_est_;

    void _JointUpdate(AtlasSensorData* data);
    void _ConfigurationAndModelUpdate();
    void _FootContactUpdate(AtlasSensorData* data);
};


text:
#include <Engine/MeshEdit/MinSurf.h>

#include <Engine/Primitive/TriMesh.h>

#include <Eigen/Sparse>

using namespace Ubpa;

using namespace std;
using namespace Eigen;

MinSurf::MinSurf(Ptr<TriMesh> triMesh)
	: heMesh(make_shared<HEMesh<V>>())
{
	Init(triMesh);
}

void MinSurf::Clear() {
	heMesh->Clear();
	triMesh = nullptr;
}

bool MinSurf::Init(Ptr<TriMesh> triMesh) {
	Clear();

	if (triMesh == nullptr)
		return true;

	if (triMesh->GetType() == TriMesh::INVALID) {
		printf("ERROR::MinSurf::Init:\n"
			"\t""trimesh is invalid\n");
		return false;
	}

	// init half-edge structure
	size_t nV = triMesh->GetPositions().size();
	vector<vector<size_t>> triangles;
	triangles.reserve(triMesh->GetTriangles().size());
	for (auto triangle : triMesh->GetTriangles())
		triangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });
	heMesh->Reserve(nV);
	heMesh->Init(triangles);

	if (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {
		printf("ERROR::MinSurf::Init:\n"
			"\t""trimesh is not a triangle mesh or hasn't a boundaries\n");
		heMesh->Clear();
		return false;
	}

	// triangle mesh's positions ->  half-edge structure's positions
	for (int i = 0; i < nV; i++) {
		auto v = heMesh->Vertices().at(i);
		v->pos = triMesh->GetPositions()[i].cast_to<vecf3>();
	}

	this->triMesh = triMesh;

	inside_count_ = 0;
	inside_points_.clear();
	map_between_inside_.clear();

	return true;
}

bool MinSurf::Run() {
	if (heMesh->IsEmpty() || !triMesh) {
		printf("ERROR::MinSurf::Run\n"
			"\t""heMesh->IsEmpty() || !triMesh\n");
		return false;
	}

	Minimize();

	// half-edge structure -> triangle mesh
	size_t nV = heMesh->NumVertices();
	size_t nF = heMesh->NumPolygons();
	vector<pointf3> positions;
	vector<unsigned> indice;
	positions.reserve(nV);
	indice.reserve(3 * nF);
	for (auto v : heMesh->Vertices())
		positions.push_back(v->pos.cast_to<pointf3>());
	for (auto f : heMesh->Polygons()) { // f is triangle
		for (auto v : f->BoundaryVertice()) // vertices of the triangle
			indice.push_back(static_cast<unsigned>(heMesh->Index(v)));
	}

	triMesh->Init(indice, positions);

	return true;
}

void MinSurf::Minimize() {
	// TODO
	//cout << "WARNING::MinSurf::Minimize:" << endl
	//     << "\t" << "not implemented" << endl;
	FindInside();
	GetMap();
	BuildLMat();
	BuildDeltaMat();

	LU_.compute(L_);
	X = LU_.solve(delta_);

	UpdateMin();
}

void MinSurf::FindInside()
{
	for (auto v : heMesh->Vertices())
		if (!v->IsBoundary())
			inside_points_.push_back(v);
	inside_count_ = inside_points_.size();
	return;
}

void MinSurf::GetMap()
{
	for (int i = 0; i < inside_count_; i++)
		map_between_inside_.insert({ heMesh->Index(inside_points_[i]), i });
		//cout << heMesh->Index(inside_points_[i]) << endl;

	return;
}

void MinSurf::BuildLMat()
{
	L_.resize(inside_count_, inside_count_);

	vector<Eigen::Triplet<double> > coefficients;

	for (int i = 0; i < inside_count_; i++)
	{
		V* v=inside_points_[i];
		coefficients.push_back(Eigen::Triplet<double>(i, i, v->AdjVertices().size()));

		for (auto adj : v->AdjVertices())
		{
			int j = heMesh->Index(adj);
			if (!adj->IsBoundary())
			{
				j = map_between_inside_[j];
				coefficients.push_back(Eigen::Triplet<double>(i, j, -1));
			}
		}
	}
	L_.setFromTriplets(coefficients.begin(), coefficients.end());
}

void MinSurf::BuildDeltaMat()
{
	delta_ = Eigen::MatrixX3d::Zero(inside_count_, 3);

	for (int i = 0; i < inside_count_; i++)
	{
		V* v = inside_points_[i];

		for (auto adj : v->AdjVertices())
		{
			int j = heMesh->Index(adj);
			if (adj->IsBoundary())
			{
				delta_(i, 0) += adj->pos[0];
				delta_(i, 1) += adj->pos[1];
				delta_(i, 2) += adj->pos[2];
			}
		}
	}
}

void MinSurf::UpdateMin()
{
	for (int i = 0; i < inside_count_; i++)
	{
		V* v = inside_points_[i];
		v->pos = vecf3({ X(i, 0), X(i, 1), X(i, 2) });
	}
}

max_stars_repo_name: L-JIN/USTC-CG

max_issues_repo_name: L-JIN/USTC-CG

max_forks_repo_name: L-JIN/USTC-CG