text:
#include <unistd.h>
#include <cstdlib>
#include <boost/filesystem.hpp>
#include "GetConfigPath.h"
#include<boost/property_tree/ptree.hpp>
#include<boost/property_tree/json_parser.hpp>
#include<boost/optional.hpp>
#include<fstream>

using namespace boost::property_tree;

string getConfigPath() {
    string basePath;
    string workingDirectory = getenv("HOME");
    workingDirectory.append(string("/") + CONFIG_DIR);
    if(!boost::filesystem::exists(workingDirectory)) {
        boost::filesystem::create_directory(workingDirectory);
    }
    string configFilePath = workingDirectory + (string("/") + CONFIG_FILE);
    if(!boost::filesystem::exists(configFilePath)) {
        generateConfigFile(configFilePath, workingDirectory);
    }
    return configFilePath;
}

void generateConfigFile(string path, string basePath) {

	ofstream out(path);
	ptree tree;
	tree.put(BASE_PATH_KEY, basePath);
	ostringstream ss;
	write_json(ss,tree,false);
	out <<ss.str();
	out.close();
}

string getData(string file) {
    ifstream in(file.c_str());
    int ct=0;
    string r="";
    char *buf=new char[1024];
    do
    {
        in.getline(buf,1024);
        ct=in.gcount();
        if(ct>0)
            r=r+buf+"\n";
    }
    while(ct>0);
    if(r.size()>0)
        r.resize(r.size()-1);
    in.close();
    return r;
}

string getBasePath() {
	istringstream ss(getData(getConfigPath()));
	ptree root;
	read_json(ss,root);
    return root.get_child(BASE_PATH_KEY).get_value<string>();
}

ext: cpp

max_stars_repo_name: AnuragNtl/PBot

max_issues_repo_name: AnuragNtl/PBot

max_forks_repo_name: AnuragNtl/PBot


text:
/*
 * Copyright (c) 2014, Stanislav Vorobiov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WeaponHeaterComponent.h"
#include "SceneObject.h"
#include "Scene.h"
#include "AssetManager.h"
#include "Const.h"
#include "Renderer.h"
#include "Utils.h"
#include "CameraComponent.h"
#include "SceneObjectFactory.h"
#include "SequentialTweening.h"
#include "SingleTweening.h"
#include "MeasurementComponent.h"
#include <boost/make_shared.hpp>

namespace af
{
    WeaponHeaterComponent::WeaponHeaterComponent(SceneObjectType objectType)
    : WeaponComponent(objectType, WeaponTypeHeater),
      damage_(0.0f),
      length_(1.0f),
      impulse_(0.0f),
      duration_(0.0f),
      interval_(0.0f),
      t_(0.0f),
      minWidth_(0.18f),
      maxWidth_(1.8f),
      measure_(false),
      snd_(audio.createSound("tetrobot_attack.ogg"))
    {

    }

    WeaponHeaterComponent::~WeaponHeaterComponent()
    {
    }

    void WeaponHeaterComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitPhasedComponent(shared_from_this());
    }

    void WeaponHeaterComponent::update(float dt)
    {
        if (tweening_) {
            t_ += dt;

            if (tweening_->finished(t_)) {
                if ((interval_ <= 0.0f) && triggerHeld()) {
                    t_ = 0.0f;
                    if (haveSound()) {
                        snd_->play();
                    }
                } else {
                    tweening_.reset();
                    t_ = interval_;

                    if (rc_) {
                        rc_->removeFromParent();
                        rc_.reset();
                    }

                    if (light_) {
                        lightC_->removeFromParent();
                        lightC_.reset();
                        light_.reset();
                    }

                    return;
                }
            }

            float v = tweening_->getValue(t_);

            b2Transform xf = b2Mul(parent()->getTransform(),
                b2Transform(pos(), b2Rot(angle())));

            b2Vec2 p1 = b2Mul(xf, b2Vec2_zero);
            b2Vec2 p2 = b2Mul(xf, b2Vec2(length_, 0.0f));

            b2Vec2 pt = p2;
            SceneObject* obj = NULL;

            scene()->rayCast(p1, p2, boost::bind(&WeaponHeaterComponent::rayCastCb, this,
                _1, _2, _3, _4, boost::ref(pt), boost::ref(obj)));

            if (obj) {
                obj->changeLife2(fakeMissile_.get(), -damage_ * dt);
                b2Vec2 tmp = p2 - p1;
                tmp.Normalize();
                obj->applyLinearImpulse(impulse_ * dt * tmp, pt, true);
                if (measure_) {
                    MeasurementComponentPtr c = obj->findComponent<MeasurementComponent>();
                    if (c) {
                        c->changeHeaterDamageReceived(impulse_ * dt);
                    }
                }
            }

            float len = (pt - p1).Length() - flashDistance();

            if (len < 0.0f) {
                len = 0.0f;
            }

            rc_->setLength(len);
            rc_->setWidth1NoTex(v);
            rc_->setWidth2NoTex(v);

            light_->setPos(pos() + angle2vec(angle(), flashDistance() + len / 2.0f));
            light_->setLength(len / 2.0f);
            light_->setDistance(0.2f + v * 0.5f);
        } else {
            t_ -= dt;

            if ((t_ > 0.0f) || !triggerHeld()) {
                return;
            }

            SequentialTweeningPtr tweening = boost::make_shared<SequentialTweening>();

            tweening->addTweening(boost::make_shared<SingleTweening>(duration_ / 2.0f, EaseInOutQuad, minWidth_, maxWidth_));
            tweening->addTweening(boost::make_shared<SingleTweening>(duration_ / 2.0f, EaseInOutQuad, maxWidth_, minWidth_));

            tweening_ = tweening;
            t_ = 0.0f;

            b2Vec2 p = pos() + angle2vec(angle(), flashDistance());

            rc_ = boost::make_shared<RenderTrailComponent>(p, angle(),
                assetManager.getDrawable("lbolt3.png", Texture::WrapModeRepeat, Texture::WrapModeClamp),
                15);
            rc_->setLength(0.0f);
            rc_->setWidth1(maxWidth_);
            rc_->setWidth2(maxWidth_);

            parent()->addComponent(rc_);

            light_ = boost::make_shared<LineLight>();
            light_->setAngle(angle() + b2_pi / 2.0f);
            light_->setColor(Color(1.0f, 0.0f, 0.0f, 0.5f));
            light_->setDiffuse(false);
            light_->setXray(true);
            light_->setBothWays(true);
            light_->setDistance(0.0f);
            light_->setIntensity(1.5f);

            lightC_ = boost::make_shared<LightComponent>();

            lightC_->attachLight(light_);

            parent()->addComponent(lightC_);

            if (haveSound()) {
                snd_->play();
            }
        }
    }

    void WeaponHeaterComponent::reload()
    {
    }

    void WeaponHeaterComponent::onRegister()
    {
        fakeMissile_ = sceneObjectFactory.createFakeMissile(objectType());
        scene()->addObject(fakeMissile_);
    }

    void WeaponHeaterComponent::onUnregister()
    {
        fakeMissile_->removeFromParent();
        fakeMissile_.reset();

        if (rc_) {
            rc_->removeFromParent();
            rc_.reset();
        }

        if (light_) {
            lightC_->removeFromParent();
            lightC_.reset();
            light_.reset();
        }
    }

    float WeaponHeaterComponent::rayCastCb(b2Fixture* fixture, const b2Vec2& point,
        const b2Vec2& normal, float fraction, b2Vec2& finalPoint,
        SceneObject*& obj)
    {
        if (fixture->IsSensor() || !fakeMissile_->collidesWith(fixture)) {
            return -1;
        }

        finalPoint = point;
        obj = SceneObject::fromFixture(fixture);

        return fraction;
    }
}

max_stars_repo_name: Sheph/TriggerTime

max_issues_repo_name: Sheph/TriggerTime

max_forks_repo_name: Sheph/TriggerTime


text:
/* ROS-CHOMP.
 *
 * Copyright (C) 2015 Jafar Qutteineh. All rights reserved.
 * License (3-Cluase BSD): https://github.com/j3sq/ROS-CHOMP/blob/master/LICENSE
 *
 * **
 * \file ros_chomp.cpp
 *
 * ROS support for chomp path adaptor for Cargo-ANTS project http://cargo-ants.eu/
 *
 *
 */
#include <iostream>
#include <Eigen/Dense>
#include "chomp.hpp"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <cargo_ants_msgs/Path.h>       //received from path_planner
#include <cargo_ants_msgs/Goal.h>       // member of Path msg
#include <cargo_ants_msgs/ReferenceTrajectory.h>
#include <cargo_ants_msgs/ReferenceTrajectoryPoint.h>
#include <cargo_ants_msgs/ObstacleMap.h>
#include <cargo_ants_msgs/Obstacle.h>

using namespace std;
typedef Eigen::VectorXd Vector;
typedef Eigen::MatrixXd Matrix;
typedef cargo_ants_msgs::ObstacleMap ObstacleMap;
typedef cargo_ants_msgs::ReferenceTrajectory Trajectory;
typedef cargo_ants_msgs::ReferenceTrajectoryPoint TrajectoryPoint;
Trajectory trajectory;
ObstacleMap obstacleMap;
Vector qs(2), qe(2), xi;

