text:
// ---------------------------------------------------------------------------
//
//  This file is part of PermLib.
//
// Copyright (c) 2009-2011 Thomas Rehn <thomas@carmen76.de>
// 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. The name of the author may not be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
//
// ---------------------------------------------------------------------------

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE partition magic
#include <boost/test/unit_test.hpp>

#include <iostream>
#include <fstream>
#include <algorithm>

#include <permlib/permutation.h>
#include <permlib/generator/product_replacement_generator.h>
#include <permlib/bsgs.h>
#include <permlib/transversal/explicit_transversal.h>
#include <permlib/construct/schreier_sims_construction.h>

#include "test-common.h"
#include <permlib/search/partition/partition.h>
//#include <permlib/search/partition/r_base.h>

using namespace permlib::partition;

BOOST_AUTO_TEST_CASE( partition_intersection )
{
	const unsigned long n = 5;
	Partition P(n);

	const unsigned long set[5] = {0,1,2,3,4};

	Partition Pprime(P);

    BOOST_CHECK( Pprime.intersect(set, set+3, 0) );
    BOOST_CHECK( Pprime.cells() == 2 );
    BOOST_CHECK( ! Pprime.intersect(set, set+3, 0) );
    BOOST_CHECK( ! Pprime.intersect(set, set+3, 1) );

    BOOST_CHECK( Pprime.intersect(set+2, set+4, 0) );
    BOOST_CHECK( Pprime.cells() == 3 );
    BOOST_CHECK( Pprime.intersect(set+2, set+4, 1) );
    BOOST_CHECK( Pprime.cells() == 4 );
    BOOST_CHECK( Pprime.intersect(set+1, set+3, 2) );
    BOOST_CHECK( Pprime.cells() == 5 );

    const unsigned long fixSizes[4] = {5,3,1,0};
    const unsigned long fixContain[4] = {0,4,2,0};
    unsigned int i = 0;
    while (Pprime.fixPointsSize() && i < 6) {
	    std::vector<unsigned long> Pfix(Pprime.fixPointsBegin(), Pprime.fixPointsEnd());
        BOOST_CHECK( Pfix.size() == Pprime.fixPointsSize() );
        BOOST_CHECK( Pfix.size() == fixSizes[i] );
        BOOST_CHECK( std::find(Pfix.begin(), Pfix.end(), fixContain[i]) != Pfix.end() );

        BOOST_CHECK( Pprime.undoIntersection() );
        ++i;
    }
    BOOST_CHECK( i == 3 );

    BOOST_CHECK( Pprime.undoIntersection() );
    BOOST_CHECK( ! Pprime.undoIntersection() );
}

max_stars_repo_name: peterlietz/PermLib

max_issues_repo_name: peterlietz/PermLib

max_forks_repo_name: peterlietz/PermLib


text:
#ifndef CAFFE_SOLVERCNN_HPP_
#define CAFFE_SOLVERCNN_HPP_
#include <boost/function.hpp>
#include <string>
#include <vector>

#include "caffe/net.hpp"
#include "caffe/solver.hpp"

namespace caffe
{

class SolverCNN : public Solver
{
 public:
 	explicit SolverCNN(const SolverParameter& param);
  void Solve(const char* resume_file = NULL);
  void dispaly_loss(float loss);

 	void Snapshot();
	void test();
	void testSegmentation();
  void Restore(const char* resume_file);
	virtual ~SolverCNN()
  {}

  inline const SolverParameter& param() const { return param_; }
  inline shared_ptr<Net > net() { return net_; }
 protected:
  SolverParameter param_;
  shared_ptr<Net > net_;
  shared_ptr<Net > test_net_;

	int start_iter_;
	float sum_loss_;

  DISABLE_COPY_AND_ASSIGN(SolverCNN);
};

}  // namespace caffe

#endif  // CAFFE_SOLVERCNN_HPP_

ext: hpp


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#include <iostream>
#include <vector>

#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>

using namespace mtl;
using namespace mtl::recursion;
using namespace std;

int main(int argc, char* argv[])
{
    // typedef dense2D<double> matrix_t;
    typedef morton_dense<double,  doppled_32_row_mask> matrix_t;
    const int                                          n= 10;
    matrix_t                                           A1(n, n), C1(n, n);

    // fill matrix, e.g.
    hessian_setup(A1, 1.0);
    hessian_setup(C1, 2.0);

    typedef mat::recursator<matrix_t>               recursator_t;
    recursator_t                                      ra1(A1), rc1(C1);
    std::vector<recursator_t>                         v;
    v.push_back(ra1); v.push_back(rc1);

    // Of course you can also add sub-matrices
    v.push_back(rc1.south_west());

    // Only correct with latest revision (due to subtle problem just fixed)
    for (int i= 0; i < v.size(); i++)
	cout << "Recursator " << i << ": \n" << *v[i].north_west() << "\n";

    // Should also work with older version
    for (int i= 0; i < v.size(); i++)
	cout << "Recursator " << i << ": \n", print_matrix(*v[i].north_west()), cout << "\n";

    return 0;
}

ext: cpp


text:
// ---------------------------------------------------------------------
// pion:  a Boost C++ framework for building lightweight HTTP interfaces
// ---------------------------------------------------------------------
// Copyright (C) 2007-2014 Splunk Inc.  (https://github.com/splunk/pion)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#ifndef __PION_PLUGIN_HEADER__
#define __PION_PLUGIN_HEADER__

#include <pion/config.hpp>

#include <vector>
#include <string>
#include <map>
#include <list>
#include <boost/noncopyable.hpp>
#include <boost/thread/once.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/filesystem/path.hpp>
#include <pion/error.hpp>

namespace pion {    // begin namespace pion

///
/// plugin: base class for plug-in management
///
class PION_API plugin {
public:

    /**
     * searches directories for a valid plug-in file
     *
     * @param path_to_file the path to the plug-in file, if found
     * @param the name name of the plug-in to search for
     * @return true if the plug-in file was found
     */
    static inline bool find_plugin_file(std::string& path_to_file,
                                      const std::string& name)
    {
        return find_file(path_to_file, name, PION_PLUGIN_EXTENSION);
    }

    /**
     * searches directories for a valid plug-in configuration file
     *
     * @param path_to_file if found, is set to the complete path to the file
     * @param name the name of the configuration file to search for
     * @return true if the configuration file was found
     */
    static inline bool find_config_file(std::string& path_to_file,
                                      const std::string& name)
    {
        return find_file(path_to_file, name, PION_CONFIG_EXTENSION);
    }

    /**
     * adds an entry point for a plugin that is statically linked
     * NOTE: USE PION_DECLARE_PLUGIN() macro instead!!!
     *
     * @param plugin_name the name of the plugin to add
     * @param create_func - pointer to the function to be used in to create plugin object
     * @param destroy_func - pointer to the function to be used to release plugin object
     */
    static void add_static_entry_point(const std::string& plugin_name,
                                    void *create_func,
                                    void *destroy_func);

    /**
     * updates path for cygwin oddities, if necessary
     *
     * @param final_path path object for the file, will be modified if necessary
     * @param start_path original path to the file.  if final_path is not valid,
     *                   this will be appended to PION_CYGWIN_DIRECTORY to attempt
     *                   attempt correction of final_path for cygwin
     */
    static void check_cygwin_path(boost::filesystem::path& final_path,
                                const std::string& path_string);

    /// appends a directory to the plug-in search path
    static void add_plugin_directory(const std::string& dir);

    /// clears all directories from the plug-in search path
    static void reset_plugin_directories(void);

    // default destructor
    virtual ~plugin() { release_data(); }

    /// returns true if a shared library is loaded/open
    inline bool is_open(void) const { return (m_plugin_data != NULL); }

    /// returns the name of the plugin that is currently open
    inline std::string get_plugin_name(void) const {
        return (is_open() ? m_plugin_data->m_plugin_name : std::string());
    }

    /// returns a list of all Plugins found in all Plugin directories
    static void get_all_plugin_names(std::vector<std::string>& plugin_names);

    /**
     * opens plug-in library within a shared object file.  If the library is
     * already being used by another plugin object, then the existing
     * code will be re-used and the reference count will be increased.  Beware
     * that this does NOT check the plug-in's base class (InterfaceClassType),
     * so you must be careful to ensure that the namespace is unique between
     * plug-ins that have different base classes.  If the plug-in's name matches
     * an existing plug-in of a different base class, the resulting behavior is
     * undefined (it will probably crash your program).
     *
     * @param plugin_name name of the plug-in library to open (without extension, etc.)
     */
    void open(const std::string& plugin_name);

    /**
     * opens plug-in library within a shared object file.  If the library is
     * already being used by another plugin object, then the existing
     * code will be re-used and the reference count will be increased.  Beware
     * that this does NOT check the plug-in's base class (InterfaceClassType),
     * so you must be careful to ensure that the namespace is unique between
     * plug-ins that have different base classes.  If the plug-in's name matches
     * an existing plug-in of a different base class, the resulting behavior is
     * undefined (it will probably crash your program).
     *
     * @param plugin_file shared object file containing the plugin code
     */
    void open_file(const std::string& plugin_file);

    /// closes plug-in library
    inline void close(void) { release_data(); }

protected:

    ///
    /// data_type: object to hold shared library symbols
    ///
    struct data_type
    {
        /// default constructors for convenience
        data_type(void)
            : m_lib_handle(NULL), m_create_func(NULL), m_destroy_func(NULL),
            m_references(0)
        {}
        data_type(const std::string& plugin_name)
            : m_lib_handle(NULL), m_create_func(NULL), m_destroy_func(NULL),
            m_plugin_name(plugin_name), m_references(0)
        {}
        data_type(const data_type& p)
            : m_lib_handle(p.m_lib_handle), m_create_func(p.m_create_func),
            m_destroy_func(p.m_destroy_func), m_plugin_name(p.m_plugin_name),
            m_references(p.m_references)
        {}

