text:
/*
    Copyright (c) 2022 Xavier Leclercq
    Released under the MIT License
    See https://github.com/nemu-cpp/web-framework/blob/main/LICENSE.txt
*/

#ifndef _NEMU_CPP_WEBFRAMEWORK_REQUESTHANDLERS_FILESYSTEMWEBREQUESTHANDLER_HPP_
#define _NEMU_CPP_WEBFRAMEWORK_REQUESTHANDLERS_FILESYSTEMWEBREQUESTHANDLER_HPP_

#include "../WebRequestHandler.hpp"
#include <boost/filesystem.hpp>
#include <string>
#include <vector>

namespace Nemu
{

class FileSystemWebRequestHandler : public WebRequestHandler
{
public:
    FileSystemWebRequestHandler(boost::filesystem::path root);

    void run(const WebRequest& request, WebResponseBuilder& response, Ishiko::Logger& logger) override;

private:
    boost::filesystem::path m_root;
    std::vector<std::string> m_defaults;
};

}

#endif

ext: hpp

max_stars_repo_name: nemu-cpp/web-server

max_issues_repo_name: nemu-cpp/web-server

max_forks_repo_name: nemu-cpp/web-server


text:
//
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/math/math_basic_types.h>
#include <OpenTissue/core/geometry/geometry_compute_volume_length_quality_measure.h>

#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>

BOOST_AUTO_TEST_SUITE(opentissue_geometry_util_compute_volume_length_quality_measure);

  BOOST_AUTO_TEST_CASE(case_by_case_testing)
  {
    using std::sqrt;

    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;
    typedef math_types::vector3_type                         vector3_type;
    typedef math_types::real_type                            real_type;

    real_type tol = 0.0001;

    {
      // semi regular
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 0, 2);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;

      BOOST_CHECK_CLOSE( quality, 0.975423, tol);
    }
    {
      // close to flat
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 0, 0.01);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0465344, tol);
    }
    {
      // flat but still a simplex
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 0, 0);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0, tol);
    }
    {
      // flat but no longer a simplex - quad-like
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 1, 1, 0);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0, tol);
    }
    {
      // inverted
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 0, -1);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.865855, tol);
    }
    {
      // degenerate 2 nodes
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 1,-1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 1, 0);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0, tol);
    }
    {
      // degenerate 3 nodes
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 0, 1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 1, 0);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0, tol);
    }
    {
      // degenerate 4 nodes
      vector3_type p0(-1,-1, 0);
      vector3_type p1( 0, 1, 0);
      vector3_type p2( 0, 1, 0);
      vector3_type p3( 0, 1, 0);
      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);
      std::cout << quality << std::endl;
      BOOST_CHECK_CLOSE( quality, 0.0, tol);
    }

  }

BOOST_AUTO_TEST_SUITE_END();

ext: cpp

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


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

#include "XMLRWPreParser.hpp"

#include "DependencyGraph.hpp"
#include "XMLErrorHandler.hpp"
#include "XMLParser.hpp"
#include "XMLParserUtil.hpp"

#include <rw/core/StringUtil.hpp>
#include <rw/core/macros.hpp>

#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
#include <fstream>
#include <iostream>
#include <vector>

using namespace boost::spirit::classic;
using namespace phoenix;

using namespace rw::loaders;
using namespace rw::core;

namespace {

struct AppendToOutputFromFile
{
    AppendToOutputFromFile (std::vector< char >& output, const std::string& currentfile,
                            DependencyGraph& graph,
                            std::vector< std::pair< size_t, file_position > >& filemap) :
        _output (output),
        _currentfile (currentfile), _graph (graph), _filemap (filemap)
    {}

    void operator() (std::string const& filename) const { append (filename); }

    template< typename IteratorT >
    void operator() (IteratorT const& first, IteratorT const& last) const
    {
        append (std::string (first, last));
    }

    void append (std::string const& filename) const
    {
        std::string absfilename;
        if (StringUtil::isAbsoluteFileName (filename)) {
            absfilename = filename;
        }
        else {
            // get directory name from filemap
            std::string dir = StringUtil::getDirectoryName (_filemap.back ().second.file);
            absfilename     = dir + filename;
        }

        // std::cout << "Absolute filename: " << absfilename << " pos: " <<
        //_output.size()<< std::endl;

        _graph.addDependency (_currentfile, absfilename);

        if (_graph.hasCycleDependency ()) {
            RW_THROW ("ERROR: including " << absfilename << " from file " << _currentfile
                                          << " because of cyclic dependencies!!!");
        }
        else {
            file_position pos (absfilename);
            file_position oldpos = _filemap.back ().second;
            std::pair< size_t, file_position > mapdata (_output.size (), pos);
            _filemap.push_back (mapdata);
            XMLRWPreParser::parse (absfilename, _output, _filemap, _graph);

            // std::cout << "Last char in output: " <<
            //(int(_output[_output.size()-1]))<< std::endl ;

            // std::cout << "Parsed include succes" << std::endl;
            // remember to push the old back again
            mapdata.first  = _output.size ();
            mapdata.second = oldpos;
            _filemap.push_back (mapdata);
        }
    }

    std::vector< char >& _output;
    const std::string& _currentfile;
    DependencyGraph& _graph;
    std::vector< std::pair< size_t, file_position > >& _filemap;
};

struct XMLPreParser : grammar< XMLPreParser, result_closure< std::vector< char > >::context_t >
{
  protected:
    DependencyGraph& _graph;
    std::string _filename;
    std::vector< char >& _output;
    std::vector< std::pair< size_t, file_position > >& _filemap;

  public:
    XMLPreParser (std::string filename, DependencyGraph& graph, std::vector< char >& output,
                  std::vector< std::pair< size_t, file_position > >& filemap) :
        _graph (graph),
        _filename (filename), _output (output), _filemap (filemap)
    {}

    template< typename ScannerT > struct definition
    {
      public:
        definition (XMLPreParser const& self);
        /**
         * @brief Gets start rule
         * @return the start rule
         */
        rule< ScannerT > const start () const { return rwpre; }

        std::string _id, _define;
        std::map< std::string, std::string > _map;

      private:
        rule< ScannerT > rwpre, build, define, use, include, main;
        rule< ScannerT, result_closure< std::string >::context_t > quotedStr;
        rule< ScannerT, result_closure< std::string >::context_t > attrstr_r;
    };
};

template< typename ScannerT >
XMLPreParser::definition< ScannerT >::definition (XMLPreParser const& self)
{
    /* The  */
    rwpre = XMLErrorHandler::XMLErrorGuard (main)[XMLErrorHandler ()];

    main = (*(define | use | include | build))[self.result_ = var (self._output)] >> end_p;

    build = (+(anychar_p - (ch_p ('<') >> (str_p ("Define") | str_p ("Use") |
                                           str_p ("Include")))))[AppendToOutput (self._output)];

    /* Saves this information in a map */
    define = XMLAttElem_p ("Define",
                           XMLAtt_p ("id", attrstr_r[var (_id) = arg1]),
                           (*(anychar_p - (str_p ("</") >> "Define")))[InsertInMap (_map, _id)]);

    /* Inserts the previusly defined at this position */
    use = XMLAttElem_p (
        "Use", XMLAtt_p ("id", attrstr_r[AppendToOutputFromMap (_map, self._output)]), eps_p);

    /* Inserts text from include files */
    include =
        XMLAttElem_p ("Include",
                      XMLAtt_p ("file",
                                attrstr_r[AppendToOutputFromFile (
                                    self._output, self._filename, self._graph, self._filemap)]),
                      eps_p);

    attrstr_r = (*(anychar_p - '"'))[attrstr_r.result_ = construct_< std::string > (arg1, arg2)];

    quotedStr =
        '"' >>
        lexeme_d[*(anychar_p - '"')][quotedStr.result_ = construct_< std::string > (arg1, arg2)] >>
        '"';
}
}    // namespace

