text:
///////////////////////////////////////////////////////////////////////////////
// kernel::functional::detail::mean_accumulator.hpp                          //
//                                                                           //
//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //
//  Software License, Version 1.0. (See accompanying file                    //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_DETAIL_MEAN_ACCUMULATOR_H_ER_2009
#define BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_DETAIL_MEAN_ACCUMULATOR_H_ER_2009
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>

namespace boost{
namespace statistics{
namespace detail{
namespace kernel{
namespace detail{

    // The Rosenblatt-Parzen estimator is a density estimator
    template<typename T>
    struct mean_accumulator{
        typedef accumulators::stats<
            accumulators::tag::mean
        >  stat_;
        typedef accumulators::accumulator_set<T,stat_> type;
    };

}// detail
}// kernel
}// detail
}// statistics
}// boost

#endif

ext: hpp


text:
#include <catch.hpp>
#include <Eigen/Core>
#include <random>

#include "check_adjoint.h"
#include "test_utils.h"
#include "renderer_interpolation.cuh"

template<typename Tensor_t>
Tensor_t accessor4D(const VectorXr& tf, const int3& xyz)
{
	const int64_t sizes[] = {
		1, xyz.x, xyz.y, xyz.z
	};
	const int64_t strides[] = {
		0, xyz.y*xyz.z, xyz.z, 1
	};
	return Tensor_t(
		const_cast<real_t*>(tf.data()), sizes, strides);
}

template<bool hasVolumeDerivative>
void testAdjointInterpolation()
{
	typedef empty TmpStorage_t;
	typedef VectorXr Vector_t;

	std::default_random_engine rnd(42);
	std::uniform_real_distribution<real_t> distr(0.01, 0.99);
	static const int3 resolution = make_int3(2, 3, 4);
	static const int resolution_prod = resolution.x * resolution.y * resolution.z;
	static const real3 voxelSize = make_real3(1.0f) / make_real3(resolution);
	Vector_t baseVolume(resolution_prod);
	for (int j = 0; j < baseVolume.size(); ++j) baseVolume[j] = distr(rnd);

	auto forward = [&baseVolume](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t
	{
		const real3 pos = fromEigen3(x.segment(0, 3));

		const Vector_t volume = hasVolumeDerivative
			? x.segment(3, resolution_prod)
			: baseVolume;
		const auto volume_acc = accessor4D<kernel::Tensor4Read>(volume, resolution);

		kernel::VolumeInterpolation<kernel::FilterTrilinear> volumeInterpolation;
		real_t density = volumeInterpolation.fetch(volume_acc, resolution, 0, pos);

		Vector_t result(1);
		result[0] = density;
		return result;
	};
	auto adjoint = [baseVolume](const Vector_t& x, const Vector_t& e, const Vector_t& g,
		Vector_t& z, const TmpStorage_t& tmp)
	{
		const real3 pos = fromEigen3(x.segment(0, 3));

		const Vector_t volume = hasVolumeDerivative
			? x.segment(3, resolution_prod)
			: baseVolume;
		const auto volume_acc = accessor4D<kernel::Tensor4Read>(volume, resolution);

		real_t density = e[0];
		real_t adj_density = g[0];
		real3 adj_pos;
		Vector_t adjVolume = Vector_t::Zero(resolution_prod);
		auto adjVolume_acc = accessor4D<kernel::BTensor4RW>(adjVolume, resolution);

		{
			kernel::VolumeInterpolation<kernel::FilterTrilinear, true, hasVolumeDerivative> volumeInterpolation(
				0, resolution, adjVolume_acc);
			volumeInterpolation.fetch(volume_acc, resolution, 0, pos);
			volumeInterpolation.adjoint(adj_density, adj_pos);
		}

		z.segment(0, 3) = toEigen(adj_pos);
		if (hasVolumeDerivative) z.segment(3, resolution_prod) = adjVolume;
	};

	int N = 20;
	for (int i = 0; i < N; ++i)
	{
		INFO("N=" << i);
		Vector_t x;
		if (hasVolumeDerivative) {
			x.resize(3 + resolution_prod);
			x.segment(3, resolution_prod) = baseVolume;
		}
		else {
			x.resize(3);
		}
		x[0] = distr(rnd) / voxelSize.x;
		x[1] = distr(rnd) / voxelSize.y;
		x[2] = distr(rnd) / voxelSize.z;
		checkAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,
			1e-5, 1e-5, 1e-6);
	}
}

TEST_CASE("Adjoint-Interpolation-NoVolumeDerivatives", "[adjoint]")
{
	testAdjointInterpolation<false>();
}

TEST_CASE("Adjoint-Interpolation-withVolumeDerivatives", "[adjoint]")
{
	testAdjointInterpolation<true>();
}

ext: cpp

max_stars_repo_name: shamanDevel/DiffDVR

max_issues_repo_name: shamanDevel/DiffDVR

max_forks_repo_name: shamanDevel/DiffDVR


text:
#include <iostream>
#include <memory>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <cmath>
#include <mgl2/mgl.h>
#include <Eigen/Dense>

#include <data.hpp>
#include <particle.hpp>
#include <gravitysolvers.hpp>
#include <first_task.hpp>

std::unique_ptr<std::vector<Particle>> p(Data::readFromFile("data.ascii"));
std::vector<Particle> particles = *p;

float pMass = 0.0;
float totalMass = 0.0;
float radius = 0.0;
float scaleLength = 0.0;
float epsilon = 0.0; // softening
float t_relax = 0.0;
float r0 = std::numeric_limits<float>::max(); // center of system to avoid problems with dividing by 0
float rhm = 0.0; // half mass radius

float Mass(float r, bool strictlyLess = false)
{
  float M = 0.0;

  for(Particle &p : particles) {
    float r2 = p.radius2();

    if((!strictlyLess && r2 <= r*r) || (strictlyLess && r2 < r*r)) {
      M += p.m();
    }
  }

  return M;
}