Trajectory generateTrajectory(Vector const &xi)
{
	Trajectory trajectory;
	trajectory.dt = 1.0;
	Vector xi_copy(xi.size()+qs.size()+qe.size());
	xi_copy<<qs,xi,qe; //copy xi and add starting point and end point
	vector <TrajectoryPoint> points(xi_copy.size() / 2);
	for (size_t ii = 0; ii < xi_copy.size() / 2; ii++){
		points[ii].xx = xi_copy[ii*2];
		points[ii].yy = xi_copy[ii*2+1];
		//finite backward difference,mind the indicies!
		if (ii>0){
			points[ii].xd = (points[ii].xx-points[ii-1].xx)/trajectory.dt;
			points[ii].yd = (points[ii].yy-points[ii-1].yy)/trajectory.dt;
		}
		if (ii>1){
			points[ii].xdd = (points[ii].xd-points[ii-1].xd)/trajectory.dt;
			points[ii].ydd = (points[ii].yd-points[ii-1].yd)/trajectory.dt;
		}
		//ds
	}
	trajectory.points.insert(trajectory.points.end(), points.begin(), points.end());
	return trajectory;
}
void pathPlannerCallback(const cargo_ants_msgs::Path::ConstPtr &msg)
{
        vector <cargo_ants_msgs::Goal> goals = msg->goals;
        if (goals.size() < 2) {
                ROS_INFO("At least 2 goal points are required, received %lu", goals.size());
                return;
        }
        int n = goals.size();
        qs << goals[0].gx, goals[0].gy;
        qe << goals[n].gx, goals[n].gy;
        xi[0] = goals[0].gx;
        for (size_t ii = 0; ii < goals.size() + 1; ii++) {
                xi[ii * 2 + 1] = goals[ii].gy;
                xi[ii * 2 + 2] = goals[ii + 1].gx;
        }
}

void obstaclesCallback(const cargo_ants_msgs::ObstacleMap::ConstPtr &msg)
{
	obstacleMap.obstacles = msg->obstacles;
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "path_adaptor");
	ros::NodeHandle node;
	ros::Subscriber path_sub = node.subscribe("path_planner", 1000, pathPlannerCallback);
	ros::Subscriber obs_sub = node.subscribe("obstacles", 1000, obstaclesCallback);
	ros::Publisher trajectory_pub = node.advertise<Trajectory> ( "/trajectory", 10);
	ros::Rate loop_rate (10);
	ROS_INFO("path_adaptor Started!");
	while ( ros::ok() ){
		ros::spinOnce();
		Matrix obs(3,obstacleMap.obstacles.size());
		for (size_t ii = 0; ii < obstacleMap.obstacles.size() ; ++ii) {
			obs.col(ii) << obstacleMap.obstacles[ii].origin.ox,
			 								obstacleMap.obstacles[ii].origin.oy,
											obstacleMap.obstacles[ii].origin.oth;
		}
		chomp::generatePath(qs, qe, xi, obs);
		trajectory = generateTrajectory(xi);
		trajectory_pub.publish(trajectory);
		loop_rate.sleep();
}
	return 0;
	// VectorXd qs(2);  //Start goal  coordinates (x,y)
	// VectorXd qe(2);  //End goal  coordinates (x,y)
	// VectorXd xi;     //Trajectory points (x0,y0,x1,y1,....)
	// MatrixXd obs;    //obstacles |x0,y0,R0;x1,y1,R1...|
	//
	// qs << 0, 0;
	// qe << 3, 5;
	//
	//
	// generatePath(qs, qe, xi, obs);
	// cout << xi << std::endl;
}


text:
// Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc.

// 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 UUID_618474C2DE1511DEB74A388C56D89593
#define UUID_618474C2DE1511DEB74A388C56D89593

#include <boost/config.hpp>
#ifdef BOOST_NO_EXCEPTIONS
#error This header requires exception handling to be enabled.
#endif
#include <boost/exception/detail/clone_current_exception.hpp>
#include <boost/exception/detail/type_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/info.hpp>
#ifndef BOOST_NO_RTTI
#include <boost/core/demangle.hpp>
#endif
#include <stdlib.h>

#include <boost/shared_ptr.hpp>
#include <ios>
#include <new>
#include <stdexcept>

#if (__GNUC__ * 100 + __GNUC_MINOR__ > 301) &&                                 \
    !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma GCC system_header
#endif
#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(push, 1)
#endif

namespace boost
{
class exception_ptr;
BOOST_NORETURN void rethrow_exception(exception_ptr const&);
exception_ptr current_exception();

class exception_ptr
{
    typedef boost::shared_ptr<exception_detail::clone_base const> impl;
    impl ptr_;
    friend void rethrow_exception(exception_ptr const&);
    typedef exception_detail::clone_base const* (
        impl::*unspecified_bool_type)() const;

  public:
    exception_ptr()
    {
    }
    explicit exception_ptr(impl const& ptr) : ptr_(ptr)
    {
    }
    bool operator==(exception_ptr const& other) const
    {
        return ptr_ == other.ptr_;
    }
    bool operator!=(exception_ptr const& other) const
    {
        return ptr_ != other.ptr_;
    }
    operator unspecified_bool_type() const
    {
        return ptr_ ? &impl::get : 0;
    }
};

template <class T>
inline exception_ptr copy_exception(T const& e)
{
    try
    {
        throw enable_current_exception(e);
    }
    catch (...)
    {
        return current_exception();
    }
}

#ifndef BOOST_NO_RTTI
typedef error_info<struct tag_original_exception_type, std::type_info const*>
    original_exception_type;

inline std::string to_string(original_exception_type const& x)
{
    return core::demangle(x.value()->name());
}
#endif

namespace exception_detail
{
struct bad_alloc_ : boost::exception, std::bad_alloc
{
    ~bad_alloc_() throw()
    {
    }
};

struct bad_exception_ : boost::exception, std::bad_exception
{
    ~bad_exception_() throw()
    {
    }
};

template <class Exception>
exception_ptr get_static_exception_object()
{
    Exception ba;
    exception_detail::clone_impl<Exception> c(ba);
#ifndef BOOST_EXCEPTION_DISABLE
    c << throw_function(BOOST_CURRENT_FUNCTION) << throw_file(__FILE__)
      << throw_line(__LINE__);
#endif
    static exception_ptr ep(shared_ptr<exception_detail::clone_base const>(
        new exception_detail::clone_impl<Exception>(c)));
    return ep;
}

template <class Exception>
struct exception_ptr_static_exception_object
{
    static exception_ptr const e;
};

template <class Exception>
exception_ptr const exception_ptr_static_exception_object<Exception>::e =
    get_static_exception_object<Exception>();
} // namespace exception_detail

#if defined(__GNUC__)
#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)
#pragma GCC visibility push(default)
#endif
#endif
class unknown_exception : public boost::exception, public std::exception
{
  public:
    unknown_exception()
    {
    }

    explicit unknown_exception(std::exception const& e)
    {
        add_original_type(e);
    }

    explicit unknown_exception(boost::exception const& e) : boost::exception(e)
    {
        add_original_type(e);
    }

    ~unknown_exception() throw()
    {
    }