bool XMLRWPreParser::parse (const std::string& absfilename, std::vector< char >& output,
                            std::vector< std::pair< size_t, file_position > >& filemap,
                            DependencyGraph& graph)
{
    std::ifstream in (absfilename.c_str ());
    if (!in) {
        RW_THROW ("Could not open input file: " << absfilename);
    }
    /*std::string absfilename = filename;
    if( !StringUtil::IsAbsoluteFileName( filename ) ){
        fs::path full_path;
        full_path = fs::system_complete( fs::path( filename.c_str(), fs::native ) );
        absfilename = full_path.native_file_string();
    }*/
    in.unsetf (std::ios::skipws);    //  Turn of white space skipping on the stream

    // If the version and encoding is specified in the workcell, skip the first line
    std::streampos oldpos = in.tellg ();    // stores the position
    std::string line;
    std::getline (in, line);
    std::string t ("<?");
    if (line.compare (0, t.length (), t) != 0)
        in.seekg (oldpos);    // get back to the position

    std::vector< char > vec;
    std::copy (std::istream_iterator< char > (in),
               std::istream_iterator< char > (),
               std::back_inserter (vec));

    typedef position_iterator< std::vector< char >::const_iterator > iterator_t;
    iterator_t first (vec.begin (), vec.end ());
    iterator_t last;

    XMLPreParser p (absfilename, graph, output, filemap);

    parse_info< iterator_t > info = boost::spirit::classic::parse (
        first, last, p, (blank_p | "<!--" >> *(anychar_p - "-->") >> "-->"));

    if (info.full) {
        return true;
    }
    RW_THROW ("Parsing of workcell failed!!");
    return false;
}

#define RULE(name, definition) typeof (definition) name = definition

bool XMLRWPreParser::parse (const std::string& absfilename, std::vector< char >& output,
                            std::vector< std::pair< size_t, file_position > >& filemap)
{ /*
     if( !StringUtil::IsAbsoluteFileName( absfilename ) ){
         RW_THROW( "Error the absfilename is not an absolute absfilename: " << absfilename );
     }*/
    file_position pos (absfilename);
    std::pair< size_t, file_position > mapdata (0, pos);
    filemap.push_back (mapdata);

    DependencyGraph graph;
    graph.hasCycleDependency ();
    bool res = XMLRWPreParser::parse (absfilename, output, filemap, graph);
    // std::cout << "Finished pre parsing step!!" << std::endl;
    return res;
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2013 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2013 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2013 Mateusz Loskot, London, UK.
// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP
#define BOOST_GEOMETRY_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP

#include <boost/geometry/multi/core/closure.hpp>
#include <boost/geometry/multi/core/point_order.hpp>
#include <boost/geometry/multi/core/tags.hpp>
#include <boost/geometry/multi/geometries/concepts/check.hpp>

#include <boost/geometry/algorithms/remove_spikes.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace remove_spikes
{

template <typename MultiGeometry, typename SingleVersion>
struct multi_remove_spikes
{
    static inline void apply(MultiGeometry& multi)
    {
        for (typename boost::range_iterator<MultiGeometry>::type
                it = boost::begin(multi);
            it != boost::end(multi);
            ++it)
        {
            SingleVersion::apply(*it);
        }
    }
};

}} // namespace detail::remove_spikes
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename MultiPolygon>
struct remove_spikes<MultiPolygon, multi_polygon_tag>
    : detail::remove_spikes::multi_remove_spikes
        <
            MultiPolygon,
            detail::remove_spikes::polygon_remove_spikes
            <
                typename boost::range_value<MultiPolygon>::type
            >
        >
{};

} // namespace dispatch
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
// Copyright (c) 2006-2007, Rodrigo Braz Monteiro, Evgeniy Stepanov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Aegisub Group nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Aegisub Project http://www.aegisub.org/

/// @file subtitles_provider_libass.cpp
/// @brief libass-based subtitle renderer
/// @ingroup subtitle_rendering
///

#include "config.h"

#include "subtitles_provider_libass.h"

#ifdef __APPLE__
#include <sys/param.h>
#include <libaegisub/util_osx.h>
#endif

#include "ass_file.h"
#include "dialog_progress.h"
#include "frame_main.h"
#include "main.h"
#include "utils.h"
#include "video_frame.h"

#include <libaegisub/dispatch.h>
#include <libaegisub/log.h>
#include <libaegisub/util.h>

#include <boost/gil/gil_all.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>
#include <memory>
#include <mutex>

namespace {
std::unique_ptr<agi::dispatch::Queue> cache_queue;
ASS_Library *library;

void msg_callback(int level, const char *fmt, va_list args, void *) {
	if (level >= 7) return;
	char buf[1024];
#ifdef _WIN32
	vsprintf_s(buf, sizeof(buf), fmt, args);
#else
	vsnprintf(buf, sizeof(buf), fmt, args);
#endif

	if (level < 2) // warning/error
		LOG_I("subtitle/provider/libass") << buf;
	else // verbose
		LOG_D("subtitle/provider/libass") << buf;
}

#ifdef __APPLE__
#define CONFIG_PATH (agi::util::GetBundleResourcesDirectory() + "/etc/fonts/fonts.conf").c_str()
#else
#define CONFIG_PATH nullptr
#endif
}

LibassSubtitlesProvider::LibassSubtitlesProvider(std::string) {
	auto done = std::make_shared<bool>(false);
	auto renderer = std::make_shared<ASS_Renderer*>(nullptr);
	cache_queue->Async([=]{
		auto ass_renderer = ass_renderer_init(library);
		if (ass_renderer) {
			ass_set_font_scale(ass_renderer, 1.);
			ass_set_fonts(ass_renderer, nullptr, "Sans", 1, CONFIG_PATH, true);
		}
		*done = true;
		*renderer = ass_renderer;
	});

	DialogProgress progress(wxGetApp().frame, _("Updating font index"), _("This may take several minutes"));
	progress.Run([=](agi::ProgressSink *ps) {
		ps->SetIndeterminate();
		while (!*done && !ps->IsCancelled())
			agi::util::sleep_for(250);
	});

	ass_renderer = *renderer;
	if (!ass_renderer) throw "ass_renderer_init failed";
}

LibassSubtitlesProvider::~LibassSubtitlesProvider() {
	if (ass_track) ass_free_track(ass_track);
	if (ass_renderer) ass_renderer_done(ass_renderer);
}