float density_hernquist(float r)
{
  return (totalMass / (2 * M_PI)) * (scaleLength / r) * (1 / std::pow(r + scaleLength, 3));
}

// Computes force F where F = m*a
float force_hernquist(float r)
{
  // Assumption: G = 1
  return -totalMass * pMass / ((r + scaleLength) * (r + scaleLength));
}

void calculate_constants()
{
  pMass = particles[0].m(); // all particles have the same mass

  for(Particle &p : particles) {
    totalMass += p.m();
    radius = std::max(p.radius2(), radius);
    r0 = std::min(p.radius2(), r0);
  }

  r0 = std::sqrt(r0) + std::numeric_limits<float>::epsilon();
  radius = std::sqrt(radius);

  float dr = radius / 100000;
  for(float r = r0; r <= radius; r += dr) {
    if(Mass(r) >= totalMass * 0.5) {
      rhm = r;
      break;
    }
  }

  scaleLength = rhm / (1 + std::sqrt(2));

  // https://en.wikipedia.org/wiki/Mean_inter-particle_distance
  // after plugging in n = totalMass / (4/3*PI*r^3) in the formula most terms cancel out
  epsilon = radius / std::pow(totalMass, 1.0/3.0);
  t_relax = compute_relaxation();

  // exact mean inter-particle separation
  /*
  epsilon = .0;

  for(Particle &p : particles) {
    for(Particle &q : particles) {
      epsilon += (p.r() - q.r()).norm();
    }
  }

  long n = particles.size();
  epsilon /= (n*(n-1));
  */

  std::cout << "First Task        " << std::endl;
  std::cout << "------------------" << std::endl;
  std::cout << "  pMass:          " << pMass << std::endl;
  std::cout << "  totalMass:      " << totalMass << std::endl;
  std::cout << "  radius:         " << radius << std::endl;
  std::cout << "  r0:             " << r0 << std::endl;
  std::cout << "  rhm:            " << rhm << std::endl;
  std::cout << "  scaleLength:    " << scaleLength << std::endl;
  std::cout << "  softening:      " << epsilon << std::endl;
  std::cout << "  t_relax:        " << t_relax << std::endl;
  std::cout << "------------------" << std::endl;
}

float compute_relaxation()
{
  // Assumption: G = 1
  float N = particles.size();
  float vc = std::sqrt(totalMass * 0.5 / rhm);
  float t_cross = rhm / vc;
  float t_relax = N / (8 * std::log(N)) * t_cross;

  return t_relax;
}

void step1()
{
  r0 = 0.005;
  int numSteps = 50;

  std::vector<float> hDensity;
  std::vector<float> nDensity;
  std::vector<float> rInput;
  std::vector<float> errors;

  // creates evenly spaced intervals on a log scale on the interval [r0, radius]
  // drLinToLog(i) gives the start of the ith interval on [r0, radius]
  auto drLinToLog = [&](int i) {
    return r0 * std::pow(radius / r0, (float)i / (float)numSteps);
  };

  // transforms the numerical data into a dimension desirable for plotting
  // here we want to avoid problems with 0 on log scales since log(0) is undefined
  auto plotFit = [](float x) {
    return x + std::numeric_limits<float>::epsilon();
  };

  for(int i = 0; i <= numSteps; i++) {
      float r = drLinToLog(i);
      float r1 = drLinToLog(i + 1);
      float MShell = Mass(r1, true) - Mass(r, true);
      float VShell = 4.0/3.0*M_PI*(r1*r1*r1 - r*r*r);

      float nRho = MShell / VShell;
      float numParticlesInShell = MShell / pMass;

      // p = n*m/v, err = sqrt(n) =>
      // p_err = sqrt(n)/n*p = sqrt(n)*n*m/(n*v) = sqrt(n)*m/v
      // p = density, n = #particles, m = pMass
      float rhoError = std::sqrt(numParticlesInShell) * pMass / VShell;

      hDensity.push_back(plotFit(density_hernquist((r + r1) / 2)));
      nDensity.push_back(plotFit(nRho));
      errors.push_back(rhoError);
      rInput.push_back(r);
  }

  mglData hData;
  hData.Set(hDensity.data(), hDensity.size());

  mglData nData;
  nData.Set(nDensity.data(), nDensity.size());

  mglData rData;
  rData.Set(rInput.data(), rInput.size());

  mglData eData;
  eData.Set(errors.data(), errors.size());

  mglGraph gr(0, 1200, 800);

  float outMin = std::min(hData.Minimal(), nData.Minimal());
  float outMax = std::max(hData.Maximal(), nData.Maximal());

  gr.SetRange('x', rData);
  gr.SetRange('y', outMin, outMax);

  gr.SetFontSize(2);
  gr.SetCoor(mglLogLog);
  gr.Axis();

  gr.Label('x', "Radius [l]", 0);
  gr.Label('y', "Density [m]/[l]^3", 0);

  gr.Plot(rData, hData, "b");
  gr.AddLegend("Hernquist", "b");

  gr.Plot(rData, nData, "r .");
  gr.AddLegend("Numeric", "r .");

  gr.Error(rData, nData, eData, "qo");
  gr.AddLegend("Poissonian Error", "qo");

  gr.Legend();
  gr.WritePNG("density_profiles.png");
}