  private:
    template <class E>
    void add_original_type(E const& e)
    {
#ifndef BOOST_NO_RTTI
        (*this) << original_exception_type(&typeid(e));
#endif
    }
};
#if defined(__GNUC__)
#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)
#pragma GCC visibility pop
#endif
#endif

namespace exception_detail
{
template <class T>
class current_exception_std_exception_wrapper : public T,
                                                public boost::exception
{
  public:
    explicit current_exception_std_exception_wrapper(T const& e1) : T(e1)
    {
        add_original_type(e1);
    }

    current_exception_std_exception_wrapper(T const& e1,
                                            boost::exception const& e2) :
        T(e1),
        boost::exception(e2)
    {
        add_original_type(e1);
    }

    ~current_exception_std_exception_wrapper() throw()
    {
    }

  private:
    template <class E>
    void add_original_type(E const& e)
    {
#ifndef BOOST_NO_RTTI
        (*this) << original_exception_type(&typeid(e));
#endif
    }
};

#ifdef BOOST_NO_RTTI
template <class T>
boost::exception const* get_boost_exception(T const*)
{
    try
    {
        throw;
    }
    catch (boost::exception& x)
    {
        return &x;
    }
    catch (...)
    {
        return 0;
    }
}
#else
template <class T>
boost::exception const* get_boost_exception(T const* x)
{
    return dynamic_cast<boost::exception const*>(x);
}
#endif

template <class T>
inline exception_ptr current_exception_std_exception(T const& e1)
{
    if (boost::exception const* e2 = get_boost_exception(&e1))
        return boost::copy_exception(
            current_exception_std_exception_wrapper<T>(e1, *e2));
    else
        return boost::copy_exception(
            current_exception_std_exception_wrapper<T>(e1));
}

inline exception_ptr current_exception_unknown_exception()
{
    return boost::copy_exception(unknown_exception());
}

inline exception_ptr
    current_exception_unknown_boost_exception(boost::exception const& e)
{
    return boost::copy_exception(unknown_exception(e));
}

inline exception_ptr
    current_exception_unknown_std_exception(std::exception const& e)
{
    if (boost::exception const* be = get_boost_exception(&e))
        return current_exception_unknown_boost_exception(*be);
    else
        return boost::copy_exception(unknown_exception(e));
}

inline exception_ptr current_exception_impl()
{
    exception_detail::clone_base const* e = 0;
    switch (exception_detail::clone_current_exception(e))
    {
        case exception_detail::clone_current_exception_result::success:
        {
            BOOST_ASSERT(e != 0);
            return exception_ptr(
                shared_ptr<exception_detail::clone_base const>(e));
        }
        case exception_detail::clone_current_exception_result::bad_alloc:
        {
            BOOST_ASSERT(!e);
            return exception_detail::exception_ptr_static_exception_object<
                bad_alloc_>::e;
        }
        case exception_detail::clone_current_exception_result::bad_exception:
        {
            BOOST_ASSERT(!e);
            return exception_detail::exception_ptr_static_exception_object<
                bad_exception_>::e;
        }
        default:
            BOOST_ASSERT(0);
        case exception_detail::clone_current_exception_result::not_supported:
        {
            BOOST_ASSERT(!e);
            try
            {
                throw;
            }
            catch (exception_detail::clone_base& e)
            {
                return exception_ptr(
                    shared_ptr<exception_detail::clone_base const>(e.clone()));
            }
            catch (std::domain_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::invalid_argument& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::length_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::out_of_range& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::logic_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::range_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::overflow_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::underflow_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::ios_base::failure& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::runtime_error& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::bad_alloc& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
#ifndef BOOST_NO_TYPEID
            catch (std::bad_cast& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::bad_typeid& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
#endif
            catch (std::bad_exception& e)
            {
                return exception_detail::current_exception_std_exception(e);
            }
            catch (std::exception& e)
            {
                return exception_detail::
                    current_exception_unknown_std_exception(e);
            }
            catch (boost::exception& e)
            {
                return exception_detail::
                    current_exception_unknown_boost_exception(e);
            }
            catch (...)
            {
                return exception_detail::current_exception_unknown_exception();
            }
        }
    }
}
} // namespace exception_detail

inline exception_ptr current_exception()
{
    exception_ptr ret;
    try
    {
        ret = exception_detail::current_exception_impl();
    }
    catch (std::bad_alloc&)
    {
        ret = exception_detail::exception_ptr_static_exception_object<
            exception_detail::bad_alloc_>::e;
    }
    catch (...)
    {
        ret = exception_detail::exception_ptr_static_exception_object<
            exception_detail::bad_exception_>::e;
    }
    BOOST_ASSERT(ret);
    return ret;
}

BOOST_NORETURN
inline void rethrow_exception(exception_ptr const& p)
{
    BOOST_ASSERT(p);
    p.ptr_->rethrow();
    BOOST_ASSERT(0);
#if defined(UNDER_CE)
    // some CE platforms don't define ::abort()
    exit(-1);
#else
    abort();
#endif
}

inline std::string diagnostic_information(exception_ptr const& p,
                                          bool verbose = true)
{
    if (p)
        try
        {
            rethrow_exception(p);
        }
        catch (...)
        {
            return current_exception_diagnostic_information(verbose);
        }
    return "<empty>";
}

inline std::string to_string(exception_ptr const& p)
{
    std::string s = '\n' + diagnostic_information(p);
    std::string padding("  ");
    std::string r;
    bool f = false;
    for (std::string::const_iterator i = s.begin(), e = s.end(); i != e; ++i)
    {
        if (f)
            r += padding;
        char c = *i;
        r += c;
        f = (c == '\n');
    }
    return r;
}
} // namespace boost

#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(pop)
#endif
#endif

ext: hpp

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
#include <boost/functional/hash.hpp>
#include <iostream>
#include <ctime>
#include <unordered_map>

constexpr int N_INTS = 2;
constexpr int N_KEYS = 1e7;

int main() {
  std::cout << "Start C++ STL benchmark:\n";

  typedef std::array<int, N_INTS> KeyType;
  std::unordered_map<std::array<int, N_INTS>, double, boost::hash<KeyType>> h;

  h.reserve(N_KEYS * 2);
  const double t0 = std::clock();

  KeyType key;
  for (int i = 1; i <= N_KEYS; i++) {
    for (int j = 1; j <= N_INTS; j++) {
      key[j - 1] = i + j;
    }
    h[key] = i * 0.5;
  }
  const double t1 = std::clock();

  double val;
  for (int i = 1; i <= N_KEYS; i++) {
    for (int j = 1; j <= N_INTS; j++) {
      key[j - 1] = i + j;
    }
    val = h[key];
  }
  const double t2 = std::clock();

  h.clear();
  const double t3 = std::clock();

  std::cout << "Time to assemble / get / clear:"
      << "       " << (t1 - t0) / CLOCKS_PER_SEC
      << "       " << (t2 - t1) / CLOCKS_PER_SEC
      << "       " << (t3 - t2) / CLOCKS_PER_SEC
      << "\n";

  return 0;
}

ext: cc

max_stars_repo_name: hennink/fhash

max_issues_repo_name: hennink/fhash

max_forks_repo_name: hennink/fhash


text:
#ifndef SQL_TEXT_GRAMMAR_RESULT_COLUMN_HPP
#define SQL_TEXT_GRAMMAR_RESULT_COLUMN_HPP

#include "sql/fusion/result_column.hpp"

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

namespace sql { namespace text {

    using boost::spirit::x3::rule;

    ///////////////////////////////////////////////////////////////////////////
    // Rule IDs
    ///////////////////////////////////////////////////////////////////////////

    struct result_column_all_class;
    struct result_column_table_class;
    struct result_column_expr_class;
    struct result_column_class;
    struct result_column_list_class;

    ///////////////////////////////////////////////////////////////////////////
    // Rules
    ///////////////////////////////////////////////////////////////////////////

    const rule<result_column_all_class, ast::result_column_all>
    result_column_all = "result_column_all";

    const rule<result_column_table_class, ast::result_column_table>
    result_column_table = "result_column_table";

    const rule<result_column_expr_class, ast::result_column_expr>
    result_column_expr = "result_column_expr";

    const rule<result_column_class, ast::result_column>
    result_column = "result_column";

    const rule<result_column_list_class, ast::result_column_list>
    result_column_list = "result_column_list";

}}

#endif //SQL_TEXT_RESULT_COLUMN_HPP

max_stars_repo_name: cviebig/lib-sql-text

max_issues_repo_name: cviebig/lib-sql-text

max_forks_repo_name: cviebig/lib-sql-text


text:
#include "definition.h"

#include <deal.II/dofs/dof_tools.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/dofs/dof_renumbering.h>

namespace bart {

namespace domain {

template <int dim>
Definition<dim>::Definition(
    std::unique_ptr<domain::mesh::MeshI<dim>> mesh,
    std::shared_ptr<domain::finite_element::FiniteElementI<dim>> finite_element,
    problem::DiscretizationType discretization)
    : mesh_(std::move(mesh)),
      finite_element_(finite_element),
      triangulation_(MPI_COMM_WORLD,
                     typename dealii::Triangulation<dim>::MeshSmoothing(
                         dealii::Triangulation<dim>::smoothing_on_refinement |
                         dealii::Triangulation<dim>::smoothing_on_coarsening)),
      dof_handler_(triangulation_),
      discretization_type_(discretization) {
  std::string description{"Domain, " + std::to_string(dim) + "D"};
  if (discretization == problem::DiscretizationType::kContinuousFEM) {
    description += ", Continuous";
  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){
    description += ", Discontinuous";
  }
  this->set_description(description, utility::DefaultImplementation(true));
}

template <>
Definition<1>::Definition(
    std::unique_ptr<domain::mesh::MeshI<1>> mesh,
    std::shared_ptr<domain::finite_element::FiniteElementI<1>> finite_element,
    problem::DiscretizationType discretization)
    : mesh_(std::move(mesh)),
      finite_element_(finite_element),
      triangulation_(typename dealii::Triangulation<1>::MeshSmoothing(
                         dealii::Triangulation<1>::smoothing_on_refinement |
                             dealii::Triangulation<1>::smoothing_on_coarsening)),
      dof_handler_(triangulation_),
      discretization_type_(discretization) {
  std::string description{"Domain, 1D"};
  if (discretization == problem::DiscretizationType::kContinuousFEM) {
    description += ", Continuous";
  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){
    description += ", Discontinuous";
  }
  this->set_description(description, utility::DefaultImplementation(true));
}

template <int dim>
Definition<dim>& Definition<dim>::SetUpMesh() {
  // SetUp triangulation using the mesh dependency
  AssertThrow(mesh_->has_material_mapping(),
                    dealii::ExcMessage("Mesh object must have initialized material mapping"));
  mesh_->FillTriangulation(triangulation_);
  mesh_->FillBoundaryID(triangulation_);
  mesh_->FillMaterialID(triangulation_);
  return *this;
}

template <int dim>
Definition<dim>& Definition<dim>::SetUpDOF() {
  // Setup dof Handler
  dof_handler_.distribute_dofs(*(finite_element_->finite_element()));
  // Populate dof IndexSets
  locally_owned_dofs_ = dof_handler_.locally_owned_dofs();
  dealii::DoFTools::extract_locally_relevant_dofs(dof_handler_,
                                                  locally_relevant_dofs_);
  // Create constraint matrix
  constraint_matrix_.clear();
  constraint_matrix_.reinit(locally_relevant_dofs_);
  dealii::DoFTools::make_hanging_node_constraints(dof_handler_,
                                                  constraint_matrix_);
  constraint_matrix_.close();

  for (auto cell = dof_handler_.begin_active();
       cell != dof_handler_.end(); ++cell) {
    if (cell->is_locally_owned())
      local_cells_.push_back(cell);
  }

  // Set up dynamic sparsity pattern
  dynamic_sparsity_pattern_.reinit(locally_relevant_dofs_.size(),
                                   locally_relevant_dofs_.size(),
                                   locally_relevant_dofs_);

  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {
    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_,
                                                 dynamic_sparsity_pattern_,
                                                 constraint_matrix_, false);
  } else {
    dealii::DoFTools::make_sparsity_pattern(dof_handler_,
                                            dynamic_sparsity_pattern_,
                                            constraint_matrix_, false);
  }

  dealii::SparsityTools::distribute_sparsity_pattern(
      dynamic_sparsity_pattern_,
      dof_handler_.n_locally_owned_dofs_per_processor(),
      MPI_COMM_WORLD, locally_relevant_dofs_);