        /// symbol library loaded from a shared object file
        void *          m_lib_handle;

        /// function used to create instances of the plug-in object
        void *          m_create_func;

        /// function used to destroy instances of the plug-in object
        void *          m_destroy_func;

        /// the name of the plugin (must be unique per process)
        std::string     m_plugin_name;

        /// number of references to this class
        unsigned long   m_references;
    };

    /// default constructor is private (use plugin_ptr class to create objects)
    plugin(void) : m_plugin_data(NULL) {}

    /// copy constructor
    plugin(const plugin& p) : m_plugin_data(NULL) { grab_data(p); }

    /// assignment operator
    plugin& operator=(const plugin& p) { grab_data(p); return *this; }

    /// returns a pointer to the plug-in's "create object" function
    inline void *get_create_function(void) {
        return (is_open() ? m_plugin_data->m_create_func : NULL);
    }

    /// returns a pointer to the plug-in's "destroy object" function
    inline void *get_destroy_function(void) {
        return (is_open() ? m_plugin_data->m_destroy_func : NULL);
    }

    /// releases the plug-in's shared library symbols
    void release_data(void);

    /// grabs a reference to another plug-in's shared library symbols
    void grab_data(const plugin& p);

private:

    /// data type that maps plug-in names to their shared library data
    typedef std::map<std::string, data_type*>  map_type;

    /// data type for static/global plugin configuration information
    struct config_type {
        /// directories containing plugin files
        std::vector<std::string>    m_plugin_dirs;

        /// maps plug-in names to shared library data
        map_type                    m_plugin_map;

        /// mutex to make class thread-safe
        boost::mutex                m_plugin_mutex;
    };

    /// returns a singleton instance of config_type
    static inline config_type& get_plugin_config(void) {
        boost::call_once(plugin::create_plugin_config, m_instance_flag);
        return *m_config_ptr;
    }

    /// creates the plugin_config singleton
    static void create_plugin_config(void);

    /**
     * searches directories for a valid plug-in file
     *
     * @param path_to_file if found, is set to the complete path to the file
     * @param name the name of the file to search for
     * @param extension will be appended to name if name is not found
     *
     * @return true if the file was found
     */
    static bool find_file(std::string& path_to_file, const std::string& name,
                         const std::string& extension);

    /**
     * normalizes complete and final path to a file while looking for it
     *
     * @param final_path if found, is set to the complete, normalized path to the file
     * @param start_path the original starting path to the file
     * @param name the name of the file to search for
     * @param extension will be appended to name if name is not found
     *
     * @return true if the file was found
     */
    static bool check_for_file(std::string& final_path, const std::string& start_path,
                             const std::string& name, const std::string& extension);

    /**
     * opens plug-in library within a shared object file
     *
     * @param plugin_file shared object file containing the plugin code
     * @param plugin_data data object to load the library into
     */
    static void open_plugin(const std::string& plugin_file,
                           data_type& plugin_data);

    /// returns the name of the plugin object (based on the plugin_file name)
    static std::string get_plugin_name(const std::string& plugin_file);

    /// load a dynamic library from plugin_file and return its handle
    static void *load_dynamic_library(const std::string& plugin_file);

    /// close the dynamic library corresponding with lib_handle
    static void close_dynamic_library(void *lib_handle);

    /// returns the address of a library symbal
    static void *get_library_symbol(void *lib_handle, const std::string& symbol);

    /// name of function defined in object code to create a new plug-in instance
    static const std::string            PION_PLUGIN_CREATE;

    /// name of function defined in object code to destroy a plug-in instance
    static const std::string            PION_PLUGIN_DESTROY;

    /// file extension used for Pion plug-in files (platform specific)
    static const std::string            PION_PLUGIN_EXTENSION;

    /// file extension used for Pion configuration files
    static const std::string            PION_CONFIG_EXTENSION;

    /// used to ensure thread safety of the plugin_config singleton
    static boost::once_flag             m_instance_flag;

    /// pointer to the plugin_config singleton
    static config_type *           m_config_ptr;

    /// points to the shared library and functions used by the plug-in
    data_type *                    m_plugin_data;
};

///
/// plugin_ptr: smart pointer that manages plug-in code loaded from shared
///                object libraries
///
template <typename InterfaceClassType>
class plugin_ptr :
    public plugin
{
protected:

    /// data type for a function that is used to create object instances
    typedef InterfaceClassType* CreateObjectFunction(void);

    /// data type for a function that is used to destroy object instances
    typedef void DestroyObjectFunction(InterfaceClassType*);

public:

    /// default constructor & destructor
    plugin_ptr(void) : plugin() {}
    virtual ~plugin_ptr() {}

    /// copy constructor
    plugin_ptr(const plugin_ptr& p) : plugin(p) {}

    /// assignment operator
    plugin_ptr& operator=(const plugin_ptr& p) { grab_data(p); return *this; }

    /// creates a new instance of the plug-in object
    inline InterfaceClassType *create(void) {
        CreateObjectFunction *create_func =
            (CreateObjectFunction*)(get_create_function());
        if (create_func == NULL)
            BOOST_THROW_EXCEPTION( error::plugin_undefined() );
        return create_func();
    }

    /// destroys an instance of the plug-in object
    inline void destroy(InterfaceClassType *object_ptr) {
        // fix warning ISO C++ forbids casting from pointer-to-object
        // to pointer to function
        union {
            void* v_;
            DestroyObjectFunction* f_;
        } Cast;
        Cast.v_ = get_destroy_function();
        DestroyObjectFunction *destroy_func = Cast.f_;
        if (destroy_func == NULL)
            BOOST_THROW_EXCEPTION( error::plugin_undefined() );
        destroy_func(object_ptr);
    }
};

///
/// plugin_instance_ptr: smart pointer that manages a plug-in instance
///
template <typename InterfaceClassType>
class plugin_instance_ptr :
    private boost::noncopyable
{
public:

    /// default constructor & destructor
    plugin_instance_ptr(void) : m_instance_ptr(NULL) {}

    /// virtual destructor / may be extended
    virtual ~plugin_instance_ptr() { reset(); }

    /// reset the instance pointer
    inline void reset(void) {
        if (m_instance_ptr) {
            m_plugin_ptr.destroy(m_instance_ptr);
        }
    }

    /// create a new instance of the given plugin_type
    inline void create(const std::string& plugin_type) {
        reset();
        m_plugin_ptr.open(plugin_type);
        m_instance_ptr = m_plugin_ptr.create();
    }

    /// returns true if pointer is empty
    inline bool empty(void) const { return m_instance_ptr==NULL; }

    /// return a raw pointer to the instance
    inline InterfaceClassType *get(void) { return m_instance_ptr; }

    /// return a reference to the instance
    inline InterfaceClassType& operator*(void) { return *m_instance_ptr; }

    /// return a const reference to the instance
    inline const InterfaceClassType& operator*(void) const { return *m_instance_ptr; }

    /// return a reference to the instance
    inline InterfaceClassType* operator->(void) { return m_instance_ptr; }

    /// return a const reference to the instance
    inline const InterfaceClassType* operator->(void) const { return m_instance_ptr; }

protected:

    /// smart pointer that manages the plugin's dynamic object code
    plugin_ptr<InterfaceClassType>   m_plugin_ptr;

    /// raw pointer to the plugin instance
    InterfaceClassType  *               m_instance_ptr;
};

/**
* Macros to declare entry points for statically linked plugins in accordance
* with the general naming convention.
*
* Typical use:
* @code
* PION_DECLARE_PLUGIN(EchoService)
* ....
* PION_DECLARE_PLUGIN(FileService)
*
* @endcode
*
*/
#ifdef PION_STATIC_LINKING

#define PION_DECLARE_PLUGIN(plugin_name)    \
    class plugin_name;                      \
    extern "C" plugin_name *pion_create_##plugin_name(void); \
    extern "C" void pion_destroy_##plugin_name(plugin_name *plugin_ptr); \
    static pion::static_entry_point_helper helper_##plugin_name(#plugin_name, (void*) pion_create_##plugin_name, (void*) pion_destroy_##plugin_name);

/// used by PION_DECLARE_PLUGIN to add an entry point for static-linked plugins
class static_entry_point_helper {
public:
    static_entry_point_helper(const std::string& name, void *create, void *destroy)
    {
        pion::plugin::add_static_entry_point(name, create, destroy);
    }
};

#else

#define PION_DECLARE_PLUGIN(plugin_name)

#endif

}   // end namespace pion

#endif

max_stars_repo_name: odant/conan-pion

max_issues_repo_name: odant/conan-pion

max_forks_repo_name: odant/conan-pion


text:
// ====================================================================================
// Copyright (c) 2012, ioriiod0@gmail.com All rights reserved.
// File         : chat_client.cpp
// Author       : ioriiod0@gmail.com
// Last Change  : 11/28/2012 05:55 PM
// Description  :
// ====================================================================================

#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>

#include "../orchid/all.hpp"

using std::string;
using std::cerr;
using std::endl;

class chat_client {
public:
    chat_client(orchid::scheduler& sche,const string& ip,const string& port)
        :sche_(sche),
        stdin_(sche_.get_io_service(),::dup(STDIN_FILENO)),
        stdout_(sche_.get_io_service(),::dup(STDOUT_FILENO)),
        sock_(sche_.get_io_service()),
        is_logined_(false),ip_(ip),port_(port) {

    }

    ~chat_client() {
        stdin_.close();
        stdout_.close();
        sock_.close();
    }
public:
    void run() {
        sche_.spawn(boost::bind(&chat_client::handle_console,this,_1));
        sche_.spawn(boost::bind(&chat_client::handle_msg,this,_1));
        sche_.run();
    }