void LibassSubtitlesProvider::LoadSubtitles(AssFile *subs) {
	std::vector<char> data;
	data.clear();
	data.reserve(0x4000);

	AssEntryGroup group = AssEntryGroup::GROUP_MAX;
	for (auto const& line : subs->Line) {
		if (group != line.Group()) {
			group = line.Group();
			boost::push_back(data, line.GroupHeader() + "\r\n");
		}
		boost::push_back(data, line.GetEntryData() + "\r\n");
	}

	if (ass_track) ass_free_track(ass_track);
	ass_track = ass_read_memory(library, &data[0], data.size(),(char *)"UTF-8");
	if (!ass_track) throw "libass failed to load subtitles.";
}

#define _r(c) ((c)>>24)
#define _g(c) (((c)>>16)&0xFF)
#define _b(c) (((c)>>8)&0xFF)
#define _a(c) ((c)&0xFF)

void LibassSubtitlesProvider::DrawSubtitles(VideoFrame &frame,double time) {
	ass_set_frame_size(ass_renderer, frame.width, frame.height);

	ASS_Image* img = ass_render_frame(ass_renderer, ass_track, int(time * 1000), nullptr);

	// libass actually returns several alpha-masked monochrome images.
	// Here, we loop through their linked list, get the colour of the current, and blend into the frame.
	// This is repeated for all of them.

	using namespace boost::gil;
	auto dst = interleaved_view(frame.width, frame.height, (bgra8_pixel_t*)frame.data.data(), frame.width * 4);
	if (frame.flipped)
		dst = flipped_up_down_view(dst);

	for (; img; img = img->next) {
		unsigned int opacity = 255 - ((unsigned int)_a(img->color));
		unsigned int r = (unsigned int)_r(img->color);
		unsigned int g = (unsigned int)_g(img->color);
		unsigned int b = (unsigned int)_b(img->color);

		auto srcview = interleaved_view(img->w, img->h, (gray8_pixel_t*)img->bitmap, img->stride);
		auto dstview = subimage_view(dst, img->dst_x, img->dst_y, img->w, img->h);

		transform_pixels(dstview, srcview, dstview, [=](const bgra8_pixel_t frame, const gray8_pixel_t src) -> bgra8_pixel_t {
			unsigned int k = ((unsigned)src) * opacity / 255;
			unsigned int ck = 255 - k;

			bgra8_pixel_t ret;
			ret[0] = (k * b + ck * frame[0]) / 255;
			ret[1] = (k * g + ck * frame[1]) / 255;
			ret[2] = (k * r + ck * frame[2]) / 255;
			ret[3] = 0;
			return ret;
		});
	}
}

void LibassSubtitlesProvider::CacheFonts() {
	// Initialize the cache worker thread
	cache_queue = agi::dispatch::Create();

	// Initialize libass
	library = ass_library_init();
	ass_set_message_cb(library, msg_callback, nullptr);

	// Initialize a renderer to force fontconfig to update its cache
	cache_queue->Async([]{
		auto ass_renderer = ass_renderer_init(library);
		ass_set_fonts(ass_renderer, nullptr, "Sans", 1, CONFIG_PATH, true);
		ass_renderer_done(ass_renderer);
	});
}

max_stars_repo_name: rcombs/Aegisub

max_issues_repo_name: rcombs/Aegisub

max_forks_repo_name: rcombs/Aegisub


text:
#include <cmath>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/LU>
#include <limits>
#include "rose499/spline.hpp"

using namespace Eigen;

constexpr int Spline::PolyOrder;
constexpr int Spline::CoeffCount;

namespace
{
    constexpr int ResampleCount = 9;

    using ValueType = Spline::ValueType;
    using MatrixXT = SimulatorTypes::MatrixXT;
    using VectorXT = SimulatorTypes::VectorXT;
    using PolySpace = Array<ValueType, 1, Spline::CoeffCount>;

    PolySpace polydiff_power(PolySpace poly, int order)
    {
        PolySpace prevPoly = poly;
        PolySpace dpoly = PolySpace::Constant(0);
        PolySpace powerCoeff = PolySpace::Constant(1);
        for(auto i = 0; i < order; i++)
        {
            Array<ValueType, 1, Dynamic> power(1, Spline::CoeffCount - i);
            power.setLinSpaced(0, Spline::PolyOrder - i);
            powerCoeff.tail(Spline::CoeffCount - i) = powerCoeff.tail(Spline::CoeffCount - i) * power;
        }
        dpoly.tail(Spline::CoeffCount - order) = poly.head(Spline::CoeffCount - order);
        dpoly = dpoly * powerCoeff;
        return dpoly;
    }

    PolySpace polydiffshift(PolySpace poly)
    {
        PolySpace dpoly = PolySpace::Constant(0);
        dpoly.head(Spline::CoeffCount - 1) = poly.tail(Spline::CoeffCount - 1);
        dpoly.head(Spline::CoeffCount - 1) *= Array<ValueType, Spline::CoeffCount - 1, 1>::LinSpaced(1, Spline::PolyOrder);
        return dpoly;
    }

    /**
        Builds an equality matrix that only provides end point guarantees and
        C^2 continuity everywhere.
    **/
    void
    polyBuildSoftEqualityMatrix(    MatrixXT& Aeq,
                                    VectorXT& beq,
                                    Matrix<ValueType, 2, Dynamic> const & waypoints,
                                    double direction = std::numeric_limits<double>::infinity() )
    {
        constexpr size_t DirectionConstraintCount = 1;
        constexpr auto CoeffCount = Spline::CoeffCount;

        auto const waypointCount = waypoints.cols();
        auto const segmentCount = waypointCount - 1;

        bool const supportDirection = std::isfinite(direction);

        Aeq.resize( 4*(waypointCount-2)                                         // Differential Constraints
                        + 2*waypointCount                                       // Equality Constraints
                        + (supportDirection ? DirectionConstraintCount : 0)     // Direction Constraint
                    , 2*CoeffCount*segmentCount );
        beq.resize(Aeq.rows(), 1);

        Aeq.setZero();
        beq.setZero();

        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);
        auto row = 0;
        for(auto indSeg = 0; indSeg < segmentCount; ++indSeg)
        {
            auto col = 2*CoeffCount*indSeg;

            ValueType leftLambda = (indSeg * 1.0) / segmentCount;
            ValueType rightLambda = ((indSeg + 1.0) * 1.0) / segmentCount;

            PolySpace leftTerms = PolySpace::Constant(leftLambda);
            PolySpace rightTerms = PolySpace::Constant(rightLambda);
            leftTerms = pow(leftTerms, powers);
            rightTerms = pow(rightTerms, powers);

            PolySpace dLeftTerms = polydiff_power(leftTerms, 1);
            PolySpace ddLeftTerms = polydiff_power(leftTerms, 2);

            PolySpace dRightTerms = polydiff_power(rightTerms, 1);
            PolySpace ddRightTerms = polydiff_power(rightTerms, 2);

            if( indSeg < segmentCount - 1 )
            {
                // Right Equality (C0)
                Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;
                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -rightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -rightTerms;
                row += 2;

                // Right Differential Continuity (C1)
                Aeq.block<1, CoeffCount>(row + 0, col) = dRightTerms;
                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -dRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = dRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -dRightTerms;
                row += 2;

                // Right Differential Continuity (C2)
                Aeq.block<1, CoeffCount>(row + 0, col) = ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -ddRightTerms;
                row += 2;
            }
            else
            {
                // Hard Right Equality
                Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;
                beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg + 1);
                row += 2;
            }