  constraint_matrix_.condense(dynamic_sparsity_pattern_);

  return *this;
}

template <>
Definition<1>& Definition<1>::SetUpDOF() {
  auto n_mpi_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
  auto this_process = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);

  dealii::GridTools::partition_triangulation(n_mpi_processes, triangulation_);
  dof_handler_.distribute_dofs(*(finite_element_)->finite_element());
  dealii::DoFRenumbering::subdomain_wise(dof_handler_);

  for (auto cell = dof_handler_.begin_active();
       cell != dof_handler_.end(); ++cell) {
    if (cell->is_locally_owned())
      local_cells_.push_back(cell);
  }

  auto locally_owned_dofs_vector =
      dealii::DoFTools::locally_owned_dofs_per_subdomain(dof_handler_);
  locally_owned_dofs_ = locally_owned_dofs_vector.at(this_process);

  constraint_matrix_.clear();
  dealii::DoFTools::make_hanging_node_constraints(dof_handler_,
                                                  constraint_matrix_);
  constraint_matrix_.close();

  dynamic_sparsity_pattern_.reinit(dof_handler_.n_dofs(), dof_handler_.n_dofs());

  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {
    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_,
                                                 constraint_matrix_, false);
  } else {
    dealii::DoFTools::make_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_,
                                            constraint_matrix_, false);
  }

  return *this;
}

template<int dim>
std::shared_ptr<system::MPISparseMatrix> Definition<dim>::MakeSystemMatrix() const {
  auto system_matrix_ptr = std::make_shared<system::MPISparseMatrix>();
  system_matrix_ptr->reinit(locally_owned_dofs_,
      locally_owned_dofs_,
      dynamic_sparsity_pattern_,
      MPI_COMM_WORLD);
  return system_matrix_ptr;
}

template<int dim>
std::shared_ptr<system::MPIVector> Definition<dim>::MakeSystemVector() const {
  auto system_vector_ptr = std::make_shared<system::MPIVector>();
  system_vector_ptr->reinit(locally_owned_dofs_, MPI_COMM_WORLD);
  return system_vector_ptr;
}

template <int dim>
int Definition<dim>::total_degrees_of_freedom() const {
  if (total_degrees_of_freedom_ == 0)
    total_degrees_of_freedom_ = dof_handler_.n_dofs();
  return total_degrees_of_freedom_;
}

template class Definition<1>;
template class Definition<2>;
template class Definition<3>;

} // namespace bart

} // namespace domain

max_stars_repo_name: narang-amit/BART

max_issues_repo_name: narang-amit/BART

max_forks_repo_name: narang-amit/BART


text:
/**
 * @file keywords.hpp
 * @author Zachary Frost
 * @copyright MIT License (See LICENSE.md in repostory root)
 * @brief Boost.Parameter keywords.
 */

#pragma once

#include <ivulk/config.hpp>

#include <boost/parameter.hpp>

namespace ivulk {
	BOOST_PARAMETER_NAME(base)
	BOOST_PARAMETER_NAME(color)
	BOOST_PARAMETER_NAME(depth)
	BOOST_PARAMETER_NAME(firstInstance)
	BOOST_PARAMETER_NAME(firstVertex)
	BOOST_PARAMETER_NAME(flags)
	BOOST_PARAMETER_NAME(index)
	BOOST_PARAMETER_NAME(indexBuffer)
	BOOST_PARAMETER_NAME(instances)
	BOOST_PARAMETER_NAME(pipeline)
	BOOST_PARAMETER_NAME(pipelines)
	BOOST_PARAMETER_NAME(priority)
	BOOST_PARAMETER_NAME(offset)
	BOOST_PARAMETER_NAME(size)
	BOOST_PARAMETER_NAME(layout)
	BOOST_PARAMETER_NAME(stageFlags)
	BOOST_PARAMETER_NAME(data)
	BOOST_PARAMETER_NAME(getPriority)
	BOOST_PARAMETER_NAME(vertexBuffer)
	BOOST_PARAMETER_NAME(vertices)
	BOOST_PARAMETER_NAME(xform)
} // namespace ivulk


text:
/// \copyright Unlicense

#pragma once
#ifndef HTTP_SERVER_HXX_
#define HTTP_SERVER_HXX_

#include <cstdint>
#include <memory>
#include <boost/asio.hpp>

#include "http_connection.hxx"

/// \brief 超文本传输协议伺服器
class http_server {
public:
    /// \biref 构造函数
    /// \details 初始化接收器，并监听端口
    explicit http_server(boost::asio::io_context &io_context, std::uint16_t port);

private:
    /// \brief 异步接受下一个连接
    void async_accept();

    /// \brief 异步接受到连接时的回调
    /// \param conn_ptr 连接共享指针（connection pointer）
    /// \param err      错误码（error code）
    void on_accepted(std::shared_ptr<http_connection> conn_ptr, const boost::system::error_code &err) noexcept;

    boost::asio::io_context &io_context_;
    boost::asio::ip::tcp::acceptor acceptor_;
};

#endif

ext: hxx

max_stars_repo_name: afoolsbag/rrCnCxx

max_issues_repo_name: afoolsbag/rrCnCxx

max_forks_repo_name: afoolsbag/rrCnCxx


text:
/**
 * Created by Beck on July 8th 2018
 * Indirect Extended Kalman Filter for the translation of the camera
 * fusing visual information with the accelerometer, given the pose;
 * With imu in 400Hz and camera translation in 30Hz
 * V1: estimation for rotation only
 * V2: give the translation of the shield, added acc bias
 * V3: estimate the translation and rotation
 */
#include <iostream>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <geometry_msgs/TwistStamped.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <queue>
//#include "rm_cv/ArmorRecord.h"

using namespace std;
using namespace Eigen;

ros::Publisher pose_pub, debug_pub, odom_pub, debug_propagate_pub;
string imu_topic, pose_topic, visual_topic;
string debug_topic, publisher_topic;
double acc_weight, acc_bias_weight;
double gravity_q_weight, visual_t_weight;
int sleep_time;

/**
 * Define states:
 *      x = [quaternion w, x, y, z; translation_x, y, z; velocity_x, y, z; acc bias; gyro bias]
 * Define inputs:
 *      u = [acc; gyro], raw accelerometer, gyroscope
 * Define noises:
 *      n = [n_acc, n_gyro, n_bias_acc, n_bias_gyro]
 */
VectorXd x(16);         // state
MatrixXd P = MatrixXd::Identity(15, 15); // covariance
MatrixXd R = MatrixXd::Identity(12, 12); // prediction noise covariance
MatrixXd Q = MatrixXd::Identity(6, 6); // observation noise covariance

// buffers to save gyro and visual reading
queue<sensor_msgs::Imu::ConstPtr> imu_buf;
queue<geometry_msgs::TwistStamped::ConstPtr> visual_buf;
queue<Matrix<double, 16, 1>> x_history;
queue<Matrix<double, 15, 15>> P_history;
Vector3d G = {0, 0, 9.8}; // Consider to add initialization later

double t_prev;          // previous propagated time

// Initialization
const int IMU_INIT_COUNT = 10;
const int MAX_GYRO_QUEUE_SIZE = 400;
const double IMU_UPDATE_TIME = 0.0025; // 1 / 400Hz
int imu_count  = 0;
bool imu_initialized = false;
bool visual_initialized = false;
bool visual_valid = false;
MatrixXd imu_R_camera = MatrixXd::Identity(3, 3); // rotation matrix from camera to imu
Vector3d imu_T_camera = MatrixXd::Zero(3, 1);

//// DEBUG only
double t_prev_update;   // previous update time
Vector3d world_T_shield_prev = MatrixXd::Zero(3, 1); // previous visual translation
Vector3d a_int = MatrixXd::Zero(3, 1);
Vector3d a_int_int = MatrixXd::Zero(3, 1);

void pub_shield_odom(const std_msgs::Header& header)
{
    nav_msgs::Odometry odom;
    odom.header = header;
    odom.child_frame_id = "world";

    odom.pose.pose.orientation.w = x(0);
    odom.pose.pose.orientation.x = x(1);
    odom.pose.pose.orientation.y = x(2);
    odom.pose.pose.orientation.z = x(3);
    odom.pose.pose.position.x = x(4);
    odom.pose.pose.position.y = x(5);
    odom.pose.pose.position.z = x(6);
    odom.twist.twist.linear.x = x(7);
    odom.twist.twist.linear.y = x(8);
    odom.twist.twist.linear.z = x(9);

    odom.pose.covariance[0]  = P(0, 0);
    odom.pose.covariance[7]  = P(1, 1);
    odom.pose.covariance[14] = P(2, 2);
    odom.pose.covariance[21] = P(3, 3);
    odom.pose.covariance[28] = P(4, 4);
    odom.pose.covariance[35] = P(5, 5);
    odom.pose.covariance[3]  = P(0, 3);
    odom.pose.covariance[10] = P(1, 4);
    odom.pose.covariance[17] = P(2, 5);
    odom.pose.covariance[18] = P(3, 0);
    odom.pose.covariance[25] = P(4, 1);
    odom.pose.covariance[32] = P(5, 2);
    odom_pub.publish(odom);
}