    void stop() {
        sche_.stop();
    }

private:
    void handle_msg(orchid::coroutine_handle co) {
        try {
            sock_.connect(ip_,port_,co);
        } catch (const orchid::io_error& e) {
            ORCHID_ERROR("err msg:%s",e.what());
            return;
        }

        orchid::writer<orchid::descriptor> out(stdout_,co);
        orchid::buffered_reader<orchid::socket> in(sock_,co);

        string line;
        try {
            for (;;) {
                in.read_until(line,'\n');
                out.write_full(line.c_str(),line.size());
            }
        } catch (const orchid::io_error& e) {
            ORCHID_ERROR("err msg:%s",e.what());
        }

    }

    void handle_console(orchid::coroutine_handle co) {
        orchid::buffered_reader<orchid::descriptor> in(stdin_,co);
        orchid::buffered_writer<orchid::socket> out(sock_,co);

        string str;
        char buf[1024] = {0};
        try {
            for(;;) {
                in.read_until(str,'\n');
                ORCHID_DEBUG("read from stdin:%s",str.c_str());

                if(str.empty()) continue;
                // 退出 /q
                if(str.size() >= 2 && str[0] == '/' && str[1] == 'q') {
                    sock_.close();
                    user_.clear();
                    is_logined_ = false;
                    ORCHID_ERROR("closed!");
                    stop();
                }
                // 发送消息 /s message
                else if(str.size() >= 4 && str[0] == '/' && str[1] =='s') {
                    if(!is_logined_) {
                        ORCHID_ERROR("please login first!");
                    } else {
                        int n = sprintf(buf,"%s:%s\r\n",user_.c_str(),str.c_str()+3);
                        out.write(buf,n);
                        out.flush();
                        ORCHID_DEBUG("send:%s n:%d",buf,n);
                    }
                }
                // 登陆 /l username
                else if(str.size() >= 4 && str[0] == '/' && str[1] == 'l') {
                    if (!is_logined_) {
                        user_.assign(str.begin()+3,str.end()-1);
                        is_logined_ = true;
                        ORCHID_DEBUG("user:%s",user_.c_str());
                    } else {
                        ORCHID_ERROR("already logined!");
                    }
                } else {
                    print_err();
                }
            }
        } catch (const orchid::io_error& e) {
            ORCHID_ERROR("err:%s",e.what());
        }

    }

    void print_err() {
        ORCHID_ERROR("usage:\r\nlogin: /l name\r\nexit: /q\r\nsend: /s ooxx");
    }

private:
    orchid::scheduler& sche_;
    orchid::descriptor stdin_;
    orchid::descriptor stdout_;
    orchid::socket sock_;
    string user_;
    bool is_logined_;
    string ip_;
    string port_;

};

int main(int argc,char* argv[]) {
    orchid::scheduler sche;
    string ip = argv[1];
    string port = argv[2];
    chat_client client(sche,ip,port);
    client.run();
}


text:
#include <CGAL/trace.h>
#include <CGAL/Timer.h>
#include <iostream>
#include <string>
#include <fstream>

#include <Eigen/Eigen>

// #define USE_SCALAR_IMPLEMENTATION
#define USE_SSE_IMPLEMENTATION
#define COMPUTE_V_AS_MATRIX
#define COMPUTE_U_AS_MATRIX

#include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Preamble.hpp>

int main() {

  std::ifstream file;
  file.open("SVD_benchmark");
  if (!file)
  {
    CGAL_TRACE_STREAM << "Error loading file!\n";
    return 0;
  }

  int ite = 200000;
  Eigen::JacobiSVD<Eigen::Matrix3d> svd;
  Eigen::Matrix3d u, v, m, r;
  Eigen::Vector3d w;

  int matrix_idx = rand()%200;
  for (int i = 0; i < matrix_idx; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      for (int k = 0; k < 3; k++)
      {
        file >> m(j, k);
      }
    }
  }

  CGAL::Timer task_timer;

  std::cout << "Start SVD decomposition...";
  task_timer.start();
  for (int i = 0; i < ite; i++)
  {

    #include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Kernel_Declarations.hpp>

    ENABLE_SCALAR_IMPLEMENTATION(Sa11.f=m(0,0);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa21.f=m(1,0);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa31.f=m(2,0);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa12.f=m(0,1);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa22.f=m(1,1);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa32.f=m(2,1);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa13.f=m(0,2);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa23.f=m(1,2);)
    ENABLE_SCALAR_IMPLEMENTATION(Sa33.f=m(2,2);)

    ENABLE_SSE_IMPLEMENTATION(Va11=_mm_set1_ps(m(0,0));)
    ENABLE_SSE_IMPLEMENTATION(Va21=_mm_set1_ps(m(1,0));)
    ENABLE_SSE_IMPLEMENTATION(Va31=_mm_set1_ps(m(2,0));)
    ENABLE_SSE_IMPLEMENTATION(Va12=_mm_set1_ps(m(0,1));)
    ENABLE_SSE_IMPLEMENTATION(Va22=_mm_set1_ps(m(1,1));)
    ENABLE_SSE_IMPLEMENTATION(Va32=_mm_set1_ps(m(2,1));)
    ENABLE_SSE_IMPLEMENTATION(Va13=_mm_set1_ps(m(0,2));)
    ENABLE_SSE_IMPLEMENTATION(Va23=_mm_set1_ps(m(1,2));)
    ENABLE_SSE_IMPLEMENTATION(Va33=_mm_set1_ps(m(2,2));)

    #include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Main_Kernel_Body.hpp>

    std::pair<Eigen::Matrix3d, Eigen::Matrix3d> solver;

#ifdef USE_SCALAR_IMPLEMENTATION
    solver.first(0,0) = Su11.f;
    solver.first(1,0) = Su21.f;
    solver.first(2,0) = Su31.f;
    solver.first(0,1) = Su12.f;
    solver.first(1,1) = Su22.f;
    solver.first(2,1) = Su32.f;
    solver.first(0,2) = Su13.f;
    solver.first(1,2) = Su23.f;
    solver.first(2,2) = Su33.f;

    solver.second(0,0) = Sv11.f;
    solver.second(1,0) = Sv21.f;
    solver.second(2,0) = Sv31.f;
    solver.second(0,1) = Sv12.f;
    solver.second(1,1) = Sv22.f;
    solver.second(2,1) = Sv32.f;
    solver.second(0,2) = Sv13.f;
    solver.second(1,2) = Sv23.f;
    solver.second(2,2) = Sv33.f;
#endif

#ifdef USE_SSE_IMPLEMENTATION
    float buf[4];
    _mm_storeu_ps(buf,Vu11);solver.first(0,0)=buf[0];
    _mm_storeu_ps(buf,Vu21);solver.first(1,0)=buf[0];
    _mm_storeu_ps(buf,Vu31);solver.first(2,0)=buf[0];
    _mm_storeu_ps(buf,Vu12);solver.first(0,1)=buf[0];
    _mm_storeu_ps(buf,Vu22);solver.first(1,1)=buf[0];
    _mm_storeu_ps(buf,Vu32);solver.first(2,1)=buf[0];
    _mm_storeu_ps(buf,Vu13);solver.first(0,2)=buf[0];
    _mm_storeu_ps(buf,Vu23);solver.first(1,2)=buf[0];
    _mm_storeu_ps(buf,Vu33);solver.first(2,2)=buf[0];

    _mm_storeu_ps(buf,Vv11);solver.second(0,0)=buf[0];
    _mm_storeu_ps(buf,Vv21);solver.second(1,0)=buf[0];
    _mm_storeu_ps(buf,Vv31);solver.second(2,0)=buf[0];
    _mm_storeu_ps(buf,Vv12);solver.second(0,1)=buf[0];
    _mm_storeu_ps(buf,Vv22);solver.second(1,1)=buf[0];
    _mm_storeu_ps(buf,Vv32);solver.second(2,1)=buf[0];
    _mm_storeu_ps(buf,Vv13);solver.second(0,2)=buf[0];
    _mm_storeu_ps(buf,Vv23);solver.second(1,2)=buf[0];
    _mm_storeu_ps(buf,Vv33);solver.second(2,2)=buf[0];
#endif

    r = solver.first * solver.second.transpose();
  }
  task_timer.stop();
  file.close();

  std::cout << "done: " << task_timer.time() << "s\n";
  return 0;
}

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


text:
#include "FileReader.hpp"
#include <string>
#include "foundation/NotSupportedException.hpp"
#include "foundation/InvalidOperationException.hpp"
#include "foundation/OutOfMemoryException.hpp"
#include "foundation/IOException.hpp"
#include "string_traits.hpp"
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/device/mapped_file.hpp>

#define AXIS_INPUTFILE_BUFFER_LENGTH		4096*1024	// 4 MB

namespace asio = axis::services::io;

static const int lineStringBufferReserve = 4096;

class asio::FileReader::InternalFileData
{
public:
  typedef axis::String::char_type string_unit;
  typedef std::basic_ifstream<axis::String::char_type> input_stream;
  typedef std::basic_filebuf<axis::String::char_type> input_stream_buffer;

  typedef boost::iostreams::stream_buffer<boost::iostreams::mapped_file_source> file_buffer;

  InternalFileData(const axis::String& filename);
  void Init(const axis::String& filename);

  axis::String fileName;
  input_stream fileStream;
//   file_buffer fileStream;
  string_unit * buffer;
  unsigned long lastLineReadIdx;
  bool wasLineRead;
  axis::String lastLineRead;
  bool hasPushedBackLine;
};

asio::FileReader::InternalFileData::InternalFileData( const axis::String& filename ) :
  fileName(filename), buffer(NULL)
{
  lastLineRead.reserve(lineStringBufferReserve);
  Init(fileName);
}