            if( indSeg == 0 )
            {
                // Left Equality (C0)
                Aeq.block<1, CoeffCount>(row + 0, col) = leftTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = leftTerms;
                beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg);
                row += 2;

                if( supportDirection )
                {
                    while(direction > M_PI) direction -= 2*M_PI;
                    while(direction < -M_PI) direction += 2*M_PI;

                    if( std::abs(direction) <= std::atan2(1.0, 1.0)
                     || std::abs(direction - M_PI) <= std::atan2(1.0, 1.0)
                     || std::abs(direction + M_PI) <= std::atan2(1.0, 1.0) )
                    {
                        // Small tangent.
                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = std::tan(direction)*dLeftTerms;
                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col + CoeffCount) = -dLeftTerms;
                    }
                    else
                    {
                        // Large tangent
                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = -dLeftTerms;
                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col + CoeffCount) = dLeftTerms / std::tan(direction);
                    }
                }
            }
        }
    }

    /**
        Builds the equality matrix that is used in least squares to achieve
        C0, C1, and C2 equality at waypoints.

    **/
    void
    polyBuildEqualityMatrix( MatrixXT& Aeq,
                             VectorXT& beq,
                             Matrix<ValueType, 2, Dynamic> const & waypoints,
                             double direction = std::numeric_limits<double>::infinity() )
    {
        constexpr size_t DirectionConstraintCount = 2;
        constexpr auto CoeffCount = Spline::CoeffCount;

        auto const waypointCount = waypoints.cols();
        auto const segmentCount = waypointCount - 1;

        bool const supportDirection = std::isfinite(direction);

        Aeq.resize( 4*(segmentCount-1)                                          // Differential Constraints
                        + 4*(segmentCount)                                      // Equality Constraints
                        + (supportDirection ? DirectionConstraintCount : 0)     // Direction Constraint
                    , 2*CoeffCount*segmentCount );
        beq.resize(Aeq.rows(), 1);

        Aeq.setZero();
        beq.setZero();

        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);
        auto row = 0;
        for(auto indSeg = 0; indSeg < segmentCount; ++indSeg)
        {
            auto col = 2*CoeffCount*indSeg;

            ValueType leftLambda = (indSeg * 1.0) / segmentCount;
            ValueType rightLambda = ((indSeg + 1.0) * 1.0) / segmentCount;

            PolySpace leftTerms = PolySpace::Constant(leftLambda);
            PolySpace rightTerms = PolySpace::Constant(rightLambda);
            leftTerms = pow(leftTerms, powers);
            rightTerms = pow(rightTerms, powers);

            PolySpace dLeftTerms = polydiff_power(leftTerms, 1);
            PolySpace ddLeftTerms = polydiff_power(leftTerms, 2);

            PolySpace dRightTerms = polydiff_power(rightTerms, 1);
            PolySpace ddRightTerms = polydiff_power(rightTerms, 2);

            // Left Equality (C0)
            Aeq.block<1, CoeffCount>(row + 0, col) = leftTerms;
            Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = leftTerms;
            beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg);
            row += 2;

            // Right Equality (C0)
            Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;
            Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;
            beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg + 1);
            row += 2;

            if( (indSeg == 0) && supportDirection )
            {
                Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = dLeftTerms;
                Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(1, col + CoeffCount) = dLeftTerms;

                Matrix<ValueType, 2, 1> vec;
                vec(0) = std::cos(direction);
                vec(1) = std::sin(direction);

                beq.tail(DirectionConstraintCount) = vec;
            }

            if( indSeg < segmentCount - 1 )
            {
                // Right Differential Continuity (C1)
                Aeq.block<1, CoeffCount>(row + 0, col) = dRightTerms;
                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -dRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = dRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -dRightTerms;
                row += 2;

                // Right Differential Continuity (C2)
                Aeq.block<1, CoeffCount>(row + 0, col) = ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = ddRightTerms;
                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -ddRightTerms;
                row += 2;
            }
        }
    }

    void
    polyBuildLSQMatrix( MatrixXT& A,
                        VectorXT& b,
                        Matrix<ValueType, 2, Dynamic> const & waypoints )
    {
        constexpr auto CoeffCount = Spline::CoeffCount;
        constexpr auto IntermediateSampleCount = 9;
        const auto waypointCount = waypoints.cols();
        const auto segmentCount = waypointCount - 1;
        const auto sampleCount = segmentCount * IntermediateSampleCount;
        using SampleRow = Matrix<ValueType, 1, IntermediateSampleCount>;

        A.resize(2*sampleCount, 2*CoeffCount*segmentCount);
        b.resize(A.rows());

        A.setZero();
        b.setZero();

        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);
        size_t row = 0;
        size_t colX = 0, colY = CoeffCount;
        for(auto si = 0; si < segmentCount; ++si)
        {
            SampleRow sampleX = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(waypoints(0, si), waypoints(0, si+1)).middleCols(1, IntermediateSampleCount);
            SampleRow sampleY = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(waypoints(1, si), waypoints(1, si+1)).middleCols(1, IntermediateSampleCount);
            SampleRow sampleLambda = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(si * 1.0 / segmentCount, (si+1) * 1.0 / segmentCount).middleCols(1, IntermediateSampleCount);

            for(auto i = 0; i < sampleLambda.cols(); ++i)
            {
                PolySpace terms = PolySpace::Constant(sampleLambda(i));
                terms = pow(terms, powers);

                // Equality at the lambda
                A.block<1, CoeffCount>(row + 0, colX) = terms;
                A.block<1, CoeffCount>(row + 1, colY) = terms;
                b(row + 0) = sampleX(i);
                b(row + 1) = sampleY(i);

                row += 2;
            }

            colX += 2 * CoeffCount;
            colY += 2 * CoeffCount;
        }
    }

    /**
     * Splines a 5th order polynomial through the waypoints that ensures C2
     * conditions are met as well as a direction requirement at lambda=0
     *
     * The system is normally underdetermined so polyfit normally calculates the
     * right pseduo-inverse and performs a full pivot LU decomposition in order to
     * solve for the coefficients.
     *
     * Implements https://stanford.edu/class/ee103/lectures/constrained-least-squares/constrained-least-squares_slides.pdf
     */
    Matrix<ValueType, Dynamic, Spline::CoeffCount>
    polyfit(Matrix<ValueType, 2, Dynamic> waypoints, double direction = std::numeric_limits<double>::infinity() )
    {
        constexpr auto CoeffCount = Spline::CoeffCount;

        auto const waypointCount = waypoints.cols();
        auto const segmentCount = waypointCount - 1;

        MatrixXT Aeq, A;
        VectorXT beq, b;

        polyBuildSoftEqualityMatrix(Aeq, beq, waypoints, direction);
        polyBuildLSQMatrix(A, b, waypoints);

        // Moore-Penrose (Right) Pseudo-Inverse
        //c = Aeq.transpose() * (Aeq * Aeq.transpose()).fullPivLu().solve(beq);

        // Build full solution matrix F * (x, z)' = (2A'b, beq)'
        MatrixXT F( A.cols() + Aeq.rows(),
                    A.cols() + Aeq.rows() );
        VectorXT v( F.rows() );

        F.setZero();
        v.setZero();

        F.block(0, 0, A.cols(), A.cols()) = 2 * A.transpose() * A;
        F.block(0, A.cols(), Aeq.cols(), Aeq.rows()) = Aeq.transpose();
        F.block(A.cols(), 0, Aeq.rows(), Aeq.cols()) = Aeq;

        v.head(A.cols()) = 2 * A.transpose() * b;
        v.tail(beq.rows()) = beq;

        VectorXT d(F.rows(), 1);
        if( F.rows() > 100 )
        {
            SparseMatrix<ValueType, ColMajor> Fs;
            Fs = F.sparseView();

            SparseLU< SparseMatrix<ValueType, ColMajor> > solver;
            solver.analyzePattern(Fs);
            solver.factorize(Fs);
            d = solver.solve(v);
        }
        else
        {
            d = F.fullPivHouseholderQr().solve(v);
        }
        VectorXT c = d.head(Aeq.cols());
        /*
        MatrixXT c(Aeq.cols(), 1);

        // Moore-Penrose (Right) Pseudo-Inverse
        c = Aeq.transpose() * (Aeq * Aeq.transpose()).fullPivLu().solve(beq);
        */
        // Map the resulting coefficient vector into our matrix form of the polynomial
        // spline!
        Matrix<ValueType, Dynamic, CoeffCount> result(2 * segmentCount, CoeffCount);
        result = Map< Matrix<ValueType, Dynamic, CoeffCount, RowMajor> >(c.data(), result.rows(), result.cols());

        return result;
    }
}