void pub_debug_update(const std_msgs::Header& header,
                      const Ref<const Vector3d> p,
                      const Quaterniond& q,
                      double t_update)
{
    nav_msgs::Odometry odom;
    odom.header = header;
    odom.child_frame_id = "world";
    odom.pose.pose.position.x = p[0];
    odom.pose.pose.position.y = p[1];
    odom.pose.pose.position.z = p[2];
    odom.pose.pose.orientation.w = q.w();
    odom.pose.pose.orientation.x = q.x();
    odom.pose.pose.orientation.y = q.y();
    odom.pose.pose.orientation.z = q.z();
    if (visual_initialized) {
        double dt_update = t_update - t_prev_update;
        odom.twist.twist.linear.x = (p[0] - world_T_shield_prev[0]) / dt_update;
        odom.twist.twist.linear.y = (p[1] - world_T_shield_prev[1]) / dt_update;
        odom.twist.twist.linear.z = (p[2] - world_T_shield_prev[2]) / dt_update;

        world_T_shield_prev = p;
        t_prev_update = t_update;
    }
    else {
        odom.twist.twist.linear.x = 0;
        odom.twist.twist.linear.y = 0;
        odom.twist.twist.linear.z = 0;
        world_T_shield_prev = p;
        t_prev_update = t_update;
    }

    debug_pub.publish(odom);
}

void pub_debug_propagate(const std_msgs::Header& header,
                         const Ref<const Vector3d> acc_world,
                         const Ref<const Vector3d> a_int)
{
    geometry_msgs::TwistStamped acc_compare;
    acc_compare.header = header;
    acc_compare.twist.linear.x = acc_world[0];
    acc_compare.twist.linear.y = acc_world[1];
    acc_compare.twist.linear.z = acc_world[2];
    acc_compare.twist.angular.x= a_int[0];
    acc_compare.twist.angular.y= a_int[1];
    acc_compare.twist.angular.z= a_int[2];
    debug_propagate_pub.publish(acc_compare);
}

void propagate(const sensor_msgs::Imu &imu)
{
    double cur_t = imu.header.stamp.toSec();
    Vector3d a, a_x, acc_wo_g, w, w_x;
    a(0) = imu.linear_acceleration.x;
    a(1) = imu.linear_acceleration.y;
    a(2) = imu.linear_acceleration.z;
    w(0) = imu.angular_velocity.x;
    w(1) = imu.angular_velocity.y;
    w(2) = imu.angular_velocity.z;
    a_x = a - x.segment<3>(10);
    w_x = w - x.segment<3>(13);
    Quaterniond world_R_imu(x(0), x(1), x(2), x(3));

    double dt = cur_t - t_prev;
    dt = (dt < IMU_UPDATE_TIME * 5) ? dt : IMU_UPDATE_TIME * 5;
    ROS_INFO("dt in propagate is %f, at the cur_t %f", dt, cur_t);
    // acc_wo_g = world_R_imu.toRotationMatrix() * (a - x.segment<3>(6)) - G;
    acc_wo_g = a_x - world_R_imu.toRotationMatrix().transpose() * G;
    x.segment<3>(4) += x.segment<3>(7) * dt + 0.5 * acc_wo_g * dt * dt;
    x.segment<3>(7) += acc_wo_g * dt;

    a_int_int += a_int * dt + 0.5 * acc_wo_g * dt * dt;
    a_int += acc_wo_g * dt;
    pub_debug_propagate(imu.header, acc_wo_g, a_int);

    Vector3d domg = w_x * dt / 2;
    Quaterniond dR(sqrt(1 - domg.squaredNorm()), domg(0), domg(1), domg(2));
    Quaterniond R_now;
    R_now = (world_R_imu * dR).normalized();
    x.segment<4>(0) << R_now.w(), R_now.x(), R_now.y(), R_now.z();

    Matrix3d R_w_x, R_a_x;
    R_w_x << 0, -w_x(2),  w_x(1),
             w_x(2),  0, -w_x(0),
            -w_x(1), w_x(0), 0;
    R_a_x << 0, -a_x(2),  a_x(1),
             a_x(2),  0, -a_x(0),
            -a_x(1), a_x(0), 0;

    MatrixXd A = MatrixXd::Zero(15, 15);
    A.block<3, 3>(0, 0) = -R_w_x;
    A.block<3, 3>(0, 12)= -MatrixXd::Identity(3, 3);
    A.block<3, 3>(3, 6) =  MatrixXd::Identity(3, 3);
    A.block<3, 3>(6, 0) = -R_a_x;
    A.block<3, 3>(6, 9) = -world_R_imu.toRotationMatrix();

    MatrixXd U = -MatrixXd::Zero(15, 12);
    U.block<3, 3>(0, 0) = -MatrixXd::Identity(3, 3);
    U.block<3, 3>(6, 3) = -world_R_imu.toRotationMatrix();
    U.block<3, 3>(9, 6) =  MatrixXd::Identity(3, 3);
    U.block<3, 3>(12,9) =  MatrixXd::Identity(3, 3);

    MatrixXd F, V;
    F = MatrixXd::Identity(15, 15) + dt * A;
    V = dt * U;
//    cout << "F " << endl << F << endl;
//    cout << "R " << endl << R << endl;
//    cout << "V " << endl << V << endl;
    P = F * P * F.transpose() + V * R * V.transpose();

    t_prev = cur_t;
//    cout << "P " << endl << P << endl;
//    cout << "x " << endl << x.transpose() << endl;
}

static void throwState(double current_time)
{
    while(imu_buf.size() > 1 &&
          imu_buf.front()->header.stamp.toSec() < current_time)
    {
        // trace backward the time to the imu timestamp
        t_prev = imu_buf.front()->header.stamp.toSec();
        ROS_INFO("throw state with time: %f", t_prev);
        imu_buf.pop();
        x_history.pop();
        P_history.pop();
    }
}

static void repropagate()
{
    while (!x_history.empty()) x_history.pop();
    while (!P_history.empty()) P_history.pop();

    queue <sensor_msgs::Imu::ConstPtr> temp_imu_buf;
    while (!imu_buf.empty() && imu_buf.size() > 1)
    {
        propagate(*imu_buf.front());
        temp_imu_buf.push(imu_buf.front());
        x_history.push(x);
        P_history.push(P);
        imu_buf.pop();
    }
    if (!temp_imu_buf.empty()) {
        pub_shield_odom(temp_imu_buf.back()->header);
    }
    swap(imu_buf, temp_imu_buf);
}

static void update(const geometry_msgs::TwistStamped &pnp)
{
    double cur_t = pnp.header.stamp.toSec();
    Vector3d camera_T_shield;

    camera_T_shield[0] = pnp.twist.linear.x;
    camera_T_shield[1] = pnp.twist.linear.y;
    camera_T_shield[2] = pnp.twist.linear.z;
    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;

    imu_T_shield *= 0.001; // Convert millimeter to meter

    throwState(cur_t);

    ROS_INFO("Update, at time %f", cur_t);
    Quaterniond world_R_imu;

    if (imu_buf.empty()) {
        world_R_imu.setIdentity();
    }
    else {
        world_R_imu = Quaterniond(imu_buf.front()->orientation.w,
                                  imu_buf.front()->orientation.x,
                                  imu_buf.front()->orientation.y,
                                  imu_buf.front()->orientation.z);
    }
    Vector3d world_T_shield = world_R_imu.toRotationMatrix() * imu_T_shield;
    // pub_debug_update(pnp.header, world_T_shield, world_R_imu, cur_t);
    pub_debug_update(pnp.header, imu_T_shield, world_R_imu, cur_t);

    MatrixXd C = MatrixXd::Zero(6, 15);
    C.block<3, 3>(0, 0) = MatrixXd::Identity(3, 3);
    C.block<3, 3>(3, 3) = MatrixXd::Identity(3, 3);

    // Matrix3d W = MatrixXd::Identity(6, 6);

    MatrixXd K(15, 6);
    K = P * C.transpose() * (C * P * C.transpose() + Q).inverse();
//    cout << "C " << endl << C << endl;
//    cout << "K " << endl << K << endl;
//    cout << "Q " << endl << Q << endl;
    // x = x + K * (world_T_shield - C * x);
    // x = x + K * (imu_T_shield - C * x);

    VectorXd r(6);
    // Quaterniond qm(world_R_imu);
    Quaterniond q  = Quaterniond(x(0), x(1), x(2), x(3));
    Quaterniond dq = q.conjugate() * world_R_imu;
    r.head<3>() = 2 * dq.vec();
    r.tail<3>() = imu_T_shield - x.segment<3>(4);
    VectorXd _r = K * r;
    Vector3d dw(0.5 * _r(0), 0.5 * _r(1), 0.5 * _r(2));
    dq = Quaterniond(1, dw(0), dw(1), dw(2)).normalized();
    q = q * dq;

    x(0) = q.w();
    x(1) = q.x();
    x(2) = q.y();
    x(3) = q.z();

    x.segment<12>(4) += _r.tail(12);

    P = P - K * C * P;
//    cout << "P " << endl << P << endl;
//    cout << "x " << endl << x.transpose() << endl;

    if (imu_buf.size() > 1) {
        // repropagate();
    }
}

/**
 * initialize the imu messages
 * @param imu
 */
static void initialize_imu(const sensor_msgs::Imu::ConstPtr &imu)
{
    t_prev = imu->header.stamp.toSec();
    x_history.push(x);
    P_history.push(P);
    imu_buf.push(imu);
    imu_count++;
    if (imu_count == IMU_INIT_COUNT) {
        imu_initialized = true;
    }
}

/**
 * initialization of the state and convariance from visual
 * @param pnp
 */