void asio::FileReader::InternalFileData::Init( const axis::String& filename )
{
  // try to allocate read buffer
  try
  {
    buffer = new string_unit[AXIS_INPUTFILE_BUFFER_LENGTH];
  }
  catch(...)
  {
    throw axis::foundation::OutOfMemoryException();
  }

  // select read buffer
  input_stream_buffer *buf = fileStream.rdbuf();
  buf->pubsetbuf(buffer, AXIS_INPUTFILE_BUFFER_LENGTH);

  // initialize variables
  lastLineReadIdx = 0;
  wasLineRead = false;
  hasPushedBackLine = false;

  // try to open the file
  if(buf->open(filename.data(), std::ios_base::in) == NULL)
  {
    // an error occurred while trying to open; abort
    buf->pubsetbuf(NULL, 0);
    delete[] buffer;

    throw axis::foundation::IOException();
  }
}

asio::FileReader::FileReader(const axis::String& filename)
{
	data_ = new InternalFileData(filename);
}

asio::FileReader::~FileReader(void)
{
	Close();
}

void asio::FileReader::ReadLine(axis::String& s)
{
	if (IsEOF())
	{	// passed the end of the file; we can't read from here
		throw axis::foundation::IOException();
	}
	if (data_ == NULL)
	{
		throw axis::foundation::InvalidOperationException();
	}

	if(data_->hasPushedBackLine)
	{
		data_->wasLineRead = true;
		s = data_->lastLineRead;
		data_->hasPushedBackLine = false;
		(data_->lastLineReadIdx)++;
	}
	else
	{
		try
		{
			// try to read a line from the file
			axis::getline(data_->fileStream, data_->lastLineRead);
			s = data_->lastLineRead;
			(data_->lastLineReadIdx)++;
			data_->wasLineRead = true;
		}
		catch(...)
		{
			throw axis::foundation::IOException();
		}
	}
}

void asio::FileReader::PushBackLine( void )
{
	if (data_->hasPushedBackLine) throw axis::foundation::NotSupportedException();
	if(!data_->wasLineRead) throw axis::foundation::InvalidOperationException();

	// ignore if it's EOF
	if (IsEOF()) return;

	data_->hasPushedBackLine = true;
	(data_->lastLineReadIdx)--;
}

bool asio::FileReader::IsEOF(void) const
{
	if (data_ == NULL)
	{
		throw axis::foundation::InvalidOperationException();
	}
	return IsOpen()? data_->fileStream.eof() : false;
}

bool asio::FileReader::IsOpen(void) const
{
	return (data_ != NULL) && (data_->fileStream.is_open());
}

void asio::FileReader::Close(void)
{
	if(IsOpen())
	{	// clean resources
		try
		{
			data_->fileStream.close();
		}
		catch (...)
		{
			throw axis::foundation::IOException();
		}
		data_->fileStream.rdbuf()->pubsetbuf(NULL, 0);
		delete[] data_->buffer;
		delete data_;
    data_ = NULL;
	}
}

axis::String asio::FileReader::GetStreamPath(void) const
{
	return data_->fileName;
}

unsigned long asio::FileReader::GetLastLineNumber( void ) const
{
	return data_->lastLineReadIdx;
}

void asio::FileReader::Reset( void )
{
	axis::String filename = data_->fileName;
	Close();
	data_ = new InternalFileData(filename);
}

max_stars_repo_name: renato-yuzup/axis-fem

max_issues_repo_name: renato-yuzup/axis-fem

max_forks_repo_name: renato-yuzup/axis-fem


text:
/*
 * @CopyRight:
 * FISCO-BCOS 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.
 *
 * FISCO-BCOS 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 FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2018 fisco-dev contributors.
 */
/** @file RocksDBStorageFactory.h
 *  @author xingqiangbai
 *  @date 20180423
 */

#include "RocksDBStorageFactory.h"
#include "BasicRocksDB.h"
#include "RocksDBStorage.h"
#include "libdevcore/Guards.h"
#include <boost/filesystem.hpp>

using namespace std;
using namespace dev;
using namespace dev::storage;

void RocksDBStorageFactory::setDBOpitons(rocksdb::Options _options)
{
    m_options = _options;
}

Storage::Ptr RocksDBStorageFactory::getStorage(const std::string& _dbName, bool _createIfMissing)
{
    auto dbName = m_DBPath + "/" + _dbName;
    if (!_createIfMissing && !boost::filesystem::exists(dbName))
    {
        return nullptr;
    }
    boost::filesystem::create_directories(dbName);

    RecursiveGuard l(x_cache);
    if (m_cache.first == dbName)
    {
        return m_cache.second;
    }
    std::shared_ptr<BasicRocksDB> rocksDB = std::make_shared<BasicRocksDB>();
    rocksDB->Open(m_options, dbName);
    std::shared_ptr<RocksDBStorage> rocksdbStorage =
        std::make_shared<RocksDBStorage>(m_disableWAL, m_completeDirty);
    rocksdbStorage->setDB(rocksDB);
    m_cache = make_pair(dbName, rocksdbStorage);
    return rocksdbStorage;
}

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
/**
 * Copyright (c) 2013 Jonan Cruz-Martin
 *
 * Distributed under the terms of the MIT license, see the accompanying
 * file COPYING or http://opensource.org/licenses/MIT.
 *
 * @file
 * @brief Class definitions for domains of tetrahedra.
 */

#ifndef DOMAINS_TETRAHEDRAL_HPP
#define DOMAINS_TETRAHEDRAL_HPP

#include "types.hpp"
#include "../points/cartesian.hpp"
#include "../points/cylindrical.hpp"
#include "../points/polar.hpp"
#include "../points/spherical.hpp"

#include "../vertices/tetrahedral.hpp"
#include "../cells/tetrahedral.hpp"

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

/**
 * Domain of lines in the cartesian 3D space.
 *
 * @since 0.1.0
 */
class TetrahedralCartesian3D_Domain {
	/**
	 * ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralCartesian3D_Domain_t     domain;
public:
	TetrahedralCartesian3D_Domain() {};

	/**
	 * Return the number of vertices contained in the domain.
	 *
	 * @return unsigned integer
	 */
	unsigned int num_vertices();

	/**
	 * Create a new vertex in the domain based on the given point.
	 *
	 * @param point Point that represents the vertex. The point object will be copied.
	 */
	void make_vertex(PointCartesian3D point);

	/**
	 * Return the vertex identified by the given index.
	 *
	 * @param index Numerical vertex ID as assigned by ViennaGrid on vertex creation.
	 */
	TetrahedralCartesian3D_Vertex get_vertex(unsigned int index);

	/**
	 * Return a Python list containing all the vertices of the domain.
	 *
	 * @return Python list
	 */
	list get_vertices();

	/**
	 * Return the number of cells contained in the segment.
	 *
	 * @return unsigned integer
	 *
	 * @since 0.1.0
	 */
	unsigned int num_cells();

	/**
	 * Create a new cell in the segment.
	 *
	 * @param vertex1
	 * @param vertex2
	 * @param vertex3
	 * @param vertex4
	 *
	 * @return The newly created cell.
	 *
	 * @since 0.1.0
	 */
	TetrahedralCartesian3D_Cell make_cell(TetrahedralCartesian3D_Vertex vertex1, TetrahedralCartesian3D_Vertex vertex2, TetrahedralCartesian3D_Vertex vertex3, TetrahedralCartesian3D_Vertex vertex4);

	/**
	 * Return a Python list containing all the cells contained in the segment.
	 *
	 * @return Python list
	 *
	 * @since 0.1.0
	 */
	list get_cells();

	/**
	 * Get a reference to the ViennaGrid domain object.
	 *
	 * @return Reference to the ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralCartesian3D_Domain_t & get_domain();
};

/**
 * Domain of lines in the cylindrical space.
 *
 * @since 0.1.0
 */
class TetrahedralCylindrical3D_Domain {
	/**
	 * ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralCylindrical3D_Domain_t     domain;
public:
	TetrahedralCylindrical3D_Domain() {};

	/**
	 * Return the number of vertices contained in the domain.
	 *
	 * @return unsigned integer
	 */
	unsigned int num_vertices();

	/**
	 * Create a new vertex in the domain based on the given point.
	 *
	 * @param point Point that represents the vertex. The point object will be copied.
	 */
	void make_vertex(PointCylindrical3D point);

	/**
	 * Return the vertex identified by the given index.
	 *
	 * @param index Numerical vertex ID as assigned by ViennaGrid on vertex creation.
	 */
	TetrahedralCylindrical3D_Vertex get_vertex(unsigned int index);

	/**
	 * Return a Python list containing all the vertices of the domain.
	 *
	 * @return Python list
	 */
	list get_vertices();

	/**
	 * Return the number of cells contained in the segment.
	 *
	 * @return unsigned integer
	 *
	 * @since 0.1.0
	 */
	unsigned int num_cells();

	/**
	 * Create a new cell in the segment.
	 *
	 * @param vertex1
	 * @param vertex2
	 * @param vertex3
	 * @param vertex4
	 *
	 * @return The newly created cell.
	 *
	 * @since 0.1.0
	 */
	TetrahedralCylindrical3D_Cell make_cell(TetrahedralCylindrical3D_Vertex vertex1, TetrahedralCylindrical3D_Vertex vertex2, TetrahedralCylindrical3D_Vertex vertex3, TetrahedralCylindrical3D_Vertex vertex4);

	/**
	 * Return a Python list containing all the cells contained in the segment.
	 *
	 * @return Python list
	 *
	 * @since 0.1.0
	 */
	list get_cells();