void step2()
{
  r0 = 0.005;
  int numSteps = 100;

  std::vector<float> softenings;
  std::vector<float> dAnalytic;
  std::vector<float> rInput;

  // creates evenly spaced intervals on a log scale on the interval [r0, radius]
  // drLinToLog(i) gives the start of the ith interval on [r0, radius]
  auto drLinToLog = [&](int i) {
    return r0 * std::pow(radius / r0, (float)i / (float)numSteps);
  };

  // transforms the numerical data into a dimension desirable for plotting
  // here we want to plot the magnitude of the force and add a small nonzero
  // number to the force to avoid problems with 0 on log scales since log(0) is undefined
  auto plotFit = [](float x) {
    return std::abs(x) + std::numeric_limits<float>::epsilon();
  };

  // calculate the analytical force in the hernquist model
  for(int i = 0; i <= numSteps; i++) {
    float r = drLinToLog(i);
    dAnalytic.push_back(plotFit(force_hernquist(r)));
    rInput.push_back(r);
  }

  std::unique_ptr<Gravitysolver::Direct> solver(new Gravitysolver::Direct());
  std::vector<mglData> plotData;

  for(int i = 1; i <= 7; i++) {
    solver->readData("data/direct-nbody-" + std::to_string(i) + ".txt");
    softenings.push_back(solver->softening());

    std::vector<float> dNumeric;

    // project the force vector of each particle towards the center of the system
    const MatrixData &solverData = solver->data();
    Eigen::VectorXf f_center(solverData.cols());

    float fx, fy, fz, x, y, z, norm;

    for(int i = 0; i < solverData.cols(); i++) {
      x = solverData(1, i);
      y = solverData(2, i);
      z = solverData(3, i);
      fx = solverData(7, i);
      fy = solverData(8, i);
      fz = solverData(9, i);

      norm = std::sqrt(x*x + y*y + z*z);

      // project the force vector onto the normalized sphere normal
      f_center(i) = (x*fx + y*fy + z*fz) / norm;
    }

    for(int i = 0; i <= numSteps; i++) {
      float r = drLinToLog(i);
      float r1 = drLinToLog(i + 1);
      float dr = r1 - r;

      float f = 0.0;
      int numParticles = 0;

      // calculate the average gravitational force in a shell
      for(int i = 0; i < particles.size(); i++) {
        Particle p = particles[i];

        if(r <= p.radius() && p.radius() < r1) {
          f += f_center(i);
          numParticles++;
        }
      }

      f = (numParticles == 0 ? .0 : f / numParticles);
      dNumeric.push_back(plotFit(f));
    }

    mglData cData;
    cData.Set(dNumeric.data(), dNumeric.size());
    plotData.push_back(cData);
  }

  mglData aData;
  aData.Set(dAnalytic.data(), dAnalytic.size());

  mglData rData;
  rData.Set(rInput.data(), rInput.size());

  mglGraph gr(0, 1200, 800);

  float outMin;
  float outMax;

  for(int i = 0; i < plotData.size(); i++) {
    outMin = std::max(std::min(plotData[i].Minimal(), aData.Minimal()), 50.0);
    outMax = std::max(plotData[i].Maximal(), aData.Maximal());
  }

  gr.SetRange('x', rData);
  gr.SetRange('y', outMin, outMax);

  gr.SetFontSize(2);
  gr.SetCoor(mglLogLog);
  gr.Axis();

  gr.Label('x', "Radius [l]", 0);
  gr.Label('y', "Force [m]^2[l]^{-2}", 0);

  gr.Plot(rData, aData, "b");
  gr.AddLegend("Analytic", "b");

  // colors for plotting
  const char *opt[7] = {"r +", "c +", "m +", "h +", "l +", "n +", "q +"};

  for(int i = 0; i < plotData.size(); i++) {
    std::stringstream ss;
    ss << "\\epsilon = " << std::setprecision(4) << softenings[i] << " [l]";

    gr.Plot(rData, plotData[i], opt[i]);
    gr.AddLegend(ss.str().c_str(), opt[i]);
  }

  gr.Legend();
  gr.WritePNG("forces.png");
}

void first_task()
{
  calculate_constants();
  step1();
  step2();
}


text:
///////////////////////////////////////////////////////////////////////////////
// statistics::model::wrap::unary::parameter.hpp                             //
//                                                                           //
//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //
//  Software License, Version 1.0. (See accompanying file                    //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_MODEL_WRAP_UNARY_PARAMETER_HPP_ER_2009
#define BOOST_STATISTICS_MODEL_WRAP_UNARY_PARAMETER_HPP_ER_2009
#include <boost/statistics/model/wrap/unary/detail/base.hpp>

namespace boost{
namespace statistics{
namespace model{

    template<typename X>
    class parameter_wrapper : detail::base_<X>{
        typedef detail::base_<X> base_;
    public:
        typedef X                       parameter_type;
        typedef parameter_wrapper<X>    parameter_wrapper_type;

        // Construction
        parameter_wrapper();
        parameter_wrapper(const X& x);
        parameter_wrapper(const parameter_wrapper&);

        // Access
        const X& parameter()const;
    };

    // Implementation //

    template<typename X>
    parameter_wrapper<X>::parameter_wrapper() : base_(){}

    template<typename X>
    parameter_wrapper<X>::parameter_wrapper( const X& x ) : base_(x){}

    template<typename X>
    parameter_wrapper<X>::parameter_wrapper(const parameter_wrapper& that)
    :base_(that){}

    template<typename X>
    const X& parameter_wrapper<X>::parameter()const{ return (this->value); }

    // Free functions

    template<typename X>
    parameter_wrapper<X>
    make_parameter_wrapper(const X& x){
        typedef parameter_wrapper<X> result_type;
        return result_type(x);
    }

}// model
}// statistics
}// boost

#endif


text:
//
// Created by stevan on 8/18/20.
//

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "clipper-py.h"

#include "../clipper/clipper.hpp"

using namespace boost::python;

namespace Path {
    ClipperLib::Path push(ClipperLib::Path &path, ClipperLib::IntPoint const &point)
    {
        path << point;
        return path;
    }

    std::string to_string(const ClipperLib::Path& path) {
        if (path.empty())
            return "Path(EMPTY)";

        std::string value = std::string();
        value += "Path(";
        for( int i = 0; i < path.size() - 1; i++) {
            ClipperLib::IntPoint point = path.at(i);
            std::string x = std::to_string(point.X);
            std::string y = std::to_string(point.Y);
            value += "[";
            value += x;
            value += ",";
            value += y;
            value += "], ";
        }
        ClipperLib::IntPoint point = path.at(path.size() - 1);
        std::string x = std::to_string(point.X);
        std::string y = std::to_string(point.Y);
        value += "[";
        value += x;
        value += ",";
        value += y;
        value += "]";

        value += ")";
        return value;
    }