Spline::Spline(Matrix<Spline::ValueType, 2, Dynamic> points)
  : mSplineCount(points.cols() - 1),
    mPoly(2 * mSplineCount, CoeffCount),
    mDPoly(2 * mSplineCount, CoeffCount),
    mDDPoly(2 * mSplineCount, CoeffCount)
{
    mPoly = ::polyfit(points);
    for( auto i = 0; i < mPoly.rows(); ++i )
    {
        mDPoly.row(i) = ::polydiffshift(mPoly.row(i));
    }
    for( auto i = 0; i < mPoly.rows(); ++i )
    {
        mDDPoly.row(i) = ::polydiffshift(mDPoly.row(i));
    }
    approximateSelf();
}

Spline::Spline(Eigen::Matrix<Spline::ValueType, 2, Eigen::Dynamic> points, double direction)
  : mSplineCount(points.cols() - 1),
    mPoly(2 * mSplineCount, CoeffCount),
    mDPoly(2 * mSplineCount, CoeffCount),
    mDDPoly(2 * mSplineCount, CoeffCount)
{
    mPoly = ::polyfit(points, direction);
    for( auto i = 0; i < mPoly.rows(); ++i )
    {
        mDPoly.row(i) = ::polydiffshift(mPoly.row(i));
    }
    for( auto i = 0; i < mPoly.rows(); ++i )
    {
        mDDPoly.row(i) = ::polydiffshift(mDPoly.row(i));
    }
    approximateSelf();
}

Spline::Spline()
  : mSplineCount(1),
    mPoly(2 * mSplineCount, CoeffCount),
    mDPoly(2 * mSplineCount, CoeffCount),
    mDDPoly(2 * mSplineCount, CoeffCount)
{
    mPoly.setZero();
    mDPoly.setZero();
    mDDPoly.setZero();
}

Matrix<Spline::ValueType, 2, 2> Spline::frame(ValueType parameter, uint32_t derivative) const
{
    // Min ops, 89 froats

    Matrix<ValueType, 2, 2> basis;
    Matrix<ValueType, 2, 1> tangent = (*this)(parameter, 1);
    ValueType speed = tangent.norm();

    if(derivative >= 0)
    {
        basis.col(0) = tangent / speed;

        // Rotate the first column by 90 degrees (right handed frame) to form the
        // full basis for R^2
        basis.col(1) = basis.col(0).reverse();
        basis(0, 1) = -basis(0, 1);
    }

    if(derivative >= 1)
    {
        Matrix<ValueType, 2, 1> accel = (*this)(parameter, 2);
        basis.col(0) = ( accel - accel.dot(basis.col(0)) * basis.col(0) ) / speed;
    }

    if(derivative >= 2)
        throw InvalidParameterException();

    // Rotate the first column by 90 degrees (right handed frame) to form the
    // full basis for R^2
    basis.col(1) = basis.col(0).reverse();
    basis(0, 1) = -basis(0, 1);
    return basis;
}

Spline::ValueType Spline::nearestPoint(Matrix<ValueType, 2, 1> point, ValueType lambdaStar) const
{
    auto error =
        [point, this](ValueType l) -> ValueType {
            return (point - this->operator()(l)).squaredNorm();
        };
    auto gradient =
        [point, this](ValueType l) -> ValueType {
            Matrix<ValueType, 2, 1> verr = point - this->operator()(l);
            return -2*verr.dot(this->operator()(l, 1));
        };

    ValueType lambda = lambdaStar;
    ValueType alpha = static_cast<ValueType>(1.0);
    alpha = std::min(alpha, alpha / speed(lambda));

    ValueType improvement = 1;
    int i = 500;
    while(std::abs(gradient(lambda)) > 1e-6 && (i > 0))
    {
        ValueType estimate = lambda - alpha * gradient(lambda);
        improvement = error(estimate) - error(lambda);
        if( improvement < 0 )
        {
            lambda = estimate;
            alpha *= 1.2;
        }
        else
            alpha *= 0.7;
        --i;
    }

    return std::max(std::min(lambda, static_cast<ValueType>(1.0)), static_cast<ValueType>(0.0));
}

int Spline::splineIndexUsed(ValueType parameter) const
{
    return std::max(0, std::min(mSplineCount - 1, (int)std::floor(mSplineCount * parameter)));
}

Spline::ValueType Spline::speed(ValueType parameter) const
{
    return (*this)(parameter, 1).norm();
}

Matrix<Spline::ValueType, 2, 1> Spline::operator() (ValueType parameter, uint32_t derivative) const
{
    using Vector = Matrix<Spline::ValueType, 2, 1>;
    using PolySpace = Array<Spline::ValueType, CoeffCount, 1>;

    // Identically zero derivative
    if( derivative > PolyOrder )
        return Vector::Zero();

    // Calculate x^0, x^1, ..., x^5
    PolySpace value = PolySpace::Constant(parameter);
    PolySpace powers = PolySpace::LinSpaced(0, PolyOrder);
    value = pow(value, powers);

    // Choose spline based on parameter value.
    int indSpline = splineIndexUsed(parameter);

    // And evaluate!
    switch(derivative)
    {
    case 0:
        return mPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();

    case 1:
        return mDPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();

    case 2:
        return mDDPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();

    default:
        throw InvalidParameterException();
    };
}