	/**
	 * Get a reference to the ViennaGrid domain object.
	 *
	 * @return Reference to the ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralCylindrical3D_Domain_t & get_domain();
};

/**
 * Domain of lines in the spherical space.
 *
 * @since 0.1.0
 */
class TetrahedralSpherical3D_Domain {
	/**
	 * ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralSpherical3D_Domain_t     domain;
public:
	TetrahedralSpherical3D_Domain() {};

	/**
	 * Return the number of vertices contained in the domain.
	 *
	 * @return unsigned integer
	 */
	unsigned int num_vertices();

	/**
	 * Create a new vertex in the domain based on the given point.
	 *
	 * @param point Point that represents the vertex. The point object will be copied.
	 */
	void make_vertex(PointSpherical3D point);

	/**
	 * Return the vertex identified by the given index.
	 *
	 * @param index Numerical vertex ID as assigned by ViennaGrid on vertex creation.
	 */
	TetrahedralSpherical3D_Vertex get_vertex(unsigned int index);

	/**
	 * Return a Python list containing all the vertices of the domain.
	 *
	 * @return Python list
	 */
	list get_vertices();

	/**
	 * Return the number of cells contained in the segment.
	 *
	 * @return unsigned integer
	 *
	 * @since 0.1.0
	 */
	unsigned int num_cells();

	/**
	 * Create a new cell in the segment.
	 *
	 * @param vertex1
	 * @param vertex2
	 * @param vertex3
	 * @param vertex4
	 *
	 * @return The newly created cell.
	 *
	 * @since 0.1.0
	 */
	TetrahedralSpherical3D_Cell make_cell(TetrahedralSpherical3D_Vertex vertex1, TetrahedralSpherical3D_Vertex vertex2, TetrahedralSpherical3D_Vertex vertex3, TetrahedralSpherical3D_Vertex vertex4);

	/**
	 * Return a Python list containing all the cells contained in the segment.
	 *
	 * @return Python list
	 *
	 * @since 0.1.0
	 */
	list get_cells();

	/**
	 * Get a reference to the ViennaGrid domain object.
	 *
	 * @return Reference to the ViennaGrid domain object.
	 * @since 0.1.0
	 */
	TetrahedralSpherical3D_Domain_t & get_domain();
};

#endif /* end of include guard: DOMAINS_TETRAHEDRAL_HPP */

max_stars_repo_name: jonancm/viennagrid-python

max_issues_repo_name: jonancm/viennagrid-python

max_forks_repo_name: jonancm/viennagrid-python


text:
#include "igl/opengl/glfw/renderer.h"

#include <GLFW/glfw3.h>
#include <igl/unproject_onto_mesh.h>
#include "igl/look_at.h"
#include <Eigen/Dense>
Renderer::Renderer() : selected_core_index(0),
					   next_core_id(2)
{
	core_list.emplace_back(igl::opengl::ViewerCore());
	core_list.front().id = 1;
	// C-style callbacks
	callback_init = nullptr;
	callback_pre_draw = nullptr;
	callback_post_draw = nullptr;
	callback_mouse_down = nullptr;
	callback_mouse_up = nullptr;
	callback_mouse_move = nullptr;
	callback_mouse_scroll = nullptr;
	callback_key_down = nullptr;
	callback_key_up = nullptr;

	callback_init_data = nullptr;
	callback_pre_draw_data = nullptr;
	callback_post_draw_data = nullptr;
	callback_mouse_down_data = nullptr;
	callback_mouse_up_data = nullptr;
	callback_mouse_move_data = nullptr;
	callback_mouse_scroll_data = nullptr;
	callback_key_down_data = nullptr;
	callback_key_up_data = nullptr;
	highdpi = 1;

	xold = 0;
	yold = 0;
}

IGL_INLINE void Renderer::draw(GLFWwindow *window)
{
	using namespace std;
	using namespace Eigen;

	int width, height;
	glfwGetFramebufferSize(window, &width, &height);

	int width_window, height_window;
	glfwGetWindowSize(window, &width_window, &height_window);

	auto highdpi_tmp = (width_window == 0 || width == 0) ? highdpi : (width / width_window);

	if (fabs(highdpi_tmp - highdpi) > 1e-8)
	{
		post_resize(window, width, height);
		highdpi = highdpi_tmp;
	}

	for (auto &core : core_list)
	{
		core.clear_framebuffers();
	}

	for (auto &core : core_list)
	{
		for (auto &mesh : scn->data_list)
		{
			if (mesh.is_visible & core.id)
			{
				core.draw(scn->MakeTrans(), mesh);
			}
		}
	}
}

void Renderer::SetScene(igl::opengl::glfw::Viewer *viewer)
{
	scn = viewer;
}

IGL_INLINE void Renderer::init(igl::opengl::glfw::Viewer *viewer)
{
	scn = viewer;
	core().init();

	core().align_camera_center(scn->data().V, scn->data().F);
}

void Renderer::UpdatePosition(double xpos, double ypos)
{
	xrel = xold - xpos;
	yrel = yold - ypos;
	xold = xpos;
	yold = ypos;
}

void Renderer::MouseProcessing(int button)
{

	if (button == 1) //right
	{

		scn->data().MyTranslate(Eigen::Vector3f(-xrel / 2000.0f, 0, 0));
		scn->data().MyTranslate(Eigen::Vector3f(0, yrel / 2000.0f, 0));
	}
	else //left
	{
		scn->data().MyRotate(Eigen::Vector3f(1, 0, 0), xrel / 180.0f);
		scn->data().MyRotate(Eigen::Vector3f(0, 0, 1), yrel / 180.0f);
	}
}

Renderer::~Renderer()
{
	//if (scn)
	//	delete scn;
}

hitObject Renderer::Picking(double newx, double newy)
{
	hitObject hitObjectCurrent;
	hitObjectCurrent.found = false;
	hitObjectCurrent.distance = 0;

	int fid;
	//Eigen::MatrixXd C = Eigen::MatrixXd::Constant(scn->data().F.rows(), 3, 1);
	Eigen::Vector3f bc;
	double x = newx;
	double y = core().viewport(3) - newy;
	Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
	igl::look_at(core().camera_eye, core().camera_center, core().camera_up, view);
	view = view * (core().trackball_angle * Eigen::Scaling(core().camera_zoom * core().camera_base_zoom) * Eigen::Translation3f(core().camera_translation + core().camera_base_translation)).matrix() * scn->MakeTrans() * scn->data().MakeTrans();
	if (igl::unproject_onto_mesh(Eigen::Vector2f(x, y), view,
								 core().proj, core().viewport, scn->data().V, scn->data().F, fid, bc))
	{
		//find vertexes - watch igl::ray_mesh_intersect to see how the verixes vere found there and replace f with fid
		Eigen::RowVector3d v0 = scn->data().V.row(scn->data().F(fid, 0)).template cast<double>();
		Eigen::RowVector3d v1 = scn->data().V.row(scn->data().F(fid, 1)).template cast<double>();
		Eigen::RowVector3d v2 = scn->data().V.row(scn->data().F(fid, 2)).template cast<double>();
		// p = alpha1 * p1 + alpha2 * p2 + alpha3 * p3
		Eigen::Vector3f alpha0MultiplyV0(bc(0) * v0(0), bc(0) * v0(1), bc(0) * v0(2));
		Eigen::Vector3f alpha1MultiplyV1(bc(1) * v1(0), bc(1) * v1(1), bc(1) * v1(2));
		Eigen::Vector3f alpha2MultiplyV2(bc(2) * v2(0), bc(2) * v2(1), bc(2) * v2(2));
		Eigen::Vector3f p(alpha0MultiplyV0(0) + alpha1MultiplyV1(0) + alpha2MultiplyV2(0),
			alpha0MultiplyV0(1) + alpha1MultiplyV1(1) + alpha2MultiplyV2(1),
			alpha0MultiplyV0(2) + alpha1MultiplyV1(2) + alpha2MultiplyV2(2));
		//perform transformatiom on P point
		Eigen::Matrix<float, 4, 1> pPointIn4dMatrix = { p(0), p(1), p(2), 1};
		//multiply view * pPointIn4dMatrix in order to get the transformed p point
		Eigen::Matrix<float, 4, 1> resultMatrix = view * pPointIn4dMatrix;
		Eigen::Vector3f resultVector(resultMatrix(0), resultMatrix(1), resultMatrix(2));
		hitObjectCurrent.distance = resultVector.norm();
		hitObjectCurrent.found = true;
		return hitObjectCurrent;
	}

	return hitObjectCurrent;
}

IGL_INLINE void Renderer::resize(GLFWwindow *window, int w, int h)
{
	if (window)
	{
		glfwSetWindowSize(window, w / highdpi, h / highdpi);
	}
	post_resize(window, w, h);
}

IGL_INLINE void Renderer::post_resize(GLFWwindow *window, int w, int h)
{
	if (core_list.size() == 1)
	{
		core().viewport = Eigen::Vector4f(0, 0, w, h);
	}
	else
	{
		// It is up to the user to define the behavior of the post_resize() function
		// when there are multiple viewports (through the `callback_post_resize` callback)
	}
	//for (unsigned int i = 0; i < plugins.size(); ++i)
	//{
	//	plugins[i]->post_resize(w, h);
	//}
	if (callback_post_resize)
	{
		callback_post_resize(window, w, h);
	}
}

IGL_INLINE igl::opengl::ViewerCore &Renderer::core(unsigned core_id /*= 0*/)
{
	assert(!core_list.empty() && "core_list should never be empty");
	int core_index;
	if (core_id == 0)
		core_index = selected_core_index;
	else
		core_index = this->core_index(core_id);
	assert((core_index >= 0 && core_index < core_list.size()) && "selected_core_index should be in bounds");
	return core_list[core_index];
}

IGL_INLINE const igl::opengl::ViewerCore &Renderer::core(unsigned core_id /*= 0*/) const
{
	assert(!core_list.empty() && "core_list should never be empty");
	int core_index;
	if (core_id == 0)
		core_index = selected_core_index;
	else
		core_index = this->core_index(core_id);
	assert((core_index >= 0 && core_index < core_list.size()) && "selected_core_index should be in bounds");
	return core_list[core_index];
}

IGL_INLINE bool Renderer::erase_core(const size_t index)
{
	assert((index >= 0 && index < core_list.size()) && "index should be in bounds");
	//assert(data_list.size() >= 1);
	if (core_list.size() == 1)
	{
		// Cannot remove last viewport
		return false;
	}
	core_list[index].shut(); // does nothing
	core_list.erase(core_list.begin() + index);
	if (selected_core_index >= index && selected_core_index > 0)
	{
		selected_core_index--;
	}
	return true;
}

IGL_INLINE size_t Renderer::core_index(const int id) const
{
	for (size_t i = 0; i < core_list.size(); ++i)
	{
		if (core_list[i].id == id)
			return i;
	}
	return 0;
}

IGL_INLINE int Renderer::append_core(Eigen::Vector4f viewport, bool append_empty /*= false*/)
{
	core_list.push_back(core()); // copies the previous active core and only changes the viewport
	core_list.back().viewport = viewport;
	core_list.back().id = next_core_id;
	next_core_id <<= 1;
	if (!append_empty)
	{
		for (auto &data : scn->data_list)
		{
			data.set_visible(true, core_list.back().id);
			//data.copy_options(core(), core_list.back());
		}
	}
	selected_core_index = core_list.size() - 1;
	return core_list.back().id;
}

//IGL_INLINE void Viewer::select_hovered_core()
//{
//	int width_window, height_window = 800;
//   glfwGetFramebufferSize(window, &width_window, &height_window);
//	for (int i = 0; i < core_list.size(); i++)
//	{
//		Eigen::Vector4f viewport = core_list[i].viewport;

//		if ((current_mouse_x > viewport[0]) &&
//			(current_mouse_x < viewport[0] + viewport[2]) &&
//			((height_window - current_mouse_y) > viewport[1]) &&
//			((height_window - current_mouse_y) < viewport[1] + viewport[3]))
//		{
//			selected_core_index = i;
//			break;
//		}
//	}
//}


text:
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/functor_row.hpp>
#include <boost/msm/back/state_machine.hpp>

#include <gmock/gmock.h>

using ::testing::StrictMock;
using ::testing::InSequence;

namespace {

struct Mock
{
    MOCK_METHOD(void, call, (int), ());
};

struct DataEvent
{
    int data;
};

struct DataSentEvent {};

namespace msmf = boost::msm::front;

struct DefFSM : msmf::state_machine_def<DefFSM>
{
    struct WaitDataState : msmf::state<> {};
    struct SendDataState : msmf::state<>
    {
        template <typename Fsm>
        void on_entry(const DataEvent& event, Fsm& fsm) {
            fsm.mock.call(event.data);
        }