    str repr(const ClipperLib::Path& path)
    {
        return str(to_string(path));
    }
}

namespace Paths {
    ClipperLib::Paths push(ClipperLib::Paths &paths, ClipperLib::Path const &path)
    {
        paths << path;
        return paths;
    }

    std::string to_string(const ClipperLib::Paths& paths) {
        if (paths.empty())
            return "Paths(EMPTY)";

        std::string value = std::string();
        value += "Paths(";
        for (int i = 0; i < paths.size() - 1; i++)
        {
            value += Path::to_string(paths.at(i));
            value += ", ";
        }
        value += Path::to_string(paths.at(paths.size() - 1));

        value += ")";
        return value;
    }

    str repr(ClipperLib::Paths const &paths)
    {
        return str(to_string(paths));
    }
}

void wrap_path()
{
    class_<ClipperLib::Path>("Path")
            .def(vector_indexing_suite<ClipperLib::Path>())
            .def("__str__", Path::repr)
            .def("__repr__", Path::repr)
            .def("push", Path::push);

    class_<ClipperLib::Paths>("Paths")
            .def(vector_indexing_suite<ClipperLib::Paths>())
            .def("__str__", Paths::repr)
            .def("__repr__", Paths::repr)
            .def("push", Paths::push);
}

max_stars_repo_name: sdedovic/clipper-py

max_issues_repo_name: sdedovic/clipper-py

max_forks_repo_name: sdedovic/clipper-py


text:
/*
*   Copyright 2017-2018 Simon Raschke
*
*   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.
*/

#pragma once

#include <cmath>
#include <cstdint>
#include <sstream>
#include <exception>
#if __has_include(<Eigen/Core>)
#include <Eigen/Core>
#elif __has_include(<eigen3/Eigen/Core>)
#include <eigen3/Eigen/Core>
#endif

namespace enhance
{
    // number of digits
    template <typename T>
    std::uint16_t numDigits(T number)
    {
        std::uint16_t digits = 0;
        if (number < 0) digits = 1; // remove this line if '-' counts as a digit
        std::uint32_t helper = static_cast<int>(number);
        while (helper)
        {
            helper /= 10;
            digits++;
        }
        return digits;
    }

    // angle between two eigen vectors
    // vectors dont have to be normalized
    // will give signed result
    template<typename DERIVED1, typename DERIVED2>
    constexpr float directed_angle(const DERIVED1& v1, const DERIVED2& v2)
    {
        assert(std::isfinite(std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0))));
        return std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0));
    }

    // will give unsigned result
    template<typename DERIVED1, typename DERIVED2>
    constexpr float absolute_angle(const DERIVED1& v1, const DERIVED2& v2)
    {
        return std::abs(directed_angle(v1,v2));
    }

    //directed angle normalized to 0 to 360°
    template<typename DERIVED1, typename DERIVED2>
    constexpr float normalized_angle(const DERIVED1& v1, const DERIVED2& v2)
    {
        const float angle = directed_angle(v1,v2);
        return angle < 0.f ? angle+M_PI : angle;
    }

    // calculate rad from given deg
    // expects floating pioint type
    template<typename T, typename ENABLER = typename std::enable_if<std::is_floating_point<T>::value>::type>
    constexpr T deg_to_rad(const T& __deg) noexcept
    {
        return __deg*M_PI/180;
    }

    // calculate deg from given rad
    // expects floating pioint type
    template<typename T, typename ENABLER = typename std::enable_if<std::is_floating_point<T>::value>::type>
    constexpr T rad_to_deg(const T& __rad) noexcept
    {
        return __rad/M_PI*180;
    }

    // calculates the volume of a sphere given its radius
    // may throw if radius is negative
    template<typename T>
    constexpr T sphere_volume(const T& __rad)
    {
        if(__rad < 0) throw std::logic_error("radius must not be negative");
        return M_PI*__rad*__rad*__rad*4.f/3.f;
    }

    // calculates the surface of a sphere given its radius
    // may throw if radius is negative
    template<typename T>
    constexpr T sphere_surface(const T& __rad)
    {
        if(__rad < 0) throw std::logic_error("radius must not be negative");
        return M_PI*__rad*__rad*4.f;
    }

    // calculates the area of a circle given its radius
    // may throw if radius is negative
    template<typename T>
    constexpr T circle_area(const T& __rad)
    {
        if(__rad < 0) throw std::logic_error("radius must not be negative");
        return M_PI*__rad*__rad;
    }

    // calculates the radius of a circle given its area
    // may throw if area is negative
    template<typename T>
    constexpr T circle_area_to_radius(const T& __area)
    {
        if(__area < 0) throw std::logic_error("area must not be negative");
        return std::sqrt( __area/M_PI );
    }

    // calculates the volume of a cone given its base radius and heigt
    // may throw if area is negative
    // may throw if height is negative
    template<typename T>
    constexpr T cone_volume(const T& __rad, const T& __height)
    {
        if(__rad < 0) throw std::logic_error("radius must not be negative");
        if(__height < 0) throw std::logic_error("height must not be negative");
        return enhance::circle_area(__rad)*__height/(static_cast<T>(3));
    }

    template<std::size_t N, typename T>
    constexpr typename std::enable_if<std::is_floating_point<T>::value,T>::type nth_root(const T& __val )
    {
        return std::pow(__val, 1.0/N);
    }
}

max_stars_repo_name: simonraschke/vesicle

max_issues_repo_name: simonraschke/vesicle

max_forks_repo_name: simonraschke/vesicle


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        :
// Author      : Avi
// Revision    : $Revision: #9 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8

#include <boost/algorithm/string/trim.hpp>