static void initialize_visual(const geometry_msgs::TwistStamped::ConstPtr &pnp)
{
    double cur_t = pnp->header.stamp.toSec();
    Vector3d camera_T_shield;
    ROS_INFO("visual init at %f", cur_t);

    camera_T_shield[0] = pnp->twist.linear.x;
    camera_T_shield[1] = pnp->twist.linear.y;
    camera_T_shield[2] = pnp->twist.linear.z;
    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;

    imu_T_shield *= 0.001; // Convert millimeter to meter

    throwState(cur_t);

    Quaterniond world_R_imu;

    if (imu_buf.empty()) {
        world_R_imu.setIdentity();
    }
    else {
        world_R_imu = Quaterniond(imu_buf.front()->orientation.w,
                                  imu_buf.front()->orientation.x,
                                  imu_buf.front()->orientation.y,
                                  imu_buf.front()->orientation.z);
    }
    // Vector3d world_T_shield = world_R_imu.toRotationMatrix() * imu_T_shield;
    pub_debug_update(pnp->header, imu_T_shield, world_R_imu, cur_t);

    x.setZero();
    x.segment<4>(0) << world_R_imu.w(), world_R_imu.x(), world_R_imu.y(), world_R_imu.z();
    x.segment<3>(4) << imu_T_shield(0), imu_T_shield(1), imu_T_shield(2);

    cout << "DEBUG: x initialized with " << endl << x.transpose() << endl;

    visual_initialized = true;

    // repropagate();
}

/**
 * handle, save, and process visual messages
 * @param pnp
 */
void visual_callback(const geometry_msgs::TwistStamped::ConstPtr &pnp)
{
    visual_valid = !(pnp->twist.linear.x == 0 &&
        pnp->twist.linear.y == 0 &&
        pnp->twist.linear.z == 0 );

    if (visual_valid) {
        if (visual_initialized) {
            update(*pnp);
        }
        else {
            initialize_visual(pnp);
        }
    }
}

/**
 * handle 400Hz raw imu data
 * @param imu
 */
void imu_callback(const sensor_msgs::Imu::ConstPtr &imu)
{
    if (!imu_initialized) {
        initialize_imu(imu);
    }
    else {
        propagate(*imu);
        x_history.push(x);
        P_history.push(P);
        imu_buf.push(imu);
		if (imu_buf.size() > MAX_GYRO_QUEUE_SIZE) {
			x_history.pop();
			P_history.pop();
			imu_buf.pop();
		}
        pub_shield_odom(imu->header);
    }
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "visual_gyro_fused");
    ros::NodeHandle n("~");

//    n.param("imu_raw", imu_topic, string("/dji_sdk/imu")); // 400Hz
    n.param("imu_pose", pose_topic, string("/attitude_estimator/imu")); // 400Hz
    n.param("visual_topic", visual_topic, string("/pnp_twist"));
    n.param("publisher_topic", publisher_topic, string("/visual_ekf/shield_T_world"));
    n.param("debug_topic", debug_topic, string("/visual_ekf/debug_odom"));
    n.param("accelerometer_noise_weight", acc_weight, 1000.0);
    n.param("accelerometer_bias_noise_weight", acc_bias_weight, 100.0);
    n.param("gravity_pose_weight", gravity_q_weight, 10.0);
    n.param("visual_translation_weight", visual_t_weight, 10.0);
    n.param("node_sleep_time", sleep_time, 0);

    ros::Duration(sleep_time).sleep();

    // TODO: initalize the R and Q matrix
    R.topLeftCorner(6, 6)     = acc_weight * MatrixXd::Identity(6, 6); // gyro, accelerometer noise
    R.bottomRightCorner(6, 6) = acc_bias_weight * MatrixXd::Identity(6, 6); // accelerometer bias, gyro bias noise
    Q.topLeftCorner(3, 3)     = gravity_q_weight * MatrixXd::Identity(3, 3); // orientation noise
    Q.bottomRightCorner(3, 3) = visual_t_weight * MatrixXd::Identity(3, 3); // position noise

    x.setZero();

    imu_R_camera <<  0, 0, 1,
                    -1, 0, 0,
                     0,-1, 0;

    imu_T_camera <<  200, 50, 0; // in millimeter

    ros::Subscriber s2 = n.subscribe(visual_topic, 10, visual_callback);
    ros::Subscriber s3 = n.subscribe(pose_topic, 100, imu_callback);
//    pose_pub = n.advertise<geometry_msgs::PoseStamped>(publisher_topic, 100);
    odom_pub = n.advertise<nav_msgs::Odometry>(publisher_topic, 100);
    debug_pub= n.advertise<nav_msgs::Odometry>(debug_topic, 100);
    debug_propagate_pub = n.advertise<geometry_msgs::TwistStamped>(string("/visual_ekf/propagate"), 100);

    ros::Rate r(100);
    ros::spin();
}

/**
 *  0   q_w     rotation from imu to world
 *  1   q_x
 *  2   q_y
 *  3   q_z
 *  4   T_x     translation of the shield in imu frame
 *  5   T_y
 *  6   T_z
 *  7   v_x     velocity of the shield in imu frame
 *  8   v_y
 *  9   v_z
 *  10  ba_x    bias in accelerometer
 *  11  ba_y
 *  12  ba_z
 *  13  bw_x    bias in gyroscope
 *  14  bw_y
 *  15  bw_z
 */


text:
#include <iostream>
#include <fstream>
#include <ctime>

#include <harp.hpp>

#include "specex_message.h"
#include "specex_psf.h"
#include "specex_psf_io.h"
#include "specex_serialization.h"
#include <boost/program_options.hpp>
#include <specex_serialization_implement.h>

namespace popts = boost::program_options;
using namespace std;

int main(int argc, char *argv[]) {

  string input_filename="";
  string output_filename="";

  popts::options_description desc ( "Allowed Options" );
  desc.add_options()
    ( "help,h", "display usage information" )
    ( "in,i", popts::value<string>( &input_filename ), "input psf filename (xml or fits)" )
    ( "out,o", popts::value<string>( &output_filename ), "output psf filename (xml or fits)" )
    ( "debug", "turn on debug mode" );

  popts::variables_map vm;
  try {
    popts::store(popts::command_line_parser( argc, argv ).options(desc).run(), vm);
    popts::notify(vm);
  }catch(std::exception) {
    cerr << "error in arguments" << endl;
    cerr << "try --help for options" << endl;
    return EXIT_FAILURE;
  }
  if ( ( argc < 2 ) || vm.count( "help" ) ) {
      cerr << endl;
      cerr << desc << endl;
      return EXIT_FAILURE;
  }
  if(input_filename=="") {
    cerr << "need input filename" << endl;
    cerr << "try --help for options" << endl;
    return EXIT_FAILURE;
  }
  if(output_filename=="") {
    cerr << "need output filename" << endl;
    cerr << "try --help for options" << endl;
    return EXIT_FAILURE;
  }

  specex_set_verbose(true);
  specex_set_debug(vm.count("debug")>0);

  specex::PSF_p psf;
  specex::read_psf(psf,input_filename);
  specex::write_psf(psf,output_filename);

  return EXIT_SUCCESS;
}

max_stars_repo_name: marcelo-alvarez/specex

max_issues_repo_name: marcelo-alvarez/specex

max_forks_repo_name: marcelo-alvarez/specex


text:
/** Copyright © 2013, Vladimir Lapshin.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may ! 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 || 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 || implied.
 *   See the License for the specific language governing permissions &&
 *   limitations under the License.
 *
 * \brief  Morpholib unit test.
 * \author Vladimir Lapshin.
 */

#include <sstream>

//#include <boost/test/unit_test.hpp>
#include <catch2/catch_test_macros.hpp>

#include "utf8_iterator.h"
#include "rus_alphabet.h"
#include "eng_alphabet.h"
#include "morpho_modifier.h"
#include "morpho.h"
#include "rus_model.h"
#include "eng_model.h"
#include "rus_model_description.h"
#include "eng_model_description.h"

#include "spdlog/spdlog.h"
#include "spdlog/cfg/env.h" // support for loading levels from the environment variable

namespace {

namespace m = strutext::morpho;
namespace rm = strutext::morpho::russian;

typedef strutext::encode::Utf8Iterator<std::string::iterator> Utf8Iterator;

} // namespace.

// English analysis test.
TEST_CASE("MorphoLib_Analysis_English") {
  typedef m::Morphologist<m::EnglishAlphabet> Morpher;
  Morpher morpher;

  uint32_t line_id = m::MorphoModifier::AddSuffixLine(morpher);

  std::string suffix = "ab";
  m::MorphoModifier::AddSuffix(morpher, line_id, 1, suffix.begin(), suffix.end());
  suffix = "acc";
  m::MorphoModifier::AddSuffix(morpher, line_id, 2, suffix.begin(), suffix.end());

  std::string base = "hello";
  m::MorphoModifier::AddBase(morpher, 1, line_id, base.begin(), base.end(), "hello");

  Morpher::LemList lem_list;
  std::string form = "helloab";
  morpher.Analize(form, lem_list);

  REQUIRE(lem_list.size()==1);
  for (Morpher::LemList::iterator it = lem_list.begin(); it != lem_list.end(); ++it) {
    REQUIRE(it->id_== 1);
    REQUIRE(it->attr_== 1);
  }
}