        using deferred_events = boost::mpl::vector<DataEvent>;
    };

    using initial_state = WaitDataState;

    struct transition_table : boost::mpl::vector<
                //          Start           Event           Next            Action
                msmf::Row < WaitDataState,  DataEvent,      SendDataState,  msmf::none >,
                msmf::Row < SendDataState,  DataEvent,      msmf::none,     msmf::Defer >,
                msmf::Row < SendDataState,  DataSentEvent,  WaitDataState,  msmf::none >
            > {};

    StrictMock<Mock> mock;
};

using FSM = boost::msm::back::state_machine<DefFSM>;

} // Anonymous namespace

TEST(Boost_MSM_defer, enqueue) {
    FSM fsm;

    EXPECT_CALL(fsm.mock, call(1));

    fsm.start();

    fsm.process_event(DataEvent{1});
    fsm.process_event(DataEvent{2});

    fsm.stop();
}

TEST(Boost_MSM_defer, dequeue) {
    FSM fsm;

    {
        InSequence _;

        EXPECT_CALL(fsm.mock, call(1));
        EXPECT_CALL(fsm.mock, call(2));
        EXPECT_CALL(fsm.mock, call(3));
    }

    fsm.start();

    fsm.process_event(DataEvent{1});
    fsm.process_event(DataEvent{2});
    fsm.process_event(DataEvent{3});

    fsm.process_event(DataSentEvent{});
    fsm.process_event(DataSentEvent{});
    fsm.process_event(DataSentEvent{});

    fsm.stop();
}

max_stars_repo_name: dvetutnev/fart-checker

max_issues_repo_name: dvetutnev/fart-checker

max_forks_repo_name: dvetutnev/fart-checker


text:
#include "blackhole/formatter/json.hpp"

#include <array>
#include <set>
#include <unordered_map>

#include <boost/optional/optional.hpp>
#include <boost/variant/apply_visitor.hpp>

#ifndef RAPIDJSON_HAS_STDSTRING
#define RAPIDJSON_HAS_STDSTRING 1
#endif
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <rapidjson/pointer.h>

#include "blackhole/attribute.hpp"
#include "blackhole/config/node.hpp"
#include "blackhole/config/option.hpp"
#include "blackhole/record.hpp"
#include "blackhole/extensions/writer.hpp"

#include "../attribute.hpp"
#include "../datetime.hpp"
#include "../memory.hpp"
#include "../util/deleter.hpp"
#include "json.hpp"

namespace blackhole {
inline namespace v1 {
namespace formatter {
namespace {

struct visitor_t {
    typedef void result_type;

    rapidjson::Value& node;
    rapidjson::MemoryPoolAllocator<>& allocator;

    const string_view& name;

    auto operator()(std::nullptr_t) -> void {
        node.AddMember(rapidjson::StringRef(name.data(), name.size()), rapidjson::kNullType, allocator);
    }

    // For `bool`, `std::int64_t`, `std::uint64_t` and `double` types.
    template<typename T>
    auto operator()(T value) -> void {
        static_assert(
            std::is_same<T, bool>::value ||
            std::is_same<T, std::int64_t>::value ||
            std::is_same<T, std::uint64_t>::value ||
            std::is_same<T, double>::value, "type mismatch");
        node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator);
    }

    auto operator()(const string_view& value) -> void {
        node.AddMember(rapidjson::StringRef(name.data(), name.size()),
            rapidjson::StringRef(value.data(), value.size()), allocator);
    }

    // For temporary buffers, rapidjson will copy the data.
    auto operator()(const char* data, std::size_t size) -> void {
        node.AddMember(rapidjson::StringRef(name.data(), name.size()),
            rapidjson::Value(data, static_cast<unsigned int>(size), allocator), allocator);
    }

    auto operator()(const attribute::view_t::function_type& value) -> void {
        writer_t wr;
        value(wr);

        node.AddMember(rapidjson::StringRef(name.data(), name.size()),
            wr.result().to_string(), allocator);
    }
};

// TODO: Decompose. Almost the same class is in `string.cpp`.
class view_visitor : public boost::static_visitor<> {
    writer_t& writer;
    const std::string& spec;

public:
    view_visitor(writer_t& writer, const std::string& spec) noexcept :
        writer(writer),
        spec(spec)
    {}

    auto operator()(std::nullptr_t) const -> void {
        writer.write(spec, "none");
    }

    template<typename T>
    auto operator()(T value) const -> void {
        writer.write(spec, value);
    }

    auto operator()(const string_view& value) const -> void {
        writer.write(spec, value.data());
    }

    auto operator()(const attribute::view_t::function_type& value) const -> void {
        value(writer);
    }
};

/// A RapidJSON Stream concept implementation required to avoid intermediate buffer allocation.
struct stream_t {
    typedef char Ch;

    writer_t& wr;

    /// Writes a character directly into the underlying buffer.
    // TODO: Seems like writing string one-by-one affects the performance. See similar benchmarks
    // that differs only with input string length.
    auto Put(Ch c) -> void {
        wr.inner << c;
    }

    /// Does nothing, because there is no intermediate buffer.
    auto Flush() -> void {}
};

}  // namespace

class json_t::properties_t {
public:
    bool unique;
    bool newline;

    std::function<void(const record_t::time_point& time, writer_t& wr)> timestamp;
    std::vector<std::string> severity;

    struct {
        std::map<std::string, std::vector<std::string>> specified;
        std::string unspecified;
    } routing;

    std::unordered_map<std::string, std::string> mapping;
    std::unordered_map<std::string, std::string> formatting;

    properties_t() :
        unique(false),
        newline(false)
    {}
};

class json_t::inner_t {
    template<typename> class builder;

public:
    // A JSON routing pointer for attributes that weren't mentioned in `routing` map.
    rapidjson::Pointer rest;
    // Routing map from attribute name to its JSON pointer.
    std::map<std::string, rapidjson::Pointer> routing;

    std::unordered_map<std::string, std::string> mapping;
    std::unordered_map<std::string, std::string> formatting;

    bool unique;
    bool newline;

    std::function<void(const record_t::time_point& time, writer_t& wr)> timestamp;
    std::vector<std::string> severity;

    inner_t(json_t::properties_t properties) :
        rest(properties.routing.unspecified),
        mapping(std::move(properties.mapping)),
        formatting(std::move(properties.formatting)),
        unique(properties.unique),
        newline(properties.newline),
        timestamp(properties.timestamp),
        severity(std::move(properties.severity))
    {
        for (const auto& route : properties.routing.specified) {
            for (const auto& name : route.second) {
                routing.insert({name, rapidjson::Pointer(route.first)});
            }
        }
    }

    template<typename Document>
    auto get(const string_view& name, Document& root) -> rapidjson::Value& {
        // TODO: Here we can avoid a temporary string construction by using multi indexed
        // containers.
        const auto it = routing.find(name.to_string());

        if (it == routing.end()) {
            return rest.GetWithDefault(root, rapidjson::kObjectType);
        } else {
            return it->second.GetWithDefault(root, rapidjson::kObjectType);
        }
    }

    template<typename Document>
    auto create(Document& root, const record_t& record) -> builder<Document>;

    auto renamed(const string_view& name) const -> string_view {
        const auto it = mapping.find(name.to_string());

        if (it == mapping.end()) {
            return name;
        } else {
            return it->second;
        }
    }
};

template<typename Document>
class json_t::inner_t::builder {
    Document& root;
    const record_t& record;
    inner_t& inner;

public:
    builder(Document& root, const record_t& record, inner_t& inner) :
        root(root),
        record(record),
        inner(inner)
    {}

    auto message() -> void {
        apply("message", record.formatted());
    }

    auto severity() -> void {
        const auto id = static_cast<std::size_t>(record.severity());

        if (inner.severity.empty() || id >= inner.severity.size()) {
            apply("severity", static_cast<std::int64_t>(record.severity()));
        } else {
            apply("severity", string_view(inner.severity[id].data(), inner.severity[id].size()));
        }
    }

    auto timestamp() -> void {
        if (inner.timestamp) {
            writer_t wr;
            inner.timestamp(record.timestamp(), wr);
            apply("timestamp", wr.inner.data(), wr.inner.size());
        } else {
            apply("timestamp", std::chrono::duration_cast<
                std::chrono::microseconds
            >(record.timestamp().time_since_epoch()).count());
        }
    }

    auto build(writer_t& writer) -> void {
        stream_t stream{writer};
        rapidjson::Writer<stream_t> wr(stream);
        root.Accept(wr);
    }

    auto attributes() -> void {
        if (inner.unique) {
            // TODO: Small buffer optimization is possible here (see stack allocator with arena).
            std::set<string_view> set;

            for (const auto& attributes : record.attributes()) {
                for (const auto& attribute : attributes.get()) {
                    if (set.insert(attribute.first).second) {
                        apply(attribute.first, attribute.second);
                    }
                }
            }
            return;
        }

        // TODO: Make flattened range
        // TODO: Make uniqued range.
        for (const auto& attributes : record.attributes()) {
            for (const auto& attribute : attributes.get()) {
                apply(attribute.first, attribute.second);
            }
        }
    }

private:
    template<typename T>
    auto apply(const string_view& name, const T& value) -> void {
        const auto renamed = inner.renamed(name);
        visitor_t visitor{inner.get(name, root), root.GetAllocator(), renamed};

        const auto it = inner.formatting.find(std::string(name.data(), name.size()));
        if (it != std::end(inner.formatting)) {
            writer_t wr;
            wr.write(it->second, value);
            visitor(wr.inner.data(), wr.inner.size());
        } else {
            visitor(value);
        }
    }

    auto apply(const string_view& name, const char* data, std::size_t size) -> void {
        const auto renamed = inner.renamed(name);
        visitor_t visitor{inner.get(name, root), root.GetAllocator(), renamed};

        const auto it = inner.formatting.find(std::string(name.data(), name.size()));
        if (it != std::end(inner.formatting)) {
            writer_t wr;
            wr.write(it->second, fmt::StringRef(data, size));
            visitor(wr.inner.data(), wr.inner.size());
        } else {
            visitor(data, size);
        }
    }

    auto apply(const string_view& name, const attribute::view_t& value) -> void {
        const auto renamed = inner.renamed(name);
        visitor_t visitor{inner.get(name, root), root.GetAllocator(), renamed};

        const auto it = inner.formatting.find(std::string(name.data(), name.size()));
        if (it != std::end(inner.formatting)) {
            writer_t wr;
            boost::apply_visitor(view_visitor(wr, it->second), value.inner().value);
            visitor(wr.inner.data(), wr.inner.size());
        } else {
            boost::apply_visitor(visitor, value.inner().value);
        }
    }
};

template<typename Document>
auto json_t::inner_t::create(Document& root, const record_t& record) ->
    builder<Document>
{
    return builder<Document>{root, record, *this};
}

json_t::json_t() :
    inner(new inner_t(properties_t()))
{}

json_t::json_t(properties_t properties) :
    inner(new inner_t(std::move(properties)))
{}

auto json_t::newline() const noexcept -> bool {
    return inner->newline;
}

auto json_t::unique() const noexcept -> bool {
    return inner->unique;
}

auto json_t::format(const record_t& record, writer_t& writer) -> void {
    typedef rapidjson::GenericDocument<
        rapidjson::UTF8<>,
        rapidjson::MemoryPoolAllocator<>,
        rapidjson::MemoryPoolAllocator<>
    > document_type;

    std::array<char, 4096> value_buffer;
    std::array<char, 1024> parse_buffer;
    rapidjson::MemoryPoolAllocator<> value_allocator(value_buffer.data(), value_buffer.size());
    rapidjson::MemoryPoolAllocator<> parse_allocator(parse_buffer.data(), parse_buffer.size());

    document_type root(&value_allocator, parse_buffer.size(), &parse_allocator);
    root.SetObject();

    // TODO: Try to use `AutoUTF<>` or `AutoUTFOutputStream` for UTF-8 validation.

    auto builder = inner->create(root, record);
    builder.message();
    builder.severity();
    builder.timestamp();
    builder.attributes();

    builder.build(writer);

    if (inner->newline) {
        writer.inner << '\n';
    }
}

}  // namespace formatter

using formatter::json_t;

class builder<json_t>::inner_t : public json_t::properties_t {};

builder<json_t>::builder() :
    d(new inner_t{}, deleter_t())
{}

auto builder<json_t>::route(std::string route) & -> builder& {
    d->routing.unspecified = std::move(route);
    return *this;
}

auto builder<json_t>::route(std::string route) && -> builder&& {
    d->routing.unspecified = std::move(route);
    return std::move(*this);
}

auto builder<json_t>::route(std::string route, std::vector<std::string> attributes) & -> builder& {
    d->routing.specified[std::move(route)] = std::move(attributes);
    return *this;
}

auto builder<json_t>::route(std::string route, std::vector<std::string> attributes) && -> builder&& {
    d->routing.specified[std::move(route)] = std::move(attributes);
    return std::move(*this);
}

auto builder<json_t>::rename(std::string from, std::string to) & -> builder& {
    d->mapping[std::move(from)] = std::move(to);
    return *this;
}

auto builder<json_t>::rename(std::string from, std::string to) && -> builder&& {
    d->mapping[std::move(from)] = std::move(to);
    return std::move(*this);
}

auto builder<json_t>::unique() & -> builder& {
    d->unique = true;
    return *this;
}

auto builder<json_t>::unique() && -> builder&& {
    return std::move(unique());
}

auto builder<json_t>::newline() & -> builder& {
    d->newline = true;
    return *this;
}

auto builder<json_t>::newline() && -> builder&& {
    d->newline = true;
    return std::move(*this);
}

auto builder<json_t>::severity(std::vector<std::string> sevmap) & -> builder& {
    d->severity = std::move(sevmap);
    return *this;
}

auto builder<json_t>::severity(std::vector<std::string> sevmap) && -> builder&& {
    d->severity = std::move(sevmap);
    return std::move(*this);
}

auto builder<json_t>::timestamp(const std::string& pattern) & -> builder& {
    auto generator = datetime::make_generator(pattern);

    d->timestamp = [=](const record_t::time_point& timestamp, writer_t& wr) {
        const auto time = record_t::clock_type::to_time_t(timestamp);
        const auto usec = std::chrono::duration_cast<
            std::chrono::microseconds
        >(timestamp.time_since_epoch()).count() % 1000000;

        std::tm tm;
        ::gmtime_r(&time, &tm);

        generator(wr.inner, tm, static_cast<std::uint64_t>(usec));
    };

    return *this;
}

auto builder<json_t>::timestamp(const std::string& pattern) && -> builder&& {
    return std::move(timestamp(pattern));
}

auto builder<json_t>::format(std::string name, std::string spec) & -> builder& {
    d->formatting[name] = spec;
    return *this;
}

auto builder<json_t>::format(std::string name, std::string spec) && -> builder&& {
    return std::move(format(std::move(name), std::move(spec)));
}

auto builder<json_t>::build() const && -> std::unique_ptr<formatter_t> {
    return blackhole::make_unique<json_t>(std::move(*d));
}

auto factory<json_t>::type() const noexcept -> const char* {
    return "json";
}

auto factory<json_t>::from(const config::node_t& config) const ->
    std::unique_ptr<formatter_t>
{
    builder<json_t> builder;

    if (auto unique = config["unique"].to_bool()) {
        if (unique.get()) {
            builder.unique();
        }
    }

    if (auto newline = config["newline"].to_bool()) {
        if (newline.get()) {
            builder.newline();
        }
    }

    if (auto mapping = config["mapping"]) {
        mapping.each_map([&](const std::string& key, const config::node_t& value) {
            builder.rename(key, value.to_string());
        });
    }

    if (auto formatting = config["formatting"]) {
        formatting.each_map([&](const std::string& key, const config::node_t& value) {
            builder.format(key, value.to_string());
        });
    }

    if (auto routing = config["routing"]) {
        routing.each_map([&](const std::string& key, const config::node_t& value) {
            try {
                // TODO: Probably it's right thing to explicitly check whether the value is string.
                value.to_string();
                builder.route(key);
                return;
            } catch (const std::logic_error&) {
                // Eat.
            }

            std::vector<std::string> attributes;
            value.each([&](const config::node_t& config) {
                attributes.emplace_back(config.to_string());
            });
            builder.route(key, std::move(attributes));
        });
    }

    if (auto mutate = config["mutate"]) {
        mutate.each_map([&](const std::string& key, const config::node_t& config) {
            if (key == "timestamp") {
                builder.timestamp(config.to_string());
            } else if (key == "severity") {
                std::vector<std::string> mapping;
                config.each([&](const config::node_t& severity) {
                    mapping.emplace_back(severity.to_string());
                });
                builder.severity(std::move(mapping));
            } else {
                throw std::invalid_argument("only \"timestamp\" and \"severity\" mutations are allowed now");
            }
        });
    }

    return std::move(builder).build();
}

template auto deleter_t::operator()(builder<formatter::json_t>::inner_t*) -> void;
template auto deleter_t::operator()(formatter::json_t::inner_t*) -> void;

}  // namespace v1
}  // namespace blackhole

max_stars_repo_name: Lyr-a-Brode/blackhole

max_issues_repo_name: Lyr-a-Brode/blackhole

max_forks_repo_name: Lyr-a-Brode/blackhole


text:
// Read Unicode character properties from the database.
// Though this file is under the Boost license, it is NOT (or not yet) part of
// Boost!

// Copyright Graham Barnett, Rogier van Dalen 2005.
// Use, modification, and distribution are subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <string>
#include <sstream>
#include <algorithm>

#include <boost/spirit.hpp>
#include <boost/lambda/lambda.hpp>

#include "read_character_properties.hpp"
#include "read_character_properties_files.hpp"

using namespace boost::spirit;
using namespace boost::unicode;
using namespace boost::unicode::ucd;
using namespace boost::lambda;

namespace boost { namespace unicode { namespace ucd {

void read_character_properties_arabicshaping
	(std::map <codepoint, character_properties> & props, const char* filename, bool required)
{
	std::cout << "+Reading arabicshaping from " << filename << "\n";

	parse_info <file_iterator<> > info;
	file_iterator<> curr, last;
	/*
	Read file containing information about the join type of Arabic characters.
	*/

	try
	{
		curr = get_file_iterator (filename);
	}
	catch (file_read_error)
	{
		if (required)
		{
			throw;
		}
		else
		{
			std::cout << "-Reading arabicshaping from optional file - not present\n";
			return;
		}
	}

	last = curr.make_end();

	eat_comments (curr, last);

	do
	{
		codepoint character;
		join_type::type joining;

		// The line being decoded is formatted as:
		// Field 0: the code point, in 4-digit hexadecimal form, of an Arabic or Syriac character.
		// Field 1: gives a short schematic name for that character, abbreviated from Unicode character name.
		// Field 2: defines the joining type (property name: Joining_Type) [RLDCUT]
		// Field 3: defines the joining group (property name: Joining_Group)
		// e.g.
		// 0629; TEH MARBUTA; R; TEH MARBUTA

		info = parse (curr, last,
			// hex character code
			hex_p [assign_a (character)] >> ';' >>
			// skip character name
			+(anychar_p - ';') >> ';' >>
			// joining type
			(
			ch_p('R') [assign_a (joining, join_type::right)] |
			ch_p('L') [assign_a (joining, join_type::left)] |
			ch_p('D') [assign_a (joining, join_type::dual)] |
			ch_p('C') [assign_a (joining, join_type::causing)] |
			ch_p('U') [assign_a (joining, join_type::none)] |
			ch_p('T') [assign_a (joining, join_type::transparent)]
			) >> ';' >>
			// TODO: Revisit this - Do we need the joining group ?
			// Skip any remaining entries, i.e., parse future versions
			// of the table as well.
			*(anychar_p - ('#' | eol_p))
			, blank_p);

		if (!info.hit)
		{
			throw syntax_error (filename, curr, last);
		}
		curr = info.stop;

		eat_comments (curr, last);

		std::map <codepoint, character_properties>::iterator prop = props.find (character);
		if (prop == props.end())
		{
			std::stringstream ss;
			ss << "Codepoint " << std::hex << character
				<< " is in ArabicShaping.txt, but not in UnicodeData.txt.";
			throw std::runtime_error (ss.str());
		}

        prop->second.joining = joining;

    } while (curr != last);

	std::cout << "-Reading arabicshaping from " << filename << "\n";
}

}}}	// namespaces

max_stars_repo_name: cordarei/boost-unicode

max_issues_repo_name: cordarei/boost-unicode

max_forks_repo_name: cordarei/boost-unicode


text:
/**
* PS Move API - An interface for the PS Move Motion Controller
* Copyright (c) 2011, 2012 Thomas Perl <m@thp.io>
* 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 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.
**/

/* General math utility functions */
#ifndef __PSMOVE_ADVANCED_MATH_H
#define __PSMOVE_ADVANCED_MATH_H

//-- includes -----
#include "psmove_platform_config.h"

#include <Eigen/Core>
#include <Eigen/Geometry>

#include "psmove_math.h"

//-- macros -----
#define assert_vector3f_is_normalized(v) assert(is_nearly_equal(v.squaredNorm(), 1.f, k_normal_epsilon))

#endif // __PSMOVE_ADVANCED_MATH_H

max_stars_repo_name: psmoveservice/psmoveapi

max_issues_repo_name: psmoveservice/psmoveapi

max_forks_repo_name: psmoveservice/psmoveapi


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

///
/// @file ThreadLocalInstance.hpp
///
/// A thread local instance that can be used as a class member instance variable.
///

#ifndef COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE
#define COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE

#include <boost/thread/tss.hpp>

namespace Balau::Concurrent {

///
/// A thread local instance that can be used as a class member instance variable.
///
template <typename T, typename Enable = void> class ThreadLocalInstance;

template <typename T>
class ThreadLocalInstance<T, typename std::enable_if<std::is_default_constructible<T>::value>::type> {
	///
	/// Get the thread local instance, instantiating it with the default constructor if necessary.
	///
	public: T & operator () () {
		if (!instance.get()) {
			instance.reset(new T);
		}

		return *instance.get();
	}