#include "NodePath.hpp"
#include "Str.hpp"

using namespace ecf;

void NodePath::split( const std::string& path, std::vector<std::string>& thePath)
{
	/// The path is of the form "/suite/family/task"
	Str::split(path,thePath,Str::PATH_SEPERATOR());
}

bool NodePath::extractHostPort(const std::string& path,std::string& host, std::string& port)
{
	if (path.empty()) return false;

 	std::vector<std::string>  thePath;
	NodePath::split(path,thePath);

 	if (thePath.empty()) return false;

	//<host>:<port>/suite/family/task
	// first path should be of form <host>:<port>
	size_t colonPos = thePath[0].find_first_of(':');
	if (colonPos == std::string::npos) return false;

	host = thePath[0].substr(0,colonPos);
 	port = thePath[0].substr(colonPos+1);

 	boost::algorithm::trim(host);
 	boost::algorithm::trim(port);
 	if (host.empty()) return false;
 	if (port.empty()) return false;

 	return true;
}

std::string NodePath::createPath(const std::vector<std::string>& vec)
{
	if (vec.empty()) return std::string();

	std::string ret;
	size_t size = vec.size();
	for(size_t i = 0; i < size; i++) {
		ret += Str::PATH_SEPERATOR();
		ret += vec[i];
	}
	return ret;
}

std::string NodePath::removeHostPortFromPath(const std::string& path)
{
 	std::vector<std::string> pathVec;
	NodePath::split(path,pathVec);
	pathVec.erase( pathVec.begin() );
	return NodePath::createPath(pathVec);
}

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
#ifndef TRISYCL_SYCL_QUEUE_DETAIL_QUEUE_HPP
#define TRISYCL_SYCL_QUEUE_DETAIL_QUEUE_HPP

/** \file Some implementation details of queue.

    Ronan at Keryell point FR

    This file is distributed under the University of Illinois Open Source
    License. See LICENSE.TXT for details.
*/

#include <atomic>
#include <condition_variable>
#include <mutex>

#ifdef TRISYCL_OPENCL
#include <boost/compute.hpp>
#endif

#include "CL/sycl/context.hpp"
#include "CL/sycl/device.hpp"
#include "CL/sycl/detail/debug.hpp"

namespace cl {
namespace sycl {
namespace detail {

/** Some implementation details about the SYCL queue
 */
struct queue : detail::debug<detail::queue> {
  /// Track the number of kernels still running to wait for their completion
  std::atomic<size_t> running_kernels;

  /// To signal when all the kernels have completed
  std::condition_variable finished;
  /// To protect the access to the condition variable
  std::mutex finished_mutex;

  /// Initialize the queue with 0 running kernel
  queue() {
    running_kernels = 0;
  }

  /// Wait for all kernel completion
  void wait_for_kernel_execution() {
    TRISYCL_DUMP_T("Queue waiting for kernel completion");
    std::unique_lock<std::mutex> ul { finished_mutex };
    finished.wait(ul, [&] {
        // When there is no kernel running in this queue, we are ready to go
        return running_kernels == 0;
      });
  }

  /// Signal that a new kernel started on this queue
  void kernel_start() {
    TRISYCL_DUMP_T("A kernel has been added to the queue");
    // One more kernel
    ++running_kernels;
  }

  /// Signal that a new kernel finished on this queue
  void kernel_end() {
    TRISYCL_DUMP_T("A kernel of the queue ended");
    if (--running_kernels == 0) {
      /* It was the last kernel running, so signal the queue just in
         case it was working for it for completion */
      finished.notify_one();
    }
  }

#ifdef TRISYCL_OPENCL
  /** Return the underlying OpenCL command queue after doing a retain

      This memory object is expected to be released by the developer.

      Retain a reference to the returned cl_command_queue object.

      Caller should release it when finished.

      If the queue is a SYCL host queue then an exception is thrown.
  */
  virtual cl_command_queue get() const = 0;

  /// Return the underlying Boost.Compute command queue
  virtual boost::compute::command_queue &get_boost_compute() = 0;
#endif

  /** Return the SYCL queue's context

      Report errors using SYCL exception classes.
  */
  virtual cl::sycl::context get_context() const = 0;

  /** Return the SYCL device the queue is associated with

      Report errors using SYCL exception classes.
  */
  virtual cl::sycl::device get_device() const = 0;

  /// Return whether the queue is executing on a SYCL host device
  virtual bool is_host() const = 0;

  /// Wait for all kernel completion before the queue destruction
  /// \todo Update according spec since queue destruction is non blocking
  virtual ~queue() {
    wait_for_kernel_execution();
  }

};

}
}
}

/*
    # Some Emacs stuff:
    ### Local Variables:
    ### ispell-local-dictionary: "american"
    ### eval: (flyspell-prog-mode)
    ### End:
*/

#endif // TRISYCL_SYCL_QUEUE_DETAIL_QUEUE_HPP

max_stars_repo_name: infinitesnow/InceptionCL

max_issues_repo_name: infinitesnow/InceptionCL

max_forks_repo_name: infinitesnow/InceptionCL


text:
#ifndef __UTIL_H_DEFINED__
#define __UTIL_H_DEFINED__

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/python.hpp>
#include <ilasynth/common.hpp>
#include <string>

namespace ilasynth {
// ---------------------------------------------------------------------- //
void ila_assert(bool b, const char* msg, const char* file, int line);
void ila_assert(bool b, const std::string& msg, const char* file, int line);
void dump_trace();

// ---------------------------------------------------------------------- //
std::string to_string(const py::object& l);
std::string to_string(const mp_int_t& i);
mp_int_t to_cpp_int(const py::object& l);
py::object to_pyint(const mp_int_t& i);
py::object to_pyint(const std::string& s);
bool is_py_int(const py::object& l);
bool is_py_int_or_long(const py::object& l);

// ---------------------------------------------------------------------- //
void set_logging_level(int level);

const int NUM_HASHTABLE_BUCKETS = 1023;
const int NUM_HASHTABLE_BUCKETS_SMALL = 63;
}; // namespace ilasynth