void Spline::approximateSelf()
{
    Spline& self = *this;

    const double maxDelta = 1.0 / (2.0 * mSplineCount);
    double startLambda = 0;
    double endLambda = maxDelta;

    mApproximation.clear();
    do
    {
        Spline::Line currentSegment;
        Matrix<ValueType, 2, 1> start = self(startLambda);
        Matrix<ValueType, 2, 1> end = self(endLambda);

        double normedIntegral = 0.0;
        do
        {
            normedIntegral = 0.0;
            endLambda = startLambda / 2.0 + endLambda / 2.0;
            end = self(endLambda);

            Matrix<ValueType, 2, 1> midpoint = self(startLambda / 2.0 + endLambda / 2.0);

            // Integrate numerically
            for(int i = 0; (i < 1000) && (normedIntegral <= 0.1); ++i)
            {
                Matrix<ValueType, 3, 1> dError = Matrix<ValueType, 3, 1>::Constant(0);
                Matrix<ValueType, 3, 1> dLine = Matrix<ValueType, 3, 1>::Constant(0);
                dError.head(2) = self(startLambda + i * (endLambda - startLambda) / 1000)
                               - (start + i * (end - start) / 1000);
                dLine.head(2)  = (end - start) / 1000;
                normedIntegral += dError.cross(dLine).norm();
            }
        } while( normedIntegral > 0.1 );

        geom::set<0, 0>(currentSegment, start[0]);
        geom::set<0, 1>(currentSegment, start[1]);
        geom::set<1, 0>(currentSegment, end[0]);
        geom::set<1, 1>(currentSegment, end[1]);

        startLambda = endLambda;
        endLambda = std::min(endLambda + maxDelta, 1.0);

        mApproximation.push_back(currentSegment);
    } while( startLambda < 1.0 );

    mArcLength = 0;
    for(auto&& line : mApproximation)
    {
        mArcLength += geom::length(line);
    }
}

Matrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::poly() const { return mPoly; }
Matrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::dpoly() const{ return mDPoly; }
Matrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::ddpoly() const{ return mDDPoly; }
Spline::ApproximateSpline const & Spline::approximation() const { return mApproximation; }
Spline::ValueType Spline::arclength() const { return mArcLength; }


text:
/*
 * Copyright 2013 Matthew Harvey
 *
 * 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.
 */

#ifndef GUARD_entry_hpp_7344880177334361
#define GUARD_entry_hpp_7344880177334361

#include "account.hpp"
#include "dcm_database_connection.hpp"
#include "transaction_side.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal_fwd.hpp>
#include <jewel/optional.hpp>
#include <sqloxx/handle.hpp>
#include <sqloxx/id.hpp>
#include <sqloxx/persistent_object.hpp>
#include <sqloxx/sql_statement_fwd.hpp>
#include <wx/string.h>
#include <memory>
#include <string>

namespace dcm
{

/**
 * Class representing an accounting entry, i.e. a single line in a journal,
 * i.e. a single change in the balance of an account.
 *
 * Client code must deal with sqloxx::Handle<Entry> rather than with Entry
 * objects directly. This is enforced via "Signature" parameters
 * in the constructors for Account.
 */
class Entry:
    public sqloxx::PersistentObject<Entry, DcmDatabaseConnection>
{
public:

    typedef sqloxx::PersistentObject<Entry, DcmDatabaseConnection>
        PersistentObject;

    typedef sqloxx::IdentityMap<Entry> IdentityMap;

    /*
     * Set up tables in the database required for the persistence of
     * Entry objects.
     */
    static void setup_tables(DcmDatabaseConnection& dbc);

    /**
     * Construct a fresh Entry, not yet persisted to database.
     *
     * Client code cannot use this constructor - see class level
     * documentation for why.
     */
    Entry
    (   IdentityMap& p_identity_map,
        IdentityMap::Signature const& p_signature
    );

    /**
     * Get an Entry by Id from the database.
     *
     * Client cod cannot use this constructor - see class level
     * documentation for why.
     */
    Entry
    (   IdentityMap& p_identity_map,
        sqloxx::Id p_id,
        IdentityMap::Signature const& p_signature
    );

    // Note copy constructor is private

    Entry(Entry&&) = delete;
    Entry& operator=(Entry const&) = delete;
    Entry& operator=(Entry&&) = delete;
    ~Entry();

    /**
     * Sets the journal_id for the Entry. Note this should \e not
     * normally be called. The usual way to associate an Entry with a
     * Journal (or DraftJournal or OrdinaryJournal) is for the Entry
     * to be added to the Journal via its push_entry(...) method.
     */
    void set_journal_id(sqloxx::Id p_journal_id);

    void set_account(sqloxx::Handle<Account> const& p_account);

    void set_comment(wxString const& p_comment);

    /**
     * Set the amount of the Entry. The amount should be: a positive number
     * for an actual debit; a negative number for an actual credit; a
     * negative number for a budget entry that increases the available
     * funds in an expenditure envelope; and a positive number for a budget
     * entry that decreases the available funds in an expenditure envelope.
     *
     * NOTE This method does \e not perform rounding to the number
     * of decimal places required for the precision of the Account's
     * native Commodity. It is the responsibility of the client to
     * ensure that the precision of \e p_amount is the same as the precision
     * of the native Commodity of the Account which was or will be set
     * as the Account for this Entry.
     */
    void set_amount(jewel::Decimal const& p_amount);

    /**
     * Set whether the Entry has been reconciled (e.g. for reconciling to
     * a bank or credit card statement.
     */
    void set_whether_reconciled(bool p_is_reconciled);

    /**
     * Set the TransactionSide for the Entry (see documentation for
     * TransactionSide).
     */
    void set_transaction_side
    (   TransactionSide p_transaction_side
    );

    /**
     * @returns comment, i.e. descriptive text generally entered by the user.
     *
     * Does not throw except possibly \c std::bad_alloc in
     * extreme circumstances.
     */
    wxString comment();

    /**
     * @returns Entry amount (+ve for debits, -ve for credits).
     *
     * Note that, when the Account of the Entry is a P&L account,
     * if we consider this P&L account from the point of view of a
     * budgeting envelope, the \e amount() will be -ve if the Entry
     * \e increases the
     * available funds in the envelope,
     * and +ve if the Entry \e decreases the available funds in an
     * envelope.
     */
    jewel::Decimal amount();

    sqloxx::Id journal_id();

    sqloxx::Handle<Account> account();

    bool is_reconciled();

    TransactionSide transaction_side();

    // Keep as std::string, for consistency with sqloxx
    static std::string exclusive_table_name();
    static std::string primary_key_name();

    /**
     * Copy attributes of rhs to *this, but do \e not copy:\n
     * \e id,\n
     * \e database_connection, or \n
     * \e journal_id.
     */
    void mimic(Entry& rhs);

    /**
     * @returns the posting date of the Entry, assuming it is associated
     * with an OrdinaryJournal. If it is associated with another kind of
     * Journal, then behaviour is undefined.
     */
    boost::gregorian::date date();

private:

    void swap(Entry& rhs);

    /**
     * Copy constructor - implemented, but deliberately private
     */
    Entry(Entry const& rhs);

    void do_load() override;
    void do_save_existing() override;
    void do_save_new() override;
    void do_ghostify() override;
    void do_remove() override;
    void process_saving_statement(sqloxx::SQLStatement& statement);

    struct EntryData;

    std::unique_ptr<EntryData> m_data;

};

/**
 * @returns a unique_ptr to a heap-allocated SQLStatement from which
 * entry_id may be selected from the first result column. Contains
 * only Entries that belong to actual (i.e. non-budget)
 * Journals that are OrdinaryJournals (i.e. not DraftJournals).
 * Filtering may optionally be performed by Account and/or date.
 * Within the result set, Entries are ordered by date.
 */
std::unique_ptr<sqloxx::SQLStatement>
create_date_ordered_actual_ordinary_entry_selector
(   DcmDatabaseConnection& p_database_connection,
    boost::optional<boost::gregorian::date> const& p_maybe_min_date =
        boost::optional<boost::gregorian::date>(),
    boost::optional<boost::gregorian::date> const& p_maybe_max_date =
        boost::optional<boost::gregorian::date>(),
    boost::optional<sqloxx::Handle<Account> > const& p_maybe_account =
        boost::optional<sqloxx::Handle<Account> >()
);

}  // namespace dcm