	///
	/// Get the thread local instance, instantiating it with the supplied function if necessary.
	///
	public: T & operator () (std::function<T * ()> instantiate) {
		if (!instance.get()) {
			instance.reset(instantiate());
		}

		return *instance.get();
	}

	///////////////////////// Private implementation //////////////////////////

	private: boost::thread_specific_ptr<T> instance;
};

template <typename T>
class ThreadLocalInstance<T, std::negation<typename std::enable_if<std::is_default_constructible<T>::value>::type>> {
	///
	/// Get the thread local instance, instantiating it with the supplied function if necessary.
	///
	public: T & operator () (std::function<T * ()> instantiate) {
		if (instance.get()) {
			instance.reset(instantiate());
		}

		return *instance.get();
	}

	///////////////////////// Private implementation //////////////////////////

	private: boost::thread_specific_ptr<T> instance;
};

} // namespace Balau::Concurrent

#endif // COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE

max_stars_repo_name: borasoftware/balau

max_issues_repo_name: borasoftware/balau

max_forks_repo_name: borasoftware/balau


text: #include <boost/format/internals_fwd.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "data_service/CDefDataProvider.h"
#include <stdio.h>
#include <chrono>
#include <iterator>
#include <iostream>
#include <numeric>
#include <cstdlib>

#include <boost/optional.hpp>
#include <boost/optional_ext.hpp>

#include <boost/lexical_cast.hpp>

template<typename T>
boost::optional<const T&> toOp(const T& value)
{
    return value;
}

template<typename T>
boost::optional<T&> toOp(T& value)
{
    return value;
}

boost::optional<double> toDouble(const std::string& value) noexcept
{
    try {
        return boost::lexical_cast<double>(value);
    }
    catch (const boost::bad_lexical_cast& exc)
    {
        std::cerr << exc.what() << std::endl;
        return boost::none;
    }
}

template<typename T>
void print(const T& value) noexcept
{
    std::cout << "new value from provider: " << value << std::endl;
}

int main()
{

    services::CDefDataProvider provider;

    double acc = 0.0;
    uint32_t errors = 0;

    uint64_t avarageTime = 0;
    uint16_t count = 0;
    std::list<double> items;
    auto bi = std::back_inserter(items);

    provider.onNewData([&avarageTime, &count, &acc, &errors, &bi, &provider](const services::IDataProvider::Data& data) mutable {

        auto errorHandler = [&errors] () mutable noexcept {
            std::cout << "a wrong data recieved" << std::endl;
            errors += 1;
        };

        auto filter = [] (auto&& el) noexcept
            {
                return std::isgreaterequal(el, 0.0) && std::islessequal(el, 50.0);
            };

        auto accept = [&bi] (auto&& el) mutable noexcept {
            *bi = el;
            std::cout << "New Value accepted: " << el << std::endl;
        };

        auto start = std::chrono::high_resolution_clock::now();

        // In an old manner it would be look like this:
        /*
            try {
                auto value = boost::lexical_cast<double>(data);
                print(value);
                if (value >= 0 && value <= 50)
                {
                    std::cout << "New Value accepted: " << value << std::endl;
                    *bi = value;
                    acc += value;
                }
            }
            catch (const boost::bad_lexical_cast& exc)
            {
                std::cerr << exc.what() << std::endl;
                errors += 1;
            };
        */

        acc += toOp(data)
                 | toDouble
                 | hof::match(print<double>, errorHandler)
                 | hof::filter_if(filter)
                 | hof::match_some(accept)
                 <<= 0.0;

        auto stop = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);

        count += 1;
        avarageTime += duration.count();

        std::cout << "----step-----ACC-[" << acc << "] avarageTime: " << avarageTime / count << " microseconds " << std::endl;

        if (acc >= 100)
        {
            provider.stop();
        }
    });

    provider.start();

    provider.wait();

    std::cout << "Final Acc: [" << acc << "], Errors: " << errors << std::endl;
    std::cout << "Elements are: ";
    auto check = 0;
    for (const auto& el: items)
    {
        check += el;
        std::cout << el << ", ";
    }
    std::cout << std::endl << " Sum is " << check << std::endl;

    return 0;
}