#endif // __UTIL_H_DEFINED__

max_stars_repo_name: Bo-Yuan-Huang/ItSy


text:
//
//  assert_test.cpp - a test for boost/assert.hpp
//
//  Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
//
//  Permission to copy, use, modify, sell and distribute this software
//  is granted provided this copyright notice appears in all copies.
//  This software is provided "as is" without express or implied
//  warranty, and with no claim as to its suitability for any purpose.
//

#include <boost/detail/lightweight_test.hpp>

#include <boost/assert.hpp>

void test_default()
{
    int x = 1;

    BOOST_ASSERT(1);
    BOOST_ASSERT(x);
    BOOST_ASSERT(x == 1);
    BOOST_ASSERT(&x);
}

#define BOOST_DISABLE_ASSERTS
#include <boost/assert.hpp>

void test_disabled()
{
    int x = 1;

    BOOST_ASSERT(1);
    BOOST_ASSERT(x);
    BOOST_ASSERT(x == 1);
    BOOST_ASSERT(&x);

    BOOST_ASSERT(0);
    BOOST_ASSERT(!x);
    BOOST_ASSERT(x == 0);

    void * p = 0;

    BOOST_ASSERT(p);

    // supress warnings
    p = &x;
    p = &p;
}

#undef BOOST_DISABLE_ASSERTS

#define BOOST_ENABLE_ASSERT_HANDLER
#include <boost/assert.hpp>
#include <cstdio>

int handler_invoked = 0;

void boost::assertion_failed(char const * expr, char const * function, char const * file, long line)
{
    std::printf("Expression: %s\nFunction: %s\nFile: %s\nLine: %ld\n\n", expr, function, file, line);
    ++handler_invoked;
}

struct X
{
    static void f()
    {
        BOOST_ASSERT(0);
    }
};

void test_handler()
{
    int x = 1;

    BOOST_ASSERT(1);
    BOOST_ASSERT(x);
    BOOST_ASSERT(x == 1);
    BOOST_ASSERT(&x);

    BOOST_ASSERT(0);
    BOOST_ASSERT(!x);
    BOOST_ASSERT(x == 0);

    void * p = 0;

    BOOST_ASSERT(p);

    X::f();

    BOOST_ASSERT(handler_invoked == 5);
    BOOST_TEST(handler_invoked == 5);
}

#undef BOOST_ENABLE_ASSERT_HANDLER

int main()
{
    test_default();
    test_disabled();
    test_handler();

    return boost::report_errors();
}


text:
#include <boost/hana.hpp>

int
main ()
{
  return 0;
}


text:
/*
 * people_det.cpp
 *
 *  Created on: Oct 20, 2015
 *      Author: Tzutalin
 */

#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <string>
#include <stdio.h>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/opencv/cv_image.h>
#include <dlib/image_loader/load_image.h>
#include <dlib/image_processing.h>
#include <dlib/opencv.h>

#define LOG_TAG "People_Det-JNI"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

class OpencvHOGDetctor {
public:
    OpencvHOGDetctor()
    {
    }

    inline int det(std::string path)
    {
        LOGD("det path %s", path.c_str());
        cv::Mat src_img = cv::imread(path, 1);
        if (src_img.empty())
            return 0;

        cv::HOGDescriptor hog;
        hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
        std::vector<cv::Rect> found, found_filtered;
        hog.detectMultiScale(src_img, found, 0, cv::Size(8, 8),
                             cv::Size(32, 32), 1.05, 2);
        size_t i, j;
        for (i = 0; i < found.size(); i++) {
            cv::Rect r = found[i];
            for (j = 0; j < found.size(); j++)
                if (j != i && (r & found[j]) == r)
                    break;
            if (j == found.size())
                found_filtered.push_back(r);
        }

        for (i = 0; i < found_filtered.size(); i++) {
            cv::Rect r = found_filtered[i];
            r.x += cvRound(r.width * 0.1);
            r.width = cvRound(r.width * 0.8);
            r.y += cvRound(r.height * 0.06);
            r.height = cvRound(r.height * 0.9);
            cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2);
        }
        mResultMat = src_img;
        //cv::imwrite(path, mResultMat);
        LOGD("det ends");
        mRets = found_filtered;
        return found_filtered.size();
    }

    inline cv::Mat& getResultMat()
    {
        return mResultMat;
    }

    inline std::vector<cv::Rect> getResult()
    {
        return mRets;
    }

private:
    cv::Mat mResultMat;
    std::vector<cv::Rect> mRets;
};

class DLibHOGDetector {
public:
    DLibHOGDetector()
    {
        mSVMPath = "/sdcard/person.svm";
    }

    DLibHOGDetector(std::string svmPath)
    {
        mSVMPath = svmPath;
    }

    virtual inline int det(std::string path)
    {
        cv::Mat src_img = cv::imread(path, 1);

        typedef dlib::scan_fhog_pyramid<dlib::pyramid_down<6> > image_scanner_type;
        dlib::object_detector<image_scanner_type> detector;
        dlib::deserialize("/sdcard/person.svm") >> detector;

        int img_width = src_img.cols;
        int img_height = src_img.rows;
        int im_size_min = MIN(img_width, img_height);
        int im_size_max = MAX(img_width, img_height);

        float scale = float(INPUT_IMG_MIN_SIZE) / float(im_size_min);
        if (scale * im_size_max > INPUT_IMG_MAX_SIZE) {
            scale = (float)INPUT_IMG_MAX_SIZE / (float)im_size_max;
        }

        if (scale != 1.0) {
            cv::Mat outputMat;
            cv::resize(src_img, outputMat, cv::Size(img_width * scale, img_height * scale));
            src_img = outputMat;
        }

        //cv::resize(src_img, src_img, cv::Size(320, 240));
        dlib::cv_image<dlib::bgr_pixel> cimg(src_img);

        double thresh = 0.5;
        std::vector<dlib::rectangle> dets = detector(cimg, thresh);
        return 0;
    }