#endif  // GUARD_entry_hpp_7344880177334361

max_stars_repo_name: skybaboon/dailycashmanager

max_issues_repo_name: skybaboon/dailycashmanager

max_forks_repo_name: skybaboon/dailycashmanager


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2014, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_ALGORITHMS_NUM_SEGMENTS_HPP
#define BOOST_GEOMETRY_ALGORITHMS_NUM_SEGMENTS_HPP

#include <cstddef>

#include <boost/mpl/size_t.hpp>
#include <boost/mpl/times.hpp>

#include <boost/range.hpp>

#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/variant_fwd.hpp>

#include <boost/geometry/core/closure.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/util/range.hpp>

#include <boost/geometry/geometries/concepts/check.hpp>

#include <boost/geometry/algorithms/not_implemented.hpp>

#include <boost/geometry/algorithms/detail/counting.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace num_segments
{

struct range_count
{
    template <typename Range>
    static inline std::size_t apply(Range const& range)
    {
        std::size_t n = boost::size(range);
        if ( n <= 1 )
        {
            return 0;
        }

        return
            geometry::closure<Range>::value == open
            ?
            n
            :
            static_cast<std::size_t>(n - 1);
    }
};

}} // namespace detail::num_segments
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct num_segments
    : not_implemented<Tag>
{};

template <typename Geometry>
struct num_segments<Geometry, point_tag>
    : detail::counting::other_count<0>
{};

// the number of segments (1-dimensional faces) of the hypercube is
// given by the formula: d * 2^(d-1), where d is the dimension of the
// hypercube; see also:
//            http://en.wikipedia.org/wiki/Hypercube
template <typename Geometry>
struct num_segments<Geometry, box_tag>
    : detail::counting::other_count
        <
            geometry::dimension<Geometry>::value
            * (1 << (geometry::dimension<Geometry>::value - 1))
        >
{};

template <typename Geometry>
struct num_segments<Geometry, segment_tag>
    : detail::counting::other_count<1>
{};

template <typename Geometry>
struct num_segments<Geometry, linestring_tag>
    : detail::num_segments::range_count
{};

template <typename Geometry>
struct num_segments<Geometry, ring_tag>
    : detail::num_segments::range_count
{};

template <typename Geometry>
struct num_segments<Geometry, polygon_tag>
    : detail::counting::polygon_count<detail::num_segments::range_count>
{};

template <typename Geometry>
struct num_segments<Geometry, multi_point_tag>
    : detail::counting::other_count<0>
{};

template <typename Geometry>
struct num_segments<Geometry, multi_linestring_tag>
    : detail::counting::multi_count
        <
            num_segments< typename boost::range_value<Geometry>::type>
        >
{};

template <typename Geometry>
struct num_segments<Geometry, multi_polygon_tag>
    : detail::counting::multi_count
        <
            num_segments< typename boost::range_value<Geometry>::type>
        >
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

namespace resolve_variant
{

template <typename Geometry>
struct num_segments
{
    static inline std::size_t apply(Geometry const& geometry)
    {
        concept::check<Geometry const>();

        return dispatch::num_segments<Geometry>::apply(geometry);
    }
};

template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct num_segments<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
{
    struct visitor: boost::static_visitor<std::size_t>
    {
        template <typename Geometry>
        inline std::size_t operator()(Geometry const& geometry) const
        {
            return num_segments<Geometry>::apply(geometry);
        }
    };

    static inline std::size_t
    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry)
    {
        return boost::apply_visitor(visitor(), geometry);
    }
};

} // namespace resolve_variant