// Russian analysis test.
TEST_CASE("MorphoLib_Analysis_Russian") {
  typedef m::Morphologist<m::RussianAlphabet> Morpher;
  Morpher morpher;

  uint32_t line_id = m::MorphoModifier::AddSuffixLine(morpher);

  std::string suffix = "а";
  m::MorphoModifier::AddSuffix(morpher, line_id, 1, Utf8Iterator(suffix.begin(), suffix.end()), Utf8Iterator());

  suffix = "ой";
  m::MorphoModifier::AddSuffix(morpher, line_id, 2, Utf8Iterator(suffix.begin(), suffix.end()), Utf8Iterator());

  // ambiguty.
  suffix = "а";
  m::MorphoModifier::AddSuffix(morpher, line_id, 3, Utf8Iterator(suffix.begin(), suffix.end()), Utf8Iterator());

  std::string base = "мам";
  m::MorphoModifier::AddBase(morpher, 1, line_id, Utf8Iterator(base.begin(), base.end()), Utf8Iterator(), "мама");

  Morpher::LemList lem_list;
  std::string form = "мама";
  morpher.Analize(form, lem_list);

  REQUIRE(lem_list.size()== 2);
  bool one_done = false, three_done = false;
  for (Morpher::LemList::iterator it = lem_list.begin(); it != lem_list.end(); ++it) {
    switch (it->attr_) {
      case 1:
        one_done = true;
        break;
      case 3:
        three_done = true;
        break;
      default:
        spdlog::critical("Incorrect attribute value: " + it->attr_);
    }
  }
  REQUIRE(one_done);
  REQUIRE(three_done);
}

// English alphabet test.
TEST_CASE("MorphoLib_Alphabet_English") {
  m::EnglishAlphabet alphabet;
  std::string alpha_str = "qwertyuiopasdfghjklzxcvbnm";
  for (Utf8Iterator sym_it(alpha_str.begin(), alpha_str.end()); sym_it != Utf8Iterator(); ++sym_it) {
    REQUIRE(*sym_it==alphabet.Encode(*sym_it));
    REQUIRE(*sym_it==alphabet.Decode(*sym_it));
  }
}

// Russian alphabet test.
TEST_CASE("MorphoLib_Alphabet_Russian") {
  m::RussianAlphabet alphabet;
  std::string alpha_str = "абвгдежзийклмнопрстуфхцчшщъыьэюяё";
  unsigned code = 1;
  for (Utf8Iterator sym_it(alpha_str.begin(), alpha_str.end()); sym_it != Utf8Iterator(); ++sym_it, ++code) {
    REQUIRE(code== alphabet.Encode(*sym_it));
    REQUIRE(*sym_it== alphabet.Decode(code));
  }
}

max_stars_repo_name: Smorodov/strutext

max_issues_repo_name: Smorodov/strutext

max_forks_repo_name: Smorodov/strutext


text:
#ifndef STAN_MATH_FWD_MAT_FUN_LOG_DETERMINANT_HPP
#define STAN_MATH_FWD_MAT_FUN_LOG_DETERMINANT_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <stan/math/fwd/mat/fun/determinant.hpp>
#include <stan/math/fwd/scal/fun/fabs.hpp>
#include <stan/math/fwd/scal/fun/log.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <boost/math/tools/promotion.hpp>
#include <vector>