    inline std::vector<dlib::rectangle> getResult()
    {
        return mRets;
    }

protected:
    std::string mModel;
    std::vector<dlib::rectangle> mRets;
    std::string mSVMPath;
    const int INPUT_IMG_MAX_SIZE = 800;
    const int INPUT_IMG_MIN_SIZE = 600;
};

class DLibHOGFaceDetector : public DLibHOGDetector {
private:
    std::string mLandMarkModel;
    dlib::shape_predictor msp;

public:
    DLibHOGFaceDetector()
    {
        mLandMarkModel = "";
    }

    DLibHOGFaceDetector(std::string landmarkmodel)
    {
        mLandMarkModel = landmarkmodel;
        dlib::deserialize(mLandMarkModel) >> msp;
    }

    virtual inline int det(std::string path)
    {
        dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();

        cv::Mat src_img = cv::imread(path, 1);
        dlib::cv_image<dlib::bgr_pixel> img(src_img);

        mRets = detector(img);
        LOGD("Dlib HOG face det size : %d", mRets.size());

        if (mRets.size() != 0 && mLandMarkModel.empty() == false) {
            std::vector<dlib::full_object_detection> shapes;
            for (unsigned long j = 0; j < mRets.size(); ++j) {
                dlib::full_object_detection shape = msp(img, mRets[j]);
                //cout << "number of parts: "<< shape.num_parts() << endl;
                //cout << "pixel position of first part:  " << shape.part(0) << endl;
                //cout << "pixel position of second part: " << shape.part(1) << endl;
                shapes.push_back(shape);
            }
        }
        /*
        // Draw on the input for test
        int i = 0;
        for (i = 0; i < mRets.size(); i++) {
            dlib::rectangle dlibrect = mRets[i];
            cv::Rect r(dlibrect.left(), dlibrect.top(), dlibrect.width(),
                    dlibrect.height());
            r.x += cvRound(r.width * 0.1);
            r.width = cvRound(r.width * 0.8);
            r.y += cvRound(r.height * 0.06);
            r.height = cvRound(r.height * 0.9);
            cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2);
        }
        cv::imwrite(path, src_img);
        */
        return mRets.size();
    }
};

OpencvHOGDetctor* mOpencvHOGDetctor = NULL;
DLibHOGDetector* mDLibDetector = NULL;

#ifdef __cplusplus
extern "C" {
#endif

struct VisionDetRetOffsets {
    jfieldID label;
    jfieldID confidence;
    jfieldID left;
    jfieldID top;
    jfieldID right;
    jfieldID bottom;
} gVisionDetRetOffsets;

// ========================================================
// JNI Mapping Methods
// ========================================================
jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
    LOGE("JNI On Load");
    JNIEnv* env = NULL;
    jint result = -1;

    if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        LOGE("GetEnv failed!");
        return result;
    }

    return JNI_VERSION_1_6;
}

void JNIEXPORT
    JNICALL Java_com_tzutalin_dlib_PeopleDet_jniNativeClassInit(JNIEnv* _env,
                                                                jclass _this)
{
    jclass detRetClass = _env->FindClass("com/tzutalin/dlib/VisionDetRet");
    gVisionDetRetOffsets.label = _env->GetFieldID(detRetClass, "mLabel",
                                                  "java/lang/String");
    gVisionDetRetOffsets.confidence = _env->GetFieldID(detRetClass,
                                                       "mConfidence", "F");
    gVisionDetRetOffsets.left = _env->GetFieldID(detRetClass, "mLeft", "I");
    gVisionDetRetOffsets.top = _env->GetFieldID(detRetClass, "mTop", "I");
    gVisionDetRetOffsets.right = _env->GetFieldID(detRetClass, "mRight", "I");
    gVisionDetRetOffsets.bottom = _env->GetFieldID(detRetClass, "mBottom", "I");
    LOGD("JniNativeClassIni Success");
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniOpencvHOGDetect(
        JNIEnv* env, jobject thiz, jstring imgPath)
{
    LOGD("com_tzutalin_dlib_PeopleDet jniOpencvHOGDetect");
    const char* img_path = env->GetStringUTFChars(imgPath, 0);
    if (mOpencvHOGDetctor == NULL)
        mOpencvHOGDetctor = new OpencvHOGDetctor();

    int nums = mOpencvHOGDetctor->det(std::string(img_path));
    env->ReleaseStringUTFChars(imgPath, img_path);
    return nums;
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniGetOpecvHOGRet(JNIEnv* env,
                                                       jobject thiz, jobject detRet, jint index)
{
    if (mOpencvHOGDetctor) {
        cv::Rect rect = mOpencvHOGDetctor->getResult()[index];
        env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.x);
        env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.y);
        env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.x + rect.width);
        env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.y + rect.height);
        env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0);
        jstring jstr = (jstring)(env->NewStringUTF("person"));
        env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr);
        return 0;
    }
    return -1;
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniDLibHOGDetect(
        JNIEnv* env, jobject thiz, jstring imgPath, jobject detRet)
{
    LOGD("com_tzutalin_dlib_PeopleDet jniDLibHOGDetect");
    const char* img_path = env->GetStringUTFChars(imgPath, 0);
    if (mDLibDetector == NULL)
        mDLibDetector = new DLibHOGFaceDetector();

    int size = mDLibDetector->det(std::string(img_path));
    env->ReleaseStringUTFChars(imgPath, img_path);
    return size;
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniGetDLibRet(JNIEnv* env,
                                                   jobject thiz, jobject detRet, jint index)
{
    if (mDLibDetector) {
        dlib::rectangle rect = mDLibDetector->getResult()[index];
        env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.left());
        env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.top());
        env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.right());
        env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.bottom());
        env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0);
        jstring jstr = (jstring)(env->NewStringUTF("face"));
        env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr);
        return 0;
    }
    return -1;
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniInit(JNIEnv* env, jobject thiz)
{

    if (mDLibDetector == NULL)
        mDLibDetector = new DLibHOGFaceDetector();

    if (mOpencvHOGDetctor == NULL)
        mOpencvHOGDetctor = new OpencvHOGDetctor();

    return 0;
}