/*!
\brief \brief_calc{number of segments}
\ingroup num_segments
\details \details_calc{num_segments, number of segments}.
\tparam Geometry \tparam_geometry
\param geometry \param_geometry
\return \return_calc{number of segments}

\qbk{[include reference/algorithms/num_segments.qbk]}
*/
template <typename Geometry>
inline std::size_t num_segments(Geometry const& geometry)
{
    return resolve_variant::num_segments<Geometry>::apply(geometry);
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_NUM_SEGMENTS_HPP

max_stars_repo_name: LazyPlanet/MX-Client

max_issues_repo_name: LazyPlanet/MX-Client

max_forks_repo_name: LazyPlanet/MX-Client


text:
#ifndef BOOST_SAFE_FORMAT_HPP
#define BOOST_SAFE_FORMAT_HPP

//  Copyright (c) 2015 Robert Ramey
//
// 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)

#include <ostream>
#include <typeinfo>

#include <boost/core/demangle.hpp>
#include <boost/safe_numerics/safe_common.hpp>

namespace {

// create an output manipulator which prints variable type and limits
// as well as value
template<typename T>
struct safe_format_impl {
    const T & m_t;
    safe_format_impl(const T & t) :
        m_t(t)
    {}
    template <class charT, class Traits>
    friend std::basic_ostream<charT,Traits> &
    operator<<(
        std::basic_ostream<charT,Traits> & os,
        const safe_format_impl<T> & f
    ){
        return os
            << "<"
            << boost::core::demangle(typeid(
                typename boost::safe_numerics::base_type<T>::type
                ).name()
            )
            << ">["
            << std::numeric_limits<T>::min() << ","
            << std::numeric_limits<T>::max() << "] = "
            << f.m_t;
    }
};

} // anonymous namespace

template<typename T>
auto safe_format(const T & t){
    return safe_format_impl<T>(t);
}

#endif // BOOST_SAFE_FORMAT_HPP

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
#include <boost/python/class.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/return_internal_reference.hpp>

#include <smtbx/refinement/constraints/occupancy.h>

namespace smtbx { namespace refinement { namespace constraints {
  namespace boost_python {

    struct affine_asu_occupancy_parameter_wrapper {
      typedef affine_asu_occupancy_parameter wt;

      static void wrap() {
        using namespace boost::python;
        class_<wt,
               bases<affine_scalar_parameter, asu_parameter>,
               std::auto_ptr<wt> >("affine_asu_occupancy_parameter", no_init)
          .def(init<scalar_parameter *, double, double,
                    wt::scatterer_type *>
               ((arg("dependee"), arg("a"), arg("b"), arg("scatterer"))))
          .def(init<scalar_parameter *, double,
                    scalar_parameter *, double,
                    double,
                    wt::scatterer_type *>
             ((arg("dependee_0"), arg("a_0"),
               arg("dependee_1"), arg("a_1"),
               arg("b"),
               arg("scatterer"))))
          .def(init<af::shared<scalar_parameter *> const &,
                    af::shared<double> const &, double,
                    wt::scatterer_type *>
               ((arg("dependees"), arg("a"), arg("b"), arg("scatterer"))))
            ;
        implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
      }
    };

    struct dependent_occu_wrapper  {
      typedef dependent_occupancy wt;

      static void wrap() {
        using namespace boost::python;
        return_internal_reference<> rir;
        class_<wt,
               bases<asu_occupancy_parameter>,
               std::auto_ptr<wt> >("dependent_occupancy", no_init)
          .def(init<scalar_parameter *,
                    double,
                    double,
                    bool,
                    wt::scatterer_type *>
               ((arg("occupancy"),
                 arg("multiplier"),
                 arg("original_multiplier"),
                 arg("as_one"),
                 arg("scatterer"))))
          .add_property("occupancy", make_function(&wt::reference, rir))
          ;
        implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
      }
    };

    void wrap_occupancy() {
      affine_asu_occupancy_parameter_wrapper::wrap();
      dependent_occu_wrapper::wrap();
    }

  }}}}


text:
// Copyright (c) 2014-2017 Jae-jun Kang
// See the file LICENSE for details.

#ifndef X2BOOST_SYNCHRONIZED_EVENT_QUEUE_HPP_
#define X2BOOST_SYNCHRONIZED_EVENT_QUEUE_HPP_

#ifndef X2BOOST_PRE_HPP_
#include "x2boost/pre.hpp"
#endif

#include <queue>

#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>

#include "x2boost/event_queue.hpp"

namespace x2boost
{
    class X2BOOST_API synchronized_event_queue : public event_queue
    {
    public:
        synchronized_event_queue() : closing_(false) {}

        virtual ~synchronized_event_queue() {}

        virtual void close()
        {
            boost::mutex::scoped_lock lock(mutex_);
            if (closing_) { return; }
            closing_ = true;
            cond_.notify_all();
        }

        virtual event_ptr dequeue()
        {
            event_ptr value;
            boost::mutex::scoped_lock lock(mutex_);
            while (store_.empty())
            {
                if (closing_)
                {
                    return value;
                }
                cond_.wait(lock);
            }
            value = store_.front();
            store_.pop();
            return value;
        }

        virtual bool enqueue(const event_ptr& value)
        {
            boost::mutex::scoped_lock lock(mutex_);
            store_.push(value);
            if (store_.size() == 1)
            {
                cond_.notify_one();
            }
            return true;
        }

        virtual bool try_dequeue(event_ptr* value)
        {
            boost::mutex::scoped_lock lock(mutex_);
            if (store_.empty())
            {
                event_ptr empty;
                *value = empty;
                return false;
            }
            *value = store_.front();
            store_.pop();
            return true;
        }

        virtual size_t size() const { return store_.size(); }

    protected:
        std::queue<event_ptr> store_;
        volatile bool closing_;

        mutable boost::mutex mutex_;
        mutable boost::condition_variable cond_;
    };
}

#endif  // X2BOOST_SYNCHRONIZED_EVENT_QUEUE_HPP_


text:
// ****************************************************************************
// entity/entity.hpp
//
// Represents an entity which is made up of components.
// Essentially an ID but not incrementable, etc.
//
// Copyright Chris Glover 2014-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
//
// ****************************************************************************
#ifndef ENTITY_ENTITY_H_INCLUDED_
#define ENTITY_ENTITY_H_INCLUDED_

#include <boost/operators.hpp>
#include <algorithm>
#include <functional>
#include <memory>

#include "entity/config.hpp" // IWYU pragma: keep
#include "entity/entity_index.hpp"

// ----------------------------------------------------------------------------
//
namespace entity
{
	// ------------------------------------------------------------------------
	//
	class entity : boost::totally_ordered<entity>
	{
	public:

		entity_index_t index() const BOOST_NOEXCEPT
		{
			return idx_;
		}

		bool operator==(entity const& rhs) const BOOST_NOEXCEPT
		{
			return index() == rhs.index();
		}

		bool operator<(entity const& rhs) const BOOST_NOEXCEPT
		{
			return index() < rhs.index();
		}

	private:

		friend entity make_entity(entity_index_t) BOOST_NOEXCEPT;

		// Only make_entity can construct entities.
		// Can consider implicit conversion here, but
		// prefer to be conservative at first.
		explicit entity(entity_index_t idx) BOOST_NOEXCEPT
			: idx_(idx)
		{}

		entity_index_t idx_;
	};

	inline std::size_t hash_value(entity const& e) BOOST_NOEXCEPT
	{
		return e.index();
	}

	inline entity make_entity(entity_index_t idx) BOOST_NOEXCEPT
	{
		return entity(idx);
	}

	// ------------------------------------------------------------------------
	//
	class unique_entity : boost::totally_ordered<unique_entity>
	{
	public:

		unique_entity()
		{}

		entity get() const
		{
			return make_entity(*ref_);
		}

		bool operator==(unique_entity const& rhs) const
		{
			return get() == rhs.get();
		}

		bool operator<(unique_entity const& rhs) const
		{
			return get() < rhs.get();
		}

		void clear()
		{
			ref_ = nullptr;
		}

	private:

		friend class entity_pool;
		friend class shared_entity;
		friend void swap(unique_entity&, unique_entity&);

		typedef std::unique_ptr<
			const entity_index_t,
			std::function<void(entity_index_t const*)>
		> const_ref_type;

		typedef std::unique_ptr<
			entity_index_t,
			std::function<void(entity_index_t const*)>
		> ref_type;

		unique_entity(const_ref_type ref)
			: ref_(std::move(ref))
		{}

		unique_entity(ref_type ref)
			: ref_(std::move(ref))
		{}

		const_ref_type ref_;
	};

	inline void swap(unique_entity& a, unique_entity& b)
	{
		std::swap(a.ref_, b.ref_);
	}

	class shared_entity : boost::totally_ordered<shared_entity>
	{
	public:

		shared_entity()
		{}

		shared_entity(unique_entity&& ref)
			: ref_(std::move(ref.ref_))
		{}

		entity get() const
		{
			return make_entity(*ref_);
		}

		bool operator==(shared_entity const& rhs) const
		{
			return get() == rhs.get();
		}

		bool operator<(shared_entity const& rhs) const
		{
			return get() < rhs.get();
		}

		void clear()
		{
			ref_ = nullptr;
		}

	private:

		friend class entity_pool;
		friend class weak_entity;
		friend void swap(shared_entity&, shared_entity&);

		typedef std::shared_ptr<const entity_index_t> const_ref_type;
		typedef std::shared_ptr<entity_index_t> ref_type;

		shared_entity(const_ref_type ref)
			: ref_(std::move(ref))
		{}

		shared_entity(ref_type ref)
			: ref_(std::move(ref))
		{}

		const_ref_type ref_;
	};

	inline void swap(shared_entity& a, shared_entity& b)
	{
		std::swap(a.ref_, b.ref_);
	}

	// ------------------------------------------------------------------------
	//
	class weak_entity : boost::totally_ordered<weak_entity>
	{
	public:

		weak_entity(shared_entity const& ref)
			: ref_(ref.ref_)
		{}

		shared_entity lock() const
		{
			return ref_.lock();
		}

		bool operator==(weak_entity const& rhs) const
		{
			return ref_.lock() == rhs.ref_.lock();
		}

		bool operator<(weak_entity const& rhs) const
		{
			return ref_.lock() < rhs.ref_.lock();
		}

	private:

		friend class shared_entity;
		std::weak_ptr<const entity_index_t> ref_;
	};
}

#endif // ENTITY_ENTITY_H_INCLUDED_

max_stars_repo_name: cdglove/entity

max_issues_repo_name: cdglove/entity

max_forks_repo_name: cdglove/entity