namespace stan {
namespace math {

template <typename T, int R, int C>
inline fvar<T> log_determinant(const Eigen::Matrix<fvar<T>, R, C>& m) {
  check_square("log_determinant", "m", m);

  return log(fabs(determinant(m)));
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math


text:
// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATORS_OSWALD_HH
#define DUNE_GDT_OPERATORS_OSWALD_HH

#include <vector>
#include <set>
#include <limits>

#include <boost/numeric/conversion/cast.hpp>

#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/vector.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/grid/walker.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/playground/spaces/dg/fem.hh>
#include <dune/gdt/playground/spaces/block.hh>

#include "interfaces.hh"

namespace Dune {
namespace GDT {
namespace Operators {

// forward
template< class GridViewImp, class FieldImp = double >
class OswaldInterpolation;

namespace internal {

template< class GridViewImp, class FieldImp >
class OswaldInterpolationTraits
{
public:
  typedef OswaldInterpolation< GridViewImp, FieldImp > derived_type;
  typedef GridViewImp                                  GridViewType;
  typedef FieldImp                                     FieldType;
};

} // namespace internal

template< class GridViewImp, class FieldImp >
class OswaldInterpolation
  : public OperatorInterface< internal::OswaldInterpolationTraits< GridViewImp, FieldImp > >
{
public:
  typedef internal::OswaldInterpolationTraits< GridViewImp, FieldImp > Traits;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::FieldType    FieldType;
  static const size_t                   dimDomain = GridViewType::dimension;

  OswaldInterpolation(const GridViewType& grd_vw, const bool zero_boundary = true)
    : grid_view_(grd_vw)
    , zero_boundary_(zero_boundary)
  {}

  template< class SGP, class SV, class RGP, class RV >
  void apply(const ConstDiscreteFunction< Spaces::DG::FemBased< SGP, 1, FieldType, 1, 1 >, SV >&
                source,
             DiscreteFunction< Spaces::DG::FemBased< RGP, 1, FieldType, 1, 1 >, RV >&
                range) const
  {
    apply_dg_fem(source, range);
  }

  template< class SGP, class SV, class RGP, class RV >
  void apply(const ConstDiscreteFunction< Spaces::Block< Spaces::DG::FemBased< SGP, 1, FieldType, 1, 1 > >, SV >&
                source,
             DiscreteFunction< Spaces::Block< Spaces::DG::FemBased< RGP, 1, FieldType, 1, 1 > >, RV >&
                range) const
  {
    apply_dg_fem(source, range);
  }

private:
  template< class SourceType, class RangeType >
  void apply_dg_fem(const SourceType& source, RangeType& range) const
  {
    // data structures we need
    // * a map from a global vertex index to global DoF indices
    //   given a vertex, one obtains a set of all global DoF ids, which are associated with this vertex
    std::map< size_t, std::set< size_t > > global_vertex_id_to_global_DoF_id_map;
    // * a map from a global DoF index to the global index of its associated vertex
    std::vector< size_t > global_DoF_id_to_global_vertex_id_map(source.space().mapper().size());
    // * a set to hold the global id of all boundary vertices
    std::set< size_t > boundary_vertices;

    const auto entity_it_end = grid_view_.template end< 0 >();
    //walk the grid to create the maps explained above and to find the boundary vertices
    for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      const size_t num_vertices = boost::numeric_cast< size_t >(entity.template count< dimDomain >());
      const auto basis = source.space().base_function_set(entity);
      if (basis.size() != num_vertices)
        DUNE_THROW(Dune::Stuff::Exceptions::internal_error, "basis.size() = " << basis.size());

      //loop over all vertices of the entitity, to find their associated global DoF indices
      for (size_t local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {
        const auto vertex_ptr = entity.template subEntity< dimDomain >(boost::numeric_cast< int >(local_vertex_id));
        const auto global_vertex_id = grid_view_.indexSet().index(*vertex_ptr);
        const auto vertex = vertex_ptr->geometry().center();
        // find the local basis function which corresponds to this vertex
        const auto basis_values = basis.evaluate(entity.geometry().local(vertex));
        if (basis_values.size() != num_vertices)
          DUNE_THROW(Dune::Stuff::Exceptions::internal_error, "basis_values.size() = " << basis_values.size());
        size_t ones = 0;
        size_t zeros = 0;
        size_t failures = 0;
        size_t local_DoF_index = 0;
        for (size_t ii = 0; ii < basis.size(); ++ii) {
          if (std::abs(basis_values[ii][0] - 1.0) < 1e-14) {
            local_DoF_index = ii;
            ++ones;
          } else if (std::abs(basis_values[ii][0] - 0.0) < 1e-14)
            ++zeros;
          else
            ++failures;
        }
        if (ones != 1 || zeros != (basis.size() - 1) || failures > 0) {
          std::stringstream ss;
          ss << "ones = " << ones << ", zeros = " << zeros << ", failures = " << failures << ", num_vertices = "
             << num_vertices << ", entity " << grid_view_.indexSet().index(entity)
             << ", vertex " << local_vertex_id << ": [ " << vertex << "], ";
          Stuff::Common::print(basis_values, "basis_values", ss);
          DUNE_THROW(Dune::Stuff::Exceptions::internal_error, ss.str());
        }
        // now we know that the local DoF index of this vertex is ii
        const size_t global_DoF_index = source.space().mapper().mapToGlobal(entity, local_DoF_index);
        global_DoF_id_to_global_vertex_id_map[global_DoF_index] = global_vertex_id;
        global_vertex_id_to_global_DoF_id_map[global_vertex_id].insert(global_DoF_index);
      } //loop over all vertices

      if (zero_boundary_) {
        // in order to determine the boundary vertices, we need to
        // loop over all intersections
        const auto intersectionEndIt = grid_view_.iend(entity);
        for (auto intersectionIt = grid_view_.ibegin(entity); intersectionIt != intersectionEndIt; ++intersectionIt) {
          const auto& intersection = *intersectionIt;
          if (intersection.boundary() && !intersection.neighbor()) {
            const auto& intersection_geometry = intersection.geometry();
            for (auto local_intersection_corner_id : DSC::valueRange(intersection_geometry.corners())) {
              const auto global_intersection_corner = intersection_geometry.corner(local_intersection_corner_id);
              // now, we need to find the entity's vertex this intersection's corner point equals to, so we
              // loop over all vertices of the entity
              for (size_t local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {
                const auto vertex_ptr = entity.template subEntity< dimDomain >(boost::numeric_cast< int >(local_vertex_id));
                const auto global_vertex_id = grid_view_.indexSet().index(*vertex_ptr);
                const auto vertex = vertex_ptr->geometry().center();
                if (Stuff::Common::FloatCmp::eq(global_intersection_corner, vertex))
                  boundary_vertices.insert(global_vertex_id);
              } // loop over all vertices of the entity
            } //loop over all intersection corners
          } // if (intersection.boundary() && !intersection.neighbor())
        } // loop over all intersections
      } // if(zero_boundary)
    } //walk the grid for the first time

    // walk the grid for the second time
    for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      const auto num_vertices = boost::numeric_cast< size_t >(entity.template count< dimDomain >());
      // get the local functions
      const auto local_source = source.local_discrete_function(entity);
      const auto& local_source_DoF_vector = local_source->vector();

      // * loop over all local DoFs
      for (size_t local_DoF_id = 0; local_DoF_id < num_vertices; ++local_DoF_id) {
      const size_t global_DoF_index = source.space().mapper().mapToGlobal(entity, local_DoF_id);
      const size_t global_vertex_id = global_DoF_id_to_global_vertex_id_map[global_DoF_index];
        // if we are on the domain boundary
        if (zero_boundary_ && boundary_vertices.count(global_vertex_id)) {
          // set the dof to zero (we have dirichlet zero)
          range.vector().set_entry(global_DoF_index, FieldType(0));
        } else {
          // do the oswald projection
          const size_t num_DoFS_per_vertex = global_vertex_id_to_global_DoF_id_map[global_vertex_id].size();
          // * get the source DoF
          const FieldType source_DoF_value = local_source_DoF_vector.get(local_DoF_id);
          // * and add it to all target DoFs
          for (size_t target_global_DoF_id : global_vertex_id_to_global_DoF_id_map[global_vertex_id])
            range.vector().add_to_entry(target_global_DoF_id, source_DoF_value / num_DoFS_per_vertex);
        } // if (boundary_vertices.find(global_vertex_id))
      } // loop over all local DoFs
    } // walk the grid for the second time
  } // ... apply(...)

  const GridViewType& grid_view_;
  const bool zero_boundary_;
}; // class OswaldInterpolation

} // namespace Operators
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_OSWALD_HH

ext: hh

max_stars_repo_name: ftalbrecht/dune-gdt

max_issues_repo_name: dune-community/dune-gdt-archive

max_forks_repo_name: dune-community/dune-gdt-archive


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

#include "kudu/master/master_cert_authority.h"

#include <memory>
#include <string>
#include <utility>

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

#include "kudu/gutil/strings/substitute.h"
#include "kudu/rpc/remote_user.h"
#include "kudu/security/ca/cert_management.h"
#include "kudu/security/cert.h"
#include "kudu/security/crypto.h"
#include "kudu/security/openssl_util.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/monotime.h"
#include "kudu/util/status.h"

using boost::optional;
using std::string;
using std::unique_ptr;

using kudu::security::Cert;
using kudu::security::CertSignRequest;
using kudu::security::PrivateKey;
using kudu::security::ca::CaCertRequestGenerator;
using kudu::security::ca::CertSigner;

DEFINE_int32(ipki_ca_key_size, 2048,
             "the number of bits for self-signed root CA cert used by Kudu IPKI "
             "(Internal Private Key Infrastructure, a.k.a. Internal Kudu CA)");
TAG_FLAG(ipki_ca_key_size, experimental);

DEFINE_int64(ipki_ca_cert_expiration_seconds, 10 * 365 * 24 * 60 * 60,
             "validity interval for self-signed root CA certifcate "
             "issued by Kudu IPKI "
             "(Internal Private Key Infrastructure, a.k.a. Internal Kudu CA)");
TAG_FLAG(ipki_ca_cert_expiration_seconds, experimental);

DEFINE_int64(ipki_server_cert_expiration_seconds, 10 * 365 * 24 * 60 * 60,
             "validity interval for server certificates issued by Kudu IPKI "
             "(Internal Private Key Infrastructure, a.k.a. Internal Kudu CA)");
TAG_FLAG(ipki_server_cert_expiration_seconds, experimental);

namespace kudu {
namespace master {

Status MasterCertAuthority::Generate(security::PrivateKey* key,
                                     security::Cert* cert) {
  CHECK(key);
  CHECK(cert);
  // Create a key and cert for the self-signed CA.
  CaCertRequestGenerator::Config config = { "kudu-ipki-ca" };
  RETURN_NOT_OK(GeneratePrivateKey(FLAGS_ipki_ca_key_size, key));
  return CertSigner::SelfSignCA(*key,
                                config,
                                FLAGS_ipki_ca_cert_expiration_seconds,
                                cert);
}

MasterCertAuthority::MasterCertAuthority(string server_uuid)
    : server_uuid_(std::move(server_uuid)) {
}

MasterCertAuthority::~MasterCertAuthority() {
}

Status MasterCertAuthority::Init(unique_ptr<PrivateKey> key,
                                 unique_ptr<Cert> cert) {
  CHECK(key);
  CHECK(cert);

  // Cache the exported DER-format cert.
  string ca_cert_der;
  RETURN_NOT_OK(cert->ToString(&ca_cert_der, security::DataFormat::DER));

  ca_private_key_ = std::move(key);
  ca_cert_ = std::move(cert);
  ca_cert_der_ = std::move(ca_cert_der);
  return Status::OK();
}

Status MasterCertAuthority::SignServerCSR(const CertSignRequest& csr,
                                          Cert* cert) {
  CHECK(ca_cert_ && ca_private_key_) << "not initialized";
  RETURN_NOT_OK_PREPEND(CertSigner(ca_cert_.get(), ca_private_key_.get())
                        .set_expiration_interval(MonoDelta::FromSeconds(
                            FLAGS_ipki_server_cert_expiration_seconds))
                        .Sign(csr, cert),
                        "failed to sign cert");
  return Status::OK();
}

Status MasterCertAuthority::SignServerCSR(const string& csr_der, const rpc::RemoteUser& user,
                                          string* cert_der) {
  CHECK(ca_cert_ && ca_private_key_) << "not initialized";

  CertSignRequest csr;
  RETURN_NOT_OK_PREPEND(csr.FromString(csr_der, security::DataFormat::DER),
                        "could not parse CSR");
  Cert cert;
  RETURN_NOT_OK(SignServerCSR(csr, &cert));

  // Validate that the cert has an included user ID.
  // It may seem funny to validate after signing, but we already have the functions
  // to get the cert details out of a Cert object, and not out of a CSR object.
  optional<string> cert_uid = cert.UserId();
  if (cert_uid != user.username()) {
    return Status::NotAuthorized(strings::Substitute(
        "CSR did not contain expected username. (CSR: '$0' RPC: '$1')",
        cert_uid.value_or(""),
        user.username()));
  }
  optional<string> cert_principal = cert.KuduKerberosPrincipal();
  if (cert_principal != user.principal()) {
    return Status::NotAuthorized(strings::Substitute(
        "CSR did not contain expected krb5 principal (CSR: '$0' RPC: '$1')",
        cert_principal.value_or(""),
        user.principal().value_or("")));
  }

  RETURN_NOT_OK_PREPEND(cert.ToString(cert_der, security::DataFormat::DER),
                        "failed to signed cert as DER format");
  return Status::OK();
}

} // namespace master
} // namespace kudu

max_stars_repo_name: attilabukor/kudu

max_issues_repo_name: attilabukor/kudu

max_forks_repo_name: attilabukor/kudu


text:
/*
 * Copyright (C) 1997 Todd Veldhuizen <tveldhui@oonumerics.org>
 * All rights reserved.  Please see <blitz/blitz.h> for terms and
 * conditions of use.
 *
 */

#ifndef BZ_TINYMATIO_CC
#define BZ_TINYMATIO_CC

#ifndef BZ_TINYMAT_H
 #include <blitz/tinymat.h>
#endif

BZ_NAMESPACE(blitz)

// NEEDS_WORK???
// This version of operator<< is updated on August 2005
// by Sergei Mingaleev <mingaleev@gmail.com>.
// Also, the corresponding operator>> is updated.

template <typename P_numtype, int N_rows, int N_columns>
ostream& operator<<(ostream& os,
    const TinyMatrix<P_numtype, N_rows, N_columns>& x)
{
    os << "(";
    for (int i=0; i < N_rows-1; ++i)
    {
        os << x(i,0);
        for (int j=1; j < N_columns; ++j)
        {
            os << "," << x(i,j);
        }
        os << "; ";
    }
    os << x(N_rows-1,0);
    for (int j=1; j < N_columns; ++j)
    {
       os << "," << x(N_rows-1,j);
    }
    os << ")";
    return os;
}

template <typename P_numtype, int N_rows, int N_columns>
istream& operator>>(istream& is,
    TinyMatrix<P_numtype, N_rows, N_columns>& x)
{
    char sep;
    is >> sep;
    BZPRECHECK(sep == '(', "Format error while scanning input TinyMatrix"
      << endl << " (expected '(' opening TinyMatrix)");

    for (int i=0; i<N_rows-1; i++) {
      is >> x(i,0);
      for (int j=1; j<N_columns; j++) {
        is >> sep;
        BZPRECHECK(sep == ',', "Format error while scanning input TinyMatrix"
	  << endl << " (expected ',' between TinyMatrix components)");
        is >> x(i,j);
      }
      is >> sep;
      BZPRECHECK(sep == ';', "Format error while scanning input TinyMatrix"
        << endl << " (expected ';' between TinyMatrix rows)");
    }
    is >> x(N_rows-1,0);
    for (int j=1; j<N_columns; j++) {
      is >> sep;
      BZPRECHECK(sep == ',', "Format error while scanning input TinyMatrix"
        << endl << " (expected ',' between TinyMatrix components)");
      is >> x(N_rows-1,j);
    }
    is >> sep;
    BZPRECHECK(sep == ')', "Format error while scanning input TinyMatrix"
      << endl << " (expected ')' closing TinyMatrix)");

    return is;
}

BZ_NAMESPACE_END

#endif // BZ_TINYMATIO_CC