jint JNIEXPORT JNICALL
    Java_com_tzutalin_dlib_PeopleDet_jniDeInit(JNIEnv* env, jobject thiz)
{
    if (mDLibDetector)
        delete mDLibDetector;

    if (mOpencvHOGDetctor)
        delete mOpencvHOGDetctor;

    return 0;
}

#ifdef __cplusplus
}
#endif

int main()
{
    const int INPUT_IMG_MAX_SIZE = 800;
    const int INPUT_IMG_MIN_SIZE = 600;
    std::string path = "/sdcard/test.jpg";

    cv::Mat src_img = cv::imread(path, 1);

    typedef dlib::scan_fhog_pyramid<dlib::pyramid_down<6> > image_scanner_type;
    dlib::object_detector<image_scanner_type> detector;
    dlib::deserialize("/sdcard/person.svm") >> detector;

    int img_width = src_img.cols;
    int img_height = src_img.rows;
    int im_size_min = MIN(img_width, img_height);
    int im_size_max = MAX(img_width, img_height);

    float scale = float(INPUT_IMG_MIN_SIZE) / float(im_size_min);
    if (scale * im_size_max > INPUT_IMG_MAX_SIZE) {
        scale = (float)INPUT_IMG_MAX_SIZE / (float)im_size_max;
    }

    if (scale != 1.0) {
        cv::Mat outputMat;
        cv::resize(src_img, outputMat, cv::Size(img_width * scale, img_height * scale));
        src_img = outputMat;
    }

    //cv::resize(src_img, src_img, cv::Size(320, 240));
    dlib::cv_image<dlib::bgr_pixel> cimg(src_img);

    double thresh = 0.5;
    std::vector<dlib::rectangle> dets = detector(cimg, thresh);
    std::cout << "size: " << dets.size() << std::endl;

    int i = 0;
    for (i = 0; i < dets.size(); i++) {
        dlib::rectangle dlibrect = dets[i];
        cv::Rect r(dlibrect.left(), dlibrect.top(), dlibrect.width(),
                   dlibrect.height());
        r.x += cvRound(r.width * 0.1);
        r.width = cvRound(r.width * 0.8);
        r.y += cvRound(r.height * 0.06);
        r.height = cvRound(r.height * 0.9);
        cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2);
    }
    path = "/sdcard/ret.jpg";
    cv::imwrite(path, src_img);
    return 0;
}

max_stars_repo_name: wearebase/dlib-android

max_issues_repo_name: wearebase/dlib-android

max_forks_repo_name: wearebase/dlib-android


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.
 *
 *************************************************************/

#ifndef _CHART2_ACCESSIBLECHARTELEMENT_HXX_
#define _CHART2_ACCESSIBLECHARTELEMENT_HXX_

#include "AccessibleBase.hxx"
#include <com/sun/star/chart2/XChartDocument.hpp>
#include <com/sun/star/accessibility/XAccessible.hpp>
#include <com/sun/star/accessibility/XAccessibleContext.hpp>
#include <com/sun/star/accessibility/XAccessibleComponent.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/document/XEventListener.hpp>
#include <com/sun/star/lang/XEventListener.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#include <com/sun/star/view/XSelectionSupplier.hpp>
#include <comphelper/accessibleeventnotifier.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <unotools/accessiblestatesethelper.hxx>

#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>

class SfxItemSet;
class SdrObject;

namespace chart
{

/** Base class for all Chart Accessibility objects except the root node (see AccessibleChartView)

    This class contains a reference to the ChartModel, thus, components can easily access all core functionality.

    Usage Instructions:

define the getAccessibleName() method of XAccessibleContext

set the ChartModel using SetChartModel() for the first node before
         creating any children

overload UpdateChildren()

 */

namespace impl
{
typedef ::cppu::ImplInheritanceHelper1<
        AccessibleBase,
        ::com::sun::star::accessibility::XAccessibleExtendedComponent
        > AccessibleChartElement_Base;
}

class AccessibleChartElement :
    public impl::AccessibleChartElement_Base
{
public:
    AccessibleChartElement( const AccessibleElementInfo & rAccInfo,
                            bool bMayHaveChildren,
                            bool bAlwaysTransparent = false );
    virtual ~AccessibleChartElement();

    // ________ AccessibleBase ________
    virtual bool ImplUpdateChildren();
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessible >
        ImplGetAccessibleChildById( sal_Int32 i ) const
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
               ::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 ImplGetAccessibleChildCount() const
        throw (::com::sun::star::uno::RuntimeException);

    // ________ XAccessibleContext ________
    virtual ::rtl::OUString SAL_CALL getAccessibleName()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getAccessibleDescription()
        throw (::com::sun::star::uno::RuntimeException);

    // ________ XAccessibleExtendedComponent ________
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitledBorderText()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getToolTipText()
        throw (::com::sun::star::uno::RuntimeException);

    // the following interface is implemented in AccessibleBase, however it is
    // also a (non-virtual) base class of XAccessibleExtendedComponent Thus
    // these methods have to be overloaded and forward to AccessibleBase

    // ________ XAccessibleComponent ________
    virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::Point SAL_CALL getLocation() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::Size SAL_CALL getSize() throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL grabFocus() throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getForeground() throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getBackground() throw (::com::sun::star::uno::RuntimeException);

    // ________ XServiceInfo ________
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw (::com::sun::star::uno::RuntimeException);

private:
    bool                m_bHasText;
    ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleContext >
                        m_xTextHelper;

    void InitTextEdit();
};

}  // namespace chart

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice