text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* @file scene.cpp
* @brief Function definitions for scenes.
*
* @author Eric Butler (edbutler)
* @author Kristin Siu (kasiu)
* @author Justin Gallagher (jrgallag)
*/
#include "scene/scene.hpp"
namespace _462 {
Geometry::Geometry():
position(Vector3::Zero()),
orientation(Quaternion::Identity()),
scale(Vector3::Ones())
{
}
Geometry::~Geometry() { }
bool Geometry::initialize()
{
make_inverse_transformation_matrix(&invMat, position, orientation, scale);
make_transformation_matrix(&mat, position, orientation, scale);
make_normal_matrix(&normMat, mat);
return true;
}
SphereLight::SphereLight():
position(Vector3::Zero()),
color(Color3::White()),
radius(real_t(0))
{
attenuation.constant = 1;
attenuation.linear = 0;
attenuation.quadratic = 0;
}
/**
* @brief Calculates whether this ray intersects the light, and at what time.
* @param ray: Ray to test.
* @param t: Where the time to intersection will be returned.
* @return: bool
*/
bool SphereLight::intersect(const Ray& ray, real_t &t) {
// Calculate quadratic coefficients
real_t a = dot(ray.d, ray.d);
real_t b = 2.0 * dot(ray.d, ray.e - position);
real_t c = dot(ray.e - position, ray.e - position) - radius * radius;
// Get t
t = solve_time(a, b, c);
return t >= EPS;
}
/**
* @brief Samples the light to determine its contribution to a point.
* @param pos: Position of intersection
* @param wnorm: Surface normal at intersection
* @param scene: Scene to sample
* @return: Color of the light, sampled on random points on the light surface
*/
Color3 SphereLight::sample(Vector3 &pos, Vector3 &wnorm, Scene &scene) {
Color3 cumulative = Color3(0.0, 0.0, 0.0);
for (int i = 0; i < DIRECT_SAMPLE_COUNT; i++) {
Vector3 rand_pos = normalize(Vector3(random_gaussian(),
random_gaussian(), random_gaussian()));
rand_pos = rand_pos * radius + position;
Ray new_ray = Ray(pos, normalize(rand_pos - pos));
real_t time = length(rand_pos - pos);
Intersection result = scene.cast_ray(new_ray);
if (result.time < EPS || time < result.time) {
real_t atten = 1.0 / (attenuation.constant + time *
attenuation.linear + time * time * attenuation.quadratic);
real_t scale = dot(new_ray.d, wnorm);
if (scale > 0) {
cumulative += scale * atten * color *
(1.0 / DIRECT_SAMPLE_COUNT);
}
}
}
return cumulative;
}
Scene::Scene()
{
reset();
}
Scene::~Scene()
{
reset();
}
bool Scene::initialize()
{
bool res = true;
for (unsigned int i = 0; i < num_geometries(); i++)
res &= geometries[i]->initialize();
intersections = 0;
if (triangles.size() > 0) {
return res;
}
for (unsigned int i = 0; i < num_geometries(); i++) {
TriangleList newtris = geometries[i]->get_triangles();
triangles.insert(triangles.end(), newtris.begin(), newtris.end());
}
if (fpga_accel) {
size_t rounded_tris = triangles.size() + PARALLEL_TESTS
- 1 - (triangles.size() - 1) % PARALLEL_TESTS;
std::cout << rounded_tris << std::endl;
axidma_interface =
new AxiDma(rounded_tris * 15 * sizeof(float), rounded_tris
* 3 * sizeof(float));
}
return res;
}
Geometry* const* Scene::get_geometries() const
{
return geometries.empty() ? NULL : &geometries[0];
}
size_t Scene::num_geometries() const
{
return geometries.size();
}
const SphereLight* Scene::get_lights() const
{
return point_lights.empty() ? NULL : &point_lights[0];
}
size_t Scene::num_lights() const
{
return point_lights.size();
}
Material* const* Scene::get_materials() const
{
return materials.empty() ? NULL : &materials[0];
}
size_t Scene::num_materials() const
{
return materials.size();
}
Mesh* const* Scene::get_meshes() const
{
return meshes.empty() ? NULL : &meshes[0];
}
size_t Scene::num_meshes() const
{
return meshes.size();
}
/**
* @brief Find the color of the point of intersection between a ray and the
* scene.
* @param ray: Ray to send.
* @param refracti: Refractive index of ray medium.
* @param depth: Number of recursive calls made.
* @return: Color of the point of intersection.
*/
Color3 Scene::trace_ray(Ray &ray, int refracti, int depth) {
// Abort if too deep
if (depth > MAX_DEPTH) return Color3(0.0, 0.0, 0.0);
// Use ray casting to find if an object is seen
Intersection intersect = cast_ray(ray);
// Calculate color
if (intersect.time >= EPS) {
return intersect.shape->color(intersect, ray, *this, depth, refracti);
} else {
return background_color;
}
}
/**
* @brief Casts a ray through the scene, returning information about the nearest
* intersection, if one occurs.
* @param ray: Ray to cast.
* @return: Intersection object representing the intersection.
*/
Intersection Scene::cast_ray(Ray &ray) {
// Use ray casting to find if an object is seen
Intersection min_inter;
min_inter.time = -1.0;
if (simd_accel) {
// Use SIMD accelerated triangle intersections
min_inter = SimpleTriangle::simd_intersect(triangles, ray);
} else if (fpga_accel) {
min_inter = SimpleTriangle::fpga_intersect(triangles, ray,
axidma_interface);
} else {
// Use normal CPU triangle intersections
for (unsigned int i = 0; i < triangles.size(); i++) {
real_t temp_beta, temp_gamma, temp_t;
temp_t = triangles[i]->intersect(ray, temp_beta, temp_gamma);
if (temp_t != -1 && temp_t >= EPS &&
(min_inter.time < EPS || temp_t < min_inter.time)) {
min_inter.time = temp_t;
min_inter.x = temp_beta;
min_inter.y = temp_gamma;
min_inter.shape = triangles[i]->parent;
min_inter.tri = triangles[i]->num_tri;
}
}
}
long long num_tris = (long long) triangles.size();
#pragma omp atomic
intersections += num_tris;
return min_inter;
}
void Scene::reset()
{
for ( TriangleList::iterator i = triangles.begin(); i != triangles.end(); ++i ) {
delete *i;
}
for ( GeometryList::iterator i = geometries.begin(); i != geometries.end(); ++i ) {
delete *i;
}
for ( MaterialList::iterator i = materials.begin(); i != materials.end(); ++i ) {
delete *i;
}
for ( MeshList::iterator i = meshes.begin(); i != meshes.end(); ++i ) {
delete *i;
}
geometries.clear();
materials.clear();
meshes.clear();
point_lights.clear();
camera = Camera();
background_color = Color3::Black();
ambient_light = Color3::Black();
refractive_index = 1.0;
}
void Scene::add_geometry( Geometry* g )
{
geometries.push_back( g );
}
void Scene::add_material( Material* m )
{
materials.push_back( m );
}
void Scene::add_mesh( Mesh* m )
{
meshes.push_back( m );
}
void Scene::add_light( const SphereLight& l )
{
point_lights.push_back( l );
}
} /* _462 */
<commit_msg>Print number of triangles to be tested<commit_after>/**
* @file scene.cpp
* @brief Function definitions for scenes.
*
* @author Eric Butler (edbutler)
* @author Kristin Siu (kasiu)
* @author Justin Gallagher (jrgallag)
*/
#include "scene/scene.hpp"
namespace _462 {
Geometry::Geometry():
position(Vector3::Zero()),
orientation(Quaternion::Identity()),
scale(Vector3::Ones())
{
}
Geometry::~Geometry() { }
bool Geometry::initialize()
{
make_inverse_transformation_matrix(&invMat, position, orientation, scale);
make_transformation_matrix(&mat, position, orientation, scale);
make_normal_matrix(&normMat, mat);
return true;
}
SphereLight::SphereLight():
position(Vector3::Zero()),
color(Color3::White()),
radius(real_t(0))
{
attenuation.constant = 1;
attenuation.linear = 0;
attenuation.quadratic = 0;
}
/**
* @brief Calculates whether this ray intersects the light, and at what time.
* @param ray: Ray to test.
* @param t: Where the time to intersection will be returned.
* @return: bool
*/
bool SphereLight::intersect(const Ray& ray, real_t &t) {
// Calculate quadratic coefficients
real_t a = dot(ray.d, ray.d);
real_t b = 2.0 * dot(ray.d, ray.e - position);
real_t c = dot(ray.e - position, ray.e - position) - radius * radius;
// Get t
t = solve_time(a, b, c);
return t >= EPS;
}
/**
* @brief Samples the light to determine its contribution to a point.
* @param pos: Position of intersection
* @param wnorm: Surface normal at intersection
* @param scene: Scene to sample
* @return: Color of the light, sampled on random points on the light surface
*/
Color3 SphereLight::sample(Vector3 &pos, Vector3 &wnorm, Scene &scene) {
Color3 cumulative = Color3(0.0, 0.0, 0.0);
for (int i = 0; i < DIRECT_SAMPLE_COUNT; i++) {
Vector3 rand_pos = normalize(Vector3(random_gaussian(),
random_gaussian(), random_gaussian()));
rand_pos = rand_pos * radius + position;
Ray new_ray = Ray(pos, normalize(rand_pos - pos));
real_t time = length(rand_pos - pos);
Intersection result = scene.cast_ray(new_ray);
if (result.time < EPS || time < result.time) {
real_t atten = 1.0 / (attenuation.constant + time *
attenuation.linear + time * time * attenuation.quadratic);
real_t scale = dot(new_ray.d, wnorm);
if (scale > 0) {
cumulative += scale * atten * color *
(1.0 / DIRECT_SAMPLE_COUNT);
}
}
}
return cumulative;
}
Scene::Scene()
{
reset();
}
Scene::~Scene()
{
reset();
}
bool Scene::initialize()
{
bool res = true;
for (unsigned int i = 0; i < num_geometries(); i++)
res &= geometries[i]->initialize();
intersections = 0;
if (triangles.size() > 0) {
return res;
}
for (unsigned int i = 0; i < num_geometries(); i++) {
TriangleList newtris = geometries[i]->get_triangles();
triangles.insert(triangles.end(), newtris.begin(), newtris.end());
}
std::cout << triangles.size() << " triangles" << std::endl;
if (fpga_accel) {
size_t rounded_tris = triangles.size() + PARALLEL_TESTS
- 1 - (triangles.size() - 1) % PARALLEL_TESTS;
axidma_interface =
new AxiDma(rounded_tris * 15 * sizeof(float), rounded_tris
* 3 * sizeof(float));
}
return res;
}
Geometry* const* Scene::get_geometries() const
{
return geometries.empty() ? NULL : &geometries[0];
}
size_t Scene::num_geometries() const
{
return geometries.size();
}
const SphereLight* Scene::get_lights() const
{
return point_lights.empty() ? NULL : &point_lights[0];
}
size_t Scene::num_lights() const
{
return point_lights.size();
}
Material* const* Scene::get_materials() const
{
return materials.empty() ? NULL : &materials[0];
}
size_t Scene::num_materials() const
{
return materials.size();
}
Mesh* const* Scene::get_meshes() const
{
return meshes.empty() ? NULL : &meshes[0];
}
size_t Scene::num_meshes() const
{
return meshes.size();
}
/**
* @brief Find the color of the point of intersection between a ray and the
* scene.
* @param ray: Ray to send.
* @param refracti: Refractive index of ray medium.
* @param depth: Number of recursive calls made.
* @return: Color of the point of intersection.
*/
Color3 Scene::trace_ray(Ray &ray, int refracti, int depth) {
// Abort if too deep
if (depth > MAX_DEPTH) return Color3(0.0, 0.0, 0.0);
// Use ray casting to find if an object is seen
Intersection intersect = cast_ray(ray);
// Calculate color
if (intersect.time >= EPS) {
return intersect.shape->color(intersect, ray, *this, depth, refracti);
} else {
return background_color;
}
}
/**
* @brief Casts a ray through the scene, returning information about the nearest
* intersection, if one occurs.
* @param ray: Ray to cast.
* @return: Intersection object representing the intersection.
*/
Intersection Scene::cast_ray(Ray &ray) {
// Use ray casting to find if an object is seen
Intersection min_inter;
min_inter.time = -1.0;
if (simd_accel) {
// Use SIMD accelerated triangle intersections
min_inter = SimpleTriangle::simd_intersect(triangles, ray);
} else if (fpga_accel) {
min_inter = SimpleTriangle::fpga_intersect(triangles, ray,
axidma_interface);
} else {
// Use normal CPU triangle intersections
for (unsigned int i = 0; i < triangles.size(); i++) {
real_t temp_beta, temp_gamma, temp_t;
temp_t = triangles[i]->intersect(ray, temp_beta, temp_gamma);
if (temp_t != -1 && temp_t >= EPS &&
(min_inter.time < EPS || temp_t < min_inter.time)) {
min_inter.time = temp_t;
min_inter.x = temp_beta;
min_inter.y = temp_gamma;
min_inter.shape = triangles[i]->parent;
min_inter.tri = triangles[i]->num_tri;
}
}
}
long long num_tris = (long long) triangles.size();
#pragma omp atomic
intersections += num_tris;
return min_inter;
}
void Scene::reset()
{
for ( TriangleList::iterator i = triangles.begin(); i != triangles.end(); ++i ) {
delete *i;
}
for ( GeometryList::iterator i = geometries.begin(); i != geometries.end(); ++i ) {
delete *i;
}
for ( MaterialList::iterator i = materials.begin(); i != materials.end(); ++i ) {
delete *i;
}
for ( MeshList::iterator i = meshes.begin(); i != meshes.end(); ++i ) {
delete *i;
}
geometries.clear();
materials.clear();
meshes.clear();
point_lights.clear();
camera = Camera();
background_color = Color3::Black();
ambient_light = Color3::Black();
refractive_index = 1.0;
}
void Scene::add_geometry( Geometry* g )
{
geometries.push_back( g );
}
void Scene::add_material( Material* m )
{
materials.push_back( m );
}
void Scene::add_mesh( Mesh* m )
{
meshes.push_back( m );
}
void Scene::add_light( const SphereLight& l )
{
point_lights.push_back( l );
}
} /* _462 */
<|endoftext|> |
<commit_before>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY [email protected]
*/
/*! \file PivotJoint.cpp
*/
#include "PivotJoint.hpp"
#include <boost/math/quaternion.hpp>
int PivotJointR::_sNbEqualities = 5;
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P)
{
SP::SiconosVector q1 = d1->q0();
::boost::math::quaternion<float> quat1(q1->getValue(3), q1->getValue(4), q1->getValue(5), q1->getValue(6));
::boost::math::quaternion<float> quatA(0, A->getValue(0), A->getValue(1), A->getValue(2));
::boost::math::quaternion<float> quatBuff(0, 0, 0, 0);
/*calcul of axis _A*/
quatBuff = quat1 * quatA / quat1;
_Ax = quatBuff.R_component_2();
_Ay = quatBuff.R_component_3();
_Az = quatBuff.R_component_4();
buildA1A2();
}
/* constructor,
\param a SP::NewtonEulerDS d1, a dynamical system containing the intial position
\param a SP::SimpleVector P0, P0 contains the coordinates of the Pivot point, in the absolute frame.
*/
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A): KneeJointR(d1, P0)
{
_Ax = A->getValue(0);
_Ay = A->getValue(1);
_Az = A->getValue(2);
buildA1A2();
}
void PivotJointR::buildA1A2()
{
double normA = sqrt(_Ax * _Ax + _Ay * _Ay + _Az * _Az);
assert(normA > 0.9 && "PivotJoint, normA to small\n");
_Ax /= normA;
_Ay /= normA;
_Az /= normA;
std::cout << "JointKnee: _Ax _Ay _Az :" << _Ax << " " << _Ay << " " << _Az << std::endl;
/*build _A1*/
if (_Ax > _Ay)
{
if (_Ax > _Az) /*_Ax is the bigest*/
{
_A1x = _Ay;
_A1y = -_Ax;
_A1z = 0;
_A2x = _Az;
_A2z = -_Ax;
_A2y = 0;
}
else /*_Az is the biggest*/
{
_A1z = _Ax;
_A1y = -_Az;
_A1x = 0;
_A2z = _Ay;
_A2x = -_Az;
_A2y = 0;
}
}
else if (_Ay > _Az) /*_Ay is the bigest*/
{
_A1y = _Ax;
_A1x = -_Ay;
_A1z = 0;
_A2y = _Az;
_A2z = -_Ay;
_A2x = 0;
}
else /*_Az is the biggest*/
{
_A1z = _Ax;
_A1y = -_Az;
_A1x = 0;
_A2z = _Ay;
_A2x = -_Az;
_A2y = 0;
}
assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n");
assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n");
assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n");
std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl;
std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl;
}
void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23)
{
KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23);
_jachq->setValue(3, 0, 0);
_jachq->setValue(3, 1, 0);
_jachq->setValue(3, 2, 0);
_jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23));
_jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22));
_jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21));
_jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20));
_jachq->setValue(3, 7, 0);
_jachq->setValue(3, 8, 0);
_jachq->setValue(3, 9, 0);
_jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13));
_jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12));
_jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11));
_jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10));
_jachq->setValue(4, 0, 0);
_jachq->setValue(4, 1, 0);
_jachq->setValue(4, 2, 0);
_jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23));
_jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22));
_jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21));
_jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20));
_jachq->setValue(4, 7, 0);
_jachq->setValue(4, 8, 0);
_jachq->setValue(4, 9, 0);
_jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13));
_jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12));
_jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11));
_jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10));
//_jachq->display();
}
void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13)
{
KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13);
_jachq->setValue(3, 0, 0);
_jachq->setValue(3, 1, 0);
_jachq->setValue(3, 2, 0);
_jachq->setValue(3, 3, 0);
_jachq->setValue(3, 4, _A1x);
_jachq->setValue(3, 5, _A1y);
_jachq->setValue(3, 6, _A1z);
_jachq->setValue(4, 0, 0);
_jachq->setValue(4, 1, 0);
_jachq->setValue(4, 2, 0);
_jachq->setValue(4, 3, 0);
_jachq->setValue(4, 4, _A2x);
_jachq->setValue(4, 5, _A2y);
_jachq->setValue(4, 6, _A2z);
}
double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
::boost::math::quaternion<float> quat1(q10, q11, q12, q13);
::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23);
::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv;
double aX = quatBuff.R_component_2();
double aY = quatBuff.R_component_3();
double aZ = quatBuff.R_component_4();
return _A1x * aX + _A1y * aY + _A1z * aZ;
}
double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
::boost::math::quaternion<float> quat1(q10, q11, q12, q13);
::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23);
::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv;
double aX = quatBuff.R_component_2();
double aY = quatBuff.R_component_3();
double aZ = quatBuff.R_component_4();
return _A2x * aX + _A2y * aY + _A2z * aZ;
}
void PivotJointR::computeh(double t)
{
KneeJointR::computeh(t);
SP::SiconosVector x1 = _d1->q();
//std::cout<<"PivotJoint computeH d1->q:\n";
//x1->display();
double q10 = x1->getValue(3);
double q11 = x1->getValue(4);
double q12 = x1->getValue(5);
double q13 = x1->getValue(6);
double q20 = 1;
double q21 = 0;
double q22 = 0;
double q23 = 0;
if (_d2)
{
SP::SiconosVector x2 = _d2->q();
q20 = x2->getValue(3);
q21 = x2->getValue(4);
q22 = x2->getValue(5);
q23 = x2->getValue(6);
}
SP::SiconosVector y = interaction()->y(0);
y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23));
y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23));
std::cout << "PivotJoint computeH:\n";
y->display();
}
<commit_msg>fix a bug:fabs(_Ax)<commit_after>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY [email protected]
*/
/*! \file PivotJoint.cpp
*/
#include "PivotJoint.hpp"
#include <boost/math/quaternion.hpp>
int PivotJointR::_sNbEqualities = 5;
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P)
{
SP::SiconosVector q1 = d1->q0();
::boost::math::quaternion<float> quat1(q1->getValue(3), q1->getValue(4), q1->getValue(5), q1->getValue(6));
::boost::math::quaternion<float> quatA(0, A->getValue(0), A->getValue(1), A->getValue(2));
::boost::math::quaternion<float> quatBuff(0, 0, 0, 0);
/*calcul of axis _A*/
quatBuff = quat1 * quatA / quat1;
_Ax = quatBuff.R_component_2();
_Ay = quatBuff.R_component_3();
_Az = quatBuff.R_component_4();
buildA1A2();
}
/* constructor,
\param a SP::NewtonEulerDS d1, a dynamical system containing the intial position
\param a SP::SimpleVector P0, P0 contains the coordinates of the Pivot point, in the absolute frame.
*/
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A): KneeJointR(d1, P0)
{
_Ax = A->getValue(0);
_Ay = A->getValue(1);
_Az = A->getValue(2);
buildA1A2();
}
void PivotJointR::buildA1A2()
{
double normA = sqrt(_Ax * _Ax + _Ay * _Ay + _Az * _Az);
assert(normA > 0.9 && "PivotJoint, normA to small\n");
_Ax /= normA;
_Ay /= normA;
_Az /= normA;
std::cout << "JointKnee: _Ax _Ay _Az :" << _Ax << " " << _Ay << " " << _Az << std::endl;
/*build _A1*/
if (fabs(_Ax) > fabs(_Ay))
{
if (fabs(_Ax) > fabs(_Az)) /*_Ax is the bigest*/
{
_A1x = _Ay;
_A1y = -_Ax;
_A1z = 0;
_A2x = _Az;
_A2z = -_Ax;
_A2y = 0;
}
else /*_Az is the biggest*/
{
_A1z = _Ax;
_A1y = -_Az;
_A1x = 0;
_A2z = _Ay;
_A2x = -_Az;
_A2y = 0;
}
}
else if (fabs(_Ay) > fabs(_Az)) /*_Ay is the bigest*/
{
_A1y = _Ax;
_A1x = -_Ay;
_A1z = 0;
_A2y = _Az;
_A2z = -_Ay;
_A2x = 0;
}
else /*_Az is the biggest*/
{
_A1z = _Ax;
_A1y = -_Az;
_A1x = 0;
_A2z = _Ay;
_A2x = -_Az;
_A2y = 0;
}
assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n");
assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n");
assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n");
std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl;
std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl;
}
void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23)
{
KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23);
_jachq->setValue(3, 0, 0);
_jachq->setValue(3, 1, 0);
_jachq->setValue(3, 2, 0);
_jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23));
_jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22));
_jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21));
_jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20));
_jachq->setValue(3, 7, 0);
_jachq->setValue(3, 8, 0);
_jachq->setValue(3, 9, 0);
_jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13));
_jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12));
_jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11));
_jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10));
_jachq->setValue(4, 0, 0);
_jachq->setValue(4, 1, 0);
_jachq->setValue(4, 2, 0);
_jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23));
_jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22));
_jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21));
_jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20));
_jachq->setValue(4, 7, 0);
_jachq->setValue(4, 8, 0);
_jachq->setValue(4, 9, 0);
_jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13));
_jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12));
_jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11));
_jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10));
//_jachq->display();
}
void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13)
{
KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13);
_jachq->setValue(3, 0, 0);
_jachq->setValue(3, 1, 0);
_jachq->setValue(3, 2, 0);
_jachq->setValue(3, 3, 0);
_jachq->setValue(3, 4, _A1x);
_jachq->setValue(3, 5, _A1y);
_jachq->setValue(3, 6, _A1z);
_jachq->setValue(4, 0, 0);
_jachq->setValue(4, 1, 0);
_jachq->setValue(4, 2, 0);
_jachq->setValue(4, 3, 0);
_jachq->setValue(4, 4, _A2x);
_jachq->setValue(4, 5, _A2y);
_jachq->setValue(4, 6, _A2z);
}
double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
::boost::math::quaternion<float> quat1(q10, q11, q12, q13);
::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23);
::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv;
double aX = quatBuff.R_component_2();
double aY = quatBuff.R_component_3();
double aZ = quatBuff.R_component_4();
return _A1x * aX + _A1y * aY + _A1z * aZ;
}
double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
::boost::math::quaternion<float> quat1(q10, q11, q12, q13);
::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23);
::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv;
double aX = quatBuff.R_component_2();
double aY = quatBuff.R_component_3();
double aZ = quatBuff.R_component_4();
return _A2x * aX + _A2y * aY + _A2z * aZ;
}
void PivotJointR::computeh(double t)
{
KneeJointR::computeh(t);
SP::SiconosVector x1 = _d1->q();
//std::cout<<"PivotJoint computeH d1->q:\n";
//x1->display();
double q10 = x1->getValue(3);
double q11 = x1->getValue(4);
double q12 = x1->getValue(5);
double q13 = x1->getValue(6);
double q20 = 1;
double q21 = 0;
double q22 = 0;
double q23 = 0;
if (_d2)
{
SP::SiconosVector x2 = _d2->q();
q20 = x2->getValue(3);
q21 = x2->getValue(4);
q22 = x2->getValue(5);
q23 = x2->getValue(6);
}
SP::SiconosVector y = interaction()->y(0);
y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23));
y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23));
std::cout << "PivotJoint computeH:\n";
y->display();
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciORBTask.cpp,v 1.4 2006/09/01 02:20:54 cparedes Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* msekoran 2003/05/22 created
*/
#include <vltPort.h>
#include <maciORBTask.h>
using namespace maci;
ORBTask::ORBTask (CORBA::ORB_ptr orb, LoggingProxy * logger, unsigned int timeToRun)
: m_orb(CORBA::ORB::_duplicate(orb)), m_logger(logger), m_timeToRun(timeToRun)
{
}
int
ORBTask::svc (void)
{
// initialize logging
if (m_logger)
{
LoggingProxy::init(m_logger);
LoggingProxy::ThreadName("ORBTask");
}
try
{
// handle CORBA requests
if (m_timeToRun == 0)
{
this->m_orb->run ();
}
else
{
ACE_Time_Value tv (m_timeToRun);
this->m_orb->run (tv);
}
}
catch( CORBA::Exception &ex )
{
ACE_PRINT_EXCEPTION(ex, "maci::ORBTask::svc");
return 1;
}
// return error free code
return 0;
}
// ************************************************************************
//
// REVISION HISTORY:
//
// $Log: maciORBTask.cpp,v $
// Revision 1.4 2006/09/01 02:20:54 cparedes
// small change, NAMESPACE_BEGIN / NAMESPACE_END / NAMESPACE_USE macross to clean up a little the cpp code
//
// Revision 1.3 2005/09/27 08:35:10 vwang
// change from ACE_TRY CATCH to C++ try catch
//
// Revision 1.2 2003/10/23 08:06:25 acaproni
// True native exception handling. No more extra parameters
//
// Revision 1.1 2003/05/23 09:26:37 msekoran
// Multi-threaded servers, hierarchical COBs reactivation deadlock fixed.
//
//
// ************************************************************************
<commit_msg>improved error handling<commit_after>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciORBTask.cpp,v 1.5 2007/07/16 09:33:14 bjeram Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* msekoran 2003/05/22 created
*/
#include <vltPort.h>
#include <maciORBTask.h>
#include <ACSErrTypeCommon.h>
using namespace maci;
ORBTask::ORBTask (CORBA::ORB_ptr orb, LoggingProxy * logger, unsigned int timeToRun)
: m_orb(CORBA::ORB::_duplicate(orb)), m_logger(logger), m_timeToRun(timeToRun)
{
}
int
ORBTask::svc (void)
{
// initialize logging
if (m_logger)
{
LoggingProxy::init(m_logger);
LoggingProxy::ThreadName("ORBTask");
}
try
{
// handle CORBA requests
if (m_timeToRun == 0)
{
this->m_orb->run ();
}
else
{
ACE_Time_Value tv (m_timeToRun);
this->m_orb->run (tv);
}
}
catch( CORBA::SystemException &ex )
{
ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
"maci::ORBTask::svc");
corbaProblemEx.setMinor(ex.minor());
corbaProblemEx.setCompletionStatus(ex.completed());
corbaProblemEx.setInfo(ex._info().c_str());
corbaProblemEx.log();
return 1;
}
catch( CORBA::Exception &ex )
{
ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
"maci::ORBTask::svc");
corbaProblemEx.setInfo(ex._info().c_str());
corbaProblemEx.log();
return 1;
}
catch(ACSErr::ACSbaseExImpl &_ex)
{
ACSErrTypeCommon::UnexpectedExceptionExImpl ex(_ex, __FILE__, __LINE__,
"maci::ORBTask::svc");
ex.log();
return 1;
}
catch(...)
{
ACSErrTypeCommon::UnexpectedExceptionExImpl ex(__FILE__, __LINE__,
"maci::ORBTask::svc");
ex.log();
return 1;
}//try-catch
// return error free code
return 0;
}
// ************************************************************************
//
// REVISION HISTORY:
//
// $Log: maciORBTask.cpp,v $
// Revision 1.5 2007/07/16 09:33:14 bjeram
// improved error handling
//
// Revision 1.4 2006/09/01 02:20:54 cparedes
// small change, NAMESPACE_BEGIN / NAMESPACE_END / NAMESPACE_USE macross to clean up a little the cpp code
//
// Revision 1.3 2005/09/27 08:35:10 vwang
// change from ACE_TRY CATCH to C++ try catch
//
// Revision 1.2 2003/10/23 08:06:25 acaproni
// True native exception handling. No more extra parameters
//
// Revision 1.1 2003/05/23 09:26:37 msekoran
// Multi-threaded servers, hierarchical COBs reactivation deadlock fixed.
//
//
// ************************************************************************
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2019-5-26 21:31:42
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, Q;
ll S[200010], T[200010], X[200010];
ll D[200010];
int ans[200010];
typedef tuple<ll, ll, ll, int> K;
vector<K> KK;
typedef tuple<ll, int, int> info;
priority_queue<info, vector<info>, greater<info>> P;
int main()
{
cin >> N >> Q;
for (auto i = 0; i < N; i++)
{
cin >> S[i] >> T[i] >> X[i];
KK.push_back(K(X[i], S[i], T[i], i));
}
sort(KK.begin(), KK.end());
for (auto i = 0; i < Q; i++)
{
cin >> D[i];
}
for (auto i = 0; i < N; i++)
{
ll x = get<0>(KK[i]);
ll s = get<1>(KK[i]);
ll t = get<2>(KK[i]);
int ind = get<3>(KK[i]);
P.push(info(s - x, ind, 0));
P.push(info(t - x, ind, 1));
}
int ind = 0;
set<int> S;
fill(ans, ans + Q, -1);
while (!P.empty())
{
info x = P.top();
P.pop();
ll next_t = get<0>(x);
int point = get<1>(x);
bool start = (get<2>(x) == 0);
while (next_t > D[ind])
{
int a = -1;
if (S.empty())
{
a = -1;
}
else
{
a = *S.begin();
}
ans[ind] = a;
ind++;
if (ind == Q)
{
goto EXIT;
}
}
if (start)
{
S.insert(point);
}
else
{
S.erase(S.find(point));
}
}
EXIT:
for (auto i = 0; i < Q; i++)
{
if (ans[i] == -1)
{
cout << -1 << endl;
}
else
{
cout << X[ans[i]] << endl;
}
}
}<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2019-5-26 21:31:42
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, Q;
ll S[200010], T[200010], X[200010];
ll D[200010];
int ans[200010];
typedef tuple<ll, ll, ll, int> K;
vector<K> KK;
typedef tuple<ll, int, int> info;
priority_queue<info, vector<info>, greater<info>> P;
int main()
{
cin >> N >> Q;
for (auto i = 0; i < N; i++)
{
cin >> S[i] >> T[i] >> X[i];
KK.push_back(K(X[i], S[i], T[i], i));
}
sort(KK.begin(), KK.end());
for (auto i = 0; i < Q; i++)
{
cin >> D[i];
}
for (auto i = 0; i < N; i++)
{
ll x = get<0>(KK[i]);
ll s = get<1>(KK[i]);
ll t = get<2>(KK[i]);
int ind = get<3>(KK[i]);
P.push(info(s - x, ind, 0));
P.push(info(t - x, ind, 1));
}
int ind = 0;
set<int> S;
fill(ans, ans + Q, -1);
while (!P.empty())
{
info x = P.top();
P.pop();
ll next_t = get<0>(x);
int point = get<1>(x);
bool start = (get<2>(x) == 0);
#if DEBUG == 1
cerr << "next_t = " << next_t << endl;
#endif
while (next_t > D[ind])
{
int a = -1;
if (S.empty())
{
a = -1;
}
else
{
a = *S.begin();
}
ans[ind] = a;
#if DEBUG == 1
cerr << "ans[" << ind << "] = " << ans[ind] << endl;
#endif
ind++;
if (ind == Q)
{
goto EXIT;
}
}
if (start)
{
S.insert(point);
#if DEBUG == 1
cerr << "insert: " << point << endl;
#endif
}
else
{
S.erase(S.find(point));
#if DEBUG == 1
cerr << "erase: " << point << endl;
#endif
}
}
EXIT:
for (auto i = 0; i < Q; i++)
{
if (ans[i] == -1)
{
cout << -1 << endl;
}
else
{
cout << X[ans[i]] << endl;
}
}
}<|endoftext|> |
<commit_before>#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include <string>
#include <cmath>
//Moving these to a seperate namespace for minimal global namespace cluttering does not work with clang++
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
namespace SimpleWeb {
//type must support size(), resize() and operator[]
namespace Crypto {
namespace Base64 {
template<class type>
void encode(const type& ascii, type& base64) {
BIO *bio, *b64;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new(BIO_s_mem());
BIO_push(b64, bio);
BIO_get_mem_ptr(b64, &bptr);
//Write directly to base64-buffer to avoid copy
int base64_length=round(4*ceil((double)ascii.size()/3.0));
base64.resize(base64_length);
bptr->length=0;
bptr->max=base64_length+1;
bptr->data=(char*)&base64[0];
BIO_write(b64, &ascii[0], ascii.size());
BIO_flush(b64);
//To keep &base64[0] through BIO_free_all(b64)
bptr->length=0;
bptr->max=0;
bptr->data=nullptr;
BIO_free_all(b64);
}
template<class type>
type encode(const type& ascii) {
type base64;
encode(ascii, base64);
return base64;
}
template<class type>
void decode(const type& base64, type& ascii) {
//Resize ascii, however, the size is a up to two bytes too large.
ascii.resize((6*base64.size())/8);
BIO *b64, *bio;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new_mem_buf((char*)&base64[0], base64.size());
bio = BIO_push(b64, bio);
int decoded_length = BIO_read(bio, &ascii[0], ascii.size());
ascii.resize(decoded_length);
BIO_free_all(b64);
}
template<class type>
type decode(const type& base64) {
type ascii;
decode(base64, ascii);
return ascii;
}
}
template<class type>
void MD5(const type& input, type& hash) {
hash.resize(128/8);
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, &input[0], input.size());
MD5_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type MD5(const type& input) {
type hash;
MD5(input, hash);
return hash;
}
template<class type>
void SHA1(const type& input, type& hash) {
hash.resize(160/8);
SHA_CTX context;
SHA1_Init(&context);
SHA1_Update(&context, &input[0], input.size());
SHA1_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA1(const type& input) {
type hash;
SHA1(input, hash);
return hash;
}
template<class type>
void SHA256(const type& input, type& hash) {
hash.resize(256/8);
SHA256_CTX context;
SHA256_Init(&context);
SHA256_Update(&context, &input[0], input.size());
SHA256_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA256(const type& input) {
type hash;
SHA256(input, hash);
return hash;
}
template<class type>
void SHA512(const type& input, type& hash) {
hash.resize(512/8);
SHA512_CTX context;
SHA512_Init(&context);
SHA512_Update(&context, &input[0], input.size());
SHA512_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA512(const type& input) {
type hash;
SHA512(input, hash);
return hash;
}
}
}
#endif /* CRYPTO_HPP */
<commit_msg>Hash functions can now be run iteratively with the two-parameter versions.<commit_after>#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include <string>
#include <cmath>
//Moving these to a seperate namespace for minimal global namespace cluttering does not work with clang++
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
namespace SimpleWeb {
//type must support size(), resize() and operator[]
namespace Crypto {
namespace Base64 {
template<class type>
void encode(const type& ascii, type& base64) {
BIO *bio, *b64;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new(BIO_s_mem());
BIO_push(b64, bio);
BIO_get_mem_ptr(b64, &bptr);
//Write directly to base64-buffer to avoid copy
int base64_length=round(4*ceil((double)ascii.size()/3.0));
base64.resize(base64_length);
bptr->length=0;
bptr->max=base64_length+1;
bptr->data=(char*)&base64[0];
BIO_write(b64, &ascii[0], ascii.size());
BIO_flush(b64);
//To keep &base64[0] through BIO_free_all(b64)
bptr->length=0;
bptr->max=0;
bptr->data=nullptr;
BIO_free_all(b64);
}
template<class type>
type encode(const type& ascii) {
type base64;
encode(ascii, base64);
return base64;
}
template<class type>
void decode(const type& base64, type& ascii) {
//Resize ascii, however, the size is a up to two bytes too large.
ascii.resize((6*base64.size())/8);
BIO *b64, *bio;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new_mem_buf((char*)&base64[0], base64.size());
bio = BIO_push(b64, bio);
int decoded_length = BIO_read(bio, &ascii[0], ascii.size());
ascii.resize(decoded_length);
BIO_free_all(b64);
}
template<class type>
type decode(const type& base64) {
type ascii;
decode(base64, ascii);
return ascii;
}
}
template<class type>
void MD5(const type& input, type& hash) {
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, &input[0], input.size());
hash.resize(128/8);
MD5_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type MD5(const type& input) {
type hash;
MD5(input, hash);
return hash;
}
template<class type>
void SHA1(const type& input, type& hash) {
SHA_CTX context;
SHA1_Init(&context);
SHA1_Update(&context, &input[0], input.size());
hash.resize(160/8);
SHA1_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA1(const type& input) {
type hash;
SHA1(input, hash);
return hash;
}
template<class type>
void SHA256(const type& input, type& hash) {
SHA256_CTX context;
SHA256_Init(&context);
SHA256_Update(&context, &input[0], input.size());
hash.resize(256/8);
SHA256_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA256(const type& input) {
type hash;
SHA256(input, hash);
return hash;
}
template<class type>
void SHA512(const type& input, type& hash) {
SHA512_CTX context;
SHA512_Init(&context);
SHA512_Update(&context, &input[0], input.size());
hash.resize(512/8);
SHA512_Final((unsigned char*)&hash[0], &context);
}
template<class type>
type SHA512(const type& input) {
type hash;
SHA512(input, hash);
return hash;
}
}
}
#endif /* CRYPTO_HPP */
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 6/11/2019, 7:17:01 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return mint(0) - *this; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
int H, W;
string S[100010];
int X[2010][2010];
int Y[2010][2010];
int main()
{
// init();
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
cin >> S[i];
}
for (auto i = 0; i < H; i++)
{
int t = 0;
for (auto j = 0; j < W; j++)
{
if (S[i][j] == '.')
{
t++;
}
else
{
for (auto k = j - 1; k >= j - t; k--)
{
X[i][k] = t;
}
}
}
for (auto k = W - 1; k >= W - t; k--)
{
X[i][k] = t;
}
}
for (auto j = 0; j < W; j++)
{
int t = 0;
for (auto i = 0; i < H; i++)
{
if (S[i][j] == '.')
{
t++;
}
else
{
for (auto k = i - 1; k >= i - t; k--)
{
Y[k][j] = t;
}
}
}
for (auto k = H - 1; k >= H - t; k--)
{
Y[k][j] = t;
}
}
int ans = 0;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
maxs(ans, X[i][j] + Y[i][j] - 1);
}
}
cout << ans << endl;
}<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 6/11/2019, 7:17:01 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return mint(0) - *this; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
int H, W;
string S[100010];
int X[2010][2010];
int Y[2010][2010];
int main()
{
// init();
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
cin >> S[i];
}
for (auto i = 0; i < H; i++)
{
int t = 0;
for (auto j = 0; j < W; j++)
{
if (S[i][j] == '.')
{
t++;
}
else
{
for (auto k = j - 1; k >= j - t; k--)
{
X[i][k] = t;
}
}
}
for (auto k = W - 1; k >= W - t; k--)
{
X[i][k] = t;
}
}
for (auto j = 0; j < W; j++)
{
int t = 0;
for (auto i = 0; i < H; i++)
{
if (S[i][j] == '.')
{
t++;
}
else
{
for (auto k = i - 1; k >= i - t; k--)
{
Y[k][j] = t;
}
}
}
for (auto k = H - 1; k >= H - t; k--)
{
Y[k][j] = t;
}
}
#if DEBUG == 1
cerr << "X:" << endl;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
cerr << X[i][j];
}
cerr << endl;
}
cerr << "Y:" << endl;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
cerr << Y[i][j];
}
cerr << endl;
}
#endif
int ans = 0;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
maxs(ans, X[i][j] + Y[i][j] - 1);
}
}
cout << ans << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
error,
};
class Go
{
public:
ban B;
vector<int> cnt = vector<int>(2, 0);
Go() {}
Go(ban V) : B(V)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = 0; a < 8; a++)
{
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + dx[a] * k;
int y = j + dy[a] * k;
if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::error;
}
bool black_turn = (t == 1);
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
else
{
return state::error;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
else
{
return state::error;
}
}
else
{
if (black_turn)
{
return state::black_even;
}
else
{
return state::white_even;
}
}
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
#if DEBUG == 1
cerr << I.cnt[0] << " VS " << I.cnt[1] << endl;
cerr << "I_state: " << (int)I_state << endl;
#endif
if (I_state == state::error)
{
No();
}
if (I_state == state::white_even || I_state == state::black_even)
{
assert(false);
Yes();
}
if (I_state == state::black_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::white_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
cerr << before.cnt[0] << " VS " << before.cnt[1] << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'x')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::black_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
}<commit_msg>submit C.cpp to 'C - 五目並べチェッカー' (arc012) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
error,
};
class Go
{
public:
ban B;
vector<int> cnt = vector<int>(2, 0);
Go() {}
Go(ban V) : B(V)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = 0; a < 8; a++)
{
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + dx[a] * k;
int y = j + dy[a] * k;
if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::error;
}
bool black_turn = (t == 1);
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
else
{
return state::error;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
else
{
return state::error;
}
}
else
{
if (black_turn)
{
return state::black_even;
}
else
{
return state::white_even;
}
}
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
#if DEBUG == 1
cerr << I.cnt[0] << " VS " << I.cnt[1] << endl;
cerr << "I_state: " << (int)I_state << endl;
#endif
if (I_state == state::error)
{
assert(false);
No();
}
if (I_state == state::white_even || I_state == state::black_even)
{
Yes();
}
if (I_state == state::black_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::white_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
cerr << before.cnt[0] << " VS " << before.cnt[1] << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'x')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::black_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 8/5/2019, 1:06:42 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
template <typename T>
class SegTree
{ // 0-indexed, [0, N).
private:
int N;
T *dat;
T UNIT; // モノイドの単位元
static T func(T x, T y)
{ // ここで演算を定義する。圏、特にモノイドであればなんでも良い。
// 実装はモノイドであるとする。
// return min(x, y);
return x + y;
}
static T _update(T x, T y)
{ // update で 値をどうするかを書く。
// return y;
return func(x, y);
}
public:
SegTree() {}
SegTree(int n, T unit)
{ // ここで unit を定義するのも変な実装だけどめんどいからこれでいい。
// min の場合は INFTY = (1LL << 60)
// + の場合は 0 とする。
UNIT = unit;
N = 1;
while (N < n)
{
N *= 2;
}
dat = new T[2 * N - 1];
for (auto i = 0; i < 2 * N - 1; ++i)
{
dat[i] = UNIT;
}
}
void update(int k, T a)
{
k += N - 1;
dat[k] = _update(dat[k], a);
while (k > 0)
{
k = (k - 1) / 2;
dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
private:
T find(int a, int b, int k, int l, int r)
{
if (r <= a || b <= l)
return UNIT;
if (a <= l && r <= b)
return dat[k];
T vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
T vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
return func(vl, vr);
}
public:
T find(int a, int b)
{ // [a, b) の find をする。
return find(a, b, 0, 0, N);
}
};
using info = tuple<ll, ll, ll, ll>;
using point = tuple<ll, ll, int>;
int N;
vector<point> V;
vector<info> I;
mint f(info x)
{
ll a, b, c, d;
tie(a, b, c, d) = x;
mint res = 0;
#if DEBUG == 1
cerr << "(" << a << ", " << b << ", " << c << ", " << d << ")" << endl;
#endif
res += mint{2}.power(N) - 1;
res -= mint{2}.power(a + b);
res -= mint{2}.power(a + c);
res -= mint{2}.power(b + d);
res -= mint{2}.power(c + d);
res += mint{2}.power(a);
res += mint{2}.power(b);
res += mint{2}.power(c);
res += mint{2}.power(d);
#if DEBUG == 1
cerr << res << endl;
#endif
return res;
}
int main()
{
cin >> N;
set<int> set_x, set_y;
for (auto i = 0; i < N; i++)
{
int x, y;
cin >> x >> y;
V.emplace_back(x, y, i);
set_x.insert(x);
set_y.insert(y);
}
I.resize(N);
map<int, int> map_x, map_y;
{
auto it = set_x.begin();
for (auto i = 0; i < N; i++)
{
map_x[*it] = i;
++it;
}
}
{
auto it = set_y.begin();
for (auto i = 0; i < N; i++)
{
map_y[*it] = i;
++it;
}
}
for (auto i = 0; i < N; i++)
{
get<0>(V[i]) = map_x[get<0>(V[i])];
get<1>(V[i]) = map_y[get<0>(V[i])];
}
sort(V.begin(), V.end());
{
SegTree<ll> tree{N, 0};
for (auto i = 0; i < N; i++)
{
int x, y, ind;
tie(x, y, ind) = V[i];
ll k = tree.find(0, y);
get<0>(I[ind]) = k;
get<1>(I[ind]) = i - k;
tree.update(y, 1);
}
}
reverse(V.begin(), V.end());
{
SegTree<ll> tree{N, 0};
for (auto i = 0; i < N; i++)
{
int x, y, ind;
tie(x, y, ind) = V[i];
ll k = tree.find(0, y);
get<2>(I[ind]) = k;
get<3>(I[ind]) = i - k;
tree.update(y, 1);
}
}
mint ans = 0;
for (auto i = 0; i < N; i++)
{
ans += f(I[i]);
}
cout << ans << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 8/5/2019, 1:06:42 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
template <typename T>
class SegTree
{ // 0-indexed, [0, N).
private:
int N;
T *dat;
T UNIT; // モノイドの単位元
static T func(T x, T y)
{ // ここで演算を定義する。圏、特にモノイドであればなんでも良い。
// 実装はモノイドであるとする。
// return min(x, y);
return x + y;
}
static T _update(T x, T y)
{ // update で 値をどうするかを書く。
// return y;
return func(x, y);
}
public:
SegTree() {}
SegTree(int n, T unit)
{ // ここで unit を定義するのも変な実装だけどめんどいからこれでいい。
// min の場合は INFTY = (1LL << 60)
// + の場合は 0 とする。
UNIT = unit;
N = 1;
while (N < n)
{
N *= 2;
}
dat = new T[2 * N - 1];
for (auto i = 0; i < 2 * N - 1; ++i)
{
dat[i] = UNIT;
}
}
void update(int k, T a)
{
k += N - 1;
dat[k] = _update(dat[k], a);
while (k > 0)
{
k = (k - 1) / 2;
dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
private:
T find(int a, int b, int k, int l, int r)
{
if (r <= a || b <= l)
return UNIT;
if (a <= l && r <= b)
return dat[k];
T vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
T vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
return func(vl, vr);
}
public:
T find(int a, int b)
{ // [a, b) の find をする。
return find(a, b, 0, 0, N);
}
};
using info = tuple<ll, ll, ll, ll>;
using point = tuple<ll, ll, int>;
int N;
vector<point> V;
vector<info> I;
mint f(info x)
{
ll a, b, c, d;
tie(a, b, d, c) = x;
mint res = 0;
#if DEBUG == 1
cerr << "(" << a << ", " << b << ", " << c << ", " << d << ")" << endl;
#endif
res += mint{2}.power(N) - 1;
res -= mint{2}.power(a + b);
res -= mint{2}.power(a + c);
res -= mint{2}.power(b + d);
res -= mint{2}.power(c + d);
res += mint{2}.power(a);
res += mint{2}.power(b);
res += mint{2}.power(c);
res += mint{2}.power(d);
#if DEBUG == 1
cerr << res << endl;
#endif
return res;
}
int main()
{
cin >> N;
set<int> set_x, set_y;
for (auto i = 0; i < N; i++)
{
int x, y;
cin >> x >> y;
V.emplace_back(x, y, i);
set_x.insert(x);
set_y.insert(y);
}
I.resize(N);
map<int, int> map_x, map_y;
{
auto it = set_x.begin();
for (auto i = 0; i < N; i++)
{
map_x[*it] = i;
++it;
}
}
{
auto it = set_y.begin();
for (auto i = 0; i < N; i++)
{
map_y[*it] = i;
++it;
}
}
for (auto i = 0; i < N; i++)
{
get<0>(V[i]) = map_x[get<0>(V[i])];
get<1>(V[i]) = map_y[get<0>(V[i])];
}
sort(V.begin(), V.end());
{
SegTree<ll> tree{N, 0};
for (auto i = 0; i < N; i++)
{
int x, y, ind;
tie(x, y, ind) = V[i];
ll k = tree.find(0, y);
get<0>(I[ind]) = k;
get<1>(I[ind]) = i - k;
tree.update(y, 1);
}
}
reverse(V.begin(), V.end());
{
SegTree<ll> tree{N, 0};
for (auto i = 0; i < N; i++)
{
int x, y, ind;
tie(x, y, ind) = V[i];
ll k = tree.find(0, y);
get<2>(I[ind]) = k;
get<3>(I[ind]) = i - k;
tree.update(y, 1);
}
}
mint ans = 0;
for (auto i = 0; i < N; i++)
{
ans += f(I[i]);
}
cout << ans << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : B.cpp
* Author : Kazune Takahashi
* Created : 12/28/2019, 10:05:50 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
class Solve
{
ll N, M, V, P;
vector<ll> A;
vector<ll> sum;
public:
Solve(ll N, ll M, ll V, ll P, vector<ll> A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)
{
sum[P - 1] = A[P - 1];
for (auto i = P; i < N; i++)
{
sum[P] = A[P] + sum[P - 1];
}
}
ll answer()
{
if (V <= P)
{
return answer0();
}
else
{
return answer1();
}
}
private:
ll answer0()
{
ll ans{0};
for (auto i = P; i < N; i++)
{
if (A[P - 1] <= A[i] + M)
{
ans++;
}
}
return ans + P;
}
ll answer1()
{
ll ok{P - 1};
ll ng{N};
if (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
#if DEBUG == 1
cerr << "t = " << t << endl;
#endif
if (test(t))
{
ok = t;
}
else
{
ng = t;
}
}
return ok + 1;
}
bool test(ll i)
{
ll K{V - (P - 1) - (N - i)};
if (K <= 0)
{
#if DEBUG == 1
cerr << "i = " << i << endl;
cerr << "A[" << i << "] = " << A[i] << endl;
cerr << "M = " << M << endl;
cerr << "P - 1 = " << P - 1 << endl;
cerr << "A[" << P - 1 << "] = " << A[P - 1] << endl;
#endif
return A[i] + M >= A[P - 1];
}
return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;
}
};
int main()
{
ll N, M, V, P;
cin >> N >> M >> V >> P;
vector<ll> A(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
sort(A.rbegin(), A.rend());
Solve solve(N, M, V, P, A);
cout << solve.answer() << endl;
}
<commit_msg>tried B.cpp to 'B'<commit_after>#define DEBUG 1
/**
* File : B.cpp
* Author : Kazune Takahashi
* Created : 12/28/2019, 10:05:50 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
class Solve
{
ll N, M, V, P;
vector<ll> A;
vector<ll> sum;
public:
Solve(ll N, ll M, ll V, ll P, vector<ll> A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)
{
sum[P - 1] = A[P - 1];
for (auto i = P; i < N; i++)
{
sum[P] = A[P] + sum[P - 1];
}
}
ll answer()
{
if (V <= P)
{
return answer0();
}
else
{
return answer1();
}
}
private:
ll answer0()
{
ll ans{0};
for (auto i = P; i < N; i++)
{
if (A[P - 1] <= A[i] + M)
{
ans++;
}
}
return ans + P;
}
ll answer1()
{
ll ok{P - 1};
ll ng{N};
while (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
#if DEBUG == 1
cerr << "t = " << t << endl;
#endif
if (test(t))
{
ok = t;
}
else
{
ng = t;
}
}
return ok + 1;
}
bool test(ll i)
{
ll K{V - (P - 1) - (N - i)};
if (K <= 0)
{
#if DEBUG == 1
cerr << "i = " << i << endl;
cerr << "A[" << i << "] = " << A[i] << endl;
cerr << "M = " << M << endl;
cerr << "P - 1 = " << P - 1 << endl;
cerr << "A[" << P - 1 << "] = " << A[P - 1] << endl;
#endif
return A[i] + M >= A[P - 1];
}
return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;
}
};
int main()
{
ll N, M, V, P;
cin >> N >> M >> V >> P;
vector<ll> A(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
sort(A.rbegin(), A.rend());
Solve solve(N, M, V, P, A);
cout << solve.answer() << endl;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2020/7/2 21:50:01
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
int main()
{
int n, m, x;
cin >> n >> m >> x;
vector<int> c(n);
vector<vector<int>> a(n, vector<int>(m));
for (auto i{0}; i < n; ++i)
{
cin >> c[i];
for (auto j{0}; j < m; ++j)
{
cin >> a[i][j];
}
}
int ans{Infty<int>()};
for (auto i{0}; i < (1 << n); ++i)
{
int cost{0};
vector<int> b(m, 0);
for (auto j{0}; j < n; ++j)
{
if (i >> n & 1)
{
cost += c[i];
}
for (auto k{0}; k < m; ++k)
{
b[k] += a[j][k];
}
}
if (all_of(b.begin(), b.end(), [&](auto t) { return t >= x; }))
{
ch_min(ans, cost);
}
}
if (ans == Infty<int>())
{
ans = -1;
}
cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2020/7/2 21:50:01
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
int main()
{
int n, m, x;
cin >> n >> m >> x;
vector<int> c(n);
vector<vector<int>> a(n, vector<int>(m));
for (auto i{0}; i < n; ++i)
{
cin >> c[i];
for (auto j{0}; j < m; ++j)
{
cin >> a[i][j];
}
}
int ans{Infty<int>()};
for (auto i{0}; i < (1 << n); ++i)
{
int cost{0};
vector<int> b(m, 0);
for (auto j{0}; j < n; ++j)
{
if (i >> n & 1)
{
cost += c[i];
}
for (auto k{0}; k < m; ++k)
{
b[k] += a[j][k];
}
}
if (all_of(b.begin(), b.end(), [&](auto t) { return t >= x; }))
{
#if DEBUG == 1
cerr << "i = " << i << endl;
cerr << "cost = " << cost << endl;
#endif
ch_min(ans, cost);
}
}
if (ans == Infty<int>())
{
ans = -1;
}
cout << ans << endl;
}
<|endoftext|> |
<commit_before>// Copyright 2014 Google Inc. All Rights Reserved
// Author: Wojtek Żółtak ([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "supersonic/contrib/storage/core/page_sink.h"
#include <vector>
#include "supersonic/base/infrastructure/types.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/exception/result.h"
#include "supersonic/contrib/storage/base/serializer.h"
#include "supersonic/contrib/storage/base/column_writer.h"
#include "supersonic/contrib/storage/core/data_type_serializer.h"
#include "supersonic/contrib/storage/base/storage_metadata.h"
#include "supersonic/contrib/storage/core/page_builder.h"
#include "supersonic/utils/exception/failureor.h"
#include "supersonic/proto/supersonic.pb.h"
namespace supersonic {
namespace {
const uint64_t kPageSizeLimit = 100 * 1024; // 100KB
class PageSinkImplementation : public PageSink {
public:
explicit PageSinkImplementation(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::unique_ptr<
std::vector<std::unique_ptr<ColumnWriter>>> column_writers,
std::shared_ptr<PageBuilder> page_builder,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family)
: finalized_(false),
builder_dirty_(false),
projector_(std::move(projector)),
page_stream_writer_(page_stream_writer),
column_writers_(std::move(column_writers)),
page_builder_(page_builder),
metadata_writer_(metadata_writer),
page_family_(page_family),
rows_in_page_(0) {}
virtual ~PageSinkImplementation() {
if (!finalized_) {
LOG(DFATAL)<< "Destroying not finalized PageSink.";
Finalize();
}
}
FailureOr<rowcount_t> Write(const View& data) {
if (finalized_) {
THROW(new Exception(ERROR_INVALID_STATE,
"Writing to finalized page sink."));
}
View projected_data(projector_->result_schema());
projected_data.set_row_count(data.row_count());
projector_->Project(data, &projected_data);
// TODO(wzoltak): Check if schema matches in debug mode?
for (int column_index = 0; column_index < projected_data.column_count();
column_index++) {
FailureOrVoid write_result = (*column_writers_)[column_index]
->WriteColumn(projected_data.column(column_index),
projected_data.row_count());
PROPAGATE_ON_FAILURE(write_result);
}
builder_dirty_ = builder_dirty_ || projected_data.row_count() > 0;
rows_in_page_ += data.row_count();
if (page_builder_->PageSize() > kPageSizeLimit) {
FailureOrVoid written_page = WritePage();
PROPAGATE_ON_FAILURE(written_page);
}
return Success(projected_data.row_count());
}
FailureOrVoid Finalize() {
if (!finalized_) {
if (builder_dirty_) {
PROPAGATE_ON_FAILURE(WritePage());
}
finalized_ = true;
}
return Success();
}
size_t BytesInPage() {
return page_builder_->PageSize();
}
private:
FailureOrVoid WritePage() {
FailureOrOwned<Page> page_result = page_builder_->CreatePage();
PROPAGATE_ON_FAILURE(page_result);
std::unique_ptr<Page> page(page_result.release());
auto page_number = page_stream_writer_->AppendPage(page_family_, *page);
PROPAGATE_ON_FAILURE(page_number);
PageMetadata page_metadata;
page_metadata.set_page_number(page_number.get());
page_metadata.set_row_count(rows_in_page_);
PROPAGATE_ON_FAILURE(
metadata_writer_->AppendPage(page_family_, page_metadata));
page_builder_->Reset();
builder_dirty_ = false;
rows_in_page_ = 0;
return Success();
}
bool finalized_;
bool builder_dirty_;
std::unique_ptr<const BoundSingleSourceProjector> projector_;
std::shared_ptr<PageStreamWriter> page_stream_writer_;
std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > column_writers_;
std::shared_ptr<PageBuilder> page_builder_;
std::shared_ptr<MetadataWriter> metadata_writer_;
uint32_t page_family_;
uint64 rows_in_page_;
DISALLOW_COPY_AND_ASSIGN(PageSinkImplementation);
};
} // namespace
FailureOrOwned<PageSink> CreatePageSink(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family,
BufferAllocator* buffer_allocator) {
std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > serializers(
new std::vector<std::unique_ptr<ColumnWriter> >());
std::shared_ptr<PageBuilder> page_builder(
new PageBuilder(0, buffer_allocator));
const TupleSchema& schema = projector->result_schema();
int streams_count = 0;
for (int i = 0; i < schema.attribute_count(); i++) {
const Attribute& attribute = schema.attribute(i);
FailureOrOwned<ColumnWriter> column_writer_result = CreateColumnWriter(
attribute, page_builder, streams_count);
PROPAGATE_ON_FAILURE(column_writer_result);
streams_count += column_writer_result->uses_streams();
serializers->emplace_back(column_writer_result.release());
}
page_builder->Reset(streams_count);
std::unique_ptr<PageSinkImplementation> sink(
new PageSinkImplementation(std::move(projector),
page_stream_writer,
std::move(serializers),
page_builder,
metadata_writer,
page_family));
return Success(sink.release());
}
// Factory function for testing purposes.
FailureOrOwned<PageSink> CreatePageSink(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::unique_ptr<
std::vector<std::unique_ptr<ColumnWriter> > > column_writers,
std::shared_ptr<PageBuilder> page_builder,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family) {
std::unique_ptr<PageSinkImplementation> page_sink(
new PageSinkImplementation(std::move(projector),
page_stream_writer,
std::move(column_writers),
page_builder,
metadata_writer,
page_family));
return Success(page_sink.release());
}
} // namespace supersonic
<commit_msg>512 page size limit.<commit_after>// Copyright 2014 Google Inc. All Rights Reserved
// Author: Wojtek Żółtak ([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "supersonic/contrib/storage/core/page_sink.h"
#include <vector>
#include "supersonic/base/infrastructure/types.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/exception/result.h"
#include "supersonic/contrib/storage/base/serializer.h"
#include "supersonic/contrib/storage/base/column_writer.h"
#include "supersonic/contrib/storage/core/data_type_serializer.h"
#include "supersonic/contrib/storage/base/storage_metadata.h"
#include "supersonic/contrib/storage/core/page_builder.h"
#include "supersonic/utils/exception/failureor.h"
#include "supersonic/proto/supersonic.pb.h"
namespace supersonic {
namespace {
const uint64_t kPageSizeLimit = 512 * 1024; // 512KB
class PageSinkImplementation : public PageSink {
public:
explicit PageSinkImplementation(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::unique_ptr<
std::vector<std::unique_ptr<ColumnWriter>>> column_writers,
std::shared_ptr<PageBuilder> page_builder,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family)
: finalized_(false),
builder_dirty_(false),
projector_(std::move(projector)),
page_stream_writer_(page_stream_writer),
column_writers_(std::move(column_writers)),
page_builder_(page_builder),
metadata_writer_(metadata_writer),
page_family_(page_family),
rows_in_page_(0) {}
virtual ~PageSinkImplementation() {
if (!finalized_) {
LOG(DFATAL)<< "Destroying not finalized PageSink.";
Finalize();
}
}
FailureOr<rowcount_t> Write(const View& data) {
if (finalized_) {
THROW(new Exception(ERROR_INVALID_STATE,
"Writing to finalized page sink."));
}
View projected_data(projector_->result_schema());
projected_data.set_row_count(data.row_count());
projector_->Project(data, &projected_data);
// TODO(wzoltak): Check if schema matches in debug mode?
for (int column_index = 0; column_index < projected_data.column_count();
column_index++) {
FailureOrVoid write_result = (*column_writers_)[column_index]
->WriteColumn(projected_data.column(column_index),
projected_data.row_count());
PROPAGATE_ON_FAILURE(write_result);
}
builder_dirty_ = builder_dirty_ || projected_data.row_count() > 0;
rows_in_page_ += data.row_count();
if (page_builder_->PageSize() > kPageSizeLimit) {
FailureOrVoid written_page = WritePage();
PROPAGATE_ON_FAILURE(written_page);
}
return Success(projected_data.row_count());
}
FailureOrVoid Finalize() {
if (!finalized_) {
if (builder_dirty_) {
PROPAGATE_ON_FAILURE(WritePage());
}
finalized_ = true;
}
return Success();
}
size_t BytesInPage() {
return page_builder_->PageSize();
}
private:
FailureOrVoid WritePage() {
FailureOrOwned<Page> page_result = page_builder_->CreatePage();
PROPAGATE_ON_FAILURE(page_result);
std::unique_ptr<Page> page(page_result.release());
auto page_number = page_stream_writer_->AppendPage(page_family_, *page);
PROPAGATE_ON_FAILURE(page_number);
PageMetadata page_metadata;
page_metadata.set_page_number(page_number.get());
page_metadata.set_row_count(rows_in_page_);
PROPAGATE_ON_FAILURE(
metadata_writer_->AppendPage(page_family_, page_metadata));
page_builder_->Reset();
builder_dirty_ = false;
rows_in_page_ = 0;
return Success();
}
bool finalized_;
bool builder_dirty_;
std::unique_ptr<const BoundSingleSourceProjector> projector_;
std::shared_ptr<PageStreamWriter> page_stream_writer_;
std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > column_writers_;
std::shared_ptr<PageBuilder> page_builder_;
std::shared_ptr<MetadataWriter> metadata_writer_;
uint32_t page_family_;
uint64 rows_in_page_;
DISALLOW_COPY_AND_ASSIGN(PageSinkImplementation);
};
} // namespace
FailureOrOwned<PageSink> CreatePageSink(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family,
BufferAllocator* buffer_allocator) {
std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > serializers(
new std::vector<std::unique_ptr<ColumnWriter> >());
std::shared_ptr<PageBuilder> page_builder(
new PageBuilder(0, buffer_allocator));
const TupleSchema& schema = projector->result_schema();
int streams_count = 0;
for (int i = 0; i < schema.attribute_count(); i++) {
const Attribute& attribute = schema.attribute(i);
FailureOrOwned<ColumnWriter> column_writer_result = CreateColumnWriter(
attribute, page_builder, streams_count);
PROPAGATE_ON_FAILURE(column_writer_result);
streams_count += column_writer_result->uses_streams();
serializers->emplace_back(column_writer_result.release());
}
page_builder->Reset(streams_count);
std::unique_ptr<PageSinkImplementation> sink(
new PageSinkImplementation(std::move(projector),
page_stream_writer,
std::move(serializers),
page_builder,
metadata_writer,
page_family));
return Success(sink.release());
}
// Factory function for testing purposes.
FailureOrOwned<PageSink> CreatePageSink(
std::unique_ptr<const BoundSingleSourceProjector> projector,
std::shared_ptr<PageStreamWriter> page_stream_writer,
std::unique_ptr<
std::vector<std::unique_ptr<ColumnWriter> > > column_writers,
std::shared_ptr<PageBuilder> page_builder,
std::shared_ptr<MetadataWriter> metadata_writer,
uint32_t page_family) {
std::unique_ptr<PageSinkImplementation> page_sink(
new PageSinkImplementation(std::move(projector),
page_stream_writer,
std::move(column_writers),
page_builder,
metadata_writer,
page_family));
return Success(page_sink.release());
}
} // namespace supersonic
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 AST_PROGRAM_H
#define AST_PROGRAM_H
#include <vector>
#include <boost/variant/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/home/support/attributes.hpp>
#include "ast/FunctionDeclaration.hpp"
#include "ast/GlobalVariableDeclaration.hpp"
namespace eddic {
typedef boost::variant<FunctionDeclaration, GlobalVariableDeclaration> FirstLevelBlock;
typedef std::vector<FirstLevelBlock> ProgramEquivalence;
//A source EDDI program
struct Program {
std::vector<FirstLevelBlock> blocks;
};
} //end of eddic
//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
eddic::Program,
(std::vector<eddic::FirstLevelBlock>, blocks)
)
//Enable the use as one-attribute
namespace boost { namespace spirit { namespace traits {
/*
template <>
struct assign_to_attribute_from_value <eddic::Program, eddic::ProgramEquivalence, qi::domain> {
static void call(const eddic::ProgramEquivalence& val, eddic::Program& attr){
attr.blocks = val;
}
};
*/
/*
template<>
struct transform_attribute<eddic::Program, std::vector<eddic::FirstLevelBlock>, qi::domain> {
typedef std::vector<eddic::FirstLevelBlock>& type;
static type pre(eddic::Program& program) { return program.blocks; }
static void post(eddic::Program&, const type) {}
static void fail(eddic::Program&) {}
};*/
}}}
#endif
<commit_msg>Remove old stuff<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 AST_PROGRAM_H
#define AST_PROGRAM_H
#include <vector>
#include <boost/variant/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/home/support/attributes.hpp>
#include "ast/FunctionDeclaration.hpp"
#include "ast/GlobalVariableDeclaration.hpp"
namespace eddic {
typedef boost::variant<FunctionDeclaration, GlobalVariableDeclaration> FirstLevelBlock;
typedef std::vector<FirstLevelBlock> ProgramEquivalence;
//A source EDDI program
struct Program {
std::vector<FirstLevelBlock> blocks;
};
} //end of eddic
//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
eddic::Program,
(std::vector<eddic::FirstLevelBlock>, blocks)
)
#endif
<|endoftext|> |
<commit_before>/*
* File: cubicspline.cpp
* Author: ruehle
*
* Created on August 22, 2008, 4:44 PM
*/
#include <cubicspline.h>
void CubicSpline::Fit(ub::vector<double> x, ub::vector<double> y)
{
ub::matrix<double> A;
A.resize(_r.size*4, x.size());
}
<commit_msg>compiles now again<commit_after>/*
* File: cubicspline.cpp
* Author: ruehle
*
* Created on August 22, 2008, 4:44 PM
*/
#include <cubicspline.h>
void CubicSpline::Fit(ub::vector<double> x, ub::vector<double> y)
{
// ub::matrix<double> A;
// A.resize(_r.size*4, x.size());
}
<|endoftext|> |
<commit_before>#include <sys/time.h>
#include <glib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;
struct timeval startTV;
struct timeval nextReportTV;
struct timeval intervalTV;
long int count =0;
pthread_t thread1;
int port;
char* hostname = "192.168.1.2";
char *stringString = "local.garden.water.counter";
void error(char *msg)
{
perror(msg);
exit(0);
}
int send(int portno, struct hostent* server, char *msg)
{
int sockfd, n;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
perror("ERROR connecting");
} else {
n = write(sockfd,msg,strlen(msg));
if (n < 0)
perror("ERROR writing to socket");
close(sockfd);
}
return 0;
}
int timeval_subtract (struct timeval *result,struct timeval *x,struct timeval *y )
{
// Perform the carry for the later subtraction by updating y.
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
// Compute the time remaining to wait. tv_usec is certainly positive.
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
// Return 1 if result is negative.
return x->tv_sec < y->tv_sec;
}
void timeval_add(struct timeval *result,struct timeval *x,struct timeval *y )
{
long int sec =0;
long int usec_sum = x->tv_usec + y->tv_usec;
while(usec_sum > 1000000 ) {
usec_sum = usec_sum - 1000000;
sec = sec + 1;
}
sec = y->tv_sec + x->tv_sec + sec;
// Compute the time remaining to wait. tv_usec is certainly positive.
result->tv_sec = sec;
result->tv_usec = usec_sum;;
}
void report(long int cnt, struct timeval *now, struct timeval *interval) {
char buf[255];
long ts = time(NULL);
sprintf(buf,"%s %d %u\n",stringString, cnt,ts);
struct hostent *server = gethostbyname(hostname);
send(port, server, buf);
}
void* reportThreadRun(void *ptr) {
while(true) {
struct timeval nowTV;
gettimeofday(&nowTV,NULL);
if(nextReportTV.tv_sec ==0) {
// first time out
timeval_add(&nextReportTV, &nowTV, &intervalTV);
cerr << "first time" << endl;
} else {
// ok now we have something real.
struct timeval deltaTV;
int neg = timeval_subtract (&deltaTV,&nextReportTV,&nowTV );
cerr << "other times, neg:" << neg << " deltaTV " << deltaTV.tv_sec << " count: "<< count << endl;
if(neg ) {
// the future
timeval_add(&nextReportTV, &nowTV, &intervalTV);
// add the delta which is now negative to get next point
if(deltaTV.tv_sec > -60 ) {
timeval_add(&nextReportTV, &nextReportTV, &deltaTV);
} else {
// this means either we really lamed out on response time, or the time actually changed.
// either way we don't want to add in that negative this
}
cerr << "-- report " << endl;
report(count,&intervalTV,&nowTV);
}
}
sleep(1);
//cerr << " and loop" << endl;
}
}
static gboolean onTransitionEvent( GIOChannel *channel,
GIOCondition condition,
gpointer user_data )
{
GError *error = 0;
gsize bytes_read = 0;
int buf_sz = 255;
char buf[buf_sz];
g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
GIOStatus rc = g_io_channel_read_chars( channel,
buf, buf_sz - 1,
&bytes_read,
&error );
count++;
if(rc == G_IO_STATUS_NORMAL) {
//cerr << " data:" << buf << endl;
} else {
cerr << "something was wrong, rc = " << rc << endl;
}
// thank you, call again!
return 1;
}
int main( int argc, char** argv )
{
int iret1;
GMainLoop* loop = g_main_loop_new( 0, 0 );
intervalTV.tv_sec=60;
intervalTV.tv_usec =0;
char *portString = "2003";
char *intervalString = "60";
int opt;
while ((opt = getopt(argc, argv, "p:h:s:i:")) != -1) {
switch (opt) {
case 'p':
portString = optarg;
break;
case 'h':
hostname = optarg;
break;
case 's':
stringString = optarg;
break;
case 'i':
intervalString = optarg;
break;
default:
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}
}
port = atoi(portString);
intervalTV.tv_sec = atoi(intervalString);
cout << " will send data to " << hostname << ":" << port << " to key " << stringString << " at interval " << intervalTV.tv_sec << " seconds " << endl;
gettimeofday(&startTV,NULL);
nextReportTV.tv_sec =0;;
int fd = open( "/sys/class/gpio/gpio30/value", O_RDONLY | O_NONBLOCK );
if(fd < 0) {
cerr << "unable to open the GPIO 'file'. Did you set that stuff up proerly ?. Will now exit ";
exit(-1);
}
GIOChannel* channel = g_io_channel_unix_new( fd );
GIOCondition cond = GIOCondition( G_IO_PRI );
guint id = g_io_add_watch( channel, cond, onTransitionEvent, 0 );
cerr << "creating thread";
iret1 = pthread_create( &thread1, NULL, reportThreadRun, NULL);
cerr << "thread created";
g_main_loop_run( loop );
pthread_join( thread1, NULL);
}
<commit_msg>more changes for more stuff monitored<commit_after>#include <sys/time.h>
#include <glib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
using namespace std;
#define MAX_BUF 64 //This is plenty large
int port;
char* hostname = "192.168.1.2";
char *stringString = "local.garden.water.counter";
struct CountUp {
string gpio;
long int count;
string reportingString;
guint id;
};
void error(char *msg)
{
perror(msg);
exit(0);
}
int send(int portno, struct hostent* server, char *msg)
{
int sockfd, n;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
n = write(sockfd,msg,strlen(msg));
if (n < 0)
error("ERROR writing to socket");
return 0;
}
//Function definitions
int readADC(unsigned int pin)
{
int fd; //file pointer
char buf[MAX_BUF]; //file buffer
char val[4]; //holds up to 4 digits for ADC value
//Create the file path by concatenating the ADC pin number to the end of the string
//Stores the file path name string into "buf"
snprintf(buf, sizeof(buf), "/sys/devices/ocp.2/helper.14/AIN%d", pin); //Concatenate ADC file name
fd = open(buf, O_RDONLY); //open ADC as read only
//Will trigger if the ADC is not enabled
if (fd < 0) {
perror("ADC - problem opening ADC");
}//end if
read(fd, &val, 4); //read ADC ing val (up to 4 digits 0-1799)
close(fd); //close file and stop reading
return atoi(val); //returns an integer value (rather than ascii)
}//end read ADC()
static gboolean sendTimerCallback (gpointer user_data) {
CountUp* countups = (CountUp*)user_data;
int lenArr = sizeof(countups)/sizeof(countups[0]);
for(int i=0; i < lenArr; i++) {
long int cnt = countups[i].count;
string reportString = countups[i].reportingString;
char buf[255];
long ts = time(NULL);
sprintf(buf,"%s %d %u\n",reportString.c_str(),cnt,ts);
struct hostent *server = gethostbyname("192.168.1.2");
send(2003, server, buf);
}
return 1;
}
static gboolean onTransitionEvent( GIOChannel *channel,
GIOCondition condition,
gpointer user_data )
{
GError *error = 0;
gsize bytes_read = 0;
int buf_sz = 255;
char buf[buf_sz];
CountUp* pCountUpStruct = (CountUp*) user_data;
g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
GIOStatus rc = g_io_channel_read_chars( channel,
buf, buf_sz - 1,
&bytes_read,
&error );
if(rc == G_IO_STATUS_NORMAL) {
cerr << " data:" << buf << endl;
} else {
cerr << "something was wrong, rc = " << rc << endl;
}
pCountUpStruct->count++;
// thank you, call again!
return 1;
}
int main( int argc, char** argv )
{
char *portString = "2003";
char *intervalString = "60";
char *hostname = "192.168.1.2";
char *intervalString = "120";
int opt;
while ((opt = getopt(argc, argv, "p:h:s:i:")) != -1) {
switch (opt) {
case 'p':
portString = optarg;
break;
case 'h':
hostname = optarg;
break;
case 's':
stringString = optarg;
break;
case 'i':
intervalString = optarg;
break;
default:
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}
}
port = atoi(portString);
interval = atoi(intervalString);
CountUp countups[]={
{ "gpio30", 0, "waterCount" },
{ "James", 0, "waterCount" },
{ "John", 0, "waterCount" },
{ "Mike", 0, "waterCount" }
};
GMainLoop* loop = g_main_loop_new( 0, 0 );
int lenArr = sizeof(countups)/sizeof(countups[0]);
for(int i=0; i < lenArr; i++) {
string gpioDesc = "/sys/class/gpio/"+countups[i].gpio+"/value";
int fd = open( gpioDesc.c_str(), O_RDONLY | O_NONBLOCK );
GIOChannel* channel = g_io_channel_unix_new( fd );
GIOCondition cond = GIOCondition( G_IO_PRI );
guint id = g_io_add_watch( channel, cond, onTransitionEvent, &(countups[i]) );
}
guint sendIntervalSecs = 60 *2;
g_timeout_add_seconds(sendIntervalSecs,sendTimerCallback,countups);
g_main_loop_run( loop );
}
<|endoftext|> |
<commit_before>#include "Search.hpp"
#include "MoveIterator.hpp"
#include <limits>
using namespace std;
ThreadPool<maskedArguments> myThreadPool(NUM_OF_THREADS,&negaScoutWrapper);
search_result allResults[64][16*2-2];
atomic<int32_t> galpha_pl;
atomic<int32_t> gbeta__pl;
template<player pl, bool mainThread>
int32_t negaScout(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst){
#ifndef NDEBUG
++totalNodes;
#endif
//An ftasame sta katw katw fyla tote gyrname thn katastash
if(depth == 0){
#ifndef NDEBUG
++horizonNodes;
#endif
int32_t temp = veryVeryGreedyAndStupidEvaluationFunction(board);
temp = (pl == NORMAL) ? temp : -temp;
return temp;
}
uint64 hash = board.getHash();
int32_t alph = alpha, bet = beta;
//alpha beta are passed by reference!!!
int kiMove = tt.retrieveTTEntry(hash, depth, alph, bet, pl == PLACER);
if (alph >= bet) {
return alph;
}
int bmove = -1;
bool firstChild = true;
MoveIterator_t<BitBoard_t, pl, mainThread> mIt(board);
if (mainThread){
// if (pl == NORMAL){
galpha_pl = +alph;
gbeta__pl = (int) pl;
// } else {
// galpha_pl = +MIN_TT_SCORE ;
// gbeta__pl = -alph;
// }
}
int iter = 0;
while(true) {
tlocal_search_result tmp_r = mIt.searchNextChild(board, kiMove,
depth-1, alph, bet, firstChild, &(allResults[depth][iter].score));
kiMove = -1;
if (tmp_r.move == -1) break; //and rt.score is invalid
firstChild = false; //set this here
if(mainThread){//Template if
if(tmp_r.move < 0) {
allResults[depth][iter].move = -(2+tmp_r.move);
++iter;
continue;
}
}
//tmp_r.move is always non-negative if a valid move was played
//Setting firstChild here permits skipping the rest of current iteration
//if score must be ignored for now
//possible set a continue here such that if a new thread is used for
//subtree search, to skip score checking ?
//if (tmp_r.move < -1) continue;
//move played!
if (tmp_r.score >= bet){
tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
return bet; //fail-hard beta cut-off
}
if ((!mainThread) && ((int) pl) != gbeta__pl && tmp_r.score >= -galpha_pl){
// if ((!mainThread) && tmp_r.score >= ((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl)){
return -galpha_pl;//((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl);//MAX_TT_SCORE;
}
if (tmp_r.score > alph){ //better move found
if (mainThread){
// if (pl == NORMAL){
galpha_pl = +tmp_r.score;
// } else {
// gbeta__pl = -tmp_r.score;
// }
}
alph = tmp_r.score;
bmove = tmp_r.move;
assert(bmove >= 0);
}
}
//Wait for threads to finish and merge scores here
if(mainThread){
bool unfinished = false;
do {
unfinished = false;
for (int i = 0 ; i < iter ; ++i){
if (allResults[depth][i].score == 0) {
unfinished = true;
continue;
} else if (allResults[depth][i].move >= 0){
tlocal_search_result tmp_r;
tmp_r.score = allResults[depth][i].score;
tmp_r.move = allResults[depth][i].move;
allResults[depth][i].move = -5;
if (tmp_r.score >= bet){
for (int j = 0 ; j < iter ; ++j){
while(allResults[depth][j].score == 0 && allResults[depth][j].move >= 0){
this_thread::yield();
}
}
tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
return bet; //fail-hard beta cut-off
}
if (tmp_r.score > alph){ //better move found
// if (pl == NORMAL){
galpha_pl = +tmp_r.score;
// } else {
// gbeta__pl = -tmp_r.score;
// }
alph = tmp_r.score;
bmove = tmp_r.move;
assert(bmove >= 0);
}
}
}
} while (unfinished);
}
if (firstChild){ //no move was available, this is a leaf node, return score
board.assert_state();
assert(pl == NORMAL);
#ifndef NDEBUG
++horizonNodes;
#endif
bool a;
return board.getHigherTile(&a) << 2;
}
NodeType nt = PV__Node;
if (bmove < 0){ //All-Node
nt = All_Node;
bmove = 0;
}
tt.addTTEntry(hash, depth, bmove, alph, pl == PLACER, nt);
return alph;
}
template<player other, bool mainThread>
int32_t search_deeper(BitBoard_t &board, int32_t depth, int32_t alpha,
int32_t beta, bool firstChild){
int32_t score;
if(firstChild == true){
score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
} else {
// score = -negaScout<other, mainThread>(board, depth, -alpha-1, -alpha, firstChild);
// if(alpha < score){
score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
// }
}
return score;
}
void negaScoutWrapper(maskedArguments args){
int32_t data;
if (args.pl == player::PLACER){
data = search_deeper<player::PLACER,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
} else {
data = search_deeper<player::NORMAL,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
}
assert(data!=0);
*(args.writeResult) = data;
}
template<player other>
void spawnThread(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild, atomic<int32_t> *score){
maskedArguments args;
args.pl = other;
args.alpha = alpha;
args.beta = beta;
args.depth = depth;
args.board = board;
args.firstChild = firstChild;
args.writeResult = score;
myThreadPool.useNewThread(args);
}
int32_t veryVeryGreedyAndStupidEvaluationFunction(BitBoard_t boardForEv){
bool inCorner = false;
int32_t v2 = boardForEv.getHigherTile(&inCorner);
int32_t score = (v2 << 6) + 1;
if(inCorner){
score += boardForEv.getMaxCornerChain() << 5;
score <<= 2;
}
score += boardForEv.getMaxChain() << 4;
int tmp = boardForEv.countFreeTiles() - 7;
tmp = (tmp < 0) ? -tmp : tmp;
score += (7-tmp) << 2;
score += boardForEv.countTileTypes() << 2;
assert(score >= 0);
return score;
}
template int32_t negaScout<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t search_deeper<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
<commit_msg>Fixed busy wait of mainThread<commit_after>#include "Search.hpp"
#include "MoveIterator.hpp"
#include <limits>
using namespace std;
ThreadPool<maskedArguments> myThreadPool(NUM_OF_THREADS,&negaScoutWrapper);
search_result allResults[64][16*2-2];
atomic<int32_t> galpha_pl;
atomic<int32_t> gbeta__pl;
template<player pl, bool mainThread>
int32_t negaScout(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst){
#ifndef NDEBUG
++totalNodes;
#endif
//An ftasame sta katw katw fyla tote gyrname thn katastash
if(depth == 0){
#ifndef NDEBUG
++horizonNodes;
#endif
int32_t temp = veryVeryGreedyAndStupidEvaluationFunction(board);
temp = (pl == NORMAL) ? temp : -temp;
return temp;
}
uint64 hash = board.getHash();
int32_t alph = alpha, bet = beta;
//alpha beta are passed by reference!!!
int kiMove = tt.retrieveTTEntry(hash, depth, alph, bet, pl == PLACER);
if (alph >= bet) {
return alph;
}
int bmove = -1;
bool firstChild = true;
MoveIterator_t<BitBoard_t, pl, mainThread> mIt(board);
if (mainThread){
// if (pl == NORMAL){
galpha_pl = +alph;
gbeta__pl = (int) pl;
// } else {
// galpha_pl = +MIN_TT_SCORE ;
// gbeta__pl = -alph;
// }
}
int iter = 0;
while(true) {
tlocal_search_result tmp_r = mIt.searchNextChild(board, kiMove,
depth-1, alph, bet, firstChild, &(allResults[depth][iter].score));
kiMove = -1;
if (tmp_r.move == -1) break; //and rt.score is invalid
firstChild = false; //set this here
if(mainThread){//Template if
if(tmp_r.move < 0) {
allResults[depth][iter].move = -(2+tmp_r.move);
++iter;
continue;
}
}
//tmp_r.move is always non-negative if a valid move was played
//Setting firstChild here permits skipping the rest of current iteration
//if score must be ignored for now
//possible set a continue here such that if a new thread is used for
//subtree search, to skip score checking ?
//if (tmp_r.move < -1) continue;
//move played!
if (tmp_r.score >= bet){
tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
return bet; //fail-hard beta cut-off
}
if ((!mainThread) && ((int) pl) != gbeta__pl && tmp_r.score >= -galpha_pl){
// if ((!mainThread) && tmp_r.score >= ((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl)){
return -galpha_pl;//((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl);//MAX_TT_SCORE;
}
if (tmp_r.score > alph){ //better move found
if (mainThread){
// if (pl == NORMAL){
galpha_pl = +tmp_r.score;
// } else {
// gbeta__pl = -tmp_r.score;
// }
}
alph = tmp_r.score;
bmove = tmp_r.move;
assert(bmove >= 0);
}
}
//Wait for threads to finish and merge scores here
if(mainThread){
bool unfinished = false;
do {
unfinished = false;
for (int i = 0 ; i < iter ; ++i){
if (allResults[depth][i].score == 0) {
unfinished = true;
} else if (allResults[depth][i].move >= 0){
tlocal_search_result tmp_r;
tmp_r.score = allResults[depth][i].score;
tmp_r.move = allResults[depth][i].move;
allResults[depth][i].move = -5;
if (tmp_r.score >= bet){
for (int j = 0 ; j < iter ; ++j){
while(allResults[depth][j].score == 0 && allResults[depth][j].move >= 0){
this_thread::yield();
}
}
tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
return bet; //fail-hard beta cut-off
}
if (tmp_r.score > alph){ //better move found
// if (pl == NORMAL){
galpha_pl = +tmp_r.score;
// } else {
// gbeta__pl = -tmp_r.score;
// }
alph = tmp_r.score;
bmove = tmp_r.move;
assert(bmove >= 0);
}
}
}
if (unfinished){
this_thread::yield();
}
} while (unfinished);
}
if (firstChild){ //no move was available, this is a leaf node, return score
board.assert_state();
assert(pl == NORMAL);
#ifndef NDEBUG
++horizonNodes;
#endif
bool a;
return board.getHigherTile(&a) << 2;
}
NodeType nt = PV__Node;
if (bmove < 0){ //All-Node
nt = All_Node;
bmove = 0;
}
tt.addTTEntry(hash, depth, bmove, alph, pl == PLACER, nt);
return alph;
}
template<player other, bool mainThread>
int32_t search_deeper(BitBoard_t &board, int32_t depth, int32_t alpha,
int32_t beta, bool firstChild){
int32_t score;
if(firstChild == true){
score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
} else {
// score = -negaScout<other, mainThread>(board, depth, -alpha-1, -alpha, firstChild);
// if(alpha < score){
score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
// }
}
return score;
}
void negaScoutWrapper(maskedArguments args){
int32_t data;
if (args.pl == player::PLACER){
data = search_deeper<player::PLACER,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
} else {
data = search_deeper<player::NORMAL,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
}
assert(data!=0);
*(args.writeResult) = data;
}
template<player other>
void spawnThread(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild, atomic<int32_t> *score){
maskedArguments args;
args.pl = other;
args.alpha = alpha;
args.beta = beta;
args.depth = depth;
args.board = board;
args.firstChild = firstChild;
args.writeResult = score;
myThreadPool.useNewThread(args);
}
int32_t veryVeryGreedyAndStupidEvaluationFunction(BitBoard_t boardForEv){
bool inCorner = false;
int32_t v2 = boardForEv.getHigherTile(&inCorner);
int32_t score = (v2 << 6) + 1;
if(inCorner){
score += boardForEv.getMaxCornerChain() << 5;
score <<= 2;
}
score += boardForEv.getMaxChain() << 4;
int tmp = boardForEv.countFreeTiles() - 7;
tmp = (tmp < 0) ? -tmp : tmp;
score += (7-tmp) << 2;
score += boardForEv.countTileTypes() << 2;
assert(score >= 0);
return score;
}
template int32_t negaScout<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t search_deeper<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
<|endoftext|> |
<commit_before>#define _USE_MATH_DEFINES
#include <math.h>
#include "bandlimited_sawtooth_oscillator.h"
#include "bandlimited_sawtooth_oscillator_note.h"
//----------------
// コンストラクタ
//----------------
bandlimited_sawtooth_oscillator::bandlimited_sawtooth_oscillator()
{
// サイン波テーブル作成
int ii = 0;
for(; ii< _sinTable.size()-1; ii++)
{
_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
}
_sinTable[ii] = 0.0;
_srate = 44100;
}
//
void bandlimited_sawtooth_oscillator::setFeedback(double value)
{
_feedback = value;
}
//-------------
//
//-------------
double bandlimited_sawtooth_oscillator::LinearInterpolatedSin( double x )
{
#ifdef _DEBUG
if( x < 0.0 ) throw;
if( 1.0 <= x ) throw;
#endif
// スケーリング
double pos = (_sinTable.size()-1) * x;
#ifdef _DEBUG
if( pos >= _sinTable.size()-1 ) throw;
#endif
// 位置を計算
unsigned int idx_A = static_cast<int>(pos);
// 距離を算出
double s = pos - idx_A;
// 線形補間
return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}
//-------------
// BLIT
//-------------
double bandlimited_sawtooth_oscillator::BLIT( double t, int N )
{
if( t < 1.0e-12 )// TODO: 要チューニング
{
// ゼロ割防止。ロピタルの定理を適用
return (2.0 * N) * 2.0;
}
// 分子
double x_numerator = LinearInterpolatedSin(::fmod((2.0*N+1.0)/2.0*t, 1.0));
// 分母
double x_denominator = LinearInterpolatedSin( t/2.0 );
return (x_numerator/x_denominator-1.0) * 2.0;
}
//-------------
//
//-------------
void bandlimited_sawtooth_oscillator::updateOscillater(bandlimited_sawtooth_oscillator_note& note)
{
note.t += note.dt;
if ( 1.0 <= note.t )note.t -= 1.0;
note.saw = note.saw*_feedback + BLIT(note.t, note.n)*note.dt;
}
//
void bandlimited_sawtooth_oscillator::updateEnvelope(bandlimited_sawtooth_oscillator_note ¬e)
{
if( note.adsr == bandlimited_sawtooth_oscillator_note::Attack )
{
// Attack
if( note.envelope + _attack_decrement < 1.0 )
{
note.envelope += _attack_decrement;
}
else
{
// Attack→定数
note.envelope = 1.0;
note.adsr = bandlimited_sawtooth_oscillator_note::Const;
}
}
else if( note.adsr == bandlimited_sawtooth_oscillator_note::Release )
{
// Release
if( 0.0 < note.envelope - _release_decrement )
{
note.envelope -= _release_decrement;
}
else
{
// リリース終了
note.envelope = 0.0;
note.adsr = bandlimited_sawtooth_oscillator_note::Silent;
// 破棄
note.kill();
}
}
}
//
void bandlimited_sawtooth_oscillator::setAttackTime(double attackTime)
{
if( attackTime > 1.0e-12)
{
_attack_decrement = 1.0 / (attackTime * _srate);
}
else
{
_attack_decrement = 1.0;
}
}
//
void bandlimited_sawtooth_oscillator::setReleaseTime(double releaseTime)
{
if( releaseTime > 1.0e-12)
{
_release_decrement = 1.0 / (releaseTime * _srate);
}
else
{
_release_decrement = 1.0;
}
}
//
void bandlimited_sawtooth_oscillator::setSampleRate(int srate)
{
_srate = srate;
}<commit_msg>ゼロ割判定を修正。戻り値に-2するのを止めた。<commit_after>#define _USE_MATH_DEFINES
#include <math.h>
#include "bandlimited_sawtooth_oscillator.h"
#include "bandlimited_sawtooth_oscillator_note.h"
//----------------
// コンストラクタ
//----------------
bandlimited_sawtooth_oscillator::bandlimited_sawtooth_oscillator()
{
// サイン波テーブル作成
int ii = 0;
for(; ii< _sinTable.size()-1; ii++)
{
_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
}
_sinTable[ii] = 0.0;
_srate = 44100;
}
//
void bandlimited_sawtooth_oscillator::setFeedback(double value)
{
_feedback = value;
}
//-------------
//
//-------------
double bandlimited_sawtooth_oscillator::LinearInterpolatedSin( double x )
{
#ifdef _DEBUG
if( x < 0.0 ) throw;
if( 1.0 <= x ) throw;
#endif
// スケーリング
double pos = (_sinTable.size()-1) * x;
#ifdef _DEBUG
if( pos >= _sinTable.size()-1 ) throw;
#endif
// 位置を計算
unsigned int idx_A = static_cast<int>(pos);
// 距離を算出
double s = pos - idx_A;
// 線形補間
return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}
//-------------
// BLIT
//-------------
double bandlimited_sawtooth_oscillator::BLIT( double t, int N )
{
// 分母
double x_denominator = LinearInterpolatedSin( 0.5*t );
if( x_denominator < 1.0e-12 )// TODO: 要チューニング
{
// ゼロ割防止。ロピタルの定理を適用
return 2.0*(2*N+1);
}
// 分子
double x_numerator = LinearInterpolatedSin(::fmod((N+0.5)*t, 1.0));
return 2.0*x_numerator/x_denominator;
}
//-------------
//
//-------------
void bandlimited_sawtooth_oscillator::updateOscillater(bandlimited_sawtooth_oscillator_note& note)
{
note.t += note.dt;
if ( 1.0 <= note.t )note.t -= 1.0;
note.saw = note.saw*_feedback + (BLIT(note.t, note.n)-2.0)*note.dt;
}
//
void bandlimited_sawtooth_oscillator::updateEnvelope(bandlimited_sawtooth_oscillator_note ¬e)
{
if( note.adsr == bandlimited_sawtooth_oscillator_note::Attack )
{
// Attack
if( note.envelope + _attack_decrement < 1.0 )
{
note.envelope += _attack_decrement;
}
else
{
// Attack→定数
note.envelope = 1.0;
note.adsr = bandlimited_sawtooth_oscillator_note::Const;
}
}
else if( note.adsr == bandlimited_sawtooth_oscillator_note::Release )
{
// Release
if( 0.0 < note.envelope - _release_decrement )
{
note.envelope -= _release_decrement;
}
else
{
// リリース終了
note.envelope = 0.0;
note.adsr = bandlimited_sawtooth_oscillator_note::Silent;
// 破棄
note.kill();
}
}
}
//
void bandlimited_sawtooth_oscillator::setAttackTime(double attackTime)
{
if( attackTime > 1.0e-12)
{
_attack_decrement = 1.0 / (attackTime * _srate);
}
else
{
_attack_decrement = 1.0;
}
}
//
void bandlimited_sawtooth_oscillator::setReleaseTime(double releaseTime)
{
if( releaseTime > 1.0e-12)
{
_release_decrement = 1.0 / (releaseTime * _srate);
}
else
{
_release_decrement = 1.0;
}
}
//
void bandlimited_sawtooth_oscillator::setSampleRate(int srate)
{
_srate = srate;
}<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/reduction_ops_common.h"
namespace tensorflow {
#define REGISTER_CPU_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx"), \
ReductionOp<CPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx"), \
ReductionOp<CPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS);
#undef REGISTER_CPU_KERNELS
#if GOOGLE_CUDA
#define REGISTER_GPU_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<GPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<GPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
TF_CALL_complex64(REGISTER_GPU_KERNELS);
TF_CALL_complex128(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
#endif
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNELS(type) \
REGISTER_KERNEL_BUILDER(Name("Sum") \
.Device(DEVICE_SYCL) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<SYCLDevice, type, int32, \
Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER(Name("Sum") \
.Device(DEVICE_SYCL) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<SYCLDevice, type, int64, \
Eigen::internal::SumReducer<type>>);
REGISTER_SYCL_KERNELS(float);
REGISTER_SYCL_KERNELS(double);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
#undef REGISTER_SYCL_KERNELS
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<commit_msg>Register a new Sum op for T:int64 and Tidx:int32<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/reduction_ops_common.h"
namespace tensorflow {
#define REGISTER_CPU_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx"), \
ReductionOp<CPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx"), \
ReductionOp<CPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS);
#undef REGISTER_CPU_KERNELS
#if GOOGLE_CUDA
#define REGISTER_GPU_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<GPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER( \
Name("Sum") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<GPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
TF_CALL_complex64(REGISTER_GPU_KERNELS);
TF_CALL_complex128(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int64, int32, Eigen::internal::SumReducer<int64>>);
#endif
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNELS(type) \
REGISTER_KERNEL_BUILDER(Name("Sum") \
.Device(DEVICE_SYCL) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<SYCLDevice, type, int32, \
Eigen::internal::SumReducer<type>>); \
REGISTER_KERNEL_BUILDER(Name("Sum") \
.Device(DEVICE_SYCL) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("Tidx") \
.HostMemory("reduction_indices"), \
ReductionOp<SYCLDevice, type, int64, \
Eigen::internal::SumReducer<type>>);
REGISTER_SYCL_KERNELS(float);
REGISTER_SYCL_KERNELS(double);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
Name("Sum")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("Tidx")
.HostMemory("input")
.HostMemory("output")
.HostMemory("reduction_indices"),
ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
#undef REGISTER_SYCL_KERNELS
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(StringPiece, Ctor) {
{
// const char* without size.
const char* hello = "hello";
StringPiece s20(hello);
EXPECT_TRUE(s20.data() == hello);
EXPECT_EQ(5, s20.size());
// const char* with size.
StringPiece s21(hello, 4);
EXPECT_TRUE(s21.data() == hello);
EXPECT_EQ(4, s21.size());
// Not recommended, but valid C++
StringPiece s22(hello, 6);
EXPECT_TRUE(s22.data() == hello);
EXPECT_EQ(6, s22.size());
}
{
string hola = "hola";
StringPiece s30(hola);
EXPECT_TRUE(s30.data() == hola.data());
EXPECT_EQ(4, s30.size());
// std::string with embedded '\0'.
hola.push_back('\0');
hola.append("h2");
hola.push_back('\0');
StringPiece s31(hola);
EXPECT_TRUE(s31.data() == hola.data());
EXPECT_EQ(8, s31.size());
}
}
TEST(StringPiece, Contains) {
StringPiece a("abcdefg");
StringPiece b("abcd");
StringPiece c("efg");
StringPiece d("gh");
EXPECT_TRUE(a.contains(b));
EXPECT_TRUE(a.contains(c));
EXPECT_TRUE(!a.contains(d));
}
} // namespace tensorflow
<commit_msg>Added tests for tensorflow::StringPiece::Hasher.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/lib/core/stringpiece.h"
#include <unordered_map>
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(StringPiece, Ctor) {
{
// const char* without size.
const char* hello = "hello";
StringPiece s20(hello);
EXPECT_TRUE(s20.data() == hello);
EXPECT_EQ(5, s20.size());
// const char* with size.
StringPiece s21(hello, 4);
EXPECT_TRUE(s21.data() == hello);
EXPECT_EQ(4, s21.size());
// Not recommended, but valid C++
StringPiece s22(hello, 6);
EXPECT_TRUE(s22.data() == hello);
EXPECT_EQ(6, s22.size());
}
{
string hola = "hola";
StringPiece s30(hola);
EXPECT_TRUE(s30.data() == hola.data());
EXPECT_EQ(4, s30.size());
// std::string with embedded '\0'.
hola.push_back('\0');
hola.append("h2");
hola.push_back('\0');
StringPiece s31(hola);
EXPECT_TRUE(s31.data() == hola.data());
EXPECT_EQ(8, s31.size());
}
}
TEST(StringPiece, Contains) {
StringPiece a("abcdefg");
StringPiece b("abcd");
StringPiece c("efg");
StringPiece d("gh");
EXPECT_TRUE(a.contains(b));
EXPECT_TRUE(a.contains(c));
EXPECT_TRUE(!a.contains(d));
}
TEST(StringPieceHasher, Equality) {
StringPiece::Hasher hasher;
StringPiece s1("foo");
StringPiece s2("bar");
StringPiece s3("baz");
StringPiece s4("zot");
EXPECT_TRUE(hasher(s1) != hasher(s2));
EXPECT_TRUE(hasher(s1) != hasher(s3));
EXPECT_TRUE(hasher(s1) != hasher(s4));
EXPECT_TRUE(hasher(s2) != hasher(s3));
EXPECT_TRUE(hasher(s2) != hasher(s4));
EXPECT_TRUE(hasher(s3) != hasher(s4));
EXPECT_TRUE(hasher(s1) == hasher(s1));
EXPECT_TRUE(hasher(s2) == hasher(s2));
EXPECT_TRUE(hasher(s3) == hasher(s3));
EXPECT_TRUE(hasher(s4) == hasher(s4));
}
TEST(StringPieceHasher, HashMap) {
string s1("foo");
string s2("bar");
string s3("baz");
StringPiece p1(s1);
StringPiece p2(s2);
StringPiece p3(s3);
std::unordered_map<StringPiece, int, StringPiece::Hasher> map;
map.insert(std::make_pair(p1, 0));
map.insert(std::make_pair(p2, 1));
map.insert(std::make_pair(p3, 2));
EXPECT_EQ(map.size(), 3);
bool found[3] = {false, false, false};
for (auto const& val : map) {
int x = val.second;
EXPECT_TRUE(x >= 0 && x < 3);
EXPECT_TRUE(!found[x]);
found[x] = true;
}
EXPECT_EQ(found[0], true);
EXPECT_EQ(found[1], true);
EXPECT_EQ(found[2], true);
auto new_iter = map.find("zot");
EXPECT_TRUE(new_iter == map.end());
new_iter = map.find("bar");
EXPECT_TRUE(new_iter != map.end());
map.erase(new_iter);
EXPECT_EQ(map.size(), 2);
found[0] = false;
found[1] = false;
found[2] = false;
for (const auto& iter : map) {
int x = iter.second;
EXPECT_TRUE(x >= 0 && x < 3);
EXPECT_TRUE(!found[x]);
found[x] = true;
}
EXPECT_EQ(found[0], true);
EXPECT_EQ(found[1], false);
EXPECT_EQ(found[2], true);
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 2001-2002 by Gunnar Kedenburg */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] or */
/* [email protected] */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
/* Modifications by Pablo d'Angelo
* updated to vigra 1.4 by Douglas Wilkins
* as of 18 Febuary 2006:
* - Added UINT16 and UINT32 pixel types.
* - Added support for obtaining extra bands beyond RGB.
* - Added support for a position field that indicates the start of this
* image relative to some global origin.
* - Added support for x and y resolution fields.
* - Added support for ICC Profiles
*/
#ifndef VIGRA_CODEC_HXX
#define VIGRA_CODEC_HXX
#include <memory>
#include <string>
#include <vector>
#include "array_vector.hxx"
#include "config.hxx"
#include "diff2d.hxx"
#include "sized_int.hxx"
// possible pixel types:
// "undefined", "UINT8", "UINT16", "INT16", "UINT32", "INT32", "FLOAT", "DOUBLE"
// possible compression types:
// "undefined", "RLE", "LZW", "LOSSLESS", "JPEG", "DEFLATE"
// possible file types:
// "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM", "EXR"
// possible name extensions:
// "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun",
// "xpm", "exr" (also capital forms)
namespace vigra
{
template <class T>
struct TypeAsString
{
static std::string result() { return "undefined"; }
};
template <>
struct TypeAsString<Int8>
{
static std::string result() { return "INT8"; }
};
template <>
struct TypeAsString<UInt8>
{
static std::string result() { return "UINT8"; }
};
template <>
struct TypeAsString<Int16>
{
static std::string result() { return "INT16"; }
};
template <>
struct TypeAsString<UInt16>
{
static std::string result() { return "UINT16"; }
};
template <>
struct TypeAsString<Int32>
{
static std::string result() { return "INT32"; }
};
template <>
struct TypeAsString<UInt32>
{
static std::string result() { return "UINT32"; }
};
template <>
struct TypeAsString<float>
{
static std::string result() { return "FLOAT"; }
};
template <>
struct TypeAsString<double>
{
static std::string result() { return "DOUBLE"; }
};
// codec description
struct CodecDesc
{
std::string fileType;
std::vector<std::string> pixelTypes;
std::vector<std::string> compressionTypes;
std::vector<std::vector<char> > magicStrings;
std::vector<std::string> fileExtensions;
std::vector<int> bandNumbers;
};
// Decoder and Encoder are virtual types that define a common
// interface for all image file formats impex supports.
struct Decoder
{
virtual ~Decoder() {};
virtual void init( const std::string & ) = 0;
virtual void close() = 0;
virtual void abort() = 0;
virtual std::string getFileType() const = 0;
virtual std::string getPixelType() const = 0;
virtual unsigned int getWidth() const = 0;
virtual unsigned int getHeight() const = 0;
virtual unsigned int getNumBands() const = 0;
virtual unsigned int getNumExtraBands() const
{
return 0;
}
virtual vigra::Diff2D getPosition() const
{
return vigra::Diff2D();
}
virtual float getXResolution() const
{
return 0.0f;
}
virtual float getYResolution() const
{
return 0.0f;
}
virtual vigra::Size2D getCanvasSize() const
{
return vigra::Size2D(this->getWidth(), this->getHeight());
}
virtual unsigned int getOffset() const = 0;
virtual const void * currentScanlineOfBand( unsigned int ) const = 0;
virtual void nextScanline() = 0;
typedef ArrayVector<unsigned char> ICCProfile;
const ICCProfile & getICCProfile() const
{
return iccProfile_;
}
ICCProfile iccProfile_;
};
struct Encoder
{
virtual ~Encoder() {};
virtual void init( const std::string & ) = 0;
virtual void close() = 0;
virtual void abort() = 0;
virtual std::string getFileType() const = 0;
virtual unsigned int getOffset() const = 0;
virtual void setWidth( unsigned int ) = 0;
virtual void setHeight( unsigned int ) = 0;
virtual void setNumBands( unsigned int ) = 0;
virtual void setCompressionType( const std::string &, int = -1 ) = 0;
virtual void setPixelType( const std::string & ) = 0;
virtual void finalizeSettings() = 0;
virtual void setPosition( const vigra::Diff2D & /*pos*/ )
{
}
virtual void setCanvasSize( const vigra::Size2D & size)
{
}
virtual void setXResolution( float /*xres*/ )
{
}
virtual void setYResolution( float /*yres*/ )
{
}
typedef ArrayVector<unsigned char> ICCProfile;
virtual void setICCProfile(const ICCProfile & /* data */)
{
}
virtual void * currentScanlineOfBand( unsigned int ) = 0;
virtual void nextScanline() = 0;
struct TIFFCompressionException {};
};
// codec factory for registration at the codec manager
struct CodecFactory
{
virtual CodecDesc getCodecDesc() const = 0;
virtual std::auto_ptr<Decoder> getDecoder() const = 0;
virtual std::auto_ptr<Encoder> getEncoder() const = 0;
virtual ~CodecFactory() {};
};
// factory functions to encapsulate the codec managers
//
// codecs are selected according to the following order:
// - (if provided) the FileType
// - (in case of decoders) the file's magic string
// - the filename extension
VIGRA_EXPORT std::auto_ptr<Decoder>
getDecoder( const std::string &, const std::string & = "undefined" );
VIGRA_EXPORT std::auto_ptr<Encoder>
getEncoder( const std::string &, const std::string & = "undefined" );
VIGRA_EXPORT std::string
getEncoderType( const std::string &, const std::string & = "undefined" );
// functions to query the capabilities of certain codecs
VIGRA_EXPORT std::vector<std::string> queryCodecPixelTypes( const std::string & );
VIGRA_EXPORT bool negotiatePixelType( std::string const & codecname,
std::string const & srcPixeltype, std::string & destPixeltype);
VIGRA_EXPORT bool isPixelTypeSupported( const std::string &, const std::string & );
VIGRA_EXPORT bool isBandNumberSupported( const std::string &, int bands );
}
#endif // VIGRA_CODEC_HXX
<commit_msg>cleanup compiler warning<commit_after>/************************************************************************/
/* */
/* Copyright 2001-2002 by Gunnar Kedenburg */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] or */
/* [email protected] */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
/* Modifications by Pablo d'Angelo
* updated to vigra 1.4 by Douglas Wilkins
* as of 18 Febuary 2006:
* - Added UINT16 and UINT32 pixel types.
* - Added support for obtaining extra bands beyond RGB.
* - Added support for a position field that indicates the start of this
* image relative to some global origin.
* - Added support for x and y resolution fields.
* - Added support for ICC Profiles
*/
#ifndef VIGRA_CODEC_HXX
#define VIGRA_CODEC_HXX
#include <memory>
#include <string>
#include <vector>
#include "array_vector.hxx"
#include "config.hxx"
#include "diff2d.hxx"
#include "sized_int.hxx"
// possible pixel types:
// "undefined", "UINT8", "UINT16", "INT16", "UINT32", "INT32", "FLOAT", "DOUBLE"
// possible compression types:
// "undefined", "RLE", "LZW", "LOSSLESS", "JPEG", "DEFLATE"
// possible file types:
// "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM", "EXR"
// possible name extensions:
// "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun",
// "xpm", "exr" (also capital forms)
namespace vigra
{
template <class T>
struct TypeAsString
{
static std::string result() { return "undefined"; }
};
template <>
struct TypeAsString<Int8>
{
static std::string result() { return "INT8"; }
};
template <>
struct TypeAsString<UInt8>
{
static std::string result() { return "UINT8"; }
};
template <>
struct TypeAsString<Int16>
{
static std::string result() { return "INT16"; }
};
template <>
struct TypeAsString<UInt16>
{
static std::string result() { return "UINT16"; }
};
template <>
struct TypeAsString<Int32>
{
static std::string result() { return "INT32"; }
};
template <>
struct TypeAsString<UInt32>
{
static std::string result() { return "UINT32"; }
};
template <>
struct TypeAsString<float>
{
static std::string result() { return "FLOAT"; }
};
template <>
struct TypeAsString<double>
{
static std::string result() { return "DOUBLE"; }
};
// codec description
struct CodecDesc
{
std::string fileType;
std::vector<std::string> pixelTypes;
std::vector<std::string> compressionTypes;
std::vector<std::vector<char> > magicStrings;
std::vector<std::string> fileExtensions;
std::vector<int> bandNumbers;
};
// Decoder and Encoder are virtual types that define a common
// interface for all image file formats impex supports.
struct Decoder
{
virtual ~Decoder() {};
virtual void init( const std::string & ) = 0;
virtual void close() = 0;
virtual void abort() = 0;
virtual std::string getFileType() const = 0;
virtual std::string getPixelType() const = 0;
virtual unsigned int getWidth() const = 0;
virtual unsigned int getHeight() const = 0;
virtual unsigned int getNumBands() const = 0;
virtual unsigned int getNumExtraBands() const
{
return 0;
}
virtual vigra::Diff2D getPosition() const
{
return vigra::Diff2D();
}
virtual float getXResolution() const
{
return 0.0f;
}
virtual float getYResolution() const
{
return 0.0f;
}
virtual vigra::Size2D getCanvasSize() const
{
return vigra::Size2D(this->getWidth(), this->getHeight());
}
virtual unsigned int getOffset() const = 0;
virtual const void * currentScanlineOfBand( unsigned int ) const = 0;
virtual void nextScanline() = 0;
typedef ArrayVector<unsigned char> ICCProfile;
const ICCProfile & getICCProfile() const
{
return iccProfile_;
}
ICCProfile iccProfile_;
};
struct Encoder
{
virtual ~Encoder() {};
virtual void init( const std::string & ) = 0;
virtual void close() = 0;
virtual void abort() = 0;
virtual std::string getFileType() const = 0;
virtual unsigned int getOffset() const = 0;
virtual void setWidth( unsigned int ) = 0;
virtual void setHeight( unsigned int ) = 0;
virtual void setNumBands( unsigned int ) = 0;
virtual void setCompressionType( const std::string &, int = -1 ) = 0;
virtual void setPixelType( const std::string & ) = 0;
virtual void finalizeSettings() = 0;
virtual void setPosition( const vigra::Diff2D & /*pos*/ )
{
}
virtual void setCanvasSize( const vigra::Size2D & /*size*/)
{
}
virtual void setXResolution( float /*xres*/ )
{
}
virtual void setYResolution( float /*yres*/ )
{
}
typedef ArrayVector<unsigned char> ICCProfile;
virtual void setICCProfile(const ICCProfile & /* data */)
{
}
virtual void * currentScanlineOfBand( unsigned int ) = 0;
virtual void nextScanline() = 0;
struct TIFFCompressionException {};
};
// codec factory for registration at the codec manager
struct CodecFactory
{
virtual CodecDesc getCodecDesc() const = 0;
virtual std::auto_ptr<Decoder> getDecoder() const = 0;
virtual std::auto_ptr<Encoder> getEncoder() const = 0;
virtual ~CodecFactory() {};
};
// factory functions to encapsulate the codec managers
//
// codecs are selected according to the following order:
// - (if provided) the FileType
// - (in case of decoders) the file's magic string
// - the filename extension
VIGRA_EXPORT std::auto_ptr<Decoder>
getDecoder( const std::string &, const std::string & = "undefined" );
VIGRA_EXPORT std::auto_ptr<Encoder>
getEncoder( const std::string &, const std::string & = "undefined" );
VIGRA_EXPORT std::string
getEncoderType( const std::string &, const std::string & = "undefined" );
// functions to query the capabilities of certain codecs
VIGRA_EXPORT std::vector<std::string> queryCodecPixelTypes( const std::string & );
VIGRA_EXPORT bool negotiatePixelType( std::string const & codecname,
std::string const & srcPixeltype, std::string & destPixeltype);
VIGRA_EXPORT bool isPixelTypeSupported( const std::string &, const std::string & );
VIGRA_EXPORT bool isBandNumberSupported( const std::string &, int bands );
}
#endif // VIGRA_CODEC_HXX
<|endoftext|> |
<commit_before>// Check that ASan dumps the CPU registers on a SIGSEGV.
// RUN: %clangxx_asan %s -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <assert.h>
#include <stdio.h>
int main() {
fprintf(stderr, "Hello\n");
char *ptr;
if (sizeof(void *) == 8)
ptr = (char *)0x6666666666666666;
else if (sizeof(void *) == 4)
ptr = (char *)0x55555555;
else
assert(0 && "Your computer is weird.");
char c = *ptr; // BOOM
// CHECK: ERROR: AddressSanitizer: {{SEGV|BUS}}
// CHECK: Register values:
// CHECK: {{0x55555555|0x6666666666666666}}
fprintf(stderr, "World\n");
return c;
}
<commit_msg>[asan] Make dump_registers.cc more stable<commit_after>// Check that ASan dumps the CPU registers on a SIGSEGV.
// RUN: %clangxx_asan %s -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
int main() {
fprintf(stderr, "Hello\n");
char *ptr;
ptr = (char *)mmap(NULL, 0x10000, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
assert(ptr && "failed to mmap");
fprintf(stderr, sizeof(uintptr_t) == 8 ? "p = 0x%016lx\n" : "p = 0x%08lx\n", (uintptr_t)ptr);
// CHECK: p = [[ADDR:0x[0-9]+]]
char c = *ptr; // BOOM
// CHECK: ERROR: AddressSanitizer: {{SEGV|BUS}}
// CHECK: Register values:
// CHECK: [[ADDR]]
fprintf(stderr, "World\n");
return c;
}
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
int multi_type_test() {
Func f1("f1"), f2("f2"), f3("f3"), f4("f4"), f5("f5"), f6("f6");
Var x, y, z;
f1(x, y, z) = cast<uint8_t>(1);
f2(x, y, z) = cast<uint32_t>(f1(x+1, y, z) + f1(x, y+1, z));
f3(x, y, z) = cast<uint16_t>(f2(x+1, y, z) + f2(x, y+1, z));
f4(x, y, z) = cast<uint16_t>(f3(x+1, y, z) + f3(x, y+1, z));
f5(x, y, z) = cast<uint32_t>(f4(x+1, y, z) + f4(x, y+1, z));
f6(x, y, z) = cast<uint8_t>(f5(x+1, y, z) + f5(x, y+1, z));
f6.compute_root().gpu_tile(x, y, 1, 1);
f5.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f4.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f3.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f2.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f1.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
const int size_x = 200;
const int size_y = 200;
const int size_z = 4;
Image<uint8_t> out = f6.realize(size_x, size_y, size_z);
uint8_t correct = 32;
for (int z = 0; z < size_z; z++) {
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y, z) != correct) {
printf("out(%d, %d, %d) = %d instead of %d\n",
x, y, z, out(x, y, z), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
int pyramid_test() {
const int levels = 10;
const int size_x = 100;
const int size_y = 100;
Var x, y, z, xo, xi, yo, yi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](2*x, y);
}
funcs[levels-1].compute_root().split(x, xo, xi, 4).split(y, yo, yi, 4).gpu_tile(xo, yo, 1, 1);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks()).split(x, xo, xi, 4).split(y, yo, yi, 4).gpu_threads(xo, yo);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int inverted_pyramid_test() {
const int levels = 6;
const int size_x = 100;
const int size_y = 400;
Var x, y, z, yo, yi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
int max_size = size_x/std::pow(2, levels-i) + 1;
funcs[i](x, y) = funcs[i-1](x%max_size, y);
}
funcs[levels-1].compute_root().split(y, yo, yi, 19).gpu_tile(x, yo, 8, 8);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks()).split(y, yo, yi, 19).gpu_threads(x, yo);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int dynamic_shared_test() {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
Func f1, f2, f3, f4;
Var x, xo, xi;
f1(x) = x;
f2(x) = f1(x) + f1(2*x);
f3(x) = f2(x) + f2(2*x);
f4(x) = f3(x) + f3(2*x);
f4.split(x, xo, xi, 16).gpu_tile(xo, 16);
f3.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xo);
f2.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xo);
f1.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xo);
// The amount of shared memory required varies with x
Image<int> out = f4.realize(500);
for (int x = 0; x < out.width(); x++) {
int correct = 27*x;
if (out(x) != correct) {
printf("out(%d) = %d instead of %d\n",
x, out(x), correct);
return -1;
}
}
printf("Success!\n");
return 0;
}
int main(int argc, char **argv) {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
printf("Running multi type test!\n");
if (multi_type_test() != 0) {
return -1;
}
printf("Running pyramid test!\n");
if (pyramid_test() != 0) {
return -1;
}
printf("Running inverted pyramid test!\n");
if (inverted_pyramid_test() != 0) {
return -1;
}
printf("Running dynamic shared test!\n");
if (dynamic_shared_test() != 0) {
return -1;
}
return 0;
}
<commit_msg>Use fewer gpu threads in shared mem reuse test<commit_after>#include "Halide.h"
using namespace Halide;
int multi_type_test() {
Func f1("f1"), f2("f2"), f3("f3"), f4("f4"), f5("f5"), f6("f6");
Var x, y, z;
f1(x, y, z) = cast<uint8_t>(1);
f2(x, y, z) = cast<uint32_t>(f1(x+1, y, z) + f1(x, y+1, z));
f3(x, y, z) = cast<uint16_t>(f2(x+1, y, z) + f2(x, y+1, z));
f4(x, y, z) = cast<uint16_t>(f3(x+1, y, z) + f3(x, y+1, z));
f5(x, y, z) = cast<uint32_t>(f4(x+1, y, z) + f4(x, y+1, z));
f6(x, y, z) = cast<uint8_t>(f5(x+1, y, z) + f5(x, y+1, z));
f6.compute_root().gpu_tile(x, y, 1, 1);
f5.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f4.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f3.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f2.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f1.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
const int size_x = 200;
const int size_y = 200;
const int size_z = 4;
Image<uint8_t> out = f6.realize(size_x, size_y, size_z);
uint8_t correct = 32;
for (int z = 0; z < size_z; z++) {
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y, z) != correct) {
printf("out(%d, %d, %d) = %d instead of %d\n",
x, y, z, out(x, y, z), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
int pyramid_test() {
const int levels = 10;
const int size_x = 100;
const int size_y = 100;
Var x, y, z, xo, xi, yo, yi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](2*x, y);
}
funcs[levels-1].compute_root()
.gpu_tile(x, y, 4, 4);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.split(x, xo, xi, 1 << (levels - i - 1))
.gpu_threads(xo, y);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int inverted_pyramid_test() {
const int levels = 6;
const int size_x = 8*16;
const int size_y = 8*16;
Var x, y, z, yo, yi, xo, xi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](x/2, y);
}
funcs[levels-1].compute_root()
.tile(x, y, xo, yo, xi, yi, 16, 16)
.gpu_tile(xo, yo, 8, 8);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.tile(x, y, xo, yo, xi, yi, 16, 16)
.gpu_threads(xo, yo);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int dynamic_shared_test() {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
Func f1, f2, f3, f4;
Var x, xo, xi;
f1(x) = x;
f2(x) = f1(x) + f1(2*x);
f3(x) = f2(x) + f2(2*x);
f4(x) = f3(x) + f3(2*x);
f4.split(x, xo, xi, 16).gpu_tile(xo, 16);
f3.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f2.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f1.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
// The amount of shared memory required varies with x
Image<int> out = f4.realize(500);
for (int x = 0; x < out.width(); x++) {
int correct = 27*x;
if (out(x) != correct) {
printf("out(%d) = %d instead of %d\n",
x, out(x), correct);
return -1;
}
}
printf("Success!\n");
return 0;
}
int main(int argc, char **argv) {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
printf("Running multi type test!\n");
if (multi_type_test() != 0) {
return -1;
}
printf("Running pyramid test!\n");
if (pyramid_test() != 0) {
return -1;
}
printf("Running inverted pyramid test!\n");
if (inverted_pyramid_test() != 0) {
return -1;
}
printf("Running dynamic shared test!\n");
if (dynamic_shared_test() != 0) {
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ManifestExport.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 17:22:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#ifndef _MANIFEST_EXPORT_HXX
#include <ManifestExport.hxx>
#endif
#ifndef _ATTRIBUTE_LIST_HXX
#include <AttributeList.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HXX
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_BEANS_PROPERTYVALUE_HPP
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#include <comphelper/documentconstants.hxx>
using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::sax;
ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler, const Sequence < Sequence < PropertyValue > > &rManList )
{
const OUString sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) );
const OUString sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) );
const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) );
const OUString sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) );
const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) );
const OUString sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) );
const OUString sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) );
const OUString sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) );
const OUString sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) );
const OUString sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) );
const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) );
const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) );
const OUString sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) );
const OUString sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) );
const OUString sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) );
const OUString sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM) );
const OUString sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) );
const OUString sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) );
const OUString sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) );
const OUString sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) );
const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) );
const OUString sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) );
const OUString sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) );
const OUString sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) );
const OUString sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) );
const OUString sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) );
const OUString sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) );
AttributeList * pRootAttrList = new AttributeList;
const Sequence < PropertyValue > *pSequence = rManList.getConstArray();
const sal_uInt32 nManLength = rManList.getLength();
// find the mediatype of the document if any
OUString aDocMediaType;
for (sal_uInt32 nInd = 0; nInd < nManLength ; nInd++ )
{
OUString aMediaType;
OUString aPath;
const PropertyValue *pValue = pSequence[nInd].getConstArray();
for (sal_uInt32 j = 0, nNum = pSequence[nInd].getLength(); j < nNum; j++, pValue++)
{
if (pValue->Name.equals (sMediaTypeProperty) )
{
pValue->Value >>= aMediaType;
}
else if (pValue->Name.equals (sFullPathProperty) )
{
pValue->Value >>= aPath;
}
if ( aPath.getLength() && aMediaType.getLength() )
break;
}
if ( aPath.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ) )
{
aDocMediaType = aMediaType;
break;
}
}
sal_Bool bProvideDTD = sal_False;
if ( aDocMediaType.getLength() )
{
if ( aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII ) ) ) )
{
// oasis format
pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
sCdataAttribute,
OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_OASIS_NAMESPACE ) ) );
}
else
{
// even if it is no SO6 format the namespace must be specified
// thus SO6 format is used as default one
pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
sCdataAttribute,
OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) );
bProvideDTD = sal_True;
}
}
Reference < XAttributeList > xRootAttrList (pRootAttrList);
xHandler->startDocument();
Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY );
if ( xExtHandler.is() && bProvideDTD )
{
OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) );
xExtHandler->unknown ( aDocType );
xHandler->ignorableWhitespace ( sWhiteSpace );
}
xHandler->startElement( sManifestElement, xRootAttrList );
for (sal_uInt32 i = 0 ; i < nManLength ; i++)
{
AttributeList *pAttrList = new AttributeList;
const PropertyValue *pValue = pSequence[i].getConstArray();
OUString aString;
const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL, *pDigest = NULL;
for (sal_uInt32 j = 0, nNum = pSequence[i].getLength(); j < nNum; j++, pValue++)
{
if (pValue->Name.equals (sMediaTypeProperty) )
{
pValue->Value >>= aString;
pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString );
}
else if (pValue->Name.equals (sFullPathProperty) )
{
pValue->Value >>= aString;
pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString );
}
else if (pValue->Name.equals (sSizeProperty) )
{
sal_Int32 nSize;
pValue->Value >>= nSize;
OUStringBuffer aBuffer;
aBuffer.append ( nSize );
pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
}
else if (pValue->Name.equals (sInitialisationVectorProperty) )
pVector = pValue;
else if (pValue->Name.equals (sSaltProperty) )
pSalt = pValue;
else if (pValue->Name.equals (sIterationCountProperty) )
pIterationCount = pValue;
else if (pValue->Name.equals ( sDigestProperty ) )
pDigest = pValue;
}
xHandler->ignorableWhitespace ( sWhiteSpace );
Reference < XAttributeList > xAttrList ( pAttrList );
xHandler->startElement( sFileEntryElement , xAttrList);
if ( pVector && pSalt && pIterationCount )
{
AttributeList * pNewAttrList = new AttributeList;
Reference < XAttributeList > xNewAttrList (pNewAttrList);
OUStringBuffer aBuffer;
Sequence < sal_uInt8 > aSequence;
xHandler->ignorableWhitespace ( sWhiteSpace );
if ( pDigest )
{
pNewAttrList->AddAttribute ( sChecksumTypeAttribute, sCdataAttribute, sChecksumType );
pDigest->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sChecksumAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
}
xHandler->startElement( sEncryptionDataElement , xNewAttrList);
pNewAttrList = new AttributeList;
xNewAttrList = pNewAttrList;
pNewAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish );
pVector->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->startElement( sAlgorithmElement , xNewAttrList);
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sAlgorithmElement );
pNewAttrList = new AttributeList;
xNewAttrList = pNewAttrList;
pNewAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 );
sal_Int32 nCount;
pIterationCount->Value >>= nCount;
aBuffer.append (nCount);
pNewAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
pSalt->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->startElement( sKeyDerivationElement , xNewAttrList);
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sKeyDerivationElement );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sEncryptionDataElement );
}
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sFileEntryElement );
}
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sManifestElement );
xHandler->endDocument();
}
<commit_msg>INTEGRATION: CWS opofxmlstorage (1.12.10); FILE MERGED 2006/06/29 15:44:05 mav 1.12.10.2: RESYNC: (1.12-1.13); FILE MERGED 2006/04/21 11:36:58 mav 1.12.10.1: #i64612# support OFOPXML format<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ManifestExport.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2006-10-13 11:47:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#ifndef _MANIFEST_EXPORT_HXX
#include <ManifestExport.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HXX
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_BEANS_PROPERTYVALUE_HPP
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#include <comphelper/documentconstants.hxx>
#include <comphelper/attributelist.hxx>
using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::sax;
ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler, const Sequence < Sequence < PropertyValue > > &rManList )
{
const OUString sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) );
const OUString sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) );
const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) );
const OUString sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) );
const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) );
const OUString sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) );
const OUString sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) );
const OUString sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) );
const OUString sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) );
const OUString sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) );
const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) );
const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) );
const OUString sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) );
const OUString sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) );
const OUString sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) );
const OUString sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM) );
const OUString sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) );
const OUString sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) );
const OUString sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) );
const OUString sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) );
const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) );
const OUString sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) );
const OUString sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) );
const OUString sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) );
const OUString sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) );
const OUString sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) );
const OUString sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) );
::comphelper::AttributeList * pRootAttrList = new ::comphelper::AttributeList;
const Sequence < PropertyValue > *pSequence = rManList.getConstArray();
const sal_uInt32 nManLength = rManList.getLength();
// find the mediatype of the document if any
OUString aDocMediaType;
for (sal_uInt32 nInd = 0; nInd < nManLength ; nInd++ )
{
OUString aMediaType;
OUString aPath;
const PropertyValue *pValue = pSequence[nInd].getConstArray();
for (sal_uInt32 j = 0, nNum = pSequence[nInd].getLength(); j < nNum; j++, pValue++)
{
if (pValue->Name.equals (sMediaTypeProperty) )
{
pValue->Value >>= aMediaType;
}
else if (pValue->Name.equals (sFullPathProperty) )
{
pValue->Value >>= aPath;
}
if ( aPath.getLength() && aMediaType.getLength() )
break;
}
if ( aPath.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ) )
{
aDocMediaType = aMediaType;
break;
}
}
sal_Bool bProvideDTD = sal_False;
if ( aDocMediaType.getLength() )
{
if ( aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII ) ) )
|| aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII ) ) ) )
{
// oasis format
pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
sCdataAttribute,
OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_OASIS_NAMESPACE ) ) );
}
else
{
// even if it is no SO6 format the namespace must be specified
// thus SO6 format is used as default one
pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
sCdataAttribute,
OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) );
bProvideDTD = sal_True;
}
}
Reference < XAttributeList > xRootAttrList (pRootAttrList);
xHandler->startDocument();
Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY );
if ( xExtHandler.is() && bProvideDTD )
{
OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) );
xExtHandler->unknown ( aDocType );
xHandler->ignorableWhitespace ( sWhiteSpace );
}
xHandler->startElement( sManifestElement, xRootAttrList );
for (sal_uInt32 i = 0 ; i < nManLength ; i++)
{
::comphelper::AttributeList *pAttrList = new ::comphelper::AttributeList;
const PropertyValue *pValue = pSequence[i].getConstArray();
OUString aString;
const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL, *pDigest = NULL;
for (sal_uInt32 j = 0, nNum = pSequence[i].getLength(); j < nNum; j++, pValue++)
{
if (pValue->Name.equals (sMediaTypeProperty) )
{
pValue->Value >>= aString;
pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString );
}
else if (pValue->Name.equals (sFullPathProperty) )
{
pValue->Value >>= aString;
pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString );
}
else if (pValue->Name.equals (sSizeProperty) )
{
sal_Int32 nSize;
pValue->Value >>= nSize;
OUStringBuffer aBuffer;
aBuffer.append ( nSize );
pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
}
else if (pValue->Name.equals (sInitialisationVectorProperty) )
pVector = pValue;
else if (pValue->Name.equals (sSaltProperty) )
pSalt = pValue;
else if (pValue->Name.equals (sIterationCountProperty) )
pIterationCount = pValue;
else if (pValue->Name.equals ( sDigestProperty ) )
pDigest = pValue;
}
xHandler->ignorableWhitespace ( sWhiteSpace );
Reference < XAttributeList > xAttrList ( pAttrList );
xHandler->startElement( sFileEntryElement , xAttrList);
if ( pVector && pSalt && pIterationCount )
{
::comphelper::AttributeList * pNewAttrList = new ::comphelper::AttributeList;
Reference < XAttributeList > xNewAttrList (pNewAttrList);
OUStringBuffer aBuffer;
Sequence < sal_uInt8 > aSequence;
xHandler->ignorableWhitespace ( sWhiteSpace );
if ( pDigest )
{
pNewAttrList->AddAttribute ( sChecksumTypeAttribute, sCdataAttribute, sChecksumType );
pDigest->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sChecksumAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
}
xHandler->startElement( sEncryptionDataElement , xNewAttrList);
pNewAttrList = new ::comphelper::AttributeList;
xNewAttrList = pNewAttrList;
pNewAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish );
pVector->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->startElement( sAlgorithmElement , xNewAttrList);
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sAlgorithmElement );
pNewAttrList = new ::comphelper::AttributeList;
xNewAttrList = pNewAttrList;
pNewAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 );
sal_Int32 nCount;
pIterationCount->Value >>= nCount;
aBuffer.append (nCount);
pNewAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
pSalt->Value >>= aSequence;
Base64Codec::encodeBase64 ( aBuffer, aSequence );
pNewAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->startElement( sKeyDerivationElement , xNewAttrList);
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sKeyDerivationElement );
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sEncryptionDataElement );
}
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sFileEntryElement );
}
xHandler->ignorableWhitespace ( sWhiteSpace );
xHandler->endElement( sManifestElement );
xHandler->endDocument();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <cstdint>
#include <vector>
#include "caf/detail/comparable.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/detail/unordered_flat_map.hpp"
#include "caf/fwd.hpp"
#include "caf/hash/fnv.hpp"
#include "caf/inspector_access.hpp"
#include "caf/intrusive_cow_ptr.hpp"
#include "caf/intrusive_ptr.hpp"
#include "caf/ip_address.hpp"
#include "caf/string_view.hpp"
#include "caf/variant.hpp"
namespace caf {
/// A URI according to RFC 3986.
class CAF_CORE_EXPORT uri : detail::comparable<uri>,
detail::comparable<uri, string_view> {
public:
// -- friends -
template <class>
friend struct inspector_access;
// -- member types -----------------------------------------------------------
/// Host subcomponent of the authority component. Either an IP address or
/// an hostname as string.
using host_type = variant<std::string, ip_address>;
/// Bundles the authority component of the URI, i.e., userinfo, host, and
/// port.
struct authority_type {
std::string userinfo;
host_type host;
uint16_t port;
authority_type() : port(0) {
// nop
}
/// Returns whether `host` is empty, i.e., the host is not an IP address
/// and the string is empty.
bool empty() const noexcept {
auto str = get_if<std::string>(&host);
return str != nullptr && str->empty();
}
};
/// Separates the query component into key-value pairs.
using path_list = std::vector<string_view>;
/// Separates the query component into key-value pairs.
using query_map = detail::unordered_flat_map<std::string, std::string>;
class CAF_CORE_EXPORT impl_type {
public:
// -- constructors, destructors, and assignment operators ------------------
impl_type();
impl_type(const impl_type&) = delete;
impl_type& operator=(const impl_type&) = delete;
// -- member variables -----------------------------------------------------
/// Null-terminated buffer for holding the string-representation of the URI.
std::string str;
/// Scheme component.
std::string scheme;
/// Assembled authority component.
uri::authority_type authority;
/// Path component.
std::string path;
/// Query component as key-value pairs.
uri::query_map query;
/// The fragment component.
std::string fragment;
// -- properties -----------------------------------------------------------
bool valid() const noexcept {
return !scheme.empty() && (!authority.empty() || !path.empty());
}
bool unique() const noexcept {
return rc_.load() == 1;
}
// -- modifiers ------------------------------------------------------------
/// Assembles the human-readable string representation for this URI.
void assemble_str();
// -- friend functions -----------------------------------------------------
friend void intrusive_ptr_add_ref(const impl_type* p) {
p->rc_.fetch_add(1, std::memory_order_relaxed);
}
friend void intrusive_ptr_release(const impl_type* p) {
if (p->rc_ == 1 || p->rc_.fetch_sub(1, std::memory_order_acq_rel) == 1)
delete p;
}
private:
// -- member variables -----------------------------------------------------
mutable std::atomic<size_t> rc_;
};
/// Pointer to implementation.
using impl_ptr = intrusive_ptr<impl_type>;
// -- constructors, destructors, and assignment operators --------------------
uri();
uri(uri&&) = default;
uri(const uri&) = default;
uri& operator=(uri&&) = default;
uri& operator=(const uri&) = default;
explicit uri(impl_ptr ptr);
// -- properties -------------------------------------------------------------
/// Returns whether all components of this URI are empty.
bool empty() const noexcept {
return str().empty();
}
/// Returns whether the URI contains valid content.
bool valid() const noexcept {
return !empty();
}
/// Returns the full URI as provided by the user.
string_view str() const noexcept {
return impl_->str;
}
/// Returns the scheme component.
string_view scheme() const noexcept {
return impl_->scheme;
}
/// Returns the authority component.
const authority_type& authority() const noexcept {
return impl_->authority;
}
/// Returns the path component as provided by the user.
string_view path() const noexcept {
return impl_->path;
}
/// Returns the query component as key-value map.
const query_map& query() const noexcept {
return impl_->query;
}
/// Returns the fragment component.
string_view fragment() const noexcept {
return impl_->fragment;
}
/// Returns a hash code over all components.
size_t hash_code() const noexcept;
/// Returns a new URI with the `authority` component only.
/// @returns A new URI in the form `scheme://authority` if the authority
/// exists, otherwise `none`.`
optional<uri> authority_only() const;
// -- comparison -------------------------------------------------------------
auto compare(const uri& other) const noexcept {
return str().compare(other.str());
}
auto compare(string_view x) const noexcept {
return str().compare(x);
}
// -- parsing ----------------------------------------------------------------
/// Returns whether `parse` would produce a valid URI.
static bool can_parse(string_view str) noexcept;
private:
impl_ptr impl_;
};
// -- related free functions ---------------------------------------------------
template <class Inspector>
bool inspect(Inspector& f, uri::authority_type& x) {
return f.object(x).fields(f.field("userinfo", x.userinfo),
f.field("host", x.host), f.field("port", x.port));
}
template <class Inspector>
bool inspect(Inspector& f, uri::impl_type& x) {
auto load_cb = [&] {
x.assemble_str();
return true;
};
return f.object(x)
.on_load(load_cb) //
.fields(f.field("str", x.str), f.field("scheme", x.scheme),
f.field("authority", x.authority), f.field("path", x.path),
f.field("query", x.query), f.field("fragment", x.fragment));
}
/// @relates uri
CAF_CORE_EXPORT std::string to_string(const uri& x);
/// @relates uri
CAF_CORE_EXPORT std::string to_string(const uri::authority_type& x);
/// @relates uri
CAF_CORE_EXPORT error parse(string_view str, uri& dest);
/// @relates uri
CAF_CORE_EXPORT expected<uri> make_uri(string_view str);
template <>
struct inspector_access<uri> : inspector_access_base<uri> {
template <class Inspector>
static bool apply_object(Inspector& f, uri& x) {
if (f.has_human_readable_format()) {
// TODO: extend the inspector DSL to promote string_view to std::string
// automatically to avoid unnecessary to_string conversions.
auto get = [&x] { return to_string(x); };
// TODO: setters should be able to return the error directly to avoid loss
// of information.
auto set = [&x](std::string str) {
auto err = parse(str, x);
return err.empty();
};
return f.object(x).fields(f.field("value", get, set));
} else {
if constexpr (Inspector::is_loading)
if (!x.impl_->unique())
x.impl_.reset(new uri::impl_type);
return inspect(f, *x.impl_);
}
}
template <class Inspector>
static bool apply_value(Inspector& f, uri& x) {
if (f.has_human_readable_format()) {
auto get = [&x] { return to_string(x); };
auto set = [&x](std::string str) {
auto err = parse(str, x);
return err.empty();
};
return detail::split_save_load(f, get, set);
} else {
if constexpr (Inspector::is_loading)
if (!x.impl_->unique())
x.impl_.reset(new uri::impl_type);
return inspect(f, *x.impl_);
}
}
};
} // namespace caf
namespace std {
template <>
struct hash<caf::uri> {
size_t operator()(const caf::uri& x) const noexcept {
return caf::hash::fnv<size_t>::compute(x);
}
};
} // namespace std
<commit_msg>Address leak warning in uri<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <cstdint>
#include <vector>
#include "caf/detail/comparable.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/detail/unordered_flat_map.hpp"
#include "caf/fwd.hpp"
#include "caf/hash/fnv.hpp"
#include "caf/inspector_access.hpp"
#include "caf/intrusive_cow_ptr.hpp"
#include "caf/intrusive_ptr.hpp"
#include "caf/ip_address.hpp"
#include "caf/make_counted.hpp"
#include "caf/string_view.hpp"
#include "caf/variant.hpp"
namespace caf {
/// A URI according to RFC 3986.
class CAF_CORE_EXPORT uri : detail::comparable<uri>,
detail::comparable<uri, string_view> {
public:
// -- friends -
template <class>
friend struct inspector_access;
// -- member types -----------------------------------------------------------
/// Host subcomponent of the authority component. Either an IP address or
/// an hostname as string.
using host_type = variant<std::string, ip_address>;
/// Bundles the authority component of the URI, i.e., userinfo, host, and
/// port.
struct authority_type {
std::string userinfo;
host_type host;
uint16_t port;
authority_type() : port(0) {
// nop
}
/// Returns whether `host` is empty, i.e., the host is not an IP address
/// and the string is empty.
bool empty() const noexcept {
auto str = get_if<std::string>(&host);
return str != nullptr && str->empty();
}
};
/// Separates the query component into key-value pairs.
using path_list = std::vector<string_view>;
/// Separates the query component into key-value pairs.
using query_map = detail::unordered_flat_map<std::string, std::string>;
class CAF_CORE_EXPORT impl_type {
public:
// -- constructors, destructors, and assignment operators ------------------
impl_type();
impl_type(const impl_type&) = delete;
impl_type& operator=(const impl_type&) = delete;
// -- member variables -----------------------------------------------------
/// Null-terminated buffer for holding the string-representation of the URI.
std::string str;
/// Scheme component.
std::string scheme;
/// Assembled authority component.
uri::authority_type authority;
/// Path component.
std::string path;
/// Query component as key-value pairs.
uri::query_map query;
/// The fragment component.
std::string fragment;
// -- properties -----------------------------------------------------------
bool valid() const noexcept {
return !scheme.empty() && (!authority.empty() || !path.empty());
}
bool unique() const noexcept {
return rc_.load() == 1;
}
// -- modifiers ------------------------------------------------------------
/// Assembles the human-readable string representation for this URI.
void assemble_str();
// -- friend functions -----------------------------------------------------
friend void intrusive_ptr_add_ref(const impl_type* p) {
p->rc_.fetch_add(1, std::memory_order_relaxed);
}
friend void intrusive_ptr_release(const impl_type* p) {
if (p->rc_ == 1 || p->rc_.fetch_sub(1, std::memory_order_acq_rel) == 1)
delete p;
}
private:
// -- member variables -----------------------------------------------------
mutable std::atomic<size_t> rc_;
};
/// Pointer to implementation.
using impl_ptr = intrusive_ptr<impl_type>;
// -- constructors, destructors, and assignment operators --------------------
uri();
uri(uri&&) = default;
uri(const uri&) = default;
uri& operator=(uri&&) = default;
uri& operator=(const uri&) = default;
explicit uri(impl_ptr ptr);
// -- properties -------------------------------------------------------------
/// Returns whether all components of this URI are empty.
bool empty() const noexcept {
return str().empty();
}
/// Returns whether the URI contains valid content.
bool valid() const noexcept {
return !empty();
}
/// Returns the full URI as provided by the user.
string_view str() const noexcept {
return impl_->str;
}
/// Returns the scheme component.
string_view scheme() const noexcept {
return impl_->scheme;
}
/// Returns the authority component.
const authority_type& authority() const noexcept {
return impl_->authority;
}
/// Returns the path component as provided by the user.
string_view path() const noexcept {
return impl_->path;
}
/// Returns the query component as key-value map.
const query_map& query() const noexcept {
return impl_->query;
}
/// Returns the fragment component.
string_view fragment() const noexcept {
return impl_->fragment;
}
/// Returns a hash code over all components.
size_t hash_code() const noexcept;
/// Returns a new URI with the `authority` component only.
/// @returns A new URI in the form `scheme://authority` if the authority
/// exists, otherwise `none`.`
optional<uri> authority_only() const;
// -- comparison -------------------------------------------------------------
auto compare(const uri& other) const noexcept {
return str().compare(other.str());
}
auto compare(string_view x) const noexcept {
return str().compare(x);
}
// -- parsing ----------------------------------------------------------------
/// Returns whether `parse` would produce a valid URI.
static bool can_parse(string_view str) noexcept;
private:
impl_ptr impl_;
};
// -- related free functions ---------------------------------------------------
template <class Inspector>
bool inspect(Inspector& f, uri::authority_type& x) {
return f.object(x).fields(f.field("userinfo", x.userinfo),
f.field("host", x.host), f.field("port", x.port));
}
template <class Inspector>
bool inspect(Inspector& f, uri::impl_type& x) {
auto load_cb = [&] {
x.assemble_str();
return true;
};
return f.object(x)
.on_load(load_cb) //
.fields(f.field("str", x.str), f.field("scheme", x.scheme),
f.field("authority", x.authority), f.field("path", x.path),
f.field("query", x.query), f.field("fragment", x.fragment));
}
/// @relates uri
CAF_CORE_EXPORT std::string to_string(const uri& x);
/// @relates uri
CAF_CORE_EXPORT std::string to_string(const uri::authority_type& x);
/// @relates uri
CAF_CORE_EXPORT error parse(string_view str, uri& dest);
/// @relates uri
CAF_CORE_EXPORT expected<uri> make_uri(string_view str);
template <>
struct inspector_access<uri> : inspector_access_base<uri> {
template <class Inspector>
static bool apply_object(Inspector& f, uri& x) {
if (f.has_human_readable_format()) {
// TODO: extend the inspector DSL to promote string_view to std::string
// automatically to avoid unnecessary to_string conversions.
auto get = [&x] { return to_string(x); };
// TODO: setters should be able to return the error directly to avoid loss
// of information.
auto set = [&x](std::string str) {
auto err = parse(str, x);
return err.empty();
};
return f.object(x).fields(f.field("value", get, set));
} else {
if constexpr (Inspector::is_loading)
if (!x.impl_->unique()) {
x.impl_.reset();
x.impl_ = make_counted<uri::impl_type>();
}
return inspect(f, *x.impl_);
}
}
template <class Inspector>
static bool apply_value(Inspector& f, uri& x) {
if (f.has_human_readable_format()) {
auto get = [&x] { return to_string(x); };
auto set = [&x](std::string str) {
auto err = parse(str, x);
return err.empty();
};
return detail::split_save_load(f, get, set);
} else {
if constexpr (Inspector::is_loading)
if (!x.impl_->unique()){
x.impl_.reset();
x.impl_ = make_counted<uri::impl_type>();
}
return inspect(f, *x.impl_);
}
}
};
} // namespace caf
namespace std {
template <>
struct hash<caf::uri> {
size_t operator()(const caf::uri& x) const noexcept {
return caf::hash::fnv<size_t>::compute(x);
}
};
} // namespace std
<|endoftext|> |
<commit_before>#include "Precompiled.h"
#include "Element.h"
#include "ElementManager.h"
namespace libgui
{
// Element Manager
void Element::SetElementManager(shared_ptr<ElementManager> elementManager)
{
m_elementManager = elementManager;
}
shared_ptr<ElementManager> Element::GetElementManager()
{
return m_elementManager;
}
// View Model
void Element::SetViewModel(shared_ptr<ViewModelBase> viewModel)
{
m_viewModel = viewModel;
}
shared_ptr<ViewModelBase> Element::GetViewModel()
{
return m_viewModel;
}
// Visual tree
shared_ptr<Element> Element::GetParent()
{
return m_parent;
}
shared_ptr<Element> Element::GetFirstChild()
{
return m_firstChild;
}
shared_ptr<Element> Element::GetLastChild()
{
return m_lastChild;
}
shared_ptr<Element> Element::GetPrevSibling()
{
return m_prevsibling;
}
shared_ptr<Element> Element::GetNextSibling()
{
return m_nextsibling;
}
void Element::RemoveChildren()
{
m_firstChild = nullptr;
m_lastChild = nullptr;
m_childrenCount = 0;
}
void Element::AddChild(shared_ptr<Element> element)
{
if (m_firstChild == nullptr)
{
m_firstChild = element;
}
else
{
element->m_prevsibling = m_lastChild;
m_lastChild->m_nextsibling = element;
}
element->m_parent = shared_from_this();
m_lastChild = element;
m_childrenCount++;
}
int Element::GetChildrenCount()
{
return m_childrenCount;
}
void Element::SetSingleChild(shared_ptr<Element> child)
{
// Could be optimized to improve performance
RemoveChildren();
AddChild(child);
}
shared_ptr<Element> Element::GetSingleChild()
{
if (m_childrenCount == 1)
{
return m_firstChild;
}
if (m_childrenCount == 0)
{
return nullptr;
}
throw std::runtime_error("There is more than one child in this element");
}
// Cache Management
void Element::ClearCache(int cacheLevel)
{
ClearElementCache(cacheLevel);
// Recurse to children
if (m_firstChild)
{
for (auto e = m_firstChild; e != nullptr; e = e->m_nextsibling)
{
e->ClearCache(cacheLevel);
}
}
}
void Element::ClearElementCache(int cacheLevel)
{
// This is intended to be overridden as needed for OS-specific needs.
}
// Arrangement
void Element::ResetArrangement()
{
if (m_parent)
{
// Copy the element manager from the parent
m_elementManager = m_parent->m_elementManager;
}
m_isVisible = true;
m_left = 0;
m_top = 0;
m_right = 0;
m_bottom = 0;
m_centerX = 0;
m_centerY = 0;
m_width = 0;
m_height = 0;
m_isLeftSet = false;
m_isTopSet = false;
m_isRightSet = false;
m_isBottomSet = false;
m_isCenterXSet = false;
m_isCenterYSet = false;
m_isWidthSet = false;
m_isHeightSet = false;
}
void Element::SetSetViewModelCallback(function<void(shared_ptr<Element>)> setViewModelCallback)
{
m_setViewModelCallback = setViewModelCallback;
}
void Element::PrepareViewModel()
{
if (m_setViewModelCallback)
{
m_setViewModelCallback(shared_from_this());
}
else
{
// By default the ViewModel is copied from the parent
if (m_parent)
{
m_viewModel = m_parent->m_viewModel;
}
}
}
void Element::SetArrangeCallback(function<void(shared_ptr<Element>)> arrangeCallback)
{
m_arrangeCallback = arrangeCallback;
}
void Element::Arrange()
{
if (m_arrangeCallback)
{
m_arrangeCallback(shared_from_this());
}
else
{
// By default each element stretches
// to fill its parent
SetLeft(m_parent->GetLeft());
SetTop(m_parent->GetTop());
SetRight(m_parent->GetRight());
SetBottom(m_parent->GetBottom());
}
}
void Element::ArrangeAndDraw(bool draw)
{
ResetArrangement();
PrepareViewModel();
Arrange();
if (draw && m_isVisible)
{
Draw();
if (m_firstChild)
{
for (auto e = m_firstChild; e != nullptr; e = e->m_nextsibling)
{
e->ArrangeAndDraw(draw);
}
}
}
}
void Element::SetIsVisible(bool isVisible)
{
m_isVisible = isVisible;
}
bool Element::GetIsVisible()
{
return m_isVisible;
}
void Element::SetLeft(double left)
{
m_isLeftSet = true;
m_left = left;
}
void Element::SetTop(double top)
{
m_isTopSet = true;
m_top = top;
}
void Element::SetRight(double right)
{
m_isRightSet = true;
m_right = right;
}
void Element::SetBottom(double bottom)
{
m_isBottomSet = true;
m_bottom = bottom;
}
void Element::SetCenterX(double centerX)
{
m_isCenterXSet = true;
m_centerX = centerX;
}
void Element::SetCenterY(double centerY)
{
m_isCenterYSet = true;
m_centerY = centerY;
}
void Element::SetWidth(double width)
{
m_isWidthSet = true;
m_width = width;
}
void Element::SetHeight(double height)
{
m_isHeightSet = true;
m_height = height;
}
double Element::GetLeft()
{
if (!m_isLeftSet)
{
if (m_isWidthSet)
{
if (m_isRightSet)
{
m_left = m_right - m_width;
}
else if (m_isCenterXSet)
{
m_left = m_centerX - (m_width / 2);
}
}
m_isLeftSet = true;
}
return m_left;
}
double Element::GetTop()
{
if (!m_isTopSet)
{
if (m_isHeightSet)
{
if (m_isBottomSet)
{
m_top = m_bottom - m_height;
}
else if (m_isCenterYSet)
{
m_top = m_centerY - (m_height / 2);
}
}
m_isTopSet = true;
}
return m_top;
}
double Element::GetRight()
{
if (!m_isRightSet)
{
if (m_isWidthSet)
{
if (m_isLeftSet)
{
m_right = m_left + m_width;
}
else if (m_isCenterXSet)
{
m_right = m_centerX + (m_width / 2);
}
}
m_isRightSet = true;
}
return m_right;
}
double Element::GetBottom()
{
if (!m_isBottomSet)
{
if (m_isHeightSet)
{
if (m_isTopSet)
{
m_bottom = m_top + m_height;
}
else if (m_isCenterYSet)
{
m_bottom = m_centerY + (m_height / 2);
}
}
m_isBottomSet = true;
}
return m_bottom;
}
double Element::GetCenterX()
{
if (!m_isCenterXSet)
{
if (m_isLeftSet && m_isRightSet)
{
m_centerX = m_left + (m_right - m_left) / 2;
}
else if (m_isLeftSet && m_isWidthSet)
{
m_centerX = m_left + (m_width / 2);
}
else if (m_isRightSet && m_isWidthSet)
{
m_centerX = m_right - (m_width / 2);
}
m_isCenterXSet = true;
}
return m_centerX;
}
double Element::GetCenterY()
{
if (!m_isCenterYSet)
{
if (m_isTopSet && m_isBottomSet)
{
m_centerY = m_top + (m_bottom - m_top) / 2;
}
else if (m_isTopSet && m_isHeightSet)
{
m_centerY = m_top + (m_height / 2);
}
else if (m_isBottomSet && m_isHeightSet)
{
m_centerY = m_bottom - (m_height / 2);
}
m_isCenterYSet = true;
}
return m_centerY;
}
double Element::GetWidth()
{
if (!m_isWidthSet)
{
if (m_isLeftSet && m_isRightSet)
{
m_width = m_right - m_left;
}
m_isWidthSet = true;
}
return m_width;
}
double Element::GetHeight()
{
if (!m_isHeightSet)
{
if (m_isTopSet && m_isBottomSet)
{
m_height = m_bottom - m_top;
}
m_isHeightSet = true;
}
return m_height;
}
// Drawing
void Element::Draw()
{
if (m_drawCallback)
{
m_drawCallback(shared_from_this());
}
else
{
// By default no drawing takes place
}
}
void Element::SetDrawCallback(function<void(shared_ptr<Element>)> drawCallback)
{
m_drawCallback = drawCallback;
}
// Hit testing
shared_ptr<Element> Element::GetElementAtPoint(Location point)
{
if (m_firstChild)
{
for (auto e = m_lastChild; e != nullptr; e = e->m_prevsibling)
{
auto elementAtPoint = e->GetElementAtPoint(point);
if (elementAtPoint)
{
return elementAtPoint;
}
}
}
if (point.x >= GetLeft() && point.x <= GetRight() &&
point.y >= GetTop() && point.y <= GetBottom())
{
return shared_from_this();
}
return nullptr;
}
}
<commit_msg>RemoveChildren now cleans all pointers between elements so that the elements will be deleted<commit_after>#include "Precompiled.h"
#include "Element.h"
#include "ElementManager.h"
namespace libgui
{
// Element Manager
void Element::SetElementManager(shared_ptr<ElementManager> elementManager)
{
m_elementManager = elementManager;
}
shared_ptr<ElementManager> Element::GetElementManager()
{
return m_elementManager;
}
// View Model
void Element::SetViewModel(shared_ptr<ViewModelBase> viewModel)
{
m_viewModel = viewModel;
}
shared_ptr<ViewModelBase> Element::GetViewModel()
{
return m_viewModel;
}
// Visual tree
shared_ptr<Element> Element::GetParent()
{
return m_parent;
}
shared_ptr<Element> Element::GetFirstChild()
{
return m_firstChild;
}
shared_ptr<Element> Element::GetLastChild()
{
return m_lastChild;
}
shared_ptr<Element> Element::GetPrevSibling()
{
return m_prevsibling;
}
shared_ptr<Element> Element::GetNextSibling()
{
return m_nextsibling;
}
void Element::RemoveChildren()
{
// Recurse into children to thoroughly clean the element tree
auto e = m_firstChild;
while (e != nullptr)
{
e->RemoveChildren();
// Clean up pointers so that the class will be deleted
e->m_parent = nullptr;
e->m_prevsibling = nullptr;
auto next_e = e->m_nextsibling;
e->m_nextsibling = nullptr;
e = next_e;
}
m_firstChild = nullptr;
m_lastChild = nullptr;
m_childrenCount = 0;
}
void Element::AddChild(shared_ptr<Element> element)
{
if (m_firstChild == nullptr)
{
m_firstChild = element;
}
else
{
element->m_prevsibling = m_lastChild;
m_lastChild->m_nextsibling = element;
}
element->m_parent = shared_from_this();
m_lastChild = element;
m_childrenCount++;
}
int Element::GetChildrenCount()
{
return m_childrenCount;
}
void Element::SetSingleChild(shared_ptr<Element> child)
{
// Could be optimized to improve performance
RemoveChildren();
AddChild(child);
}
shared_ptr<Element> Element::GetSingleChild()
{
if (m_childrenCount == 1)
{
return m_firstChild;
}
if (m_childrenCount == 0)
{
return nullptr;
}
throw std::runtime_error("There is more than one child in this element");
}
// Cache Management
void Element::ClearCache(int cacheLevel)
{
ClearElementCache(cacheLevel);
// Recurse to children
if (m_firstChild)
{
for (auto e = m_firstChild; e != nullptr; e = e->m_nextsibling)
{
e->ClearCache(cacheLevel);
}
}
}
void Element::ClearElementCache(int cacheLevel)
{
// This is intended to be overridden as needed for OS-specific needs.
}
// Arrangement
void Element::ResetArrangement()
{
if (m_parent)
{
// Copy the element manager from the parent
m_elementManager = m_parent->m_elementManager;
}
m_isVisible = true;
m_left = 0;
m_top = 0;
m_right = 0;
m_bottom = 0;
m_centerX = 0;
m_centerY = 0;
m_width = 0;
m_height = 0;
m_isLeftSet = false;
m_isTopSet = false;
m_isRightSet = false;
m_isBottomSet = false;
m_isCenterXSet = false;
m_isCenterYSet = false;
m_isWidthSet = false;
m_isHeightSet = false;
}
void Element::SetSetViewModelCallback(function<void(shared_ptr<Element>)> setViewModelCallback)
{
m_setViewModelCallback = setViewModelCallback;
}
void Element::PrepareViewModel()
{
if (m_setViewModelCallback)
{
m_setViewModelCallback(shared_from_this());
}
else
{
// By default the ViewModel is copied from the parent
if (m_parent)
{
m_viewModel = m_parent->m_viewModel;
}
}
}
void Element::SetArrangeCallback(function<void(shared_ptr<Element>)> arrangeCallback)
{
m_arrangeCallback = arrangeCallback;
}
void Element::Arrange()
{
if (m_arrangeCallback)
{
m_arrangeCallback(shared_from_this());
}
else
{
// By default each element stretches
// to fill its parent
SetLeft(m_parent->GetLeft());
SetTop(m_parent->GetTop());
SetRight(m_parent->GetRight());
SetBottom(m_parent->GetBottom());
}
}
void Element::ArrangeAndDraw(bool draw)
{
ResetArrangement();
PrepareViewModel();
Arrange();
if (draw && m_isVisible)
{
Draw();
if (m_firstChild)
{
for (auto e = m_firstChild; e != nullptr; e = e->m_nextsibling)
{
e->ArrangeAndDraw(draw);
}
}
}
}
void Element::SetIsVisible(bool isVisible)
{
m_isVisible = isVisible;
}
bool Element::GetIsVisible()
{
return m_isVisible;
}
void Element::SetLeft(double left)
{
m_isLeftSet = true;
m_left = left;
}
void Element::SetTop(double top)
{
m_isTopSet = true;
m_top = top;
}
void Element::SetRight(double right)
{
m_isRightSet = true;
m_right = right;
}
void Element::SetBottom(double bottom)
{
m_isBottomSet = true;
m_bottom = bottom;
}
void Element::SetCenterX(double centerX)
{
m_isCenterXSet = true;
m_centerX = centerX;
}
void Element::SetCenterY(double centerY)
{
m_isCenterYSet = true;
m_centerY = centerY;
}
void Element::SetWidth(double width)
{
m_isWidthSet = true;
m_width = width;
}
void Element::SetHeight(double height)
{
m_isHeightSet = true;
m_height = height;
}
double Element::GetLeft()
{
if (!m_isLeftSet)
{
if (m_isWidthSet)
{
if (m_isRightSet)
{
m_left = m_right - m_width;
}
else if (m_isCenterXSet)
{
m_left = m_centerX - (m_width / 2);
}
}
m_isLeftSet = true;
}
return m_left;
}
double Element::GetTop()
{
if (!m_isTopSet)
{
if (m_isHeightSet)
{
if (m_isBottomSet)
{
m_top = m_bottom - m_height;
}
else if (m_isCenterYSet)
{
m_top = m_centerY - (m_height / 2);
}
}
m_isTopSet = true;
}
return m_top;
}
double Element::GetRight()
{
if (!m_isRightSet)
{
if (m_isWidthSet)
{
if (m_isLeftSet)
{
m_right = m_left + m_width;
}
else if (m_isCenterXSet)
{
m_right = m_centerX + (m_width / 2);
}
}
m_isRightSet = true;
}
return m_right;
}
double Element::GetBottom()
{
if (!m_isBottomSet)
{
if (m_isHeightSet)
{
if (m_isTopSet)
{
m_bottom = m_top + m_height;
}
else if (m_isCenterYSet)
{
m_bottom = m_centerY + (m_height / 2);
}
}
m_isBottomSet = true;
}
return m_bottom;
}
double Element::GetCenterX()
{
if (!m_isCenterXSet)
{
if (m_isLeftSet && m_isRightSet)
{
m_centerX = m_left + (m_right - m_left) / 2;
}
else if (m_isLeftSet && m_isWidthSet)
{
m_centerX = m_left + (m_width / 2);
}
else if (m_isRightSet && m_isWidthSet)
{
m_centerX = m_right - (m_width / 2);
}
m_isCenterXSet = true;
}
return m_centerX;
}
double Element::GetCenterY()
{
if (!m_isCenterYSet)
{
if (m_isTopSet && m_isBottomSet)
{
m_centerY = m_top + (m_bottom - m_top) / 2;
}
else if (m_isTopSet && m_isHeightSet)
{
m_centerY = m_top + (m_height / 2);
}
else if (m_isBottomSet && m_isHeightSet)
{
m_centerY = m_bottom - (m_height / 2);
}
m_isCenterYSet = true;
}
return m_centerY;
}
double Element::GetWidth()
{
if (!m_isWidthSet)
{
if (m_isLeftSet && m_isRightSet)
{
m_width = m_right - m_left;
}
m_isWidthSet = true;
}
return m_width;
}
double Element::GetHeight()
{
if (!m_isHeightSet)
{
if (m_isTopSet && m_isBottomSet)
{
m_height = m_bottom - m_top;
}
m_isHeightSet = true;
}
return m_height;
}
// Drawing
void Element::Draw()
{
if (m_drawCallback)
{
m_drawCallback(shared_from_this());
}
else
{
// By default no drawing takes place
}
}
void Element::SetDrawCallback(function<void(shared_ptr<Element>)> drawCallback)
{
m_drawCallback = drawCallback;
}
// Hit testing
shared_ptr<Element> Element::GetElementAtPoint(Location point)
{
if (m_firstChild)
{
for (auto e = m_lastChild; e != nullptr; e = e->m_prevsibling)
{
auto elementAtPoint = e->GetElementAtPoint(point);
if (elementAtPoint)
{
return elementAtPoint;
}
}
}
if (point.x >= GetLeft() && point.x <= GetRight() &&
point.y >= GetTop() && point.y <= GetBottom())
{
return shared_from_this();
}
return nullptr;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: AliTHn.cxx 20164 2007-08-14 15:31:50Z morsch $ */
//
// this storage container is optimized for small memory usage
// under/over flow bins do not exist
// sumw2 structure is float only and only create when the weight != 1
// all histogram functionality (projections, axis, ranges, etc) are taken from THnSparse by propagating
// the information up into the THnSparse structure (in the ananalysis *after* data processing and merging)
//
// the derivation from THnSparse is obviously against many OO rules. correct would be a common baseclass of THnSparse and THn.
//
// Author: Jan Fiete Grosse-Oetringhaus
#include "AliTHn.h"
#include "TList.h"
#include "TCollection.h"
#include "AliLog.h"
#include "TArrayF.h"
#include "THnSparse.h"
#include "TMath.h"
ClassImp(AliTHn)
AliTHn::AliTHn() :
AliCFContainer(),
fNBins(0),
fNVars(0),
fNSteps(0),
fValues(0),
fSumw2(0),
axisCache(0)
{
// Constructor
}
AliTHn::AliTHn(const Char_t* name, const Char_t* title,const Int_t nSelStep, const Int_t nVarIn, const Int_t* nBinIn) :
AliCFContainer(name, title, nSelStep, nVarIn, nBinIn),
fNBins(0),
fNVars(nVarIn),
fNSteps(nSelStep),
fValues(0),
fSumw2(0),
axisCache(0)
{
// Constructor
fNBins = 1;
for (Int_t i=0; i<fNVars; i++)
fNBins *= nBinIn[i];
Init();
}
void AliTHn::Init()
{
// initialize
fValues = new TArrayF*[fNSteps];
fSumw2 = new TArrayF*[fNSteps];
for (Int_t i=0; i<fNSteps; i++)
{
fValues[i] = 0;
fSumw2[i] = 0;
}
}
AliTHn::AliTHn(const AliTHn &c) :
AliCFContainer(c),
fNBins(c.fNBins),
fNVars(c.fNVars),
fNSteps(c.fNSteps),
fValues(new TArrayF*[c.fNSteps]),
fSumw2(new TArrayF*[c.fNSteps]),
axisCache(0)
{
//
// AliTHn copy constructor
//
memset(fValues,0,fNSteps*sizeof(TArrayF*));
memset(fSumw2,0,fNSteps*sizeof(TArrayF*));
for (Int_t i=0; i<fNSteps; i++) {
if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
if (c.fSumw2[i]) fSumw2[i] = new TArrayF(*(c.fSumw2[i]));
}
}
AliTHn::~AliTHn()
{
// Destructor
DeleteContainers();
delete[] fValues;
delete[] fSumw2;
delete[] axisCache;
}
void AliTHn::DeleteContainers()
{
// delete data containers
for (Int_t i=0; i<fNSteps; i++)
{
if (fValues && fValues[i])
{
delete fValues[i];
fValues[i] = 0;
}
if (fSumw2 && fSumw2[i])
{
delete fSumw2[i];
fSumw2[i] = 0;
}
}
}
//____________________________________________________________________
AliTHn &AliTHn::operator=(const AliTHn &c)
{
// assigment operator
if (this != &c) {
AliCFContainer::operator=(c);
fNBins=c.fNBins;
fNVars=c.fNVars;
if(fNSteps) {
for(Int_t i=0; i< fNSteps; ++i) {
delete fValues[i];
delete fSumw2[i];
}
delete [] fValues;
delete [] fSumw2;
}
fNSteps=c.fNSteps;
if(fNSteps) {
fValues=new TArrayF*[fNSteps];
fSumw2=new TArrayF*[fNSteps];
memset(fValues,0,fNSteps*sizeof(TArrayF*));
memset(fSumw2,0,fNSteps*sizeof(TArrayF*));
for (Int_t i=0; i<fNSteps; i++) {
if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
if (c.fSumw2[i]) fSumw2[i] = new TArrayF(*(c.fSumw2[i]));
}
} else {
fValues = 0;
fSumw2 = 0;
}
delete [] axisCache;
axisCache = new TAxis*[fNVars];
memcpy(axisCache, c.axisCache, fNVars*sizeof(TAxis**));
}
return *this;
}
//____________________________________________________________________
void AliTHn::Copy(TObject& c) const
{
// copy function
AliTHn& target = (AliTHn &) c;
AliCFContainer::Copy(target);
target.fNSteps = fNSteps;
target.fNBins = fNBins;
target.fNVars = fNVars;
target.Init();
for (Int_t i=0; i<fNSteps; i++)
{
if (fValues[i])
target.fValues[i] = new TArrayF(*(fValues[i]));
else
target.fValues[i] = 0;
if (fSumw2[i])
target.fSumw2[i] = new TArrayF(*(fSumw2[i]));
else
target.fSumw2[i] = 0;
}
}
//____________________________________________________________________
Long64_t AliTHn::Merge(TCollection* list)
{
// Merge a list of AliTHn objects with this (needed for
// PROOF).
// Returns the number of merged objects (including this).
if (!list)
return 0;
if (list->IsEmpty())
return 1;
AliCFContainer::Merge(list);
TIterator* iter = list->MakeIterator();
TObject* obj;
Int_t count = 0;
while ((obj = iter->Next())) {
AliTHn* entry = dynamic_cast<AliTHn*> (obj);
if (entry == 0)
continue;
for (Int_t i=0; i<fNSteps; i++)
{
if (entry->fValues[i])
{
if (!fValues[i])
fValues[i] = new TArrayF(fNBins);
for (Long64_t l = 0; l<fNBins; l++)
fValues[i]->GetArray()[l] += entry->fValues[i]->GetArray()[l];
}
if (entry->fSumw2[i])
{
if (!fSumw2[i])
fSumw2[i] = new TArrayF(fNBins);
for (Long64_t l = 0; l<fNBins; l++)
fSumw2[i]->GetArray()[l] += entry->fSumw2[i]->GetArray()[l];
}
}
count++;
}
return count+1;
}
void AliTHn::Fill(const Double_t *var, Int_t istep, Double_t weight)
{
// fills an entry
// fill axis cache
if (!axisCache)
{
axisCache = new TAxis*[fNVars];
for (Int_t i=0; i<fNVars; i++)
axisCache[i] = GetAxis(i, 0);
}
// calculate global bin index
Long64_t bin = 0;
for (Int_t i=0; i<fNVars; i++)
{
bin *= axisCache[i]->GetNbins();
Int_t tmpBin = axisCache[i]->FindBin(var[i]);
// Printf("%d", tmpBin);
// under/overflow not supported
if (tmpBin < 1 || tmpBin > axisCache[i]->GetNbins())
return;
// bins start from 0 here
bin += tmpBin - 1;
// Printf("%lld", bin);
}
if (!fValues[istep])
{
fValues[istep] = new TArrayF(fNBins);
AliInfo(Form("Created values container for step %d", istep));
}
if (weight != 1)
{
// initialize with already filled entries (which have been filled with weight == 1), in this case fSumw2 := fValues
if (!fSumw2[istep])
{
fSumw2[istep] = new TArrayF(*fValues[istep]);
AliInfo(Form("Created sumw2 container for step %d", istep));
}
}
fValues[istep]->GetArray()[bin] += weight;
if (fSumw2[istep])
fSumw2[istep]->GetArray()[bin] += weight * weight;
// Printf("%f", fValues[istep][bin]);
// debug
// AliCFContainer::Fill(var, istep, weight);
}
Long64_t AliTHn::GetGlobalBinIndex(const Int_t* binIdx)
{
// calculates global bin index
// binIdx contains TAxis bin indexes
// here bin count starts at 0 because we do not have over/underflow bins
Long64_t bin = 0;
for (Int_t i=0; i<fNVars; i++)
{
bin *= GetAxis(i, 0)->GetNbins();
bin += binIdx[i] - 1;
}
return bin;
}
void AliTHn::FillContainer(AliCFContainer* cont)
{
// fills the information stored in the buffer in this class into the container <cont>
for (Int_t i=0; i<fNSteps; i++)
{
if (!fValues[i])
continue;
Float_t* source = fValues[i]->GetArray();
// if fSumw2 is not stored, the sqrt of the number of bin entries in source is filled below; otherwise we use fSumw2
Float_t* sourceSumw2 = source;
if (fSumw2[i])
sourceSumw2 = fSumw2[i]->GetArray();
THnSparse* target = cont->GetGrid(i)->GetGrid();
Int_t* binIdx = new Int_t[fNVars];
Int_t* nBins = new Int_t[fNVars];
for (Int_t j=0; j<fNVars; j++)
{
binIdx[j] = 1;
nBins[j] = target->GetAxis(j)->GetNbins();
}
Long64_t count = 0;
while (1)
{
// for (Int_t j=0; j<fNVars; j++)
// printf("%d ", binIdx[j]);
Long64_t globalBin = GetGlobalBinIndex(binIdx);
// Printf(" --> %lld", globalBin);
if (source[globalBin] != 0)
{
target->SetBinContent(binIdx, source[globalBin]);
target->SetBinError(binIdx, TMath::Sqrt(sourceSumw2[globalBin]));
count++;
}
binIdx[fNVars-1]++;
for (Int_t j=fNVars-1; j>0; j--)
{
if (binIdx[j] > nBins[j])
{
binIdx[j] = 1;
binIdx[j-1]++;
}
}
if (binIdx[0] > nBins[0])
break;
}
AliInfo(Form("Step %d: copied %lld entries out of %lld bins", i, count, GetGlobalBinIndex(binIdx)));
delete[] binIdx;
delete[] nBins;
}
}
void AliTHn::FillParent()
{
// fills the information stored in the buffer in this class into the baseclass containers
FillContainer(this);
}
void AliTHn::ReduceAxis()
{
// "removes" one axis by summing over the axis and putting the entry to bin 1
// TODO presently only implemented for the last axis
Int_t axis = fNVars-1;
for (Int_t i=0; i<fNSteps; i++)
{
if (!fValues[i])
continue;
Float_t* source = fValues[i]->GetArray();
Float_t* sourceSumw2 = 0;
if (fSumw2[i])
sourceSumw2 = fSumw2[i]->GetArray();
THnSparse* target = GetGrid(i)->GetGrid();
Int_t* binIdx = new Int_t[fNVars];
Int_t* nBins = new Int_t[fNVars];
for (Int_t j=0; j<fNVars; j++)
{
binIdx[j] = 1;
nBins[j] = target->GetAxis(j)->GetNbins();
}
Long64_t count = 0;
while (1)
{
// sum over axis <axis>
Float_t sumValues = 0;
Float_t sumSumw2 = 0;
for (Int_t j=1; j<=nBins[axis]; j++)
{
binIdx[axis] = j;
Long64_t globalBin = GetGlobalBinIndex(binIdx);
sumValues += source[globalBin];
source[globalBin] = 0;
if (sourceSumw2)
{
sumSumw2 += sourceSumw2[globalBin];
sourceSumw2[globalBin] = 0;
}
}
binIdx[axis] = 1;
Long64_t globalBin = GetGlobalBinIndex(binIdx);
source[globalBin] = sumValues;
if (sourceSumw2)
sourceSumw2[globalBin] = sumSumw2;
count++;
// next bin
binIdx[fNVars-2]++;
for (Int_t j=fNVars-2; j>0; j--)
{
if (binIdx[j] > nBins[j])
{
binIdx[j] = 1;
binIdx[j-1]++;
}
}
if (binIdx[0] > nBins[0])
break;
}
AliInfo(Form("Step %d: reduced %lld bins to %lld entries", i, GetGlobalBinIndex(binIdx), count));
delete[] binIdx;
delete[] nBins;
}
}
<commit_msg>Coverity 19601<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: AliTHn.cxx 20164 2007-08-14 15:31:50Z morsch $ */
//
// this storage container is optimized for small memory usage
// under/over flow bins do not exist
// sumw2 structure is float only and only create when the weight != 1
// all histogram functionality (projections, axis, ranges, etc) are taken from THnSparse by propagating
// the information up into the THnSparse structure (in the ananalysis *after* data processing and merging)
//
// the derivation from THnSparse is obviously against many OO rules. correct would be a common baseclass of THnSparse and THn.
//
// Author: Jan Fiete Grosse-Oetringhaus
#include "AliTHn.h"
#include "TList.h"
#include "TCollection.h"
#include "AliLog.h"
#include "TArrayF.h"
#include "THnSparse.h"
#include "TMath.h"
ClassImp(AliTHn)
AliTHn::AliTHn() :
AliCFContainer(),
fNBins(0),
fNVars(0),
fNSteps(0),
fValues(0),
fSumw2(0),
axisCache(0)
{
// Constructor
}
AliTHn::AliTHn(const Char_t* name, const Char_t* title,const Int_t nSelStep, const Int_t nVarIn, const Int_t* nBinIn) :
AliCFContainer(name, title, nSelStep, nVarIn, nBinIn),
fNBins(0),
fNVars(nVarIn),
fNSteps(nSelStep),
fValues(0),
fSumw2(0),
axisCache(0)
{
// Constructor
fNBins = 1;
for (Int_t i=0; i<fNVars; i++)
fNBins *= nBinIn[i];
Init();
}
void AliTHn::Init()
{
// initialize
fValues = new TArrayF*[fNSteps];
fSumw2 = new TArrayF*[fNSteps];
for (Int_t i=0; i<fNSteps; i++)
{
fValues[i] = 0;
fSumw2[i] = 0;
}
}
AliTHn::AliTHn(const AliTHn &c) :
AliCFContainer(c),
fNBins(c.fNBins),
fNVars(c.fNVars),
fNSteps(c.fNSteps),
fValues(new TArrayF*[c.fNSteps]),
fSumw2(new TArrayF*[c.fNSteps]),
axisCache(0)
{
//
// AliTHn copy constructor
//
memset(fValues,0,fNSteps*sizeof(TArrayF*));
memset(fSumw2,0,fNSteps*sizeof(TArrayF*));
for (Int_t i=0; i<fNSteps; i++) {
if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
if (c.fSumw2[i]) fSumw2[i] = new TArrayF(*(c.fSumw2[i]));
}
}
AliTHn::~AliTHn()
{
// Destructor
DeleteContainers();
delete[] fValues;
delete[] fSumw2;
delete[] axisCache;
}
void AliTHn::DeleteContainers()
{
// delete data containers
for (Int_t i=0; i<fNSteps; i++)
{
if (fValues && fValues[i])
{
delete fValues[i];
fValues[i] = 0;
}
if (fSumw2 && fSumw2[i])
{
delete fSumw2[i];
fSumw2[i] = 0;
}
}
}
//____________________________________________________________________
AliTHn &AliTHn::operator=(const AliTHn &c)
{
// assigment operator
if (this != &c) {
AliCFContainer::operator=(c);
fNBins=c.fNBins;
fNVars=c.fNVars;
if(fNSteps) {
for(Int_t i=0; i< fNSteps; ++i) {
delete fValues[i];
delete fSumw2[i];
}
delete [] fValues;
delete [] fSumw2;
}
fNSteps=c.fNSteps;
if(fNSteps) {
fValues=new TArrayF*[fNSteps];
fSumw2=new TArrayF*[fNSteps];
memset(fValues,0,fNSteps*sizeof(TArrayF*));
memset(fSumw2,0,fNSteps*sizeof(TArrayF*));
for (Int_t i=0; i<fNSteps; i++) {
if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
if (c.fSumw2[i]) fSumw2[i] = new TArrayF(*(c.fSumw2[i]));
}
} else {
fValues = 0;
fSumw2 = 0;
}
delete [] axisCache;
axisCache = new TAxis*[fNVars];
memcpy(axisCache, c.axisCache, fNVars*sizeof(TAxis*));
}
return *this;
}
//____________________________________________________________________
void AliTHn::Copy(TObject& c) const
{
// copy function
AliTHn& target = (AliTHn &) c;
AliCFContainer::Copy(target);
target.fNSteps = fNSteps;
target.fNBins = fNBins;
target.fNVars = fNVars;
target.Init();
for (Int_t i=0; i<fNSteps; i++)
{
if (fValues[i])
target.fValues[i] = new TArrayF(*(fValues[i]));
else
target.fValues[i] = 0;
if (fSumw2[i])
target.fSumw2[i] = new TArrayF(*(fSumw2[i]));
else
target.fSumw2[i] = 0;
}
}
//____________________________________________________________________
Long64_t AliTHn::Merge(TCollection* list)
{
// Merge a list of AliTHn objects with this (needed for
// PROOF).
// Returns the number of merged objects (including this).
if (!list)
return 0;
if (list->IsEmpty())
return 1;
AliCFContainer::Merge(list);
TIterator* iter = list->MakeIterator();
TObject* obj;
Int_t count = 0;
while ((obj = iter->Next())) {
AliTHn* entry = dynamic_cast<AliTHn*> (obj);
if (entry == 0)
continue;
for (Int_t i=0; i<fNSteps; i++)
{
if (entry->fValues[i])
{
if (!fValues[i])
fValues[i] = new TArrayF(fNBins);
for (Long64_t l = 0; l<fNBins; l++)
fValues[i]->GetArray()[l] += entry->fValues[i]->GetArray()[l];
}
if (entry->fSumw2[i])
{
if (!fSumw2[i])
fSumw2[i] = new TArrayF(fNBins);
for (Long64_t l = 0; l<fNBins; l++)
fSumw2[i]->GetArray()[l] += entry->fSumw2[i]->GetArray()[l];
}
}
count++;
}
return count+1;
}
void AliTHn::Fill(const Double_t *var, Int_t istep, Double_t weight)
{
// fills an entry
// fill axis cache
if (!axisCache)
{
axisCache = new TAxis*[fNVars];
for (Int_t i=0; i<fNVars; i++)
axisCache[i] = GetAxis(i, 0);
}
// calculate global bin index
Long64_t bin = 0;
for (Int_t i=0; i<fNVars; i++)
{
bin *= axisCache[i]->GetNbins();
Int_t tmpBin = axisCache[i]->FindBin(var[i]);
// Printf("%d", tmpBin);
// under/overflow not supported
if (tmpBin < 1 || tmpBin > axisCache[i]->GetNbins())
return;
// bins start from 0 here
bin += tmpBin - 1;
// Printf("%lld", bin);
}
if (!fValues[istep])
{
fValues[istep] = new TArrayF(fNBins);
AliInfo(Form("Created values container for step %d", istep));
}
if (weight != 1)
{
// initialize with already filled entries (which have been filled with weight == 1), in this case fSumw2 := fValues
if (!fSumw2[istep])
{
fSumw2[istep] = new TArrayF(*fValues[istep]);
AliInfo(Form("Created sumw2 container for step %d", istep));
}
}
fValues[istep]->GetArray()[bin] += weight;
if (fSumw2[istep])
fSumw2[istep]->GetArray()[bin] += weight * weight;
// Printf("%f", fValues[istep][bin]);
// debug
// AliCFContainer::Fill(var, istep, weight);
}
Long64_t AliTHn::GetGlobalBinIndex(const Int_t* binIdx)
{
// calculates global bin index
// binIdx contains TAxis bin indexes
// here bin count starts at 0 because we do not have over/underflow bins
Long64_t bin = 0;
for (Int_t i=0; i<fNVars; i++)
{
bin *= GetAxis(i, 0)->GetNbins();
bin += binIdx[i] - 1;
}
return bin;
}
void AliTHn::FillContainer(AliCFContainer* cont)
{
// fills the information stored in the buffer in this class into the container <cont>
for (Int_t i=0; i<fNSteps; i++)
{
if (!fValues[i])
continue;
Float_t* source = fValues[i]->GetArray();
// if fSumw2 is not stored, the sqrt of the number of bin entries in source is filled below; otherwise we use fSumw2
Float_t* sourceSumw2 = source;
if (fSumw2[i])
sourceSumw2 = fSumw2[i]->GetArray();
THnSparse* target = cont->GetGrid(i)->GetGrid();
Int_t* binIdx = new Int_t[fNVars];
Int_t* nBins = new Int_t[fNVars];
for (Int_t j=0; j<fNVars; j++)
{
binIdx[j] = 1;
nBins[j] = target->GetAxis(j)->GetNbins();
}
Long64_t count = 0;
while (1)
{
// for (Int_t j=0; j<fNVars; j++)
// printf("%d ", binIdx[j]);
Long64_t globalBin = GetGlobalBinIndex(binIdx);
// Printf(" --> %lld", globalBin);
if (source[globalBin] != 0)
{
target->SetBinContent(binIdx, source[globalBin]);
target->SetBinError(binIdx, TMath::Sqrt(sourceSumw2[globalBin]));
count++;
}
binIdx[fNVars-1]++;
for (Int_t j=fNVars-1; j>0; j--)
{
if (binIdx[j] > nBins[j])
{
binIdx[j] = 1;
binIdx[j-1]++;
}
}
if (binIdx[0] > nBins[0])
break;
}
AliInfo(Form("Step %d: copied %lld entries out of %lld bins", i, count, GetGlobalBinIndex(binIdx)));
delete[] binIdx;
delete[] nBins;
}
}
void AliTHn::FillParent()
{
// fills the information stored in the buffer in this class into the baseclass containers
FillContainer(this);
}
void AliTHn::ReduceAxis()
{
// "removes" one axis by summing over the axis and putting the entry to bin 1
// TODO presently only implemented for the last axis
Int_t axis = fNVars-1;
for (Int_t i=0; i<fNSteps; i++)
{
if (!fValues[i])
continue;
Float_t* source = fValues[i]->GetArray();
Float_t* sourceSumw2 = 0;
if (fSumw2[i])
sourceSumw2 = fSumw2[i]->GetArray();
THnSparse* target = GetGrid(i)->GetGrid();
Int_t* binIdx = new Int_t[fNVars];
Int_t* nBins = new Int_t[fNVars];
for (Int_t j=0; j<fNVars; j++)
{
binIdx[j] = 1;
nBins[j] = target->GetAxis(j)->GetNbins();
}
Long64_t count = 0;
while (1)
{
// sum over axis <axis>
Float_t sumValues = 0;
Float_t sumSumw2 = 0;
for (Int_t j=1; j<=nBins[axis]; j++)
{
binIdx[axis] = j;
Long64_t globalBin = GetGlobalBinIndex(binIdx);
sumValues += source[globalBin];
source[globalBin] = 0;
if (sourceSumw2)
{
sumSumw2 += sourceSumw2[globalBin];
sourceSumw2[globalBin] = 0;
}
}
binIdx[axis] = 1;
Long64_t globalBin = GetGlobalBinIndex(binIdx);
source[globalBin] = sumValues;
if (sourceSumw2)
sourceSumw2[globalBin] = sumSumw2;
count++;
// next bin
binIdx[fNVars-2]++;
for (Int_t j=fNVars-2; j>0; j--)
{
if (binIdx[j] > nBins[j])
{
binIdx[j] = 1;
binIdx[j-1]++;
}
}
if (binIdx[0] > nBins[0])
break;
}
AliInfo(Form("Step %d: reduced %lld bins to %lld entries", i, GetGlobalBinIndex(binIdx), count));
delete[] binIdx;
delete[] nBins;
}
}
<|endoftext|> |
<commit_before>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include <sstream>
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/connector.hh"
#include "com/centreon/broker/influxdb/factory.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::influxdb;
/**************************************
* *
* Static Objects *
* *
**************************************/
/**
* Find a parameter in configuration.
*
* @param[in] cfg Configuration object.
* @param[in] key Property to get.
*
* @return Property value.
*/
static std::string find_param(
config::endpoint const& cfg,
QString const& key) {
QMap<QString, QString>::const_iterator it(cfg.params.find(key));
if (cfg.params.end() == it)
throw (exceptions::msg() << "influxdb: no '" << key
<< "' defined for endpoint '" << cfg.name << "'");
return (it.value().toStdString());
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
factory::factory() {}
/**
* Copy constructor.
*
* @param[in] f Object to copy.
*/
factory::factory(factory const& f) : io::factory(f) {}
/**
* Destructor.
*/
factory::~factory() {}
/**
* Assignment operator.
*
* @param[in] f Object to copy.
*
* @return This object.
*/
factory& factory::operator=(factory const& f) {
io::factory::operator=(f);
return (*this);
}
/**
* Clone this object.
*
* @return Exact copy of this factory.
*/
io::factory* factory::clone() const {
return (new factory(*this));
}
/**
* Check if a configuration match the storage layer.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_input true if endpoint should act as input.
* @param[in] is_output true if endpoint should act as output.
*
* @return true if the configuration matches the storage layer.
*/
bool factory::has_endpoint(
config::endpoint& cfg,
bool is_input,
bool is_output) const {
(void)is_input;
bool is_ifdb(!cfg.type.compare("influxdb", Qt::CaseInsensitive)
&& is_output);
return (is_ifdb);
}
/**
* Build a storage endpoint from a configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_input true if endpoint should act as input.
* @param[in] is_output true if endpoint should act as output.
* @param[out] is_acceptor Will be set to false.
*
* @return Endpoint matching the given configuration.
*/
io::endpoint* factory::new_endpoint(
config::endpoint& cfg,
bool is_input,
bool is_output,
bool& is_acceptor) const {
(void)is_input;
(void)is_output;
std::string user(find_param(cfg, "user"));
std::string passwd(find_param(cfg, "password"));
std::string addr(find_param(cfg, "host"));
std::string db(find_param(cfg, "db"));
unsigned short port(0);
{
std::stringstream ss;
ss << find_param(cfg, "port");
ss >> port;
if (!ss.eof())
throw (exceptions::msg() << "influxdb: couldn't parse port '" << ss.str()
<< "' defined for endpoint '" << cfg.name << "'");
}
unsigned int queries_per_transaction(0);
{
QMap<QString, QString>::const_iterator
it(cfg.params.find("queries_per_transaction"));
if (it != cfg.params.end())
queries_per_transaction = it.value().toUInt();
else
queries_per_transaction = 1000;
}
std::string version;
{
QMap<QString, QString>::const_iterator
it(cfg.params.find("influxdb_version"));
if (it != cfg.params.end())
version = it.value().toStdString();
else
version = "0.9";
}
// Connector.
std::auto_ptr<influxdb::connector> c(new influxdb::connector);
c->connect_to(user, passwd, addr, port, db, queries_per_transaction, version);
is_acceptor = false;
return (c.release());
}
<commit_msg>Influxdb: Follow documentation for configuration option.<commit_after>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include <sstream>
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/connector.hh"
#include "com/centreon/broker/influxdb/factory.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::influxdb;
/**************************************
* *
* Static Objects *
* *
**************************************/
/**
* Find a parameter in configuration.
*
* @param[in] cfg Configuration object.
* @param[in] key Property to get.
*
* @return Property value.
*/
static std::string find_param(
config::endpoint const& cfg,
QString const& key) {
QMap<QString, QString>::const_iterator it(cfg.params.find(key));
if (cfg.params.end() == it)
throw (exceptions::msg() << "influxdb: no '" << key
<< "' defined for endpoint '" << cfg.name << "'");
return (it.value().toStdString());
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
factory::factory() {}
/**
* Copy constructor.
*
* @param[in] f Object to copy.
*/
factory::factory(factory const& f) : io::factory(f) {}
/**
* Destructor.
*/
factory::~factory() {}
/**
* Assignment operator.
*
* @param[in] f Object to copy.
*
* @return This object.
*/
factory& factory::operator=(factory const& f) {
io::factory::operator=(f);
return (*this);
}
/**
* Clone this object.
*
* @return Exact copy of this factory.
*/
io::factory* factory::clone() const {
return (new factory(*this));
}
/**
* Check if a configuration match the storage layer.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_input true if endpoint should act as input.
* @param[in] is_output true if endpoint should act as output.
*
* @return true if the configuration matches the storage layer.
*/
bool factory::has_endpoint(
config::endpoint& cfg,
bool is_input,
bool is_output) const {
(void)is_input;
bool is_ifdb(!cfg.type.compare("influxdb", Qt::CaseInsensitive)
&& is_output);
return (is_ifdb);
}
/**
* Build a storage endpoint from a configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_input true if endpoint should act as input.
* @param[in] is_output true if endpoint should act as output.
* @param[out] is_acceptor Will be set to false.
*
* @return Endpoint matching the given configuration.
*/
io::endpoint* factory::new_endpoint(
config::endpoint& cfg,
bool is_input,
bool is_output,
bool& is_acceptor) const {
(void)is_input;
(void)is_output;
std::string user(find_param(cfg, "db_user"));
std::string passwd(find_param(cfg, "db_password"));
std::string addr(find_param(cfg, "db_host"));
std::string db(find_param(cfg, "db_name"));
unsigned short port(0);
{
std::stringstream ss;
ss << find_param(cfg, "db_port");
ss >> port;
if (!ss.eof())
throw (exceptions::msg() << "influxdb: couldn't parse port '" << ss.str()
<< "' defined for endpoint '" << cfg.name << "'");
}
unsigned int queries_per_transaction(0);
{
QMap<QString, QString>::const_iterator
it(cfg.params.find("queries_per_transaction"));
if (it != cfg.params.end())
queries_per_transaction = it.value().toUInt();
else
queries_per_transaction = 1000;
}
std::string version;
{
QMap<QString, QString>::const_iterator
it(cfg.params.find("influxdb_version"));
if (it != cfg.params.end())
version = it.value().toStdString();
else
version = "0.9";
}
// Connector.
std::auto_ptr<influxdb::connector> c(new influxdb::connector);
c->connect_to(user, passwd, addr, port, db, queries_per_transaction, version);
is_acceptor = false;
return (c.release());
}
<|endoftext|> |
<commit_before>#include "process_splitters/Alignment.hpp"
#include "TestData.hpp"
#include "testing/TestBamRecords.hpp"
#include <sam.h>
#include <stdint.h>
#include <gtest/gtest.h>
#include <string>
#include <stdexcept>
class TestAlignment : public ::testing::Test {
public:
bam1_t *record1;
bam1_t *record2;
TestBamRecords records;
TestAlignment() {
record1 = records.record;
record2 = records.record2;
}
};
TEST_F(TestAlignment, create_from_bam) {
Alignment test_obj(record1, records.header);
ASSERT_EQ(test_obj.chrom, "chr21");
ASSERT_EQ(test_obj.strand, '+');
ASSERT_EQ(test_obj.rapos, 44877125u);
// TODO add additional tests once we're certain about the values
}
TEST_F(TestAlignment, create_from_sa) {
uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
std::string data = (char const*) sa_ptr;
char const* beg = data.data();
char const* end = data.data() + data.size() - 1; //subtracting off the semicolon
Alignment test_obj(beg, end);
ASSERT_EQ(test_obj.chrom, "chr21");
ASSERT_EQ(test_obj.strand, '+');
ASSERT_EQ(test_obj.rapos, 44877125u);
}
TEST_F(TestAlignment, create_from_truncated_sa) {
uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
std::string data((char const*) sa_ptr, 28); //truncate the string
ASSERT_EQ(data, "chr21,44877125,+,101S41M9S,3");
char const* beg = data.data();
char const* end = data.data() + data.size();
ASSERT_THROW(Alignment test_obj(beg, end), std::runtime_error);
}
TEST_F(TestAlignment, calculate_additional_offsets) {
}
TEST_F(TestAlignment, start_diagonal) {
}
TEST_F(TestAlignment, end_diagonal) {
}
TEST_F(TestAlignment, mno) {
}
TEST_F(TestAlignment, desert) {
}
TEST_F(TestAlignment, insert_size) {
}
TEST_F(TestAlignment, should_check) {
}
<commit_msg>flesh out more tests from Alignment<commit_after>#include "process_splitters/Alignment.hpp"
#include "TestData.hpp"
#include "testing/TestBamRecords.hpp"
#include <sam.h>
#include <stdint.h>
#include <gtest/gtest.h>
#include <string>
#include <stdexcept>
class TestAlignment : public ::testing::Test {
public:
bam1_t *record1;
bam1_t *record2;
TestBamRecords records;
TestAlignment() {
record1 = records.record;
record2 = records.record2;
}
};
TEST_F(TestAlignment, create_from_bam) {
Alignment test_obj(record1, records.header);
ASSERT_EQ("chr21", test_obj.chrom);
ASSERT_EQ('+', test_obj.strand);
ASSERT_EQ(44877125u, test_obj.rapos);
// TODO add additional tests once we're certain about the values
}
TEST_F(TestAlignment, create_from_sa) {
uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
std::string data = (char const*) sa_ptr;
char const* beg = data.data();
char const* end = data.data() + data.size() - 1; //subtracting off the semicolon
Alignment test_obj(beg, end);
ASSERT_EQ("chr21", test_obj.chrom);
ASSERT_EQ('+', test_obj.strand);
ASSERT_EQ(44877125u, test_obj.rapos);
ASSERT_EQ(41u, test_obj.offsets.raLen);
}
TEST_F(TestAlignment, create_from_truncated_sa) {
uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
std::string data((char const*) sa_ptr, 28); //truncate the string
ASSERT_EQ(data, "chr21,44877125,+,101S41M9S,3");
char const* beg = data.data();
char const* end = data.data() + data.size();
ASSERT_THROW(Alignment test_obj(beg, end), std::runtime_error);
}
TEST_F(TestAlignment, calculate_additional_offsets) {
AlignmentOffsets data("2H5S10M2D5M3I5M4S");
Alignment test_obj;
test_obj.rapos = 50u;
test_obj.strand = '+';
test_obj.offsets = data;
test_obj.calculate_additional_offsets();
ASSERT_EQ(43u, test_obj.pos);
ASSERT_EQ(test_obj.SQO, 7);
ASSERT_EQ(test_obj.EQO, 29);
test_obj.strand = '-';
test_obj.calculate_additional_offsets();
ASSERT_EQ(75u, test_obj.pos);
ASSERT_EQ(test_obj.SQO, 4);
ASSERT_EQ(test_obj.EQO, 26);
}
TEST_F(TestAlignment, start_diagonal) {
Alignment a1(record1, records.header);
ASSERT_EQ(44877125 - 101, a1.start_diagonal());
}
TEST_F(TestAlignment, end_diagonal) {
Alignment a1(record1, records.header);
ASSERT_EQ((44877125 + 41) - (101 + 41), a1.end_diagonal());
}
TEST_F(TestAlignment, mno) {
}
TEST_F(TestAlignment, desert) {
}
TEST_F(TestAlignment, insert_size) {
}
TEST_F(TestAlignment, should_check) {
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include <tinyara/config.h>
#include <tinyara/init.h>
#include <apps/platform/cxxinitialize.h>
#include <tinyalsa/tinyalsa.h>
#include <fcntl.h>
#include <errno.h>
#include <media/MediaRecorder.h>
#include <media/MediaRecorderObserverInterface.h>
#include <media/MediaPlayer.h>
#include <media/MediaPlayerObserverInterface.h>
#include <media/FileOutputDataSource.h>
#include <media/BufferOutputDataSource.h>
#include <media/FileInputDataSource.h>
#include <iostream>
#include <memory>
constexpr int APP_ON = 1;
constexpr int RECORDER_START = 2;
constexpr int RECORDER_PAUSE = 3;
constexpr int RECORDER_RESUME = 4;
constexpr int RECORDER_STOP = 5;
constexpr int VOLUME_UP = 6;
constexpr int VOLUME_DOWN = 7;
constexpr int PLAY_DATA = 8;
constexpr int DELETE_FILE = 9;
constexpr int APP_OFF = 0;
using namespace std;
using namespace media;
using namespace media::stream;
static const int TEST_MEDIATYPE_PCM = 0;
static const int TEST_MEDIATYPE_OPUS = 1;
static const int TEST_DATASOURCE_TYPE_FILE = 0;
static const int TEST_DATASOURCE_TYPE_BUFFER = 1;
static const char *filePath = "";
class MediaRecorderTest : public MediaRecorderObserverInterface,
public MediaPlayerObserverInterface,
public enable_shared_from_this<MediaRecorderTest>
{
public:
void onRecordStarted(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordStarted" << std::endl;
if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
mfp = fopen(filePath, "w");
if (mfp == NULL) {
std::cout << "FILE OPEN FAILED" << std::endl;
return;
}
}
}
void onRecordPaused(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordPaused" << std::endl;
}
void onRecordFinished(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordFinished" << std::endl;
if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER && mfp != NULL) {
fclose(mfp);
}
mediaRecorder.unprepare();
}
void onRecordStartError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordStartError!! errCode : " << errCode << std::endl;
}
void onRecordPauseError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordPauseError!! errCode : " << errCode << std::endl;
}
void onRecordStopError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordStopError!! errCode : " << errCode << std::endl;
}
void onRecordBufferDataReached(MediaRecorder& mediaRecorder, std::shared_ptr<unsigned char> data, size_t size)
{
if (mfp != NULL) {
fwrite(data, sizeof(unsigned char), size, mfp);
}
std::cout << "onRecordBufferDataReached, data size : " << size << std::endl;
}
void onPlaybackStarted(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackStarted" << std::endl;
mIsPlaying = true;
}
void onPlaybackFinished(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackFinished" << std::endl;
mIsPlaying = false;
if (mMp.unprepare() != PLAYER_OK) {
std::cout << "Mediaplayer::unprepare failed" << std::endl;
}
if (mMp.destroy() != PLAYER_OK) {
std::cout << "Mediaplayer::destroy failed" << std::endl;
}
}
void onPlaybackError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onPlaybackError" << std::endl;
}
void onStartError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onStartError" << std::endl;
}
void onStopError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onStopError" << std::endl;
}
void onPauseError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onPauseError" << std::endl;
}
void onPlaybackPaused(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackPaused" << std::endl;
}
void start(const int mediaType, const int dataSourceType)
{
mMediaType = mediaType;
mDataSourceType = dataSourceType;
uint8_t volume;
mAppRunning = true;
while (mAppRunning) {
printRecorderMenu();
switch (userInput(APP_ON, DELETE_FILE)) {
case APP_ON:
std::cout << "SELECTED APP ON" << std::endl;
mMr.create();
mMr.setObserver(shared_from_this());
break;
case RECORDER_START:
std::cout << "SELECTED RECORDER_START" << std::endl;
if (mIsPaused) {
if (mMr.start()) {
std::cout << "START IN PAUSE STATE SUCCESS" << std::endl;
mIsPaused = false;
}
} else {
if (mMediaType == TEST_MEDIATYPE_PCM) {
filePath = "/tmp/record.pcm";
} else if (mMediaType == TEST_MEDIATYPE_OPUS) {
filePath = "/tmp/record.opus";
}
if (mDataSourceType == TEST_DATASOURCE_TYPE_FILE) {
mMr.setDataSource(unique_ptr<FileOutputDataSource>(
new FileOutputDataSource(2, 16000, AUDIO_FORMAT_TYPE_S16_LE, filePath)));
} else if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
mMr.setDataSource(unique_ptr<BufferOutputDataSource>(new BufferOutputDataSource()));
}
if (mMr.setDuration(3) == RECORDER_ERROR_NONE && mMr.prepare() == RECORDER_ERROR_NONE) {
mMr.start();
std::cout << "START IN NONE-PAUSE STATE SUCCESS" << std::endl;
} else {
std::cout << "PREPARE FAILED" << std::endl;
}
}
break;
case RECORDER_PAUSE:
std::cout << "SELECTED RECORDER_PAUSE" << std::endl;
if (mMr.pause()) {
mIsPaused = true;
std::cout << "PAUSE SUCCESS" << std::endl;
} else {
std::cout << "PAUSE FAILED" << std::endl;
}
break;
case RECORDER_RESUME:
std::cout << "SELECTED RECORDER_RESUME" << std::endl;
if (mMr.start()) {
mIsPaused = false;
std::cout << "RESUME SUCCESS" << std::endl;
} else {
std::cout << "RESUME FAILED" << std::endl;
}
break;
case RECORDER_STOP:
std::cout << "SELECTED RECORDER_STOP" << std::endl;
if (mMr.stop() == RECORDER_ERROR_NONE) {
mIsPaused = false;
std::cout << "STOP SUCCESS" << std::endl;
} else {
std::cout << "STOP FAILED" << std::endl;
}
break;
case PLAY_DATA:
std::cout << "PLAY_DATA" << std::endl;
play_data();
break;
case VOLUME_UP:
cout << "VOLUME_UP is selected" << endl;
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Volume was " << (int)volume << endl;
}
if (mMr.setVolume(volume + 1) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::setVolume failed" << endl;
}
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Now, Volume is " << (int)volume << endl;
}
break;
case VOLUME_DOWN:
cout << "VOLUME_DOWN is selected" << endl;
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Volume was " << (int)volume << endl;
}
if (mMr.setVolume(volume - 1) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::setVolume failed" << endl;
}
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Now, Volume is " << (int)volume << endl;
}
break;
case APP_OFF:
std::cout << "SELECTED APP_OFF" << std::endl;
mMr.destroy();
mAppRunning = false;
break;
case DELETE_FILE:
if (unlink(filePath) == OK) {
std::cout << "FILE DELETED" << std::endl;
} else {
std::cout << "DELETE FAILED ERRPR " << errno << std::endl;
}
break;
}
}
}
void play_data()
{
if (mIsPlaying) {
std::cout << "Already in playback" << std::endl;
return;
}
std::cout << "playback " << filePath << std::endl;
auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource(filePath)));
source->setSampleRate(16000);
source->setChannels(2);
source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE);
if (mMp.create() != PLAYER_OK) {
std::cout << "Mediaplayer::create failed" << std::endl;
return;
}
if (mMp.setObserver(shared_from_this()) != PLAYER_OK) {
std::cout << "Mediaplayer::setObserver failed" << std::endl;
return;
}
if (mMp.setDataSource(std::move(source)) != PLAYER_OK) {
std::cout << "Mediaplayer::setDataSource failed" << std::endl;
return;
}
if (mMp.prepare() != PLAYER_OK) {
std::cout << "Mediaplayer::prepare failed" << std::endl;
return;
}
if (mMp.start() != PLAYER_OK) {
std::cout << "Mediaplayer::start failed" << std::endl;
if (mMp.unprepare() != PLAYER_OK) {
std::cout << "Mediaplayer::unprepare failed" << std::endl;
}
return;
}
}
void printRecorderMenu()
{
std::cout << "========================================" << std::endl;
std::cout << "1. RECORDER APP ON" << std::endl;
std::cout << "2. RECORDER Start" << std::endl;
std::cout << "3. RECORDER Pause" << std::endl;
std::cout << "4. RECORDER Resume" << std::endl;
std::cout << "5. RECORDER Stop" << std::endl;
std::cout << "6. RECORDER Volume Up" << std::endl;
std::cout << "7. RECORDER Volume Down" << std::endl;
std::cout << "8. play Data" << std::endl;
std::cout << "9. Delete file" << std::endl;
std::cout << "0. RECORDER APP OFF" << std::endl;
std::cout << "========================================" << std::endl;
}
int userInput(int min, int max)
{
assert(min <= max);
int input = 0;
std::cin >> input;
std::cout << std::endl;
if (!std::cin.fail()) {
if (min <= input && input <= max) {
std::cout << "return input" << std::endl;
return input;
}
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid Input, please try again" << std::endl;
return input;
}
MediaRecorderTest() : mAppRunning(false), mIsPaused(false), mIsPlaying(false)
{
}
~MediaRecorderTest()
{
}
private:
bool mAppRunning;
bool mIsPaused;
MediaRecorder mMr;
bool mIsPlaying;
MediaPlayer mMp;
FILE *mfp;
int mMediaType;
int mDataSourceType;
};
extern "C" {
int mediarecorder_main(int argc, char *argv[])
{
up_cxxinitialize();
auto mediaRecorderTest = make_shared<MediaRecorderTest>();
mediaRecorderTest->start(TEST_MEDIATYPE_PCM, TEST_DATASOURCE_TYPE_FILE);
return 0;
}
}
<commit_msg>media: Fix build error because of invalid type casting<commit_after>/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include <tinyara/config.h>
#include <tinyara/init.h>
#include <apps/platform/cxxinitialize.h>
#include <tinyalsa/tinyalsa.h>
#include <fcntl.h>
#include <errno.h>
#include <media/MediaRecorder.h>
#include <media/MediaRecorderObserverInterface.h>
#include <media/MediaPlayer.h>
#include <media/MediaPlayerObserverInterface.h>
#include <media/FileOutputDataSource.h>
#include <media/BufferOutputDataSource.h>
#include <media/FileInputDataSource.h>
#include <iostream>
#include <memory>
constexpr int APP_ON = 1;
constexpr int RECORDER_START = 2;
constexpr int RECORDER_PAUSE = 3;
constexpr int RECORDER_RESUME = 4;
constexpr int RECORDER_STOP = 5;
constexpr int VOLUME_UP = 6;
constexpr int VOLUME_DOWN = 7;
constexpr int PLAY_DATA = 8;
constexpr int DELETE_FILE = 9;
constexpr int APP_OFF = 0;
using namespace std;
using namespace media;
using namespace media::stream;
static const int TEST_MEDIATYPE_PCM = 0;
static const int TEST_MEDIATYPE_OPUS = 1;
static const int TEST_DATASOURCE_TYPE_FILE = 0;
static const int TEST_DATASOURCE_TYPE_BUFFER = 1;
static const char *filePath = "";
class MediaRecorderTest : public MediaRecorderObserverInterface,
public MediaPlayerObserverInterface,
public enable_shared_from_this<MediaRecorderTest>
{
public:
void onRecordStarted(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordStarted" << std::endl;
if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
mfp = fopen(filePath, "w");
if (mfp == NULL) {
std::cout << "FILE OPEN FAILED" << std::endl;
return;
}
}
}
void onRecordPaused(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordPaused" << std::endl;
}
void onRecordFinished(MediaRecorder& mediaRecorder)
{
std::cout << "onRecordFinished" << std::endl;
if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER && mfp != NULL) {
fclose(mfp);
}
mediaRecorder.unprepare();
}
void onRecordStartError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordStartError!! errCode : " << errCode << std::endl;
}
void onRecordPauseError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordPauseError!! errCode : " << errCode << std::endl;
}
void onRecordStopError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
{
std::cout << "onRecordStopError!! errCode : " << errCode << std::endl;
}
void onRecordBufferDataReached(MediaRecorder& mediaRecorder, std::shared_ptr<unsigned char> data, size_t size)
{
if (mfp != NULL) {
fwrite((const void *)data.get(), sizeof(unsigned char), size, mfp);
}
std::cout << "onRecordBufferDataReached, data size : " << size << std::endl;
}
void onPlaybackStarted(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackStarted" << std::endl;
mIsPlaying = true;
}
void onPlaybackFinished(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackFinished" << std::endl;
mIsPlaying = false;
if (mMp.unprepare() != PLAYER_OK) {
std::cout << "Mediaplayer::unprepare failed" << std::endl;
}
if (mMp.destroy() != PLAYER_OK) {
std::cout << "Mediaplayer::destroy failed" << std::endl;
}
}
void onPlaybackError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onPlaybackError" << std::endl;
}
void onStartError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onStartError" << std::endl;
}
void onStopError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onStopError" << std::endl;
}
void onPauseError(MediaPlayer &mediaPlayer, player_error_t error)
{
std::cout << "onPauseError" << std::endl;
}
void onPlaybackPaused(MediaPlayer &mediaPlayer)
{
std::cout << "onPlaybackPaused" << std::endl;
}
void start(const int mediaType, const int dataSourceType)
{
mMediaType = mediaType;
mDataSourceType = dataSourceType;
uint8_t volume;
mAppRunning = true;
while (mAppRunning) {
printRecorderMenu();
switch (userInput(APP_ON, DELETE_FILE)) {
case APP_ON:
std::cout << "SELECTED APP ON" << std::endl;
mMr.create();
mMr.setObserver(shared_from_this());
break;
case RECORDER_START:
std::cout << "SELECTED RECORDER_START" << std::endl;
if (mIsPaused) {
if (mMr.start()) {
std::cout << "START IN PAUSE STATE SUCCESS" << std::endl;
mIsPaused = false;
}
} else {
if (mMediaType == TEST_MEDIATYPE_PCM) {
filePath = "/tmp/record.pcm";
} else if (mMediaType == TEST_MEDIATYPE_OPUS) {
filePath = "/tmp/record.opus";
}
if (mDataSourceType == TEST_DATASOURCE_TYPE_FILE) {
mMr.setDataSource(unique_ptr<FileOutputDataSource>(
new FileOutputDataSource(2, 16000, AUDIO_FORMAT_TYPE_S16_LE, filePath)));
} else if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
mMr.setDataSource(unique_ptr<BufferOutputDataSource>(new BufferOutputDataSource()));
}
if (mMr.setDuration(3) == RECORDER_ERROR_NONE && mMr.prepare() == RECORDER_ERROR_NONE) {
mMr.start();
std::cout << "START IN NONE-PAUSE STATE SUCCESS" << std::endl;
} else {
std::cout << "PREPARE FAILED" << std::endl;
}
}
break;
case RECORDER_PAUSE:
std::cout << "SELECTED RECORDER_PAUSE" << std::endl;
if (mMr.pause()) {
mIsPaused = true;
std::cout << "PAUSE SUCCESS" << std::endl;
} else {
std::cout << "PAUSE FAILED" << std::endl;
}
break;
case RECORDER_RESUME:
std::cout << "SELECTED RECORDER_RESUME" << std::endl;
if (mMr.start()) {
mIsPaused = false;
std::cout << "RESUME SUCCESS" << std::endl;
} else {
std::cout << "RESUME FAILED" << std::endl;
}
break;
case RECORDER_STOP:
std::cout << "SELECTED RECORDER_STOP" << std::endl;
if (mMr.stop() == RECORDER_ERROR_NONE) {
mIsPaused = false;
std::cout << "STOP SUCCESS" << std::endl;
} else {
std::cout << "STOP FAILED" << std::endl;
}
break;
case PLAY_DATA:
std::cout << "PLAY_DATA" << std::endl;
play_data();
break;
case VOLUME_UP:
cout << "VOLUME_UP is selected" << endl;
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Volume was " << (int)volume << endl;
}
if (mMr.setVolume(volume + 1) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::setVolume failed" << endl;
}
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Now, Volume is " << (int)volume << endl;
}
break;
case VOLUME_DOWN:
cout << "VOLUME_DOWN is selected" << endl;
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Volume was " << (int)volume << endl;
}
if (mMr.setVolume(volume - 1) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::setVolume failed" << endl;
}
if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
cout << "MediaRecorder::getVolume failed" << endl;
} else {
cout << "Now, Volume is " << (int)volume << endl;
}
break;
case APP_OFF:
std::cout << "SELECTED APP_OFF" << std::endl;
mMr.destroy();
mAppRunning = false;
break;
case DELETE_FILE:
if (unlink(filePath) == OK) {
std::cout << "FILE DELETED" << std::endl;
} else {
std::cout << "DELETE FAILED ERRPR " << errno << std::endl;
}
break;
}
}
}
void play_data()
{
if (mIsPlaying) {
std::cout << "Already in playback" << std::endl;
return;
}
std::cout << "playback " << filePath << std::endl;
auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource(filePath)));
source->setSampleRate(16000);
source->setChannels(2);
source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE);
if (mMp.create() != PLAYER_OK) {
std::cout << "Mediaplayer::create failed" << std::endl;
return;
}
if (mMp.setObserver(shared_from_this()) != PLAYER_OK) {
std::cout << "Mediaplayer::setObserver failed" << std::endl;
return;
}
if (mMp.setDataSource(std::move(source)) != PLAYER_OK) {
std::cout << "Mediaplayer::setDataSource failed" << std::endl;
return;
}
if (mMp.prepare() != PLAYER_OK) {
std::cout << "Mediaplayer::prepare failed" << std::endl;
return;
}
if (mMp.start() != PLAYER_OK) {
std::cout << "Mediaplayer::start failed" << std::endl;
if (mMp.unprepare() != PLAYER_OK) {
std::cout << "Mediaplayer::unprepare failed" << std::endl;
}
return;
}
}
void printRecorderMenu()
{
std::cout << "========================================" << std::endl;
std::cout << "1. RECORDER APP ON" << std::endl;
std::cout << "2. RECORDER Start" << std::endl;
std::cout << "3. RECORDER Pause" << std::endl;
std::cout << "4. RECORDER Resume" << std::endl;
std::cout << "5. RECORDER Stop" << std::endl;
std::cout << "6. RECORDER Volume Up" << std::endl;
std::cout << "7. RECORDER Volume Down" << std::endl;
std::cout << "8. play Data" << std::endl;
std::cout << "9. Delete file" << std::endl;
std::cout << "0. RECORDER APP OFF" << std::endl;
std::cout << "========================================" << std::endl;
}
int userInput(int min, int max)
{
assert(min <= max);
int input = 0;
std::cin >> input;
std::cout << std::endl;
if (!std::cin.fail()) {
if (min <= input && input <= max) {
std::cout << "return input" << std::endl;
return input;
}
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid Input, please try again" << std::endl;
return input;
}
MediaRecorderTest() : mAppRunning(false), mIsPaused(false), mIsPlaying(false)
{
}
~MediaRecorderTest()
{
}
private:
bool mAppRunning;
bool mIsPaused;
MediaRecorder mMr;
bool mIsPlaying;
MediaPlayer mMp;
FILE *mfp;
int mMediaType;
int mDataSourceType;
};
extern "C" {
int mediarecorder_main(int argc, char *argv[])
{
up_cxxinitialize();
auto mediaRecorderTest = make_shared<MediaRecorderTest>();
mediaRecorderTest->start(TEST_MEDIATYPE_PCM, TEST_DATASOURCE_TYPE_FILE);
return 0;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.6 2001/05/21 17:22:50 buncic
Fixed problem with missing AliConfig while reading galice.root
Revision 1.5 2001/05/16 14:57:07 alibrary
New files for folders and Stack
Revision 1.4 2000/12/20 08:39:37 fca
Support for Cerenkov and process list in Virtual MC
Revision 1.3 1999/09/29 09:24:07 fca
Introduction of the Copyright and cvs Log
*/
//////////////////////////////////////////////////////////////////////////
// //
// aliroot //
// //
// Main program used to create aliroot application. //
// //
// //
// To be able to communicate between the FORTRAN code of GEANT and the //
// ROOT data structure, a number of interface routines have been //
// developed. //
//Begin_Html
/*
<img src="picts/newg.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#include <AliConfig.h>
#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif
#if defined WIN32
extern "C" int __fastflag=0;
extern "C" int _pctype=0;
extern "C" int __mb_cur_max=0;
#endif
int gcbank_[3000000];
//Initialise the Root environment
extern void InitGui();
VoidFuncPtr_t initfuncs[] = { InitGui, 0 };
TROOT root("galice","The Alice/ROOT Interface", initfuncs);
//_____________________________________________________________________________
int main(int argc, char **argv)
{
//
// gAlice main program.
// It creates the main Geant3 and AliRun objects.
//
// The Hits are written out after each track in a ROOT Tree structure TreeH,
// of the file galice.root. There is one such tree per event. The kinematics
// of all the particles that produce hits, together with their genealogy up
// to the primary tracks is stared in the galice.root file in an other tree
// TreeK of which exists one per event. Finally the information of the events
// in the run is stored in the same file in the tree TreeE, containing the
// run and event number, the number of vertices, tracks and primary tracks
// in the event.
// Create new configuration
new AliConfig ("Folders","Alice data exchange");
new AliRun("gAlice","The ALICE Off-line Simulation Framework");
// Start interactive geant
TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0);
// --- Start the event loop ---
theApp->Run();
return(0);
}
<commit_msg>Instantiation of AliConfig removed<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.7 2001/05/22 11:39:48 buncic
Restored proper name for top level AliRoot folder.
Revision 1.6 2001/05/21 17:22:50 buncic
Fixed problem with missing AliConfig while reading galice.root
Revision 1.5 2001/05/16 14:57:07 alibrary
New files for folders and Stack
Revision 1.4 2000/12/20 08:39:37 fca
Support for Cerenkov and process list in Virtual MC
Revision 1.3 1999/09/29 09:24:07 fca
Introduction of the Copyright and cvs Log
*/
//////////////////////////////////////////////////////////////////////////
// //
// aliroot //
// //
// Main program used to create aliroot application. //
// //
// //
// To be able to communicate between the FORTRAN code of GEANT and the //
// ROOT data structure, a number of interface routines have been //
// developed. //
//Begin_Html
/*
<img src="picts/newg.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#include <AliConfig.h>
#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif
#if defined WIN32
extern "C" int __fastflag=0;
extern "C" int _pctype=0;
extern "C" int __mb_cur_max=0;
#endif
int gcbank_[3000000];
//Initialise the Root environment
extern void InitGui();
VoidFuncPtr_t initfuncs[] = { InitGui, 0 };
TROOT root("galice","The Alice/ROOT Interface", initfuncs);
//_____________________________________________________________________________
int main(int argc, char **argv)
{
//
// gAlice main program.
// It creates the main Geant3 and AliRun objects.
//
// The Hits are written out after each track in a ROOT Tree structure TreeH,
// of the file galice.root. There is one such tree per event. The kinematics
// of all the particles that produce hits, together with their genealogy up
// to the primary tracks is stared in the galice.root file in an other tree
// TreeK of which exists one per event. Finally the information of the events
// in the run is stored in the same file in the tree TreeE, containing the
// run and event number, the number of vertices, tracks and primary tracks
// in the event.
// Create new configuration
new AliRun("gAlice","The ALICE Off-line Simulation Framework");
// Start interactive geant
TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0);
// --- Start the event loop ---
theApp->Run();
return(0);
}
<|endoftext|> |
<commit_before>// RUN: %clangxx -fsanitize=return -g %s -O3 -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
// RUN: UBSAN_OPTIONS=print_stacktrace=1 not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os-STACKTRACE
// CHECK: missing_return.cpp:[[@LINE+1]]:5: runtime error: execution reached the end of a value-returning function without returning a value
int f() {
// Slow stack unwinding is disabled on Darwin for now, see
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
// CHECK-Linux-STACKTRACE: #0 {{.*}} in f(){{.*}}missing_return.cpp:[[@LINE-3]]
// Check for already checked line to avoid lit error reports.
// CHECK-Darwin-STACKTRACE: missing_return.cpp
}
int main(int, char **argv) {
return f();
}
<commit_msg>[Ubsan] Fix the missing_return.cpp test to pass on FreeBSD Differential Revision: http://reviews.llvm.org/D6088<commit_after>// RUN: %clangxx -fsanitize=return -g %s -O3 -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
// RUN: UBSAN_OPTIONS=print_stacktrace=1 not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os-STACKTRACE
// CHECK: missing_return.cpp:[[@LINE+1]]:5: runtime error: execution reached the end of a value-returning function without returning a value
int f() {
// Slow stack unwinding is disabled on Darwin for now, see
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
// CHECK-Linux-STACKTRACE: #0 {{.*}} in f(){{.*}}missing_return.cpp:[[@LINE-3]]
// CHECK-FreeBSD-STACKTRACE: #0 {{.*}} in f(void){{.*}}missing_return.cpp:[[@LINE-4]]
// Check for already checked line to avoid lit error reports.
// CHECK-Darwin-STACKTRACE: missing_return.cpp
}
int main(int, char **argv) {
return f();
}
<|endoftext|> |
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __test_communication__message_fixtures__hpp__
#define __test_communication__message_fixtures__hpp__
#include <vector>
#include <test_communication/msg/builtins.hpp>
#include <test_communication/msg/dynamic_array_primitives.hpp>
#include <test_communication/msg/empty.hpp>
#include <test_communication/msg/nested.hpp>
#include <test_communication/msg/primitives.hpp>
#include <test_communication/msg/static_array_primitives.hpp>
std::vector<test_communication::msg::Empty::Ptr>
get_messages_empty()
{
std::vector<test_communication::msg::Empty::Ptr> messages;
auto msg = std::make_shared<test_communication::msg::Empty>();
messages.push_back(msg);
return messages;
}
std::vector<test_communication::msg::Primitives::Ptr>
get_messages_primitives()
{
std::vector<test_communication::msg::Primitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = false;
msg->byte_value = 0;
msg->char_value = '\0';
msg->float32_value = 0.0f;
msg->float64_value = 0;
msg->int8_value = 0;
msg->uint8_value = 0;
msg->int16_value = 0;
msg->uint16_value = 0;
msg->int32_value = 0;
msg->uint32_value = 0;
msg->int64_value = 0;
msg->uint64_value = 0;
msg->string_value = "";
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = true;
msg->byte_value = 255;
msg->char_value = 0xff;
msg->float32_value = 1.11f;
msg->float64_value = 1.11;
msg->int8_value = 127;
msg->uint8_value = 255;
msg->int16_value = 32767;
msg->uint16_value = 65535;
msg->int32_value = 2147483647;
msg->uint32_value = 4294967295;
msg->int64_value = 9223372036854775807;
msg->uint64_value = 18446744073709551615UL;
msg->string_value = "max value";
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = false;
msg->byte_value = 0;
msg->char_value = 0x0;
msg->float32_value = -2.22f;
msg->float64_value = -2.22;
msg->int8_value = -128;
msg->uint8_value = 0;
msg->int16_value = -32768;
msg->uint16_value = 0;
msg->int32_value = -2147483648;
msg->uint32_value = 0;
msg->int64_value = -9223372036854775808UL;
msg->uint64_value = 0;
msg->string_value = "min value";
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::StaticArrayPrimitives::Ptr>
get_messages_static_array_primitives()
{
std::vector<test_communication::msg::StaticArrayPrimitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::StaticArrayPrimitives>();
msg->bool_values = {false, true, false};
msg->byte_values = {0, 0xff, 0};
msg->char_values = {'\0', '\255', '\0'};
msg->float32_values = {0.0f, 1.11f, -2.22f};
msg->float64_values = {0, 1.11, -2.22};
msg->int8_values = {0, 127, -128};
msg->uint8_values = {0, 255, 0};
msg->int16_values = {0, 32767, -32768};
msg->uint16_values = {0, 65535, 0};
// The narrowing static cast is required to avoid build errors on Windows.
msg->int32_values = {
static_cast<int32_t>(0),
static_cast<int32_t>(2147483647),
static_cast<int32_t>(-2147483648)
};
msg->uint32_values = {0, 4294967295, 0};
msg->int64_values[0] = 0;
msg->int64_values[1] = 9223372036854775807;
msg->int64_values[2] = -9223372036854775808UL;
msg->uint64_values = {0, 18446744073709551615UL, 0};
msg->string_values = {"", "max value", "min value"};
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr>
get_messages_dynamic_array_primitives()
{
std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {{}};
msg->byte_values = {{}};
msg->char_values = {{}};
msg->float32_values = {{}};
msg->float64_values = {{}};
msg->int8_values = {{}};
msg->uint8_values = {{}};
msg->int16_values = {{}};
msg->uint16_values = {{}};
msg->int32_values = {{}};
msg->uint32_values = {{}};
msg->int64_values = {{}};
msg->uint64_values = {{}};
msg->string_values = {{}};
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {{true}};
msg->byte_values = {{0xff}};
msg->char_values = {{'\255'}};
msg->float32_values = {{1.11f}};
msg->float64_values = {{1.11}};
msg->int8_values = {{127}};
msg->uint8_values = {{255}};
msg->int16_values = {{32767}};
msg->uint16_values = {{65535}};
msg->int32_values = {{2147483647}};
msg->uint32_values = {{4294967295}};
msg->int64_values = {{9223372036854775807}};
msg->uint64_values = {{18446744073709551615UL}};
msg->string_values = {{"max value"}};
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {{false, true}};
msg->byte_values = {{0, 0xff}};
msg->char_values = {{'\0', '\255'}};
msg->float32_values = {{0.0f, 1.11f, -2.22f}};
msg->float64_values = {{0, 1.11, -2.22}};
msg->int8_values = {{0, 127, -128}};
msg->uint8_values = {{0, 255}};
msg->int16_values = {{0, 32767, -32768}};
msg->uint16_values = {{0, 65535}};
// The narrowing static cast is required to avoid build errors on Windows.
msg->int32_values = {{
static_cast<int32_t>(0),
static_cast<int32_t>(2147483647),
static_cast<int32_t>(-2147483648)
}};
msg->uint32_values = {{0, 4294967295}};
msg->int64_values.resize(3);
msg->int64_values[0] = 0;
msg->int64_values[1] = 9223372036854775807;
msg->int64_values[2] = -9223372036854775808UL;
msg->uint64_values = {{0, 18446744073709551615UL}};
msg->string_values = {{"", "max value", "optional min value"}};
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::Nested::Ptr>
get_messages_nested()
{
std::vector<test_communication::msg::Nested::Ptr> messages;
auto primitive_msgs = get_messages_primitives();
for (auto primitive_msg : primitive_msgs) {
auto msg = std::make_shared<test_communication::msg::Nested>();
msg->primitive_values = *primitive_msg;
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::Builtins::Ptr>
get_messages_builtins()
{
std::vector<test_communication::msg::Builtins::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::Builtins>();
msg->duration_value.sec = -1234567890;
msg->duration_value.nanosec = 123456789;
msg->time_value.sec = -1234567890;
msg->time_value.nanosec = 987654321;
messages.push_back(msg);
}
return messages;
}
#endif // __test_communication__message_fixtures__hpp__
<commit_msg>adjust use of braces to fix warnings with clang<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __test_communication__message_fixtures__hpp__
#define __test_communication__message_fixtures__hpp__
#include <vector>
#include <test_communication/msg/builtins.hpp>
#include <test_communication/msg/dynamic_array_primitives.hpp>
#include <test_communication/msg/empty.hpp>
#include <test_communication/msg/nested.hpp>
#include <test_communication/msg/primitives.hpp>
#include <test_communication/msg/static_array_primitives.hpp>
std::vector<test_communication::msg::Empty::Ptr>
get_messages_empty()
{
std::vector<test_communication::msg::Empty::Ptr> messages;
auto msg = std::make_shared<test_communication::msg::Empty>();
messages.push_back(msg);
return messages;
}
std::vector<test_communication::msg::Primitives::Ptr>
get_messages_primitives()
{
std::vector<test_communication::msg::Primitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = false;
msg->byte_value = 0;
msg->char_value = '\0';
msg->float32_value = 0.0f;
msg->float64_value = 0;
msg->int8_value = 0;
msg->uint8_value = 0;
msg->int16_value = 0;
msg->uint16_value = 0;
msg->int32_value = 0;
msg->uint32_value = 0;
msg->int64_value = 0;
msg->uint64_value = 0;
msg->string_value = "";
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = true;
msg->byte_value = 255;
msg->char_value = 0xff;
msg->float32_value = 1.11f;
msg->float64_value = 1.11;
msg->int8_value = 127;
msg->uint8_value = 255;
msg->int16_value = 32767;
msg->uint16_value = 65535;
msg->int32_value = 2147483647;
msg->uint32_value = 4294967295;
msg->int64_value = 9223372036854775807;
msg->uint64_value = 18446744073709551615UL;
msg->string_value = "max value";
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::Primitives>();
msg->bool_value = false;
msg->byte_value = 0;
msg->char_value = 0x0;
msg->float32_value = -2.22f;
msg->float64_value = -2.22;
msg->int8_value = -128;
msg->uint8_value = 0;
msg->int16_value = -32768;
msg->uint16_value = 0;
msg->int32_value = -2147483648;
msg->uint32_value = 0;
msg->int64_value = -9223372036854775808UL;
msg->uint64_value = 0;
msg->string_value = "min value";
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::StaticArrayPrimitives::Ptr>
get_messages_static_array_primitives()
{
std::vector<test_communication::msg::StaticArrayPrimitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::StaticArrayPrimitives>();
msg->bool_values = {{false, true, false}};
msg->byte_values = {{0, 0xff, 0}};
msg->char_values = {{'\0', '\255', '\0'}};
msg->float32_values = {{0.0f, 1.11f, -2.22f}};
msg->float64_values = {{0, 1.11, -2.22}};
msg->int8_values = {{0, 127, -128}};
msg->uint8_values = {{0, 255, 0}};
msg->int16_values = {{0, 32767, -32768}};
msg->uint16_values = {{0, 65535, 0}};
msg->int32_values = {{
static_cast<int32_t>(0),
static_cast<int32_t>(2147483647),
static_cast<int32_t>(-2147483648)
}};
msg->uint32_values = {{0, 4294967295, 0}};
msg->int64_values[0] = 0;
msg->int64_values[1] = 9223372036854775807;
msg->int64_values[2] = -9223372036854775808UL;
msg->uint64_values = {{0, 18446744073709551615UL, 0}};
msg->string_values = {{"", "max value", "min value"}};
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr>
get_messages_dynamic_array_primitives()
{
std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {{}};
msg->byte_values = {{}};
msg->char_values = {{}};
msg->float32_values = {{}};
msg->float64_values = {{}};
msg->int8_values = {{}};
msg->uint8_values = {{}};
msg->int16_values = {{}};
msg->uint16_values = {{}};
msg->int32_values = {{}};
msg->uint32_values = {{}};
msg->int64_values = {{}};
msg->uint64_values = {{}};
msg->string_values = {{}};
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {true};
msg->byte_values = {0xff};
msg->char_values = {'\255'};
msg->float32_values = {1.11f};
msg->float64_values = {1.11};
msg->int8_values = {127};
msg->uint8_values = {255};
msg->int16_values = {32767};
msg->uint16_values = {65535};
msg->int32_values = {2147483647};
msg->uint32_values = {4294967295};
msg->int64_values = {9223372036854775807};
msg->uint64_values = {18446744073709551615UL};
msg->string_values = {{"max value"}};
messages.push_back(msg);
}
{
auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
msg->bool_values = {{false, true}};
msg->byte_values = {{0, 0xff}};
msg->char_values = {{'\0', '\255'}};
msg->float32_values = {{0.0f, 1.11f, -2.22f}};
msg->float64_values = {{0, 1.11, -2.22}};
msg->int8_values = {{0, 127, -128}};
msg->uint8_values = {{0, 255}};
msg->int16_values = {{0, 32767, -32768}};
msg->uint16_values = {{0, 65535}};
// The narrowing static cast is required to avoid build errors on Windows.
msg->int32_values = {{
static_cast<int32_t>(0),
static_cast<int32_t>(2147483647),
static_cast<int32_t>(-2147483648)
}};
msg->uint32_values = {{0, 4294967295}};
msg->int64_values.resize(3);
msg->int64_values[0] = 0;
msg->int64_values[1] = 9223372036854775807;
msg->int64_values[2] = -9223372036854775808UL;
msg->uint64_values = {{0, 18446744073709551615UL}};
msg->string_values = {{"", "max value", "optional min value"}};
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::Nested::Ptr>
get_messages_nested()
{
std::vector<test_communication::msg::Nested::Ptr> messages;
auto primitive_msgs = get_messages_primitives();
for (auto primitive_msg : primitive_msgs) {
auto msg = std::make_shared<test_communication::msg::Nested>();
msg->primitive_values = *primitive_msg;
messages.push_back(msg);
}
return messages;
}
std::vector<test_communication::msg::Builtins::Ptr>
get_messages_builtins()
{
std::vector<test_communication::msg::Builtins::Ptr> messages;
{
auto msg = std::make_shared<test_communication::msg::Builtins>();
msg->duration_value.sec = -1234567890;
msg->duration_value.nanosec = 123456789;
msg->time_value.sec = -1234567890;
msg->time_value.nanosec = 987654321;
messages.push_back(msg);
}
return messages;
}
#endif // __test_communication__message_fixtures__hpp__
<|endoftext|> |
<commit_before>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013 Due date: 30 NOV 2013
Problem:
Write a program that plays the game of HANGMAN(guessing a
mystery word). Read a word to be guessed from a file into
successive elements of the array WORD. The player must
guess the letters belonging to WORD. A single guessing
session should be terminated when either all letters have
been guessed correctly (player wins) or a specified number
of incorrect guesses have been made (computer wins). A run
must consist of at least two sessions: one player wins and
one computer wins. The player decides whether or not to
start a new session.
***************************************************************/
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;
ifstream inFile; // define ifstream to inFile command
void readString();
void initialize(unsigned long); // function to initalize everything
void guess();
// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
unsigned long wordLength; // length of word
// functions
int main() // reads in the file and sets the functions in motion
{
readString(); // reads the file and stores variables
initialize(wordLength); // sends length of word to initialize function
cout << "Let's play hangman!\n";
guess(); // game logic
return 0;
}
void readString()
{
int random20 = 0; // random number
string dictionary[20]; // 20 words to load from file
inFile.open("Words4Hangman.txt"); // open input file
while (inFile.good())
{
for (int i = 0; i < 20; i++)
{
inFile >> dictionary[i]; // load file and fill dict
}
}
inFile.close(); // close the file
srand((int)time(NULL)); // initialize random seed
random20 = (rand() % 20); // set random to 20 +-
word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
cout << word << endl; // cheater! (testing)
wordLength = word.size(); // size (length) of the string
}
void initialize(unsigned long wordLength)
{
solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}
void guess()
{
char guessLetter = ' '; // letter to guess
string solutionOld = solution; // solution string to compare with
int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
int guessesCounter = 7; // hangman countdown
cout << solution << endl; // output solution
cout << "Guess a letter\n";
cin >> guessLetter;
while ((guessesCounter > 0) && (winning == 0))
{
guessLetter = toupper(guessLetter); // make guess uppercase
for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
{
if (guessLetter == word[i])
{
//cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct
solution[i] = guessLetter; // set the i char in solution to guessLetter
goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
}
}
if (solution == word) // thus victory
{
winning = 1; // you won
cout << "Victory!\n"; // quick output for testing
}
else if (goodGuess == 1)
{
cout << "Good guess!\n"
<< solution << endl; // display positive
goodGuess = 0; // clear flag for next run
cout << "Enter your next guess: ";
cin >> guessLetter;
}
else
{
guessesCounter--; // decrement guess
cout << "The letter " << guessLetter << " does not appear in the word.\n"
<< "You have " << guessesCounter << "remaining.\n"
<< "Enter another letter: ";
cin >> guessLetter;
}
}
}<commit_msg>added space where needed<commit_after>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013 Due date: 30 NOV 2013
Problem:
Write a program that plays the game of HANGMAN(guessing a
mystery word). Read a word to be guessed from a file into
successive elements of the array WORD. The player must
guess the letters belonging to WORD. A single guessing
session should be terminated when either all letters have
been guessed correctly (player wins) or a specified number
of incorrect guesses have been made (computer wins). A run
must consist of at least two sessions: one player wins and
one computer wins. The player decides whether or not to
start a new session.
***************************************************************/
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;
ifstream inFile; // define ifstream to inFile command
void readString();
void initialize(unsigned long); // function to initalize everything
void guess();
// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
unsigned long wordLength; // length of word
// functions
int main() // reads in the file and sets the functions in motion
{
readString(); // reads the file and stores variables
initialize(wordLength); // sends length of word to initialize function
cout << "Let's play hangman!\n";
guess(); // game logic
return 0;
}
void readString()
{
int random20 = 0; // random number
string dictionary[20]; // 20 words to load from file
inFile.open("Words4Hangman.txt"); // open input file
while (inFile.good())
{
for (int i = 0; i < 20; i++)
{
inFile >> dictionary[i]; // load file and fill dict
}
}
inFile.close(); // close the file
srand((int)time(NULL)); // initialize random seed
random20 = (rand() % 20); // set random to 20 +-
word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
cout << word << endl; // cheater! (testing)
wordLength = word.size(); // size (length) of the string
}
void initialize(unsigned long wordLength)
{
solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}
void guess()
{
char guessLetter = ' '; // letter to guess
string solutionOld = solution; // solution string to compare with
int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
int guessesCounter = 7; // hangman countdown
cout << solution << endl; // output solution
cout << "Guess a letter\n";
cin >> guessLetter;
while ((guessesCounter > 0) && (winning == 0))
{
guessLetter = toupper(guessLetter); // make guess uppercase
for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
{
if (guessLetter == word[i])
{
//cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct
solution[i] = guessLetter; // set the i char in solution to guessLetter
goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
}
}
if (solution == word) // thus victory
{
winning = 1; // you won
cout << "Victory!\n"; // quick output for testing
}
else if (goodGuess == 1)
{
cout << "Good guess!\n"
<< solution << endl; // display positive
goodGuess = 0; // clear flag for next run
cout << "Enter your next guess: ";
cin >> guessLetter;
}
else
{
guessesCounter--; // decrement guess
cout << "The letter " << guessLetter << " does not appear in the word.\n"
<< "You have " << guessesCounter << " remaining.\n"
<< "Enter another letter: ";
cin >> guessLetter;
}
}
cout << "You are dead!\n"; // end if you run out of guesses
}<|endoftext|> |
<commit_before>#ifndef INCLUDE_AL_ISOSURFACE_HPP
#define INCLUDE_AL_ISOSURFACE_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File author(s):
Lance Putnam, 2010, [email protected]
This file incorporates work covered by the following copyright(s) and
permission notice(s):
Author: Raghavendra Chandrashekara
Email: [email protected], [email protected]
Last Modified: 5/8/2000
This work incorporates work covered by the following copyright and
permission notice:
Marching Cubes Example Program
by Cory Bloyd ([email protected])
A simple, portable and complete implementation of the Marching Cubes
and Marching Tetrahedrons algorithms in a single source file.
There are many ways that this code could be made faster, but the
intent is for the code to be easy to understand.
For a description of the algorithm go to
http://astronomy.swin.edu.au/pbourke/modelling/polygonise/
This code is public domain.
*/
#include <ciso646> // http://marshall.calepin.co/c-and-xcode-46.html
#include "allocore/system/al_Config.h"
#ifdef AL_WINDOWS
#include <tr1/unordered_map>
//#include <unordered_map>
#else
#ifdef _LIBCPP_VERSION
#include <unordered_map>
#else
#include <tr1/unordered_map>
#endif
#endif
#include <map>
#include <vector>
#include "allocore/types/al_Buffer.hpp"
#include "allocore/graphics/al_Graphics.hpp"
namespace al{
/// Isosurface generated using marching cubes
class Isosurface : public Mesh {
public:
struct EdgeVertex {
Vec3i pos; // cell coordinates
Vec3i corners[2]; // edge corners as offsets from cell coordinates
float x, y, z; // vertex position
float mu; // fraction along edge of vertex
/// Returns position of edge vertices
Vec3i edgePos(int i) const { return pos + corners[i]; }
};
struct EdgeTriangle {
int edgeIDs[3];
};
struct VertexAction {
virtual ~VertexAction(){}
virtual void operator()(const Isosurface::EdgeVertex& v, Isosurface& s) = 0;
};
struct NoVertexAction : public VertexAction{
virtual void operator()(const EdgeVertex& v, Isosurface& s){}
};
static NoVertexAction noVertexAction;
/// @param[in] level value to construct surface on
/// @param[in] action user defined functor called upon adding a new edge vertex
Isosurface(float level=0, VertexAction& action = noVertexAction);
virtual ~Isosurface();
/// Get a field dimension
int fieldDim(int i) const { return mNF[i]; }
/// Get isolevel
float level() const { return mIsolevel; }
/// Returns true if a valid surface has been generated
bool validSurface() const { return mValidSurface; }
/// Gets the length, width, and height of the isosurface volume
/// \returns true upon success and false if the surface is not valid
///
bool volumeLengths(double& volLengthX, double& volLengthY, double& volLengthZ) const;
// Get unique identifier of 3d position indices
int posID(int ix, int iy, int iz) const { return ix + mNF[0] * (iy + mNF[1] * iz); }
template <class VEC3I>
int posID(const VEC3I& i3) const { return posID(i3[0], i3[1], i3[2]); }
// Get unique identifier of cell
int cellID(int ix, int iy, int iz) const{ return 3*posID(ix,iy,iz); }
// Get unique identifier of edge
int edgeID(int cellID, int edgeNo) const{ return cellID + mEdgeIDOffsets[edgeNo]; }
/// Set individual dimensions of the scalar field
Isosurface& fieldDims(int nx, int ny, int nz);
/// Set all dimensions of the scalar field
Isosurface& fieldDims(int n){ return fieldDims(n,n,n); }
/// Set individual lengths of cell
Isosurface& cellLengths(double dx, double dy, double dz);
/// Set all lengths of cell
Isosurface& cellLengths(double v){ return cellLengths(v,v,v); }
/// Set isolevel
Isosurface& level(float v){ mIsolevel=v; return *this; }
/// Set whether to compute normals
Isosurface& normals(bool v){ mComputeNormals=v; return *this; }
/// Set whether to normalize normals (if being computed)
Isosurface& normalize(bool v){ mNormalize=v; return *this; }
/// Begin cell-at-a-time mode
void begin();
/// End cell-at-a-time mode
void end();
/// Clear the isosurface
void clear();
/// Add a cell from a scalar field
/// This should be called in between calls to begin() and end().
///
template <class T>
void addCell(
int ix, int iy, int iz,
const T& xyz, const T& Xyz,
const T& xYz, const T& XYz,
const T& xyZ, const T& XyZ,
const T& xYZ, const T& XYZ
){
int inds[3] = { ix, iy, iz };
const float vals[8] = { xyz, Xyz, xYz, XYz, xyZ, XyZ, xYZ, XYZ };
addCell(inds, vals);
}
/// Add a cell from a scalar field
void addCell(const int * indices3, const float * values8);
/// Generate isosurface from scalar field
template <class T>
void generate(const T * scalarField);
/// Generate isosurface from scalar field
/// The total number of elements in the field is expected to be nX*nY*nZ.
/// The field elements are located at the corners of the cuboidal cells used
/// to generate the surface. Thus, the surface is evaluated on a total of
/// (nX-1)*(nY-1)*(nZ-1) cells.
template <class T>
void generate(const T * scalarField, int nX, int nY, int nZ, float cellLengthX, float cellLengthY, float cellLengthZ){
fieldDims(nX, nY, nZ);
cellLengths(cellLengthX, cellLengthY, cellLengthZ);
generate(scalarField);
}
template <class T>
void generate(const T * scalarField, int n, float cellLength){
generate(scalarField, n,n,n, cellLength,cellLength,cellLength);
}
/// A variation that shifts & wraps all the cells by integer amounts
template <class T>
void generate_shifted(const T * scalarField, const int sx, const int sy, const int sz);
void vertexAction(VertexAction& a){ mVertexAction = &a; }
const bool inBox() const { return mInBox; }
/// Set whether isosurface is assumed to fit snugly within a box
/// Setting this to true will speed up extraction when the isosurface
/// is mostly dense and box shaped, i.e., a rectangular cuboid. If the
/// isosurface is to be computed on sparse or irregularly shaped grid, then
/// it is recommended to set this to false to save memory.
Isosurface& inBox(bool v);
protected:
struct IsosurfaceHashInt{
size_t operator()(int v) const { return v; }
// size_t operator()(int v) const { return v*2654435761UL; }
};
//#ifdef AL_WINDOWS
//typedef std::unordered_map<int, int, IsosurfaceHashInt> EdgeToVertex;
//#else
#ifdef _LIBCPP_VERSION
typedef std::unordered_map<int, int, IsosurfaceHashInt> EdgeToVertex;
#else
typedef std::tr1::unordered_map<int, int, IsosurfaceHashInt> EdgeToVertex;
#endif
//#endif
// typedef std::tr1::unordered_map<int, VertexData, IsosurfaceHashInt> EdgeToVertex;
// typedef std::hash_map<int, VertexData, IsosurfaceHashInt> EdgeToVertex;
// typedef std::map<int, VertexData> EdgeToVertex;
EdgeToVertex mEdgeToVertex; // map from edge ID to vertex
al::Buffer<EdgeTriangle> mEdgeTriangles; // surface triangles in terms of edge IDs
std::vector<int> mEdgeToVertexArray;
// al::Buffer<int> mTempEdges;
double mL[3]; // cell length in x, y, and z directions
int mNF[3]; // number of field points in x, y, and z directions
int mEdgeIDOffsets[12]; // used to obtain edge ID from vertex ID and edge number
float mIsolevel; // isosurface level
VertexAction * mVertexAction;
bool mValidSurface; // indicates whether a valid surface is present
bool mComputeNormals; // whether to compute normals
bool mNormalize; // whether to normalize normals
bool mInBox;
EdgeVertex calcIntersection(int nX, int nY, int nZ, int nEdgeNo, const float * vals) const;
void addEdgeVertex(int x, int y, int z, int cellID, int edge, const float * vals);
void compressTriangles();
};
// Implementation ______________________________________________________________
template <class T>
void Isosurface::generate(const T * vals){
inBox(true);
begin();
int Nx = mNF[0];
int Nxy = Nx*mNF[1];
// iterate through cubes (not field points)
//for(int z=0; z < mNF[2]-1; ++z){
// support transparency (assumes higher indices are farther away)
for(int z=mNF[2]-2; z>=0; --z){
int z0 = z *Nxy;
int z1 =(z+1)*Nxy;
for(int y=0; y < mNF[1]-1; ++y){
int y0 = y *Nx;
int y1 =(y+1)*Nx;
int z0y0 = z0+y0;
int z0y1 = z0+y1;
int z1y0 = z1+y0;
int z1y1 = z1+y1;
int z0y0_1 = z0y0+1;
int z0y1_1 = z0y1+1;
int z1y0_1 = z1y0+1;
int z1y1_1 = z1y1+1;
for(int x=0; x < mNF[0]-1; ++x){
float v8[] = {
vals[z0y0 + x], vals[z0y0_1 + x],
vals[z0y1 + x], vals[z0y1_1 + x],
vals[z1y0 + x], vals[z1y0_1 + x],
vals[z1y1 + x], vals[z1y1_1 + x]
};
int i3[] = {x,y,z};
addCell(i3, v8);
}
}
}
end();
}
// generate but shift & wrap the cubes by an integer amount:
template <class T>
void Isosurface::generate_shifted(const T * vals, const int sx, const int sy, const int sz){
inBox(true);
begin();
int Nx = mNF[0];
int Nxy = Nx*mNF[1];
// iterate through cubes (not field points)
//for(int z=0; z < mNF[2]-1; ++z){
// support transparency (assumes higher indices are farther away)
for(int z=mNF[2]-2; z>=0; --z){
int z0 = z *Nxy;
int z1 =(z+1)*Nxy;
for(int y=0; y < mNF[1]-1; ++y){
int y0 = y *Nx;
int y1 =(y+1)*Nx;
int z0y0 = z0+y0;
int z0y1 = z0+y1;
int z1y0 = z1+y0;
int z1y1 = z1+y1;
int z0y0_1 = z0y0+1;
int z0y1_1 = z0y1+1;
int z1y0_1 = z1y0+1;
int z1y1_1 = z1y1+1;
for(int x=0; x < mNF[0]-1; ++x){
float v8[] = {
vals[z0y0 + x], vals[z0y0_1 + x],
vals[z0y1 + x], vals[z0y1_1 + x],
vals[z1y0 + x], vals[z1y0_1 + x],
vals[z1y1 + x], vals[z1y1_1 + x]
};
int i3[] = {x, y, z};
addCell(i3, v8);
}
}
}
end();
}
} // al::
#endif
<commit_msg>remove unnecessary Windows checks<commit_after>#ifndef INCLUDE_AL_ISOSURFACE_HPP
#define INCLUDE_AL_ISOSURFACE_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File author(s):
Lance Putnam, 2010, [email protected]
This file incorporates work covered by the following copyright(s) and
permission notice(s):
Author: Raghavendra Chandrashekara
Email: [email protected], [email protected]
Last Modified: 5/8/2000
This work incorporates work covered by the following copyright and
permission notice:
Marching Cubes Example Program
by Cory Bloyd ([email protected])
A simple, portable and complete implementation of the Marching Cubes
and Marching Tetrahedrons algorithms in a single source file.
There are many ways that this code could be made faster, but the
intent is for the code to be easy to understand.
For a description of the algorithm go to
http://astronomy.swin.edu.au/pbourke/modelling/polygonise/
This code is public domain.
*/
#include <ciso646> // http://marshall.calepin.co/c-and-xcode-46.html
#include "allocore/system/al_Config.h"
#ifdef _LIBCPP_VERSION
#include <unordered_map>
#else
#include <tr1/unordered_map>
#endif
#include <map>
#include <vector>
#include "allocore/types/al_Buffer.hpp"
#include "allocore/graphics/al_Graphics.hpp"
namespace al{
/// Isosurface generated using marching cubes
class Isosurface : public Mesh {
public:
struct EdgeVertex {
Vec3i pos; // cell coordinates
Vec3i corners[2]; // edge corners as offsets from cell coordinates
float x, y, z; // vertex position
float mu; // fraction along edge of vertex
/// Returns position of edge vertices
Vec3i edgePos(int i) const { return pos + corners[i]; }
};
struct EdgeTriangle {
int edgeIDs[3];
};
struct VertexAction {
virtual ~VertexAction(){}
virtual void operator()(const Isosurface::EdgeVertex& v, Isosurface& s) = 0;
};
struct NoVertexAction : public VertexAction{
virtual void operator()(const EdgeVertex& v, Isosurface& s){}
};
static NoVertexAction noVertexAction;
/// @param[in] level value to construct surface on
/// @param[in] action user defined functor called upon adding a new edge vertex
Isosurface(float level=0, VertexAction& action = noVertexAction);
virtual ~Isosurface();
/// Get a field dimension
int fieldDim(int i) const { return mNF[i]; }
/// Get isolevel
float level() const { return mIsolevel; }
/// Returns true if a valid surface has been generated
bool validSurface() const { return mValidSurface; }
/// Gets the length, width, and height of the isosurface volume
/// \returns true upon success and false if the surface is not valid
///
bool volumeLengths(double& volLengthX, double& volLengthY, double& volLengthZ) const;
// Get unique identifier of 3d position indices
int posID(int ix, int iy, int iz) const { return ix + mNF[0] * (iy + mNF[1] * iz); }
template <class VEC3I>
int posID(const VEC3I& i3) const { return posID(i3[0], i3[1], i3[2]); }
// Get unique identifier of cell
int cellID(int ix, int iy, int iz) const{ return 3*posID(ix,iy,iz); }
// Get unique identifier of edge
int edgeID(int cellID, int edgeNo) const{ return cellID + mEdgeIDOffsets[edgeNo]; }
/// Set individual dimensions of the scalar field
Isosurface& fieldDims(int nx, int ny, int nz);
/// Set all dimensions of the scalar field
Isosurface& fieldDims(int n){ return fieldDims(n,n,n); }
/// Set individual lengths of cell
Isosurface& cellLengths(double dx, double dy, double dz);
/// Set all lengths of cell
Isosurface& cellLengths(double v){ return cellLengths(v,v,v); }
/// Set isolevel
Isosurface& level(float v){ mIsolevel=v; return *this; }
/// Set whether to compute normals
Isosurface& normals(bool v){ mComputeNormals=v; return *this; }
/// Set whether to normalize normals (if being computed)
Isosurface& normalize(bool v){ mNormalize=v; return *this; }
/// Begin cell-at-a-time mode
void begin();
/// End cell-at-a-time mode
void end();
/// Clear the isosurface
void clear();
/// Add a cell from a scalar field
/// This should be called in between calls to begin() and end().
///
template <class T>
void addCell(
int ix, int iy, int iz,
const T& xyz, const T& Xyz,
const T& xYz, const T& XYz,
const T& xyZ, const T& XyZ,
const T& xYZ, const T& XYZ
){
int inds[3] = { ix, iy, iz };
const float vals[8] = { xyz, Xyz, xYz, XYz, xyZ, XyZ, xYZ, XYZ };
addCell(inds, vals);
}
/// Add a cell from a scalar field
void addCell(const int * indices3, const float * values8);
/// Generate isosurface from scalar field
template <class T>
void generate(const T * scalarField);
/// Generate isosurface from scalar field
/// The total number of elements in the field is expected to be nX*nY*nZ.
/// The field elements are located at the corners of the cuboidal cells used
/// to generate the surface. Thus, the surface is evaluated on a total of
/// (nX-1)*(nY-1)*(nZ-1) cells.
template <class T>
void generate(const T * scalarField, int nX, int nY, int nZ, float cellLengthX, float cellLengthY, float cellLengthZ){
fieldDims(nX, nY, nZ);
cellLengths(cellLengthX, cellLengthY, cellLengthZ);
generate(scalarField);
}
template <class T>
void generate(const T * scalarField, int n, float cellLength){
generate(scalarField, n,n,n, cellLength,cellLength,cellLength);
}
/// A variation that shifts & wraps all the cells by integer amounts
template <class T>
void generate_shifted(const T * scalarField, const int sx, const int sy, const int sz);
void vertexAction(VertexAction& a){ mVertexAction = &a; }
const bool inBox() const { return mInBox; }
/// Set whether isosurface is assumed to fit snugly within a box
/// Setting this to true will speed up extraction when the isosurface
/// is mostly dense and box shaped, i.e., a rectangular cuboid. If the
/// isosurface is to be computed on sparse or irregularly shaped grid, then
/// it is recommended to set this to false to save memory.
Isosurface& inBox(bool v);
protected:
struct IsosurfaceHashInt{
size_t operator()(int v) const { return v; }
// size_t operator()(int v) const { return v*2654435761UL; }
};
#ifdef _LIBCPP_VERSION
typedef std::unordered_map<int, int, IsosurfaceHashInt> EdgeToVertex;
#else
typedef std::tr1::unordered_map<int, int, IsosurfaceHashInt> EdgeToVertex;
#endif
// typedef std::map<int, VertexData> EdgeToVertex;
EdgeToVertex mEdgeToVertex; // map from edge ID to vertex
al::Buffer<EdgeTriangle> mEdgeTriangles; // surface triangles in terms of edge IDs
std::vector<int> mEdgeToVertexArray;
// al::Buffer<int> mTempEdges;
double mL[3]; // cell length in x, y, and z directions
int mNF[3]; // number of field points in x, y, and z directions
int mEdgeIDOffsets[12]; // used to obtain edge ID from vertex ID and edge number
float mIsolevel; // isosurface level
VertexAction * mVertexAction;
bool mValidSurface; // indicates whether a valid surface is present
bool mComputeNormals; // whether to compute normals
bool mNormalize; // whether to normalize normals
bool mInBox;
EdgeVertex calcIntersection(int nX, int nY, int nZ, int nEdgeNo, const float * vals) const;
void addEdgeVertex(int x, int y, int z, int cellID, int edge, const float * vals);
void compressTriangles();
};
// Implementation ______________________________________________________________
template <class T>
void Isosurface::generate(const T * vals){
inBox(true);
begin();
int Nx = mNF[0];
int Nxy = Nx*mNF[1];
// iterate through cubes (not field points)
//for(int z=0; z < mNF[2]-1; ++z){
// support transparency (assumes higher indices are farther away)
for(int z=mNF[2]-2; z>=0; --z){
int z0 = z *Nxy;
int z1 =(z+1)*Nxy;
for(int y=0; y < mNF[1]-1; ++y){
int y0 = y *Nx;
int y1 =(y+1)*Nx;
int z0y0 = z0+y0;
int z0y1 = z0+y1;
int z1y0 = z1+y0;
int z1y1 = z1+y1;
int z0y0_1 = z0y0+1;
int z0y1_1 = z0y1+1;
int z1y0_1 = z1y0+1;
int z1y1_1 = z1y1+1;
for(int x=0; x < mNF[0]-1; ++x){
float v8[] = {
vals[z0y0 + x], vals[z0y0_1 + x],
vals[z0y1 + x], vals[z0y1_1 + x],
vals[z1y0 + x], vals[z1y0_1 + x],
vals[z1y1 + x], vals[z1y1_1 + x]
};
int i3[] = {x,y,z};
addCell(i3, v8);
}
}
}
end();
}
// generate but shift & wrap the cubes by an integer amount:
template <class T>
void Isosurface::generate_shifted(const T * vals, const int sx, const int sy, const int sz){
inBox(true);
begin();
int Nx = mNF[0];
int Nxy = Nx*mNF[1];
// iterate through cubes (not field points)
//for(int z=0; z < mNF[2]-1; ++z){
// support transparency (assumes higher indices are farther away)
for(int z=mNF[2]-2; z>=0; --z){
int z0 = z *Nxy;
int z1 =(z+1)*Nxy;
for(int y=0; y < mNF[1]-1; ++y){
int y0 = y *Nx;
int y1 =(y+1)*Nx;
int z0y0 = z0+y0;
int z0y1 = z0+y1;
int z1y0 = z1+y0;
int z1y1 = z1+y1;
int z0y0_1 = z0y0+1;
int z0y1_1 = z0y1+1;
int z1y0_1 = z1y0+1;
int z1y1_1 = z1y1+1;
for(int x=0; x < mNF[0]-1; ++x){
float v8[] = {
vals[z0y0 + x], vals[z0y0_1 + x],
vals[z0y1 + x], vals[z0y1_1 + x],
vals[z1y0 + x], vals[z1y0_1 + x],
vals[z1y1 + x], vals[z1y1_1 + x]
};
int i3[] = {x, y, z};
addCell(i3, v8);
}
}
}
end();
}
} // al::
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "sysdef.h"
#include "csutil/scanstr.h"
int ScanStr (char* in, char* format, ...)
{
va_list arg;
va_start (arg, format);
int num = 0;
in += strspn (in, " \t\n\f");
while (*format)
{
if (*format == '%')
{
format++;
switch (*format)
{
case 'd':
{
int* a = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
*a = atoi (in);
in += strspn (in, "0123456789+- \t\n\f");
num++;
break;
}
case 'D':
{
int i;
int* list = va_arg (arg, int*);
int* nr = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
i = 0;
while ((*in >= '0' && *in <= '9') || *in == '+' || *in == '-')
{
list[i++] = atoi (in);
in += strspn (in, "0123456789+-");
in += strspn (in, " \t\n\f");
if (*in != ',') break;
in++;
in += strspn (in, " \t\n\f");
}
*nr = i;
num++;
break;
}
case 'b':
{
int* a = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
char* in2 = in + strspn (in, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
int l = (int)(in2-in);
*a = !strncasecmp (in, "yes", l) || !strncasecmp (in, "true", l) || !strncasecmp (in, "on", l) ||
!strncasecmp (in, "1", l);
in = in2 + strspn (in2, " \t\n\f");
num++;
break;
}
case 'f':
{
float* a = va_arg (arg, float*);
in += strspn (in, " \t\n\f");
*a = atof (in);
in += strspn (in, "0123456789.eE+- \t\n\f");
num++;
break;
}
case 'F':
{
int i;
float* list = va_arg (arg, float*);
int* nr = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
i = 0;
while ((*in >= '0' && *in <= '9') || *in == '.' || *in == '+' || *in == '-' || *in == 'e' || *in == 'E')
{
list[i++] = atof (in);
in += strspn (in, "0123456789.eE+-");
in += strspn (in, " \t\n\f");
if (*in != ',') break;
in++;
in += strspn (in, " \t\n\f");
}
*nr = i;
num++;
break;
}
case 's':
{
char* a = va_arg (arg, char*);
in += strspn (in, " \t\n\f");
if (*in == '\'')
{
in++;
char* in2 = strchr (in, '\'');
strncpy (a, in, (int)(in2-in));
a[(int)(in2-in)] = 0;
in = in2+1;
}
else
{
char* in2 = in + strspn (in, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789");
strncpy (a, in, (int)(in2-in));
a[(int)(in2-in)] = 0;
in = in2;
}
in += strspn (in, " \t\n\f");
num++;
break;
}
}
if (*format) format++;
}
else if (*format == ' ') { format++; in += strspn (in, " \t\n\f"); }
else if (*in == *format) { in++; format++; }
else { num = -1; break; }
}
va_end (arg);
return num;
}
<commit_msg>Fixed ScanStr() so that '.' is also in string.<commit_after>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "sysdef.h"
#include "csutil/scanstr.h"
int ScanStr (char* in, char* format, ...)
{
va_list arg;
va_start (arg, format);
int num = 0;
in += strspn (in, " \t\n\f");
while (*format)
{
if (*format == '%')
{
format++;
switch (*format)
{
case 'd':
{
int* a = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
*a = atoi (in);
in += strspn (in, "0123456789+- \t\n\f");
num++;
break;
}
case 'D':
{
int i;
int* list = va_arg (arg, int*);
int* nr = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
i = 0;
while ((*in >= '0' && *in <= '9') || *in == '+' || *in == '-')
{
list[i++] = atoi (in);
in += strspn (in, "0123456789+-");
in += strspn (in, " \t\n\f");
if (*in != ',') break;
in++;
in += strspn (in, " \t\n\f");
}
*nr = i;
num++;
break;
}
case 'b':
{
int* a = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
char* in2 = in + strspn (in, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
int l = (int)(in2-in);
*a = !strncasecmp (in, "yes", l) || !strncasecmp (in, "true", l) || !strncasecmp (in, "on", l) ||
!strncasecmp (in, "1", l);
in = in2 + strspn (in2, " \t\n\f");
num++;
break;
}
case 'f':
{
float* a = va_arg (arg, float*);
in += strspn (in, " \t\n\f");
*a = atof (in);
in += strspn (in, "0123456789.eE+- \t\n\f");
num++;
break;
}
case 'F':
{
int i;
float* list = va_arg (arg, float*);
int* nr = va_arg (arg, int*);
in += strspn (in, " \t\n\f");
i = 0;
while ((*in >= '0' && *in <= '9') || *in == '.' || *in == '+' || *in == '-' || *in == 'e' || *in == 'E')
{
list[i++] = atof (in);
in += strspn (in, "0123456789.eE+-");
in += strspn (in, " \t\n\f");
if (*in != ',') break;
in++;
in += strspn (in, " \t\n\f");
}
*nr = i;
num++;
break;
}
case 's':
{
char* a = va_arg (arg, char*);
in += strspn (in, " \t\n\f");
if (*in == '\'')
{
in++;
char* in2 = strchr (in, '\'');
strncpy (a, in, (int)(in2-in));
a[(int)(in2-in)] = 0;
in = in2+1;
}
else
{
char* in2 = in + strspn (in, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.");
strncpy (a, in, (int)(in2-in));
a[(int)(in2-in)] = 0;
in = in2;
}
in += strspn (in, " \t\n\f");
num++;
break;
}
}
if (*format) format++;
}
else if (*format == ' ') { format++; in += strspn (in, " \t\n\f"); }
else if (*in == *format) { in++; format++; }
else { num = -1; break; }
}
va_end (arg);
return num;
}
<|endoftext|> |
<commit_before>/*
BelaCsound.cpp:
Copyright (C) 2017 V Lazzarini
This file is part of Csound.
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <csound/plugin.h>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
static int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiOutDevice(CSOUND *csound, void *userData);
static int WriteMidiData(CSOUND *csound, void *userData, const unsigned char *mbuf,
int nbytes);
/** DigiIn opcode
ksig digiInBela ipin
asig digiInBela ipin
*/
struct DigiIn : csnd::Plugin<1, 1> {
int pin;
int fcount;
int frms;
BelaContext *context;
int init() {
pin = (int) inargs[0];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
pinMode(context,0,pin,0);
fcount = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
outargs[0] = digitalRead(context,fcount,pin);
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig out(this, outargs(0));
int cnt = fcount;
for (auto &s : out) {
s = digitalRead(context,cnt,pin);
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
}
};
/** DigiOut opcode
digiOutBela ksig,ipin
digiOutBela asig,ipin
*/
struct DigiOut : csnd::Plugin<0, 2> {
int pin;
int fcount;
int frms;
BelaContext *context;
int init() {
pin = (int) inargs[1];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
pinMode(context,0,pin,1);
fcount = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
digitalWrite(context,fcount,pin,inargs[0]);
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig in(this, inargs(0));
int cnt = fcount;
for (auto s : in) {
digitalWriteOnce(context,cnt,pin,s);
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
}
};
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
CsChan ochannel[ANCHNS];
};
static CsData gCsData;
static Midi gMidi;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI IN device */
const char *midiOutDev = "-Qhw:1,0,0"; /* MIDI OUT device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev, midiOutDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Error: number of audio inputs != number of audio outputs.\n");
return false;
}
if(context->analogInChannels != context->analogOutChannels) {
printf("Error: number of analog inputs != number of analog outputs.\n");
return false;
}
/* set up Csound */
csound = new Csound();
gCsData.csound = csound;
csound->SetHostData((void *) context);
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
csound->SetExternalMidiOutOpenCallback(OpenMidiOutDevice);
csound->SetExternalMidiWriteCallback(WriteMidiData);
csound->SetExternalMidiOutCloseCallback(CloseMidiOutDevice);
/* set up digi opcodes */
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "k",
"i", csnd::thread::ik) != 0)
printf("Warning: could not add digiInBela k-rate opcode\n");
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "a",
"i", csnd::thread::ia) != 0)
printf("Warning: could not add digiInBela a-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ki", csnd::thread::ik) != 0)
printf("Warning: could not add digiOutBela k-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ai", csnd::thread::ia) != 0)
printf("Warning: could not add digiOutBela a-rate opcode\n");
if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
printf("Error: Csound could not compile CSD file.\n");
return false;
}
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i=0; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogIn" << i+1;
gCsData.ochannel[i].data.resize(csound->GetKsmps());
gCsData.ochannel[i].name << "analogOut" << i+1;
}
return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
CsChan *ochannel = &(gCsData.ochannel[0]);
float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* processing loop */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
csound->GetAudioChannel(ochannel[i].name.str().c_str(),
&(ochannel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else break;
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos frm gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
analogWriteOnce(context,k,i,ochannel[i].data[frmcount]);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.readFrom(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi in device %s", dev);
return -1;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
return 0;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0, byte;
if(userData) {
Midi *midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
return 0;
}
int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.writeTo(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi out device %s", dev);
return -1;
}
int CloseMidiOutDevice(CSOUND *csound, void *userData) {
return 0;
}
int WriteMidiData(CSOUND *csound, void *userData,
const unsigned char *mbuf, int nbytes) {
if(userData) {
Midi *midi = (Midi *) userData;
if(midi->writeOutput((midi_byte_t *)mbuf, nbytes) > 0) return nbytes;
return 0;
}
return 0;
}
<commit_msg>init_done<commit_after>/*
BelaCsound.cpp:
Copyright (C) 2017 V Lazzarini
This file is part of Csound.
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <csound/plugin.h>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
static int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiOutDevice(CSOUND *csound, void *userData);
static int WriteMidiData(CSOUND *csound, void *userData, const unsigned char *mbuf,
int nbytes);
/** DigiIn opcode
ksig digiInBela ipin
asig digiInBela ipin
*/
struct DigiIn : csnd::Plugin<1, 1> {
int pin;
int fcount;
int frms;
init init_done;
BelaContext *context;
int init() {
pin = (int) inargs[0];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
fcount = 0;
init_done = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
outargs[0] = (MYFLT) digitalRead(context,fcount,pin);
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig out(this, outargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
for (auto &s : out) {
s = (MYFLT) digitalRead(context,cnt,pin);
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
/** DigiOut opcode
digiOutBela ksig,ipin
digiOutBela asig,ipin
*/
struct DigiOut : csnd::Plugin<0, 2> {
int pin;
int fcount;
int frms;
int init_done;
BelaContext *context;
int init() {
pin = (int) inargs[1];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
init_done = 0;
fcount = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
digitalWrite(context,fcount,pin,(inargs[0] > 0.0 ? 1 : 0));
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig in(this, inargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
for (auto s : in) {
digitalWriteOnce(context,cnt,pin, (s > 0.0 ? 1 : 0));
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
CsChan ochannel[ANCHNS];
};
static CsData gCsData;
static Midi gMidi;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI IN device */
const char *midiOutDev = "-Qhw:1,0,0"; /* MIDI OUT device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev, midiOutDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Error: number of audio inputs != number of audio outputs.\n");
return false;
}
if(context->analogInChannels != context->analogOutChannels) {
printf("Error: number of analog inputs != number of analog outputs.\n");
return false;
}
/* set up Csound */
csound = new Csound();
gCsData.csound = csound;
csound->SetHostData((void *) context);
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
csound->SetExternalMidiOutOpenCallback(OpenMidiOutDevice);
csound->SetExternalMidiWriteCallback(WriteMidiData);
csound->SetExternalMidiOutCloseCallback(CloseMidiOutDevice);
/* set up digi opcodes */
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "k",
"i", csnd::thread::ik) != 0)
printf("Warning: could not add digiInBela k-rate opcode\n");
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "a",
"i", csnd::thread::ia) != 0)
printf("Warning: could not add digiInBela a-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ki", csnd::thread::ik) != 0)
printf("Warning: could not add digiOutBela k-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ai", csnd::thread::ia) != 0)
printf("Warning: could not add digiOutBela a-rate opcode\n");
if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
printf("Error: Csound could not compile CSD file.\n");
return false;
}
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i=0; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogIn" << i+1;
gCsData.ochannel[i].data.resize(csound->GetKsmps());
gCsData.ochannel[i].name << "analogOut" << i+1;
}
return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
CsChan *ochannel = &(gCsData.ochannel[0]);
float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* processing loop */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
csound->GetAudioChannel(ochannel[i].name.str().c_str(),
&(ochannel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else break;
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos frm gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
analogWriteOnce(context,k,i,ochannel[i].data[frmcount]);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.readFrom(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi in device %s", dev);
return -1;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
return 0;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0, byte;
if(userData) {
Midi *midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
return 0;
}
int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.writeTo(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi out device %s", dev);
return -1;
}
int CloseMidiOutDevice(CSOUND *csound, void *userData) {
return 0;
}
int WriteMidiData(CSOUND *csound, void *userData,
const unsigned char *mbuf, int nbytes) {
if(userData) {
Midi *midi = (Midi *) userData;
if(midi->writeOutput((midi_byte_t *)mbuf, nbytes) > 0) return nbytes;
return 0;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright 2015 Adam Bloniarz, Jonathan Terhorst, Ameet Talwalkar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tclap/CmdLine.h>
#include "api/BamReader.h"
using namespace std;
using namespace BamTools;
string get_cigar(vector<CigarOp> cig_ops) {
string cigar;
for (auto cig_op : cig_ops) {
cigar += to_string(cig_op.Length);
cigar += cig_op.Type;
}
return cigar;
}
int main(int argc, char** argv) {
/* Command line arguments:
* 1) Bamfile
* 2) Contig
* 3) Start
* 4) End
*/
try {
TCLAP::CmdLine cmd("Bamdump - dump the contents of a bam file to stdout, to be piped to CAGe");
TCLAP::UnlabeledValueArg<string> bamfile_arg("bamfile", "bam file", true, "", "bamfile", cmd);
TCLAP::UnlabeledValueArg<string> contig_arg("contig", "contig name", true, "", "contig", cmd);
TCLAP::UnlabeledValueArg<int> start_arg("start", "start position", true, 0, "start", cmd);
TCLAP::UnlabeledValueArg<int> end_arg("end", "end position", true, 0, "end", cmd);
cmd.parse(argc, argv);
BamReader reader;
string bamfile = bamfile_arg.getValue();
if (!reader.Open(bamfile)) {
throw runtime_error(string("Unable to open bam file ") + bamfile);
}
if (!reader.OpenIndex(bamfile + ".bai")) {
throw runtime_error(string("Unable to open bam file ") + bamfile + ".bai");
}
string contig = contig_arg.getValue();
int refID = reader.GetReferenceID(contig);
int start = start_arg.getValue();
int end = end_arg.getValue();
reader.SetRegion(refID, start, refID, end);
BamAlignment al;
while (reader.GetNextAlignment(al)) {
printf("%i %s %s %s %i %i\n", al.Position, al.QueryBases.c_str(), get_cigar(al.CigarData).c_str(), al.Qualities.c_str(), al.MapQuality, al.IsReverseStrand() ? 1 : 0);
}
reader.Close();
} catch (exception& e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}
<commit_msg>Fixed indentation<commit_after>/**
* Copyright 2015 Adam Bloniarz, Jonathan Terhorst, Ameet Talwalkar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tclap/CmdLine.h>
#include "api/BamReader.h"
using namespace std;
using namespace BamTools;
string get_cigar(vector<CigarOp> cig_ops) {
string cigar;
for (auto cig_op : cig_ops) {
cigar += to_string(cig_op.Length);
cigar += cig_op.Type;
}
return cigar;
}
int main(int argc, char** argv) {
/* Command line arguments:
* 1) Bamfile
* 2) Contig
* 3) Start
* 4) End
*/
try {
TCLAP::CmdLine cmd("Bamdump - dump the contents of a bam file to stdout, to be piped to CAGe");
TCLAP::UnlabeledValueArg<string> bamfile_arg("bamfile", "bam file", true, "", "bamfile", cmd);
TCLAP::UnlabeledValueArg<string> contig_arg("contig", "contig name", true, "", "contig", cmd);
TCLAP::UnlabeledValueArg<int> start_arg("start", "start position", true, 0, "start", cmd);
TCLAP::UnlabeledValueArg<int> end_arg("end", "end position", true, 0, "end", cmd);
cmd.parse(argc, argv);
BamReader reader;
string bamfile = bamfile_arg.getValue();
if (!reader.Open(bamfile)) {
throw runtime_error(string("Unable to open bam file ") + bamfile);
}
if (!reader.OpenIndex(bamfile + ".bai")) {
throw runtime_error(string("Unable to open bam file ") + bamfile + ".bai");
}
string contig = contig_arg.getValue();
int refID = reader.GetReferenceID(contig);
int start = start_arg.getValue();
int end = end_arg.getValue();
reader.SetRegion(refID, start, refID, end);
BamAlignment al;
while (reader.GetNextAlignment(al)) {
printf("%i %s %s %s %i %i\n", al.Position, al.QueryBases.c_str(), get_cigar(al.CigarData).c_str(), al.Qualities.c_str(), al.MapQuality, al.IsReverseStrand() ? 1 : 0);
}
reader.Close();
} catch (exception& e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#if defined(WEBRTC_ANDROID)
#include "webrtc/base/ifaddrs-android.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <errno.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
namespace {
struct netlinkrequest {
nlmsghdr header;
ifaddrmsg msg;
};
const int kMaxReadSize = 4096;
} // namespace
namespace rtc {
int set_ifname(struct ifaddrs* ifaddr, int interface) {
char buf[IFNAMSIZ] = {0};
char* name = if_indextoname(interface, buf);
if (name == NULL) {
return -1;
}
ifaddr->ifa_name = new char[strlen(name) + 1];
strncpy(ifaddr->ifa_name, name, strlen(name) + 1);
return 0;
}
int set_flags(struct ifaddrs* ifaddr) {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
return -1;
}
ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifaddr->ifa_name, IFNAMSIZ - 1);
int rc = ioctl(fd, SIOCGIFFLAGS, &ifr);
close(fd);
if (rc == -1) {
return -1;
}
ifaddr->ifa_flags = ifr.ifr_flags;
return 0;
}
int set_addresses(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* data,
size_t len) {
if (msg->ifa_family == AF_INET) {
sockaddr_in* sa = new sockaddr_in;
sa->sin_family = AF_INET;
memcpy(&sa->sin_addr, data, len);
ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
} else if (msg->ifa_family == AF_INET6) {
sockaddr_in6* sa = new sockaddr_in6;
sa->sin6_family = AF_INET6;
sa->sin6_scope_id = msg->ifa_index;
memcpy(&sa->sin6_addr, data, len);
ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
} else {
return -1;
}
return 0;
}
int make_prefixes(struct ifaddrs* ifaddr, int family, int prefixlen) {
char* prefix = NULL;
if (family == AF_INET) {
sockaddr_in* mask = new sockaddr_in;
mask->sin_family = AF_INET;
memset(&mask->sin_addr, 0, sizeof(in_addr));
ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
if (prefixlen > 32) {
prefixlen = 32;
}
prefix = reinterpret_cast<char*>(&mask->sin_addr);
} else if (family == AF_INET6) {
sockaddr_in6* mask = new sockaddr_in6;
mask->sin6_family = AF_INET6;
memset(&mask->sin6_addr, 0, sizeof(in6_addr));
ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
if (prefixlen > 128) {
prefixlen = 128;
}
prefix = reinterpret_cast<char*>(&mask->sin6_addr);
} else {
return -1;
}
for (int i = 0; i < (prefixlen / 8); i++) {
*prefix++ = 0xFF;
}
char remainder = 0xff;
remainder <<= (8 - prefixlen % 8);
*prefix = remainder;
return 0;
}
int populate_ifaddrs(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* bytes,
size_t len) {
if (set_ifname(ifaddr, msg->ifa_index) != 0) {
return -1;
}
if (set_flags(ifaddr) != 0) {
return -1;
}
if (set_addresses(ifaddr, msg, bytes, len) != 0) {
return -1;
}
if (make_prefixes(ifaddr, msg->ifa_family, msg->ifa_prefixlen) != 0) {
return -1;
}
return 0;
}
int getifaddrs(struct ifaddrs** result) {
int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
return -1;
}
netlinkrequest ifaddr_request;
memset(&ifaddr_request, 0, sizeof(ifaddr_request));
ifaddr_request.header.nlmsg_flags = NLM_F_ROOT | NLM_F_REQUEST;
ifaddr_request.header.nlmsg_type = RTM_GETADDR;
ifaddr_request.header.nlmsg_len = NLMSG_LENGTH(sizeof(ifaddrmsg));
ssize_t count = send(fd, &ifaddr_request, ifaddr_request.header.nlmsg_len, 0);
if (static_cast<size_t>(count) != ifaddr_request.header.nlmsg_len) {
close(fd);
return -1;
}
struct ifaddrs* start = NULL;
struct ifaddrs* current = NULL;
char buf[kMaxReadSize];
ssize_t amount_read = recv(fd, &buf, kMaxReadSize, 0);
while (amount_read > 0) {
nlmsghdr* header = reinterpret_cast<nlmsghdr*>(&buf[0]);
size_t header_size = static_cast<size_t>(amount_read);
for ( ; NLMSG_OK(header, header_size);
header = NLMSG_NEXT(header, header_size)) {
switch (header->nlmsg_type) {
case NLMSG_DONE:
// Success. Return.
*result = start;
close(fd);
return 0;
case NLMSG_ERROR:
close(fd);
freeifaddrs(start);
return -1;
case RTM_NEWADDR: {
ifaddrmsg* address_msg =
reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(header));
rtattr* rta = IFA_RTA(address_msg);
ssize_t payload_len = IFA_PAYLOAD(header);
while (RTA_OK(rta, payload_len)) {
if (rta->rta_type == IFA_ADDRESS) {
int family = address_msg->ifa_family;
if (family == AF_INET || family == AF_INET6) {
ifaddrs* newest = new ifaddrs;
memset(newest, 0, sizeof(ifaddrs));
if (current) {
current->ifa_next = newest;
} else {
start = newest;
}
if (populate_ifaddrs(newest, address_msg, RTA_DATA(rta),
RTA_PAYLOAD(rta)) != 0) {
freeifaddrs(start);
*result = NULL;
return -1;
}
current = newest;
}
}
rta = RTA_NEXT(rta, payload_len);
}
break;
}
}
}
amount_read = recv(fd, &buf, kMaxReadSize, 0);
}
close(fd);
freeifaddrs(start);
return -1;
}
void freeifaddrs(struct ifaddrs* addrs) {
struct ifaddrs* last = NULL;
struct ifaddrs* cursor = addrs;
while (cursor) {
delete[] cursor->ifa_name;
delete cursor->ifa_addr;
delete cursor->ifa_netmask;
last = cursor;
cursor = cursor->ifa_next;
delete last;
}
}
#endif // defined(WEBRTC_ANDROID)
} // namespace rtc
<commit_msg>Move end of namespace inside #ifdef<commit_after>/*
* Copyright 2012 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#if defined(WEBRTC_ANDROID)
#include "webrtc/base/ifaddrs-android.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <errno.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
namespace {
struct netlinkrequest {
nlmsghdr header;
ifaddrmsg msg;
};
const int kMaxReadSize = 4096;
} // namespace
namespace rtc {
int set_ifname(struct ifaddrs* ifaddr, int interface) {
char buf[IFNAMSIZ] = {0};
char* name = if_indextoname(interface, buf);
if (name == NULL) {
return -1;
}
ifaddr->ifa_name = new char[strlen(name) + 1];
strncpy(ifaddr->ifa_name, name, strlen(name) + 1);
return 0;
}
int set_flags(struct ifaddrs* ifaddr) {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
return -1;
}
ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifaddr->ifa_name, IFNAMSIZ - 1);
int rc = ioctl(fd, SIOCGIFFLAGS, &ifr);
close(fd);
if (rc == -1) {
return -1;
}
ifaddr->ifa_flags = ifr.ifr_flags;
return 0;
}
int set_addresses(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* data,
size_t len) {
if (msg->ifa_family == AF_INET) {
sockaddr_in* sa = new sockaddr_in;
sa->sin_family = AF_INET;
memcpy(&sa->sin_addr, data, len);
ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
} else if (msg->ifa_family == AF_INET6) {
sockaddr_in6* sa = new sockaddr_in6;
sa->sin6_family = AF_INET6;
sa->sin6_scope_id = msg->ifa_index;
memcpy(&sa->sin6_addr, data, len);
ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
} else {
return -1;
}
return 0;
}
int make_prefixes(struct ifaddrs* ifaddr, int family, int prefixlen) {
char* prefix = NULL;
if (family == AF_INET) {
sockaddr_in* mask = new sockaddr_in;
mask->sin_family = AF_INET;
memset(&mask->sin_addr, 0, sizeof(in_addr));
ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
if (prefixlen > 32) {
prefixlen = 32;
}
prefix = reinterpret_cast<char*>(&mask->sin_addr);
} else if (family == AF_INET6) {
sockaddr_in6* mask = new sockaddr_in6;
mask->sin6_family = AF_INET6;
memset(&mask->sin6_addr, 0, sizeof(in6_addr));
ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
if (prefixlen > 128) {
prefixlen = 128;
}
prefix = reinterpret_cast<char*>(&mask->sin6_addr);
} else {
return -1;
}
for (int i = 0; i < (prefixlen / 8); i++) {
*prefix++ = 0xFF;
}
char remainder = 0xff;
remainder <<= (8 - prefixlen % 8);
*prefix = remainder;
return 0;
}
int populate_ifaddrs(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* bytes,
size_t len) {
if (set_ifname(ifaddr, msg->ifa_index) != 0) {
return -1;
}
if (set_flags(ifaddr) != 0) {
return -1;
}
if (set_addresses(ifaddr, msg, bytes, len) != 0) {
return -1;
}
if (make_prefixes(ifaddr, msg->ifa_family, msg->ifa_prefixlen) != 0) {
return -1;
}
return 0;
}
int getifaddrs(struct ifaddrs** result) {
int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
return -1;
}
netlinkrequest ifaddr_request;
memset(&ifaddr_request, 0, sizeof(ifaddr_request));
ifaddr_request.header.nlmsg_flags = NLM_F_ROOT | NLM_F_REQUEST;
ifaddr_request.header.nlmsg_type = RTM_GETADDR;
ifaddr_request.header.nlmsg_len = NLMSG_LENGTH(sizeof(ifaddrmsg));
ssize_t count = send(fd, &ifaddr_request, ifaddr_request.header.nlmsg_len, 0);
if (static_cast<size_t>(count) != ifaddr_request.header.nlmsg_len) {
close(fd);
return -1;
}
struct ifaddrs* start = NULL;
struct ifaddrs* current = NULL;
char buf[kMaxReadSize];
ssize_t amount_read = recv(fd, &buf, kMaxReadSize, 0);
while (amount_read > 0) {
nlmsghdr* header = reinterpret_cast<nlmsghdr*>(&buf[0]);
size_t header_size = static_cast<size_t>(amount_read);
for ( ; NLMSG_OK(header, header_size);
header = NLMSG_NEXT(header, header_size)) {
switch (header->nlmsg_type) {
case NLMSG_DONE:
// Success. Return.
*result = start;
close(fd);
return 0;
case NLMSG_ERROR:
close(fd);
freeifaddrs(start);
return -1;
case RTM_NEWADDR: {
ifaddrmsg* address_msg =
reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(header));
rtattr* rta = IFA_RTA(address_msg);
ssize_t payload_len = IFA_PAYLOAD(header);
while (RTA_OK(rta, payload_len)) {
if (rta->rta_type == IFA_ADDRESS) {
int family = address_msg->ifa_family;
if (family == AF_INET || family == AF_INET6) {
ifaddrs* newest = new ifaddrs;
memset(newest, 0, sizeof(ifaddrs));
if (current) {
current->ifa_next = newest;
} else {
start = newest;
}
if (populate_ifaddrs(newest, address_msg, RTA_DATA(rta),
RTA_PAYLOAD(rta)) != 0) {
freeifaddrs(start);
*result = NULL;
return -1;
}
current = newest;
}
}
rta = RTA_NEXT(rta, payload_len);
}
break;
}
}
}
amount_read = recv(fd, &buf, kMaxReadSize, 0);
}
close(fd);
freeifaddrs(start);
return -1;
}
void freeifaddrs(struct ifaddrs* addrs) {
struct ifaddrs* last = NULL;
struct ifaddrs* cursor = addrs;
while (cursor) {
delete[] cursor->ifa_name;
delete cursor->ifa_addr;
delete cursor->ifa_netmask;
last = cursor;
cursor = cursor->ifa_next;
delete last;
}
}
} // namespace rtc
#endif // defined(WEBRTC_ANDROID)
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "SqBiTree.h"
Status visit(TElemType e){
printf("%c ",e);
return OK;
}
int main(){
SqBiTree bt;
InitBiTree(bt);
CreateBiTree(bt);
PreOrderTraverse(bt,visit);
InOrderTraverse(bt,visit);
PostOrderTraverse(bt,visit);
LevelOrderTraverse(bt,visit);
PrintTree(bt);
system("pause");
return 0;
}
<commit_msg>Update Main.cpp<commit_after>#include <stdio.h>
#include "SqBiTree.h"
Status visit(TElemType e){
printf("%c ",e);
return OK;
}
int main(){
SqBiTree bt;
InitBiTree(bt);
CreateBiTree(bt);
PreOrderTraverse(bt,visit);
InOrderTraverse(bt,visit);
PostOrderTraverse(bt,visit);
LevelOrderTraverse(bt,visit);
PrintTree(bt);
system("pause");
return 0;
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief RX DSP サンプル @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
SCI1 を使用する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
SCI9 を使用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX66T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX72N: (Renesas Envision kit RX72N) @n
16MHz のベースクロックを使用する @n
P40 ピンにLEDを接続する @n
SCI2 を使用する @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_mgr.hpp"
#include "common/command.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
namespace {
#if defined(SIG_RX71M)
static const char* system_str_ = { "RX71M" };
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX64M)
static const char* system_str_ = { "RX64M" };
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX65N)
static const char* system_str_ = { "RX65N" };
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
#elif defined(SIG_RX24T)
static const char* system_str_ = { "RX24T" };
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX66T)
static const char* system_str_ = { "RX66T" };
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX72N)
static const char* system_str_ = { "RX72N" };
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
#elif defined(SIG_RX72T)
static const char* system_str_ = { "RX72T" };
typedef device::PORT<device::PORT0, device::bitpos::B1> LED;
typedef device::SCI1 SCI_CH;
#endif
// クロックの定義は、「RXxxx/clock_profile.hpp」を参照。
typedef device::system_io<> SYSTEM_IO;
// 内蔵高速発信器
// typedef device::system_io<device::system_base::OSC_TYPE::HOCO> SYSTEM_IO;
typedef utils::fixed_fifo<char, 512> RXB; // RX (受信) バッファの定義
typedef utils::fixed_fifo<char, 256> TXB; // TX (送信) バッファの定義
typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
// typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::ORDER::SECOND> SCI;
SCI sci_;
typedef device::cmt_mgr<device::CMT0> CMT;
CMT cmt_;
const uint32_t PARAM_SIZE = 1024;
int32_t parama_[PARAM_SIZE];
int32_t paramb_[PARAM_SIZE];
int32_t dsp_opr_(uint32_t loop)
{
#ifdef __RXV3__
__mvtacgu_a0(0);
#endif
__mvtachi_a0(0);
__mvtaclo_a0(0);
for(uint32_t i = 0; i < loop; ++i) {
auto a = parama_[i % PARAM_SIZE];
auto b = paramb_[i % PARAM_SIZE];
__emaca_a0(a, b);
}
return __mvfaclo_s0_a0();
}
int32_t cpu_opr_(uint32_t loop)
{
int32_t sum = 0;
for(uint32_t i = 0; i < loop; ++i) {
auto a = parama_[i % PARAM_SIZE];
auto b = paramb_[i % PARAM_SIZE];
sum += a * b;
}
return sum;
}
}
extern "C" {
// syscalls.c から呼ばれる、標準出力(stdout, stderr)
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
// syscalls.c から呼ばれる、標準入力(stdin)
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::boost_master_clock();
{ // タイマー設定(1000Hz)
uint8_t intr = 4;
cmt_.start(1000, intr);
}
{ // SCI の開始
uint8_t intr = 2; // 割り込みレベル(0を指定すると、ポーリング動作になる)
uint32_t baud = 115200; // ボーレート(任意の整数値を指定可能)
sci_.start(baud, intr); // 標準では、8ビット、1ストップビットを選択
}
auto clk = device::clock_profile::ICLK / 1'000'000;
utils::format("Start DSP sample for '%s' %d[MHz]\n") % system_str_ % clk;
LED::DIR = 1;
LED::P = 0;
{
utils::format("SCI PCLK: %u\n") % SCI_CH::PCLK;
utils::format("SCI Baud rate (set): %u\n") % sci_.get_baud_rate();
float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true);
rate *= 100.0f;
utils::format("SCI Baud rate (real): %u (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate;
utils::format("CMT rate (set): %d [Hz]\n") % cmt_.get_rate();
rate = 1.0f - static_cast<float>(cmt_.get_rate()) / cmt_.get_rate(true);
rate *= 100.0f;
utils::format("CMT rate (real): %d [Hz] (%3.2f [%%])\n") % cmt_.get_rate(true) % rate;
}
cmt_.sync();
for(uint32_t i = 0; i < PARAM_SIZE; ++i) {
parama_[i] = rand() & 0x8fffffff;
paramb_[i] = rand() & 0x8fffffff;
}
uint32_t loop = 50000000;
{
auto st = cmt_.get_counter();
auto a = dsp_opr_(loop);
auto et = cmt_.get_counter();
utils::format("DSP %d loops: ans = %d, (%u [ms])\n") % loop % a % (et - st);
}
{
auto st = cmt_.get_counter();
auto a = cpu_opr_(loop);
auto et = cmt_.get_counter();
utils::format("CPU %d loops: ans = %d, (%u [ms])\n") % loop % a % (et - st);
}
uint16_t cnt = 0;
while(1) {
cmt_.sync();
++cnt;
if(cnt >= (50 * 10)) {
cnt = 0;
}
if(cnt < (25 * 10)) {
LED::P = 0;
} else {
LED::P = 1;
}
}
}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*! @file
@brief RX DSP サンプル @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
SCI1 を使用する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
SCI9 を使用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX66T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX72N: (Renesas Envision kit RX72N) @n
16MHz のベースクロックを使用する @n
P40 ピンにLEDを接続する @n
SCI2 を使用する @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_mgr.hpp"
#include "common/command.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
namespace {
#if defined(SIG_RX71M)
static const char* system_str_ = { "RX71M" };
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX64M)
static const char* system_str_ = { "RX64M" };
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX65N)
static const char* system_str_ = { "RX65N" };
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
#elif defined(SIG_RX24T)
static const char* system_str_ = { "RX24T" };
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX66T)
static const char* system_str_ = { "RX66T" };
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
#elif defined(SIG_RX72N)
static const char* system_str_ = { "RX72N" };
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
#elif defined(SIG_RX72T)
static const char* system_str_ = { "RX72T" };
typedef device::PORT<device::PORT0, device::bitpos::B1> LED;
typedef device::SCI1 SCI_CH;
#endif
// クロックの定義は、「RXxxx/clock_profile.hpp」を参照。
typedef device::system_io<> SYSTEM_IO;
typedef utils::fixed_fifo<char, 512> RXB; // RX (受信) バッファの定義
typedef utils::fixed_fifo<char, 256> TXB; // TX (送信) バッファの定義
typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
// typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::ORDER::SECOND> SCI;
SCI sci_;
typedef device::cmt_mgr<device::CMT0> CMT;
CMT cmt_;
const uint32_t PARAM_SIZE = 1024;
int32_t parama_[PARAM_SIZE];
int32_t paramb_[PARAM_SIZE];
int32_t dsp_opr_(uint32_t loop)
{
#ifdef __RXV3__
__mvtacgu_a0(0);
#endif
__mvtachi_a0(0);
__mvtaclo_a0(0);
for(uint32_t i = 0; i < loop; ++i) {
auto a = parama_[i % PARAM_SIZE];
auto b = paramb_[i % PARAM_SIZE];
__emaca_a0(a, b);
}
return __mvfaclo_s0_a0();
}
int32_t cpu_opr_(uint32_t loop)
{
int32_t sum = 0;
for(uint32_t i = 0; i < loop; ++i) {
auto a = parama_[i % PARAM_SIZE];
auto b = paramb_[i % PARAM_SIZE];
sum += a * b;
}
return sum;
}
}
extern "C" {
// syscalls.c から呼ばれる、標準出力(stdout, stderr)
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
// syscalls.c から呼ばれる、標準入力(stdin)
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::boost_master_clock();
{ // タイマー設定(1000Hz)
uint8_t intr = 4;
cmt_.start(1000, intr);
}
{ // SCI の開始
uint8_t intr = 2; // 割り込みレベル(0を指定すると、ポーリング動作になる)
uint32_t baud = 115200; // ボーレート(任意の整数値を指定可能)
sci_.start(baud, intr); // 標準では、8ビット、1ストップビットを選択
}
auto clk = device::clock_profile::ICLK / 1'000'000;
utils::format("Start DSP sample for '%s' %d[MHz]\n") % system_str_ % clk;
LED::DIR = 1;
LED::P = 0;
{
utils::format("SCI PCLK: %u\n") % SCI_CH::PCLK;
utils::format("SCI Baud rate (set): %u\n") % sci_.get_baud_rate();
float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true);
rate *= 100.0f;
utils::format("SCI Baud rate (real): %u (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate;
utils::format("CMT rate (set): %d [Hz]\n") % cmt_.get_rate();
rate = 1.0f - static_cast<float>(cmt_.get_rate()) / cmt_.get_rate(true);
rate *= 100.0f;
utils::format("CMT rate (real): %d [Hz] (%3.2f [%%])\n") % cmt_.get_rate(true) % rate;
}
cmt_.sync();
for(uint32_t i = 0; i < PARAM_SIZE; ++i) {
parama_[i] = rand() & 0x8fffffff;
paramb_[i] = rand() & 0x8fffffff;
}
uint32_t loop = 50000000;
{
auto st = cmt_.get_counter();
auto a = dsp_opr_(loop);
auto et = cmt_.get_counter();
utils::format("DSP %d loops: ans = %d, (%u [ms])\n") % loop % a % (et - st);
}
{
auto st = cmt_.get_counter();
auto a = cpu_opr_(loop);
auto et = cmt_.get_counter();
utils::format("CPU %d loops: ans = %d, (%u [ms])\n") % loop % a % (et - st);
}
uint16_t cnt = 0;
while(1) {
cmt_.sync();
++cnt;
if(cnt >= (50 * 10)) {
cnt = 0;
}
if(cnt < (25 * 10)) {
LED::P = 0;
} else {
LED::P = 1;
}
}
}
<|endoftext|> |
<commit_before>#include "wled.h"
/*
* Physical IO
*/
#define WLED_DEBOUNCE_THRESHOLD 50 //only consider button input of at least 50ms as valid (debouncing)
void shortPressAction(uint8_t b)
{
if (!macroButton[b])
{
toggleOnOff();
colorUpdated(NOTIFIER_CALL_MODE_BUTTON);
} else {
applyPreset(macroButton[b]);
}
}
bool isButtonPressed(uint8_t i)
{
if (btnPin[i]<0) return false;
switch (buttonType[i]) {
case BTN_TYPE_NONE:
case BTN_TYPE_RESERVED:
break;
case BTN_TYPE_PUSH:
case BTN_TYPE_SWITCH:
if (digitalRead(btnPin[i]) == LOW) return true;
break;
case BTN_TYPE_PUSH_ACT_HIGH:
case BTN_TYPE_SWITCH_ACT_HIGH:
if (digitalRead(btnPin[i]) == HIGH) return true;
break;
case BTN_TYPE_TOUCH:
#ifdef ARDUINO_ARCH_ESP32
if (touchRead(btnPin[i]) <= touchThreshold) return true;
#endif
break;
}
return false;
}
void handleSwitch(uint8_t b)
{
if (buttonPressedBefore[b] != isButtonPressed(b)) {
buttonPressedTime[b] = millis();
buttonPressedBefore[b] = !buttonPressedBefore[b];
}
if (buttonLongPressed[b] == buttonPressedBefore[b]) return;
if (millis() - buttonPressedTime[b] > WLED_DEBOUNCE_THRESHOLD) { //fire edge event only after 50ms without change (debounce)
if (buttonPressedBefore[b]) { //LOW, falling edge, switch closed
if (macroButton[b]) applyPreset(macroButton[b]);
else { //turn on
if (!bri) {toggleOnOff(); colorUpdated(NOTIFIER_CALL_MODE_BUTTON);}
}
} else { //HIGH, rising edge, switch opened
if (macroLongPress[b]) applyPreset(macroLongPress[b]);
else { //turn off
if (bri) {toggleOnOff(); colorUpdated(NOTIFIER_CALL_MODE_BUTTON);}
}
}
buttonLongPressed[b] = buttonPressedBefore[b]; //save the last "long term" switch state
}
}
void handleAnalog(uint8_t b)
{
static uint8_t oldRead[WLED_MAX_BUTTONS];
#ifdef ESP8266
uint8_t aRead = analogRead(A0) >> 2; // convert 10bit read to 8bit
#else
uint8_t aRead = analogRead(btnPin[b]) >> 4; // convert 12bit read to 8bit
#endif
if (oldRead[b] == aRead) return; // no change in reading
// if no macro for "short press" and "long press" is defined use brightness control
if (!macroButton[b] && !macroLongPress[b]) {
// if "double press" macro is 250 or greater use global brightness
if (macroDoublePress[b]>=250) {
// if change in analog read was detected change global brightness
bri = aRead;
} else {
// otherwise use "double press" for segment selection
//uint8_t mainSeg = strip.getMainSegmentId();
WS2812FX::Segment& seg = strip.getSegment(macroDoublePress[b]);
if (aRead == 0) {
seg.setOption(SEG_OPTION_ON, 0, macroDoublePress[b]); // off
} else {
seg.setOpacity(aRead, macroDoublePress[b]);
seg.setOption(SEG_OPTION_ON, 1, macroDoublePress[b]);
}
}
} else {
//TODO:
// we can either trigger a preset depending on the level (between short and long entries)
// or use it for RGBW direct control
}
colorUpdated(NOTIFIER_CALL_MODE_DIRECT_CHANGE);
}
void handleButton()
{
for (uint8_t b=0; b<WLED_MAX_BUTTONS; b++) {
if (btnPin[b]<0 || !(buttonType[b] > BTN_TYPE_NONE)) continue;
if (buttonType[b] == BTN_TYPE_ANALOG) { // button is not a button but a potentiometer
handleAnalog(b); continue;
}
if (buttonType[b] == BTN_TYPE_SWITCH || buttonType[b] == BTN_TYPE_SWITCH_ACT_HIGH) { //button is not momentary, but switch. This is only suitable on pins whose on-boot state does not matter (NOT gpio0)
handleSwitch(b); continue;
}
//momentary button logic
if (isButtonPressed(b)) //pressed
{
if (!buttonPressedBefore[b]) buttonPressedTime[b] = millis();
buttonPressedBefore[b] = true;
if (millis() - buttonPressedTime[b] > 600) //long press
{
if (!buttonLongPressed[b])
{
if (macroLongPress[b]) {applyPreset(macroLongPress[b]);}
else _setRandomColor(false,true);
buttonLongPressed[b] = true;
}
}
}
else if (!isButtonPressed(b) && buttonPressedBefore[b]) //released
{
long dur = millis() - buttonPressedTime[b];
if (dur < WLED_DEBOUNCE_THRESHOLD) {buttonPressedBefore[b] = false; continue;} //too short "press", debounce
bool doublePress = buttonWaitTime[b];
buttonWaitTime[b] = 0;
if (dur > 6000 && b==0) //long press on button 0
{
WLED::instance().initAP(true);
}
else if (!buttonLongPressed[b]) { //short press
if (macroDoublePress[b])
{
if (doublePress) applyPreset(macroDoublePress[b]);
else buttonWaitTime[b] = millis();
} else shortPressAction(b);
}
buttonPressedBefore[b] = false;
buttonLongPressed[b] = false;
}
if (buttonWaitTime[b] && millis() - buttonWaitTime[b] > 450 && !buttonPressedBefore[b])
{
buttonWaitTime[b] = 0;
shortPressAction(b);
}
}
}
void handleIO()
{
handleButton();
//set relay when LEDs turn on
if (strip.getBrightness())
{
lastOnTime = millis();
if (offMode)
{
if (rlyPin>=0) {
pinMode(rlyPin, OUTPUT);
digitalWrite(rlyPin, rlyMde);
}
offMode = false;
}
} else if (millis() - lastOnTime > 600)
{
if (!offMode) {
#ifdef ESP8266
// turn off built-in LED if strip is turned off
// this will break digital bus so will need to be reinitialised on On
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
#endif
if (rlyPin>=0) {
pinMode(rlyPin, OUTPUT);
digitalWrite(rlyPin, !rlyMde);
}
}
offMode = true;
}
}
<commit_msg>Fixes for analog.<commit_after>#include "wled.h"
/*
* Physical IO
*/
#define WLED_DEBOUNCE_THRESHOLD 50 //only consider button input of at least 50ms as valid (debouncing)
void shortPressAction(uint8_t b)
{
if (!macroButton[b])
{
toggleOnOff();
colorUpdated(NOTIFIER_CALL_MODE_BUTTON);
} else {
applyPreset(macroButton[b]);
}
}
bool isButtonPressed(uint8_t i)
{
if (btnPin[i]<0) return false;
switch (buttonType[i]) {
case BTN_TYPE_NONE:
case BTN_TYPE_RESERVED:
break;
case BTN_TYPE_PUSH:
case BTN_TYPE_SWITCH:
if (digitalRead(btnPin[i]) == LOW) return true;
break;
case BTN_TYPE_PUSH_ACT_HIGH:
case BTN_TYPE_SWITCH_ACT_HIGH:
if (digitalRead(btnPin[i]) == HIGH) return true;
break;
case BTN_TYPE_TOUCH:
#ifdef ARDUINO_ARCH_ESP32
if (touchRead(btnPin[i]) <= touchThreshold) return true;
#endif
break;
}
return false;
}
void handleSwitch(uint8_t b)
{
if (buttonPressedBefore[b] != isButtonPressed(b)) {
buttonPressedTime[b] = millis();
buttonPressedBefore[b] = !buttonPressedBefore[b];
}
if (buttonLongPressed[b] == buttonPressedBefore[b]) return;
if (millis() - buttonPressedTime[b] > WLED_DEBOUNCE_THRESHOLD) { //fire edge event only after 50ms without change (debounce)
if (buttonPressedBefore[b]) { //LOW, falling edge, switch closed
if (macroButton[b]) applyPreset(macroButton[b]);
else { //turn on
if (!bri) {toggleOnOff(); colorUpdated(NOTIFIER_CALL_MODE_BUTTON);}
}
} else { //HIGH, rising edge, switch opened
if (macroLongPress[b]) applyPreset(macroLongPress[b]);
else { //turn off
if (bri) {toggleOnOff(); colorUpdated(NOTIFIER_CALL_MODE_BUTTON);}
}
}
buttonLongPressed[b] = buttonPressedBefore[b]; //save the last "long term" switch state
}
}
void handleAnalog(uint8_t b)
{
static uint8_t oldRead[WLED_MAX_BUTTONS];
#ifdef ESP8266
uint16_t aRead = analogRead(A0) >> 5; // convert 10bit read to 5bit (remove noise)
#else
uint16_t aRead = analogRead(btnPin[b]) >> 7; // convert 12bit read to 5bit (remove noise)
#endif
if (oldRead[b] == aRead) return; // no change in reading
oldRead[b] = aRead;
// if no macro for "short press" and "long press" is defined use brightness control
if (!macroButton[b] && !macroLongPress[b]) {
// if "double press" macro is 250 or greater use global brightness
if (macroDoublePress[b] >= 250) {
// if change in analog read was detected change global brightness
if (aRead == 0) {
briLast = bri;
bri = 0;
} else{
bri = aRead << 3;
}
} else {
// otherwise use "double press" for segment selection
//uint8_t mainSeg = strip.getMainSegmentId();
WS2812FX::Segment& seg = strip.getSegment(macroDoublePress[b]);
if (aRead == 0) {
seg.setOption(SEG_OPTION_ON, 0); // off
} else {
seg.setOpacity(aRead << 3, macroDoublePress[b]);
seg.setOption(SEG_OPTION_ON, 1);
}
// this will notify clients of update (websockets,mqtt,etc)
//call for notifier -> 0: init 1: direct change 2: button 3: notification 4: nightlight 5: other (No notification)
// 6: fx changed 7: hue 8: preset cycle 9: blynk 10: alexa
updateInterfaces(NOTIFIER_CALL_MODE_BUTTON);
}
} else {
//TODO:
// we can either trigger a preset depending on the level (between short and long entries)
// or use it for RGBW direct control
}
//call for notifier -> 0: init 1: direct change 2: button 3: notification 4: nightlight 5: other (No notification)
// 6: fx changed 7: hue 8: preset cycle 9: blynk 10: alexa
colorUpdated(NOTIFIER_CALL_MODE_BUTTON);
}
void handleButton()
{
static unsigned long lastRead = 0UL;
for (uint8_t b=0; b<WLED_MAX_BUTTONS; b++) {
if (btnPin[b]<0 || buttonType[b] == BTN_TYPE_NONE) continue;
if (buttonType[b] == BTN_TYPE_ANALOG && millis() - lastRead > 250) { // button is not a button but a potentiometer
if (b+1 == WLED_MAX_BUTTONS) lastRead = millis();
handleAnalog(b); continue;
}
if (buttonType[b] == BTN_TYPE_SWITCH || buttonType[b] == BTN_TYPE_SWITCH_ACT_HIGH) { //button is not momentary, but switch. This is only suitable on pins whose on-boot state does not matter (NOT gpio0)
handleSwitch(b); continue;
}
//momentary button logic
if (isButtonPressed(b)) //pressed
{
if (!buttonPressedBefore[b]) buttonPressedTime[b] = millis();
buttonPressedBefore[b] = true;
if (millis() - buttonPressedTime[b] > 600) //long press
{
if (!buttonLongPressed[b])
{
if (macroLongPress[b]) {applyPreset(macroLongPress[b]);}
else _setRandomColor(false,true);
buttonLongPressed[b] = true;
}
}
}
else if (!isButtonPressed(b) && buttonPressedBefore[b]) //released
{
long dur = millis() - buttonPressedTime[b];
if (dur < WLED_DEBOUNCE_THRESHOLD) {buttonPressedBefore[b] = false; continue;} //too short "press", debounce
bool doublePress = buttonWaitTime[b];
buttonWaitTime[b] = 0;
if (dur > 6000 && b==0) //long press on button 0
{
WLED::instance().initAP(true);
}
else if (!buttonLongPressed[b]) { //short press
if (macroDoublePress[b])
{
if (doublePress) applyPreset(macroDoublePress[b]);
else buttonWaitTime[b] = millis();
} else shortPressAction(b);
}
buttonPressedBefore[b] = false;
buttonLongPressed[b] = false;
}
if (buttonWaitTime[b] && millis() - buttonWaitTime[b] > 450 && !buttonPressedBefore[b])
{
buttonWaitTime[b] = 0;
shortPressAction(b);
}
}
}
void handleIO()
{
handleButton();
//set relay when LEDs turn on
if (strip.getBrightness())
{
lastOnTime = millis();
if (offMode)
{
if (rlyPin>=0) {
pinMode(rlyPin, OUTPUT);
digitalWrite(rlyPin, rlyMde);
}
offMode = false;
}
} else if (millis() - lastOnTime > 600)
{
if (!offMode) {
#ifdef ESP8266
// turn off built-in LED if strip is turned off
// this will break digital bus so will need to be reinitialised on On
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
#endif
if (rlyPin>=0) {
pinMode(rlyPin, OUTPUT);
digitalWrite(rlyPin, !rlyMde);
}
}
offMode = true;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSTLReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSTLReader.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkFloatArray.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include <ctype.h>
vtkCxxRevisionMacro(vtkSTLReader, "1.67");
vtkStandardNewMacro(vtkSTLReader);
#define VTK_ASCII 0
#define VTK_BINARY 1
// Construct object with merging set to true.
vtkSTLReader::vtkSTLReader()
{
this->FileName = NULL;
this->Merging = 1;
this->ScalarTags = 0;
this->Locator = NULL;
}
vtkSTLReader::~vtkSTLReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Overload standard modified time function. If locator is modified,
// then this object is modified as well.
unsigned long vtkSTLReader::GetMTime()
{
unsigned long mTime1=this->vtkPolyDataSource::GetMTime();
unsigned long mTime2;
if (this->Locator)
{
mTime2 = this->Locator->GetMTime();
mTime1 = ( mTime1 > mTime2 ? mTime1 : mTime2 );
}
return mTime1;
}
void vtkSTLReader::Execute()
{
FILE *fp;
vtkPoints *newPts, *mergedPts;
vtkCellArray *newPolys, *mergedPolys;
vtkFloatArray *newScalars=0, *mergedScalars=0;
vtkPolyData *output = this->GetOutput();
// All of the data in the first piece.
if (output->GetUpdatePiece() > 0)
{
return;
}
if (!this->FileName)
{
vtkErrorMacro(<<"A FileName must be specified.");
return;
}
// Initialize
//
if ((fp = fopen(this->FileName, "r")) == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
return;
}
newPts = vtkPoints::New();
newPts->Allocate(5000,10000);
newPolys = vtkCellArray::New();
newPolys->Allocate(10000,20000);
// Depending upon file type, read differently
//
if ( this->GetSTLFileType(fp) == VTK_ASCII )
{
if (ScalarTags)
{
newScalars = vtkFloatArray::New();
newScalars->Allocate(5000,10000);
}
if ( this->ReadASCIISTL(fp,newPts,newPolys,newScalars) )
{
return;
}
}
else
{
fclose(fp);
fp = fopen(this->FileName, "rb");
if ( this->ReadBinarySTL(fp,newPts,newPolys) )
{
return;
}
}
vtkDebugMacro(<< "Read: "
<< newPts->GetNumberOfPoints() << " points, "
<< newPolys->GetNumberOfCells() << " triangles");
fclose(fp);
//
// If merging is on, create hash table and merge points/triangles.
//
// if (0)
if ( this->Merging )
{
int i;
vtkIdType *pts = 0;
vtkIdType nodes[3];
vtkIdType npts = 0;
float *x;
int nextCell=0;
mergedPts = vtkPoints::New();
mergedPts->Allocate(newPts->GetNumberOfPoints()/2);
mergedPolys = vtkCellArray::New();
mergedPolys->Allocate(newPolys->GetSize());
if (newScalars)
{
mergedScalars = vtkFloatArray::New();
mergedScalars->Allocate(newPolys->GetSize());
}
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (mergedPts, newPts->GetBounds());
for (newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts); )
{
for (i=0; i < 3; i++)
{
x = newPts->GetPoint(pts[i]);
this->Locator->InsertUniquePoint(x, nodes[i]);
}
if ( nodes[0] != nodes[1] &&
nodes[0] != nodes[2] &&
nodes[1] != nodes[2] )
{
mergedPolys->InsertNextCell(3,nodes);
if (newScalars)
{
mergedScalars->InsertNextValue(newScalars->GetValue(nextCell));
}
}
nextCell++;
}
newPts->Delete();
newPolys->Delete();
if (newScalars)
{
newScalars->Delete();
}
vtkDebugMacro(<< "Merged to: "
<< mergedPts->GetNumberOfPoints() << " points, "
<< mergedPolys->GetNumberOfCells() << " triangles");
}
else
{
mergedPts = newPts;
mergedPolys = newPolys;
mergedScalars = newScalars;
}
//
// Update ourselves
//
output->SetPoints(mergedPts);
mergedPts->Delete();
output->SetPolys(mergedPolys);
mergedPolys->Delete();
if (mergedScalars)
{
output->GetCellData()->SetScalars(mergedScalars);
mergedScalars->Delete();
}
if (this->Locator)
{
this->Locator->Initialize(); //free storage
}
output->Squeeze();
}
int vtkSTLReader::ReadBinarySTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys)
{
int i, numTris;
vtkIdType pts[3];
unsigned long ulint;
unsigned short ibuff2;
char header[81];
typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t;
facet_t facet;
vtkDebugMacro(<< " Reading BINARY STL file");
// File is read to obtain raw information as well as bounding box
//
fread (header, 1, 80, fp);
fread (&ulint, 1, 4, fp);
vtkByteSwap::Swap4LE(&ulint);
// Many .stl files contain bogus count. Hence we will ignore and read
// until end of file.
//
if ( (numTris = (int) ulint) <= 0 )
{
vtkDebugMacro(<< "Bad binary count: attempting to correct ("
<< numTris << ")");
}
for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
{
fread(&ibuff2,2,1,fp); //read extra junk
vtkByteSwap::Swap4LE (facet.n);
vtkByteSwap::Swap4LE (facet.n+1);
vtkByteSwap::Swap4LE (facet.n+2);
vtkByteSwap::Swap4LE (facet.v1);
vtkByteSwap::Swap4LE (facet.v1+1);
vtkByteSwap::Swap4LE (facet.v1+2);
pts[0] = newPts->InsertNextPoint(facet.v1);
vtkByteSwap::Swap4LE (facet.v2);
vtkByteSwap::Swap4LE (facet.v2+1);
vtkByteSwap::Swap4LE (facet.v2+2);
pts[1] = newPts->InsertNextPoint(facet.v2);
vtkByteSwap::Swap4LE (facet.v3);
vtkByteSwap::Swap4LE (facet.v3+1);
vtkByteSwap::Swap4LE (facet.v3+2);
pts[2] = newPts->InsertNextPoint(facet.v3);
newPolys->InsertNextCell(3,pts);
if ( (i % 5000) == 0 && i != 0 )
{
vtkDebugMacro(<< "triangle# " << i);
this->UpdateProgress((i%50000)/50000.0);
}
}
return 0;
}
int vtkSTLReader::ReadASCIISTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys, vtkFloatArray *scalars)
{
char line[256];
float x[3];
vtkIdType pts[3];
int done;
int currentSolid = 0;
vtkDebugMacro(<< " Reading ASCII STL file");
// Ingest header and junk to get to first vertex
//
fgets (line, 255, fp);
done = (fscanf(fp,"%s %*s %f %f %f\n", line, x, x+1, x+2)==EOF);
// Go into loop, reading facet normal and vertices
//
// while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
while (!done)
{
//if (ctr>=253840) {
// fprintf(stdout, "Reading record %d\n", ctr);
//}
//ctr += 7;
fgets (line, 255, fp);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[0] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[1] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[2] = newPts->InsertNextPoint(x);
fgets (line, 255, fp); // end loop
fgets (line, 255, fp); // end facet
newPolys->InsertNextCell(3,pts);
if (scalars)
{
scalars->InsertNextValue(currentSolid);
}
if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
{
vtkDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
this->UpdateProgress((newPolys->GetNumberOfCells()%50000)/50000.0);
}
done = (fscanf(fp,"%s", line)==EOF);
if (strcmp(line, "ENDSOLID") == 0)
{
currentSolid++;
fgets(line, 255, fp);
done = feof(fp);
while (strncmp(line, "SOLID", 5) && !done)
{
fgets(line, 255, fp);
done = feof(fp);
}
done = (fscanf(fp,"%s", line)==EOF);
}
if (!done) {
done = (fscanf(fp,"%*s %f %f %f\n", x, x+1, x+2)==EOF);
}
}
//fprintf(stdout, "Maximum ctr val %d\n", ctr);
return 0;
}
int vtkSTLReader::GetSTLFileType(FILE *fp)
{
unsigned char header[256];
int type, i;
int numChars;
// Read a little from the file to figure what type it is.
//
// skip 255 characters so we are past any first line comment */
numChars = static_cast<int>(fread ((unsigned char *)header, 1, 255, fp));
for (i = 0, type=VTK_ASCII; i< numChars && type == VTK_ASCII; i++) // don't test \0
{
if (header[i] > 127)
{
type = VTK_BINARY;
}
}
// Reset file for reading
//
rewind (fp);
return type;
}
// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkSTLReader::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkSTLReader::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
this->Locator->Register(this);
this->Locator->Delete();
}
}
void vtkSTLReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
os << indent << "Merging: " << (this->Merging ? "On\n" : "Off\n");
os << indent << "ScalarTags: " << (this->ScalarTags ? "On\n" : "Off\n");
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<commit_msg>ENH: Handle multiple objects in file.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSTLReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSTLReader.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkFloatArray.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include <ctype.h>
vtkCxxRevisionMacro(vtkSTLReader, "1.68");
vtkStandardNewMacro(vtkSTLReader);
#define VTK_ASCII 0
#define VTK_BINARY 1
// Construct object with merging set to true.
vtkSTLReader::vtkSTLReader()
{
this->FileName = NULL;
this->Merging = 1;
this->ScalarTags = 0;
this->Locator = NULL;
}
vtkSTLReader::~vtkSTLReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Overload standard modified time function. If locator is modified,
// then this object is modified as well.
unsigned long vtkSTLReader::GetMTime()
{
unsigned long mTime1=this->vtkPolyDataSource::GetMTime();
unsigned long mTime2;
if (this->Locator)
{
mTime2 = this->Locator->GetMTime();
mTime1 = ( mTime1 > mTime2 ? mTime1 : mTime2 );
}
return mTime1;
}
void vtkSTLReader::Execute()
{
FILE *fp;
vtkPoints *newPts, *mergedPts;
vtkCellArray *newPolys, *mergedPolys;
vtkFloatArray *newScalars=0, *mergedScalars=0;
vtkPolyData *output = this->GetOutput();
// All of the data in the first piece.
if (output->GetUpdatePiece() > 0)
{
return;
}
if (!this->FileName)
{
vtkErrorMacro(<<"A FileName must be specified.");
return;
}
// Initialize
//
if ((fp = fopen(this->FileName, "r")) == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
return;
}
newPts = vtkPoints::New();
newPts->Allocate(5000,10000);
newPolys = vtkCellArray::New();
newPolys->Allocate(10000,20000);
// Depending upon file type, read differently
//
if ( this->GetSTLFileType(fp) == VTK_ASCII )
{
if (ScalarTags)
{
newScalars = vtkFloatArray::New();
newScalars->Allocate(5000,10000);
}
if ( this->ReadASCIISTL(fp,newPts,newPolys,newScalars) )
{
return;
}
}
else
{
fclose(fp);
fp = fopen(this->FileName, "rb");
if ( this->ReadBinarySTL(fp,newPts,newPolys) )
{
return;
}
}
vtkDebugMacro(<< "Read: "
<< newPts->GetNumberOfPoints() << " points, "
<< newPolys->GetNumberOfCells() << " triangles");
fclose(fp);
//
// If merging is on, create hash table and merge points/triangles.
//
// if (0)
if ( this->Merging )
{
int i;
vtkIdType *pts = 0;
vtkIdType nodes[3];
vtkIdType npts = 0;
float *x;
int nextCell=0;
mergedPts = vtkPoints::New();
mergedPts->Allocate(newPts->GetNumberOfPoints()/2);
mergedPolys = vtkCellArray::New();
mergedPolys->Allocate(newPolys->GetSize());
if (newScalars)
{
mergedScalars = vtkFloatArray::New();
mergedScalars->Allocate(newPolys->GetSize());
}
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (mergedPts, newPts->GetBounds());
for (newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts); )
{
for (i=0; i < 3; i++)
{
x = newPts->GetPoint(pts[i]);
this->Locator->InsertUniquePoint(x, nodes[i]);
}
if ( nodes[0] != nodes[1] &&
nodes[0] != nodes[2] &&
nodes[1] != nodes[2] )
{
mergedPolys->InsertNextCell(3,nodes);
if (newScalars)
{
mergedScalars->InsertNextValue(newScalars->GetValue(nextCell));
}
}
nextCell++;
}
newPts->Delete();
newPolys->Delete();
if (newScalars)
{
newScalars->Delete();
}
vtkDebugMacro(<< "Merged to: "
<< mergedPts->GetNumberOfPoints() << " points, "
<< mergedPolys->GetNumberOfCells() << " triangles");
}
else
{
mergedPts = newPts;
mergedPolys = newPolys;
mergedScalars = newScalars;
}
//
// Update ourselves
//
output->SetPoints(mergedPts);
mergedPts->Delete();
output->SetPolys(mergedPolys);
mergedPolys->Delete();
if (mergedScalars)
{
output->GetCellData()->SetScalars(mergedScalars);
mergedScalars->Delete();
}
if (this->Locator)
{
this->Locator->Initialize(); //free storage
}
output->Squeeze();
}
int vtkSTLReader::ReadBinarySTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys)
{
int i, numTris;
vtkIdType pts[3];
unsigned long ulint;
unsigned short ibuff2;
char header[81];
typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t;
facet_t facet;
vtkDebugMacro(<< " Reading BINARY STL file");
// File is read to obtain raw information as well as bounding box
//
fread (header, 1, 80, fp);
fread (&ulint, 1, 4, fp);
vtkByteSwap::Swap4LE(&ulint);
// Many .stl files contain bogus count. Hence we will ignore and read
// until end of file.
//
if ( (numTris = (int) ulint) <= 0 )
{
vtkDebugMacro(<< "Bad binary count: attempting to correct ("
<< numTris << ")");
}
for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
{
fread(&ibuff2,2,1,fp); //read extra junk
vtkByteSwap::Swap4LE (facet.n);
vtkByteSwap::Swap4LE (facet.n+1);
vtkByteSwap::Swap4LE (facet.n+2);
vtkByteSwap::Swap4LE (facet.v1);
vtkByteSwap::Swap4LE (facet.v1+1);
vtkByteSwap::Swap4LE (facet.v1+2);
pts[0] = newPts->InsertNextPoint(facet.v1);
vtkByteSwap::Swap4LE (facet.v2);
vtkByteSwap::Swap4LE (facet.v2+1);
vtkByteSwap::Swap4LE (facet.v2+2);
pts[1] = newPts->InsertNextPoint(facet.v2);
vtkByteSwap::Swap4LE (facet.v3);
vtkByteSwap::Swap4LE (facet.v3+1);
vtkByteSwap::Swap4LE (facet.v3+2);
pts[2] = newPts->InsertNextPoint(facet.v3);
newPolys->InsertNextCell(3,pts);
if ( (i % 5000) == 0 && i != 0 )
{
vtkDebugMacro(<< "triangle# " << i);
this->UpdateProgress((i%50000)/50000.0);
}
}
return 0;
}
int vtkSTLReader::ReadASCIISTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys, vtkFloatArray *scalars)
{
char line[256];
float x[3];
vtkIdType pts[3];
int done;
int currentSolid = 0;
vtkDebugMacro(<< " Reading ASCII STL file");
// Ingest header and junk to get to first vertex
//
fgets (line, 255, fp);
done = (fscanf(fp,"%s %*s %f %f %f\n", line, x, x+1, x+2)==EOF);
// Go into loop, reading facet normal and vertices
//
// while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
while (!done)
{
//if (ctr>=253840) {
// fprintf(stdout, "Reading record %d\n", ctr);
//}
//ctr += 7;
fgets (line, 255, fp);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[0] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[1] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[2] = newPts->InsertNextPoint(x);
fgets (line, 255, fp); // end loop
fgets (line, 255, fp); // end facet
newPolys->InsertNextCell(3,pts);
if (scalars)
{
scalars->InsertNextValue(currentSolid);
}
if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
{
vtkDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
this->UpdateProgress((newPolys->GetNumberOfCells()%50000)/50000.0);
}
done = (fscanf(fp,"%s", line)==EOF);
if ((strcmp(line, "ENDSOLID") == 0) || (strcmp(line, "endsolid") == 0))
{
currentSolid++;
fgets(line, 255, fp);
done = feof(fp);
while ((strstr(line, "SOLID") == 0) && (strstr(line, "solid") == 0) && !done)
{
fgets(line, 255, fp);
done = feof(fp);
}
done = (fscanf(fp,"%s", line)==EOF);
}
if (!done) {
done = (fscanf(fp,"%*s %f %f %f\n", x, x+1, x+2)==EOF);
}
}
//fprintf(stdout, "Maximum ctr val %d\n", ctr);
return 0;
}
int vtkSTLReader::GetSTLFileType(FILE *fp)
{
unsigned char header[256];
int type, i;
int numChars;
// Read a little from the file to figure what type it is.
//
// skip 255 characters so we are past any first line comment */
numChars = static_cast<int>(fread ((unsigned char *)header, 1, 255, fp));
for (i = 0, type=VTK_ASCII; i< numChars && type == VTK_ASCII; i++) // don't test \0
{
if (header[i] > 127)
{
type = VTK_BINARY;
}
}
// Reset file for reading
//
rewind (fp);
return type;
}
// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkSTLReader::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkSTLReader::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
this->Locator->Register(this);
this->Locator->Delete();
}
}
void vtkSTLReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
os << indent << "Merging: " << (this->Merging ? "On\n" : "Off\n");
os << indent << "ScalarTags: " << (this->ScalarTags ? "On\n" : "Off\n");
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<|endoftext|> |
<commit_before>#include "Geodude.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Player.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1EntityElementsScene.h"
Geodude::Geodude()
{
}
Geodude::~Geodude()
{
}
bool Geodude::Awake(pugi::xml_node &conf, uint id, iPoint pos)
{
name = conf.attribute("name").as_string("");
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("attack").as_int(0);
speed = conf.attribute("speed").as_int(0);
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
cooldown = conf.attribute("cooldown").as_int(0);
mode_stone = conf.attribute("mode_stone").as_bool(false);
if(mode_stone)
position = iPoint(pos.x, pos.y);
else
position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));
return true;
}
bool Geodude::Start()
{
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 7;
gamestate = TIMETOPLAY;
movable = true;
collision_feet = App->collision->AddCollider({ position.x, position.y, 15, 15 }, COLLIDER_POKEMON, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
//Get the animations
animation = *App->anim_manager->GetAnimStruct(4); //id 4 = Geodude
return true;
}
bool Geodude::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
case HIT:
{
Movebyhit();
break;
}
case DYING:
{
Death();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Geodude::Draw()
{
BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
//App->anim_manager->Drawing_Manager(state, direction, position, 6);
int id;
switch (state)
{
case IDLE:
id = 0;
break;
case WALKING:
id = 1;
break;
case ATTACKING:
id = 2;
break;
case DYING:
id = 3;
break;
case HIT:
id = 3;
break;
default:
break;
}
if (direction == UP)
{
anim_rect = animation.anim[id].North_action.GetCurrentFrame();
pivot = animation.anim[id].North_action.GetCurrentOffset();
}
else if (direction == DOWN)
{
anim_rect = animation.anim[id].South_action.GetCurrentFrame();
pivot = animation.anim[id].South_action.GetCurrentOffset();
}
else if (direction == LEFT)
{
anim_rect = animation.anim[id].West_action.GetCurrentFrame();
pivot = animation.anim[id].West_action.GetCurrentOffset();
}
else if (direction == RIGHT)
{
anim_rect = animation.anim[id].East_action.GetCurrentFrame();
pivot = animation.anim[id].East_action.GetCurrentOffset();
}
//DRAW
App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}
bool Geodude::CleanUp()
{
return false;
}
void Geodude::AddItem(Item* item)
{
item_inside = item;
item->canBlit = false;
}
void Geodude::Drop_item()
{
item_inside->canBlit = true;
item_inside->position.x = position.x;
item_inside->position.y = position.y;
item_inside = NULL;
}
bool Geodude::Idle()
{
if (movable)
{
if (reset_run)
{
timetorun = SDL_GetTicks();
reset_run = false;
}
else
{
if (SDL_GetTicks() - timetorun > 2000)
{
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
state = WALKING;
reset_distance = true;
}
}
}
return true;
}
bool Geodude::Walking()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}
bool Geodude::Move()
{
if (direction == LEFT)
{
//App->map->MovementCost(position.x - speed, position.y, LEFT)
if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= speed;
dis_moved++;
}
else
{
//Function to change direction
dis_moved++;
}
walking = true;
}
if (direction == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == DOWN)
{
//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
return true;
}
bool Geodude::Attack()
{
//CHECK IF ATTACK ANIMATION IS FINISHED
if (animation.anim[state].East_action.Finished() ||
animation.anim[state].West_action.Finished() ||
animation.anim[state].North_action.Finished() ||
animation.anim[state].South_action.Finished())
{
state = IDLE;
}
return true;
}
bool Geodude::Death()
{
if (App->scene->player->bombmanager != nullptr)
{
iPoint pos;
pos.create(position.x - offset_x, position.y - offset_y);
App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
}
App->entity_elements->DeletePokemon(this);
return true;
}
bool Geodude::Movebyhit()
{
if (hp <= 0)
{
state = DYING;
return true;
}
if (hurt_timer.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
/*
if (dir_hit == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(position.x, position.y - 10, offset_x, offset_y, UP) == 0)
{
position.y -= 10;
}
if (position.y < (previus_position.y - 30))
{
state = IDLE;
}
}
if (dir_hit == DOWN)
{
//App->map->MovementCost(position.x, position.y + (4 + height), DOWN)
if (App->map->MovementCost(position.x, position.y + 10, offset_x, offset_y, DOWN) == 0)
{
position.y += 10;
}
if (position.y > (previus_position.y + 30))
{
state = IDLE;
}
}
if (dir_hit == LEFT)
{
//App->map->MovementCost(position.x - 4, position.y, LEFT)
if (App->map->MovementCost(position.x - 10, position.y, offset_x, offset_y, LEFT) == 0)
{
position.x -= 10;
}
if (position.x < (previus_position.x - 30))
{
state = IDLE;
}
}
if (dir_hit == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(position.x + 10, position.y, offset_x, offset_y, RIGHT) == 0)
{
position.x += 10;
}
if (position.x > (previus_position.x + 30))
{
state = IDLE;
}
}
*/
return true;
}
void Geodude::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT)
{
animation.anim[3].ResetAnimations();
hurt_timer.Start();
state = HIT;
hp--;
}
{
state == ATTACKING;
animation.anim[state].ResetAnimations();
Orientate();
}
}
}<commit_msg>Geodude collision fixed<commit_after>#include "Geodude.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Player.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1EntityElementsScene.h"
Geodude::Geodude()
{
}
Geodude::~Geodude()
{
}
bool Geodude::Awake(pugi::xml_node &conf, uint id, iPoint pos)
{
name = conf.attribute("name").as_string("");
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("attack").as_int(0);
speed = conf.attribute("speed").as_int(0);
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
cooldown = conf.attribute("cooldown").as_int(0);
mode_stone = conf.attribute("mode_stone").as_bool(false);
if(mode_stone)
position = iPoint(pos.x, pos.y);
else
position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));
return true;
}
bool Geodude::Start()
{
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 7;
gamestate = TIMETOPLAY;
movable = true;
collision_feet = App->collision->AddCollider({ position.x, position.y, 15, 15 }, COLLIDER_POKEMON, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
//Get the animations
animation = *App->anim_manager->GetAnimStruct(4); //id 4 = Geodude
return true;
}
bool Geodude::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
case HIT:
{
Movebyhit();
break;
}
case DYING:
{
Death();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Geodude::Draw()
{
BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
//App->anim_manager->Drawing_Manager(state, direction, position, 6);
int id;
switch (state)
{
case IDLE:
id = 0;
break;
case WALKING:
id = 1;
break;
case ATTACKING:
id = 2;
break;
case DYING:
id = 3;
break;
case HIT:
id = 3;
break;
default:
break;
}
if (direction == UP)
{
anim_rect = animation.anim[id].North_action.GetCurrentFrame();
pivot = animation.anim[id].North_action.GetCurrentOffset();
}
else if (direction == DOWN)
{
anim_rect = animation.anim[id].South_action.GetCurrentFrame();
pivot = animation.anim[id].South_action.GetCurrentOffset();
}
else if (direction == LEFT)
{
anim_rect = animation.anim[id].West_action.GetCurrentFrame();
pivot = animation.anim[id].West_action.GetCurrentOffset();
}
else if (direction == RIGHT)
{
anim_rect = animation.anim[id].East_action.GetCurrentFrame();
pivot = animation.anim[id].East_action.GetCurrentOffset();
}
//DRAW
App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}
bool Geodude::CleanUp()
{
return false;
}
void Geodude::AddItem(Item* item)
{
item_inside = item;
item->canBlit = false;
}
void Geodude::Drop_item()
{
item_inside->canBlit = true;
item_inside->position.x = position.x;
item_inside->position.y = position.y;
item_inside = NULL;
}
bool Geodude::Idle()
{
if (movable)
{
if (reset_run)
{
timetorun = SDL_GetTicks();
reset_run = false;
}
else
{
if (SDL_GetTicks() - timetorun > 2000)
{
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
state = WALKING;
reset_distance = true;
}
}
}
return true;
}
bool Geodude::Walking()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}
bool Geodude::Move()
{
if (direction == LEFT)
{
//App->map->MovementCost(position.x - speed, position.y, LEFT)
if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= speed;
dis_moved++;
}
else
{
//Function to change direction
dis_moved++;
}
walking = true;
}
if (direction == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
if (direction == DOWN)
{
//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += speed;
dis_moved++;
}
else
{
dis_moved++;
}
walking = true;
}
return true;
}
bool Geodude::Attack()
{
//CHECK IF ATTACK ANIMATION IS FINISHED
if (animation.anim[state].East_action.Finished() ||
animation.anim[state].West_action.Finished() ||
animation.anim[state].North_action.Finished() ||
animation.anim[state].South_action.Finished())
{
state = IDLE;
}
return true;
}
bool Geodude::Death()
{
if (App->scene->player->bombmanager != nullptr)
{
iPoint pos;
pos.create(position.x - offset_x, position.y - offset_y);
App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
}
App->entity_elements->DeletePokemon(this);
return true;
}
bool Geodude::Movebyhit()
{
if (hp <= 0)
{
state = DYING;
return true;
}
if (hurt_timer.ReadSec() >= 0.2)
{
state = IDLE;
return true;
}
/*
if (dir_hit == UP)
{
//App->map->MovementCost(position.x, position.y - speed, UP)
if (App->map->MovementCost(position.x, position.y - 10, offset_x, offset_y, UP) == 0)
{
position.y -= 10;
}
if (position.y < (previus_position.y - 30))
{
state = IDLE;
}
}
if (dir_hit == DOWN)
{
//App->map->MovementCost(position.x, position.y + (4 + height), DOWN)
if (App->map->MovementCost(position.x, position.y + 10, offset_x, offset_y, DOWN) == 0)
{
position.y += 10;
}
if (position.y > (previus_position.y + 30))
{
state = IDLE;
}
}
if (dir_hit == LEFT)
{
//App->map->MovementCost(position.x - 4, position.y, LEFT)
if (App->map->MovementCost(position.x - 10, position.y, offset_x, offset_y, LEFT) == 0)
{
position.x -= 10;
}
if (position.x < (previus_position.x - 30))
{
state = IDLE;
}
}
if (dir_hit == RIGHT)
{
//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
if (App->map->MovementCost(position.x + 10, position.y, offset_x, offset_y, RIGHT) == 0)
{
position.x += 10;
}
if (position.x > (previus_position.x + 30))
{
state = IDLE;
}
}
*/
return true;
}
void Geodude::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT)
{
animation.anim[3].ResetAnimations();
hurt_timer.Start();
state = HIT;
hp--;
}
if (c1 == collision_feet && c2->type == COLLIDER_PLAYER && c1->callback->state != HIT)
{
state == ATTACKING;
animation.anim[state].ResetAnimations();
Orientate();
}
}
}<|endoftext|> |
<commit_before>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <zippylog/device/store_writer_sender.hpp>
#include <zippylog/store.hpp>
#include <zippylog/zeromq.hpp>
#include <vector>
namespace zippylog {
namespace device {
using ::std::string;
using ::std::vector;
using ::zmq::message_t;
StoreWriterSender::StoreWriterSender(StoreWriterSenderStartParams ¶ms) :
ctx(params.ctx),
own_context(false),
envelope_pull_endpoint(params.envelope_pull_endpoint),
envelope_rep_endpoint(params.envelope_rep_endpoint),
envelope_pull_sock(NULL),
envelope_rep_sock(NULL)
{
// TODO perform validation
if (!this->ctx) {
this->ctx = new ::zmq::context_t(1);
this->own_context = true;
}
if (this->envelope_pull_endpoint.length()) {
this->envelope_pull_sock = new ::zmq::socket_t(*this->ctx, ZMQ_PUSH);
this->envelope_pull_sock->bind(this->envelope_pull_endpoint.c_str());
}
if (this->envelope_rep_endpoint.length()) {
this->envelope_rep_sock = new ::zmq::socket_t(*this->ctx, ZMQ_REQ);
this->envelope_rep_sock->bind(this->envelope_rep_endpoint.c_str());
}
}
StoreWriterSender::~StoreWriterSender()
{
if (this->own_context && this->ctx) {
delete this->ctx;
}
if (this->envelope_pull_sock) delete this->envelope_pull_sock;
if (this->envelope_rep_sock) delete this->envelope_rep_sock;
}
bool StoreWriterSender::DeliverEnvelope(const string &bucket, const string &set, ::zippylog::Envelope &e)
{
// TODO is this appropriate? I think it signifies a coding error (no param to constructor) and thus is
if (!this->envelope_pull_sock)
throw "can not deliver envelopes since the pull socket is not configured";
vector<string> preceding;
string path = ::zippylog::Store::StreamsetPath(bucket, set);
preceding.push_back(path);
return ::zippylog::zeromq::send_envelope_with_preceding(this->envelope_pull_sock, preceding, e);
}
bool StoreWriterSender::WriteEnvelope(const string &bucket, const string &set, ::zippylog::Envelope &e)
{
if (!this->envelope_rep_sock)
throw "can not deliver envelopes since the rep sock is not configured";
vector<string> preceding;
string path = ::zippylog::Store::StreamsetPath(bucket, set);
preceding.push_back(path);
if (!::zippylog::zeromq::send_envelope_with_preceding(this->envelope_rep_sock, preceding, e)) {
// TODO we might want to reconnect the socket in case the FSM is messed up
return false;
}
// now wait for the reply
vector<message_t *> msgs;
if (!::zippylog::zeromq::receive_multipart_message(this->envelope_rep_sock, msgs)) {
// TODO recover socket
return false;
}
bool result = true;
if (msgs.size() < 1 || msgs[0]->size() != 0 || msgs.size() > 1) {
result = false;
}
for (vector<message_t *>::iterator i = msgs.begin(); i != msgs.end(); i++) {
delete *i;
}
return result;
}
}} // namespaces<commit_msg>connect(), don't bind(), duh<commit_after>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <zippylog/device/store_writer_sender.hpp>
#include <zippylog/store.hpp>
#include <zippylog/zeromq.hpp>
#include <vector>
namespace zippylog {
namespace device {
using ::std::string;
using ::std::vector;
using ::zmq::message_t;
StoreWriterSender::StoreWriterSender(StoreWriterSenderStartParams ¶ms) :
ctx(params.ctx),
own_context(false),
envelope_pull_endpoint(params.envelope_pull_endpoint),
envelope_rep_endpoint(params.envelope_rep_endpoint),
envelope_pull_sock(NULL),
envelope_rep_sock(NULL)
{
// TODO perform validation
if (!this->ctx) {
this->ctx = new ::zmq::context_t(1);
this->own_context = true;
}
if (this->envelope_pull_endpoint.length()) {
this->envelope_pull_sock = new ::zmq::socket_t(*this->ctx, ZMQ_PUSH);
this->envelope_pull_sock->connect(this->envelope_pull_endpoint.c_str());
}
if (this->envelope_rep_endpoint.length()) {
this->envelope_rep_sock = new ::zmq::socket_t(*this->ctx, ZMQ_REQ);
this->envelope_rep_sock->connect(this->envelope_rep_endpoint.c_str());
}
}
StoreWriterSender::~StoreWriterSender()
{
if (this->own_context && this->ctx) {
delete this->ctx;
}
if (this->envelope_pull_sock) delete this->envelope_pull_sock;
if (this->envelope_rep_sock) delete this->envelope_rep_sock;
}
bool StoreWriterSender::DeliverEnvelope(const string &bucket, const string &set, ::zippylog::Envelope &e)
{
// TODO is this appropriate? I think it signifies a coding error (no param to constructor) and thus is
if (!this->envelope_pull_sock)
throw "can not deliver envelopes since the pull socket is not configured";
vector<string> preceding;
string path = ::zippylog::Store::StreamsetPath(bucket, set);
preceding.push_back(path);
return ::zippylog::zeromq::send_envelope_with_preceding(this->envelope_pull_sock, preceding, e);
}
bool StoreWriterSender::WriteEnvelope(const string &bucket, const string &set, ::zippylog::Envelope &e)
{
if (!this->envelope_rep_sock)
throw "can not deliver envelopes since the rep sock is not configured";
vector<string> preceding;
string path = ::zippylog::Store::StreamsetPath(bucket, set);
preceding.push_back(path);
if (!::zippylog::zeromq::send_envelope_with_preceding(this->envelope_rep_sock, preceding, e)) {
// TODO we might want to reconnect the socket in case the FSM is messed up
return false;
}
// now wait for the reply
vector<message_t *> msgs;
if (!::zippylog::zeromq::receive_multipart_message(this->envelope_rep_sock, msgs)) {
// TODO recover socket
return false;
}
bool result = true;
if (msgs.size() < 1 || msgs[0]->size() != 0 || msgs.size() > 1) {
result = false;
}
for (vector<message_t *>::iterator i = msgs.begin(); i != msgs.end(); i++) {
delete *i;
}
return result;
}
}} // namespaces<|endoftext|> |
<commit_before>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&](){ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&](){ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&](){ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->connect_to_p2p_network();
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
_client->set_daemon_mode(true);
_client->start();
_client->start_delegate_loop();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&](){ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
main_thread->async( [&](){ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&](){ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&](){ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&](){ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<commit_msg>removing call to client->start_delegate_loop as it's no longer available from client interface, but it's automatically called at client start.<commit_after>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&](){ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&](){ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&](){ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->connect_to_p2p_network();
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&](){ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
main_thread->async( [&](){ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&](){ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&](){ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&](){ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/promote_common.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl.hpp>
#endif
namespace stan {
namespace math {
/**
* Returns the solution of the system Ax=b when A is triangular.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam T1 type of elements in A
* @tparam T2 type of elements in b
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @tparam R2 number of rows in b
* @tparam C2 number of columns in b
* @param A Triangular matrix.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,
R1, C2>
mdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,
const Eigen::Matrix<T2, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(
A)
.template triangularView<TriView>()
.solve(
promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(
b));
}
/**
* Returns the solution of the system Ax=b when A is triangular and b=I.
* @tparam T type of elements in A
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @param A Triangular matrix.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <int TriView, typename T, int R1, int C1>
inline Eigen::Matrix<T, R1, C1> mdivide_left_tri(
const Eigen::Matrix<T, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
int n = A.rows();
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
}
/**
* Returns the solution of the system Ax=b when A is triangular
* and A and b are matrices of doubles.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @tparam R2 number of rows in b
* @tparam C2 number of columns in b
* @param A Triangular matrix.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2> mdivide_left_tri(
const Eigen::Matrix<double, R1, C1> &A,
const Eigen::Matrix<double, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
#ifdef STAN_OPENCL
if (A.rows()
>= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {
matrix_cl<double> A_cl(A, TriView == Eigen::Lower ? PartialViewCL::Lower
: PartialViewCL::Upper);
matrix_cl<double> b_cl(b);
matrix_cl<double> A_inv_cl = tri_inverse(A_cl);
matrix_cl<double> C_cl = A_inv_cl * b_cl;
return from_matrix_cl(C_cl);
} else {
#endif
return A.template triangularView<TriView>().solve(b);
#ifdef STAN_OPENCL
}
#endif
}
/**
* Returns the solution of the system Ax=b when A is triangular, b=I and
* both are matrices of doubles.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @param A Triangular matrix.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <Eigen::UpLoType TriView, int R1, int C1>
inline Eigen::Matrix<double, R1, C1> mdivide_left_tri(
const Eigen::Matrix<double, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
const int n = A.rows();
#ifdef STAN_OPENCL
if (A.rows()
>= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {
matrix_cl<double> A_cl(A, from_eigen_triangular_type(TriView));
A_cl = tri_inverse(A_cl);
return from_matrix_cl(A_cl);
} else {
#endif
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
#ifdef STAN_OPENCL
}
#endif
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fix missing from_eigen_triangular_type() call<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/promote_common.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl.hpp>
#endif
namespace stan {
namespace math {
/**
* Returns the solution of the system Ax=b when A is triangular.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam T1 type of elements in A
* @tparam T2 type of elements in b
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @tparam R2 number of rows in b
* @tparam C2 number of columns in b
* @param A Triangular matrix.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,
R1, C2>
mdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,
const Eigen::Matrix<T2, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(
A)
.template triangularView<TriView>()
.solve(
promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(
b));
}
/**
* Returns the solution of the system Ax=b when A is triangular and b=I.
* @tparam T type of elements in A
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @param A Triangular matrix.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <int TriView, typename T, int R1, int C1>
inline Eigen::Matrix<T, R1, C1> mdivide_left_tri(
const Eigen::Matrix<T, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
int n = A.rows();
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
}
/**
* Returns the solution of the system Ax=b when A is triangular
* and A and b are matrices of doubles.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @tparam R2 number of rows in b
* @tparam C2 number of columns in b
* @param A Triangular matrix.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <Eigen::UpLoType TriView, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2> mdivide_left_tri(
const Eigen::Matrix<double, R1, C1> &A,
const Eigen::Matrix<double, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
#ifdef STAN_OPENCL
if (A.rows()
>= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {
matrix_cl<double> A_cl(A, from_eigen_triangular_type(TriView);
matrix_cl<double> b_cl(b);
matrix_cl<double> A_inv_cl = tri_inverse(A_cl);
matrix_cl<double> C_cl = A_inv_cl * b_cl;
return from_matrix_cl(C_cl);
} else {
#endif
return A.template triangularView<TriView>().solve(b);
#ifdef STAN_OPENCL
}
#endif
}
/**
* Returns the solution of the system Ax=b when A is triangular, b=I and
* both are matrices of doubles.
* @tparam TriView Specifies whether A is upper (Eigen::Upper)
* or lower triangular (Eigen::Lower).
* @tparam R1 number of rows in A
* @tparam C1 number of columns in A
* @param A Triangular matrix.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <Eigen::UpLoType TriView, int R1, int C1>
inline Eigen::Matrix<double, R1, C1> mdivide_left_tri(
const Eigen::Matrix<double, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
const int n = A.rows();
#ifdef STAN_OPENCL
if (A.rows()
>= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {
matrix_cl<double> A_cl(A, from_eigen_triangular_type(TriView));
A_cl = tri_inverse(A_cl);
return from_matrix_cl(A_cl);
} else {
#endif
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
#ifdef STAN_OPENCL
}
#endif
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- standard modules used ----------------------------------------------------
#include "Anything.h"
#include "SSLSocket.h"
#include "SSLModule.h"
#include "Dbg.h"
//--- test modules used --------------------------------------------------------
#include "TestSuite.h"
//--- module under test --------------------------------------------------------
#include "RequestListener.h"
//--- interface include --------------------------------------------------------
#include "SSLListenerPoolTest.h"
#include "ListenerPoolTest.h"
//---- SSLListenerPoolTest ----------------------------------------------------------------
SSLListenerPoolTest::SSLListenerPoolTest(TString tname) : ListenerPoolTest(tname)
{
StartTrace(SSLListenerPoolTest.Ctor);
}
SSLListenerPoolTest::~SSLListenerPoolTest()
{
StartTrace(SSLListenerPoolTest.Dtor);
}
void SSLListenerPoolTest::PoolTest()
{
StartTrace(SSLListenerPoolTest.PoolTest);
Anything config;
config.Append("TCP5010");
config.Append("TCP5011");
config.Append("TCP5012");
config.Append("TCP5013");
config.Append("TCP5014");
config.Append("TCP5015");
config.Append("TCP5016");
config.Append("TCP5017");
config.Append("TCP5018");
config.Append("TCP5019");
TestCallBackFactory *tcbf = new TestCallBackFactory;
ListenerPool lpToTest(tcbf);
if ( t_assertm( lpToTest.Init(config.GetSize(), config), "Init should work") && t_assertm(lpToTest.Start(false, 0, 0) == 0, "Start should work")) {
DoTestConnect();
if (t_assertm(lpToTest.Terminate(1, 10) == 0, "Terminate failed")) {
t_assertm(lpToTest.Join() == 0, "Join failed");
Anything result = tcbf->GetResult();
t_assert(result.Contains("5010_timeout_0"));
t_assert(result.Contains("5011_timeout_0"));
t_assert(result.Contains("5012_timeout_0"));
t_assert(result.Contains("5013_timeout_0"));
t_assert(result.Contains("5014_timeout_0"));
t_assert(result.Contains("5010_timeout_1000"));
t_assert(result.Contains("5011_timeout_1000"));
t_assert(result.Contains("5012_timeout_1000"));
t_assert(result.Contains("5012_timeout_2000"));
t_assert(result.Contains("5011_timeout_2000"));
t_assert(result.Contains("5016_timeout_1000"));
t_assert(result.Contains("5017_timeout_1000"));
}
}
Anything failures = tcbf->GetFailures();
t_assertm(failures.GetSize() == 0, "Receivers encountered a least one error");
if (failures.GetSize()) {
TraceAny(failures, "EYECATCHER Receivers encountered the following errors");
}
}
void SSLListenerPoolTest::DoTestConnect()
{
StartTrace(SSLListenerPoolTest.DoTestConnect);
FOREACH_ENTRY("SSLListenerPoolTest", cConfig, cName) {
TraceAny(cConfig, "cConfig");
Trace(cConfig["SSLConnector"].AsLong(1));
if ( cConfig["SSLConnector"].AsLong(1) == 1 ) {
if ( cConfig["ConnectorToUse"].AsString() != "" ) {
// deep clone, no side effect when adding Timeout
Anything connectorConfig = fTestCaseConfig[cConfig["ConnectorToUse"].AsString()].DeepClone();
if ( cConfig.IsDefined("TimeoutToUse") ) {
connectorConfig["Timeout"] = 1000L;
}
SSLConnector sc(connectorConfig);
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&sc, cConfig["Data"].DeepClone());
}
} else {
SSLConnector sc("localhost", cConfig["PortToUse"].AsLong(0), cConfig["TimeoutToUse"].AsLong(0));
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&sc, cConfig["Data"].DeepClone());
}
}
} else {
Trace("Using configured NON SSL connector");
Connector c("localhost", cConfig["PortToUse"].AsLong(0L), cConfig["TimeoutToUse"].AsLong(0L));
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&c, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&c, cConfig["Data"].DeepClone());
}
}
}
}
// builds up a suite of testcases, add a line for each testmethod
Test *SSLListenerPoolTest::suite ()
{
StartTrace(SSLListenerPoolTest.suite);
TestSuite *testSuite = new TestSuite;
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, PoolTest));
//#if !defined(WIN32)
// testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureTest)); // test does not work on WIN32
//#endif
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, NullCallBackFactoryTest));
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureNullAcceptorTest));
return testSuite;
} // suite
<commit_msg>added one-level self signed cert test<commit_after>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- standard modules used ----------------------------------------------------
#include "Anything.h"
#include "SSLSocket.h"
#include "SSLModule.h"
#include "Dbg.h"
//--- test modules used --------------------------------------------------------
#include "TestSuite.h"
//--- module under test --------------------------------------------------------
#include "RequestListener.h"
//--- interface include --------------------------------------------------------
#include "SSLListenerPoolTest.h"
#include "ListenerPoolTest.h"
//---- SSLListenerPoolTest ----------------------------------------------------------------
SSLListenerPoolTest::SSLListenerPoolTest(TString tname) : ListenerPoolTest(tname)
{
StartTrace(SSLListenerPoolTest.Ctor);
}
SSLListenerPoolTest::~SSLListenerPoolTest()
{
StartTrace(SSLListenerPoolTest.Dtor);
}
void SSLListenerPoolTest::PoolTest()
{
StartTrace(SSLListenerPoolTest.PoolTest);
Anything config;
config.Append("TCP5010");
config.Append("TCP5011");
config.Append("TCP5012");
config.Append("TCP5013");
config.Append("TCP5014");
config.Append("TCP5015");
config.Append("TCP5016");
config.Append("TCP5017");
config.Append("TCP5018");
config.Append("TCP5019");
config.Append("TCP5020");
TestCallBackFactory *tcbf = new TestCallBackFactory;
ListenerPool lpToTest(tcbf);
if ( t_assertm( lpToTest.Init(config.GetSize(), config), "Init should work") && t_assertm(lpToTest.Start(false, 0, 0) == 0, "Start should work")) {
DoTestConnect();
if (t_assertm(lpToTest.Terminate(1, 10) == 0, "Terminate failed")) {
t_assertm(lpToTest.Join() == 0, "Join failed");
Anything result = tcbf->GetResult();
t_assert(result.Contains("5010_timeout_0"));
t_assert(result.Contains("5011_timeout_0"));
t_assert(result.Contains("5012_timeout_0"));
t_assert(result.Contains("5013_timeout_0"));
t_assert(result.Contains("5014_timeout_0"));
t_assert(result.Contains("5010_timeout_1000"));
t_assert(result.Contains("5011_timeout_1000"));
t_assert(result.Contains("5012_timeout_1000"));
t_assert(result.Contains("5012_timeout_2000"));
t_assert(result.Contains("5011_timeout_2000"));
t_assert(result.Contains("5016_timeout_1000"));
t_assert(result.Contains("5017_timeout_1000"));
t_assert(result.Contains("5020_timeout_0"));
}
}
Anything failures = tcbf->GetFailures();
t_assertm(failures.GetSize() == 0, "Receivers encountered a least one error");
if (failures.GetSize()) {
TraceAny(failures, "EYECATCHER Receivers encountered the following errors");
}
}
void SSLListenerPoolTest::DoTestConnect()
{
StartTrace(SSLListenerPoolTest.DoTestConnect);
FOREACH_ENTRY("SSLListenerPoolTest", cConfig, cName) {
TraceAny(cConfig, "cConfig");
Trace(cConfig["SSLConnector"].AsLong(1));
if ( cConfig["SSLConnector"].AsLong(1) == 1 ) {
if ( cConfig["ConnectorToUse"].AsString() != "" ) {
// deep clone, no side effect when adding Timeout
Anything connectorConfig = fTestCaseConfig[cConfig["ConnectorToUse"].AsString()].DeepClone();
if ( cConfig.IsDefined("TimeoutToUse") ) {
connectorConfig["Timeout"] = 1000L;
}
SSLConnector sc(connectorConfig);
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&sc, cConfig["Data"].DeepClone());
}
} else {
SSLConnector sc("localhost", cConfig["PortToUse"].AsLong(0), cConfig["TimeoutToUse"].AsLong(0));
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&sc, cConfig["Data"].DeepClone());
}
}
} else {
Trace("Using configured NON SSL connector");
Connector c("localhost", cConfig["PortToUse"].AsLong(0L), cConfig["TimeoutToUse"].AsLong(0L));
if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
DoSendReceiveWithFailure(&c, cConfig["Data"].DeepClone(),
cConfig["IOSGoodAfterSend"].AsLong(0),
cConfig["IOSGoodBeforeSend"].AsLong(1));
} else {
DoSendReceive(&c, cConfig["Data"].DeepClone());
}
}
}
}
// builds up a suite of testcases, add a line for each testmethod
Test *SSLListenerPoolTest::suite ()
{
StartTrace(SSLListenerPoolTest.suite);
TestSuite *testSuite = new TestSuite;
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, PoolTest));
//#if !defined(WIN32)
// testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureTest)); // test does not work on WIN32
//#endif
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, NullCallBackFactoryTest));
testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureNullAcceptorTest));
return testSuite;
} // suite
<|endoftext|> |
<commit_before>#include "User.h"
namespace TpQt4Communication
{
User::User(Tp::ConnectionPtr tp_connection): user_id_(""), protocol_(""), tp_connection_(tp_connection)
{
tp_contact_ = tp_connection->selfContact();
}
void User::SetPresenceStatus(std::string status, std::string message)
{
QString s(status.c_str());
QString m(message.c_str());
tp_connection_->setSelfPresence(s, m);
}
std::string User::GetUserID()
{
return user_id_;
}
PresenceStatus* User::GetPresenceStatus()
{
return &presence_status_;
}
std::string User::GetProtocol()
{
return protocol_;
}
void User::AddContacts(ContactVector &contacts)
{
contacts_.assign(contacts.begin(), contacts.end());
emit ContactListChangend();
}
} // end of TpQt4Communication:
<commit_msg>Added GetContacts function.<commit_after>#include "User.h"
namespace TpQt4Communication
{
User::User(Tp::ConnectionPtr tp_connection): user_id_(""), protocol_(""), tp_connection_(tp_connection)
{
tp_contact_ = tp_connection->selfContact();
}
void User::SetPresenceStatus(std::string status, std::string message)
{
QString s(status.c_str());
QString m(message.c_str());
tp_connection_->setSelfPresence(s, m);
}
std::string User::GetUserID()
{
return user_id_;
}
PresenceStatus* User::GetPresenceStatus()
{
return &presence_status_;
}
std::string User::GetProtocol()
{
return protocol_;
}
void User::AddContacts(ContactVector &contacts)
{
contacts_.assign(contacts.begin(), contacts.end());
emit ContactListChangend();
}
ContactVector User::GetContacts()
{
ContactVector contacts;
contacts.assign(contacts_.begin(), contacts_.end());
return contacts;
}
} // end of TpQt4Communication:
<|endoftext|> |
<commit_before>//
// CRTC6845.hpp
// Clock Signal
//
// Created by Thomas Harte on 31/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef CRTC6845_hpp
#define CRTC6845_hpp
#include "../../ClockReceiver/ClockReceiver.hpp"
#include <cstdint>
#include <cstdio>
namespace Motorola {
namespace CRTC {
struct BusState {
bool display_enable;
bool hsync;
bool vsync;
bool cursor;
uint16_t refresh_address;
uint16_t row_address;
};
template <class T> class CRTC6845 {
public:
CRTC6845(T &bus_handler) : bus_handler_(bus_handler) {}
void run_for(Cycles cycles) {
int cyles_remaining = cycles.as_int();
while(cyles_remaining--) {
// check for end of horizontal sync
if(hsync_down_counter_) {
hsync_down_counter_--;
if(!hsync_down_counter_) {
bus_state_.hsync = false;
}
}
// advance horizontal counter
character_counter_++;
// check for start of horizontal sync
if(character_counter_ == registers_[2]) {
hsync_down_counter_ = registers_[3] & 15;
if(hsync_down_counter_) bus_state_.hsync = true;
}
// check for end of visible characters
if(character_counter_ == registers_[1]) {
character_is_visible_ = false;
}
// check for end-of-line
if(character_counter_ == registers_[0]+1) {
character_counter_ = 0;
character_is_visible_ = true;
// check for end of vertical sync
if(vsync_down_counter_) {
vsync_down_counter_--;
if(!vsync_down_counter_) {
bus_state_.vsync = false;
}
}
if(is_in_adjustment_period_) {
line_counter_++;
if(line_counter_ == registers_[5]) {
line_is_visible_ = true;
line_counter_ = 0;
is_in_adjustment_period_ = false;
line_address_ = (registers_[12] << 8) | registers_[13];
bus_state_.refresh_address = line_address_;
}
} else {
// advance vertical counter
bus_state_.row_address++;
if(bus_state_.row_address == registers_[9]) {
line_address_ = bus_state_.refresh_address;
bus_state_.row_address = 0;
line_counter_++;
// check for end of visible lines
if(line_counter_ == registers_[6]) {
line_is_visible_ = false;
}
// check for start of vertical sync
if(line_counter_ == registers_[7]) {
bus_state_.vsync = true;
vsync_down_counter_ = 16; // TODO
}
// check for entry into the overflow area
if(line_counter_ == registers_[4]) {
is_in_adjustment_period_ = true;
bus_state_.row_address = 0;
line_counter_ = 0;
}
} else {
bus_state_.refresh_address = line_address_;
}
}
}
bus_state_.display_enable = line_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle(bus_state_);
}
}
void select_register(uint8_t r) {
selected_register_ = (int)r & 15;
}
uint8_t get_status() {
return 0xff;
}
uint8_t get_register() {
return registers_[selected_register_];
}
void set_register(uint8_t value) {
registers_[selected_register_] = value;
}
private:
T &bus_handler_;
BusState bus_state_;
uint8_t registers_[16];
int selected_register_;
uint8_t character_counter_;
uint8_t line_counter_;
bool character_is_visible_, line_is_visible_;
int hsync_down_counter_;
int vsync_down_counter_;
bool is_in_adjustment_period_;
uint16_t line_address_;
};
}
}
#endif /* CRTC6845_hpp */
<commit_msg>Added an explicit cast.<commit_after>//
// CRTC6845.hpp
// Clock Signal
//
// Created by Thomas Harte on 31/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef CRTC6845_hpp
#define CRTC6845_hpp
#include "../../ClockReceiver/ClockReceiver.hpp"
#include <cstdint>
#include <cstdio>
namespace Motorola {
namespace CRTC {
struct BusState {
bool display_enable;
bool hsync;
bool vsync;
bool cursor;
uint16_t refresh_address;
uint16_t row_address;
};
template <class T> class CRTC6845 {
public:
CRTC6845(T &bus_handler) : bus_handler_(bus_handler) {}
void run_for(Cycles cycles) {
int cyles_remaining = cycles.as_int();
while(cyles_remaining--) {
// check for end of horizontal sync
if(hsync_down_counter_) {
hsync_down_counter_--;
if(!hsync_down_counter_) {
bus_state_.hsync = false;
}
}
// advance horizontal counter
character_counter_++;
// check for start of horizontal sync
if(character_counter_ == registers_[2]) {
hsync_down_counter_ = registers_[3] & 15;
if(hsync_down_counter_) bus_state_.hsync = true;
}
// check for end of visible characters
if(character_counter_ == registers_[1]) {
character_is_visible_ = false;
}
// check for end-of-line
if(character_counter_ == registers_[0]+1) {
character_counter_ = 0;
character_is_visible_ = true;
// check for end of vertical sync
if(vsync_down_counter_) {
vsync_down_counter_--;
if(!vsync_down_counter_) {
bus_state_.vsync = false;
}
}
if(is_in_adjustment_period_) {
line_counter_++;
if(line_counter_ == registers_[5]) {
line_is_visible_ = true;
line_counter_ = 0;
is_in_adjustment_period_ = false;
line_address_ = (uint16_t)((registers_[12] << 8) | registers_[13]);
bus_state_.refresh_address = line_address_;
}
} else {
// advance vertical counter
bus_state_.row_address++;
if(bus_state_.row_address == registers_[9]) {
line_address_ = bus_state_.refresh_address;
bus_state_.row_address = 0;
line_counter_++;
// check for end of visible lines
if(line_counter_ == registers_[6]) {
line_is_visible_ = false;
}
// check for start of vertical sync
if(line_counter_ == registers_[7]) {
bus_state_.vsync = true;
vsync_down_counter_ = 16; // TODO
}
// check for entry into the overflow area
if(line_counter_ == registers_[4]) {
is_in_adjustment_period_ = true;
bus_state_.row_address = 0;
line_counter_ = 0;
}
} else {
bus_state_.refresh_address = line_address_;
}
}
}
bus_state_.display_enable = line_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle(bus_state_);
}
}
void select_register(uint8_t r) {
selected_register_ = (int)r & 15;
}
uint8_t get_status() {
return 0xff;
}
uint8_t get_register() {
return registers_[selected_register_];
}
void set_register(uint8_t value) {
registers_[selected_register_] = value;
}
private:
T &bus_handler_;
BusState bus_state_;
uint8_t registers_[16];
int selected_register_;
uint8_t character_counter_;
uint8_t line_counter_;
bool character_is_visible_, line_is_visible_;
int hsync_down_counter_;
int vsync_down_counter_;
bool is_in_adjustment_period_;
uint16_t line_address_;
};
}
}
#endif /* CRTC6845_hpp */
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>
#include <cmath>
#define NUM_FIELDS 16
using Entry = std::array<double, NUM_FIELDS>;
using IntPair = std::pair<int, int>;
struct CompareSecond: std::binary_function<IntPair, IntPair, bool>
{
bool operator()(const IntPair& a, const IntPair& b)
{
return a.second < b.second;
}
};
int main(int argc, char** argv)
{
// smoothing factor
const double alpha = 1.0;
// decision rule
const int decision = 1;
if (argc < 2)
return 1;
// preparing data
int total = 0, correct = 0, totalClassified = 0;
std::map<std::string, std::vector<Entry> > data;
std::map<std::string, int> n;
std::map<std::string, double> priors;
std::map<std::string, std::vector<double> > multinomialLikelihoods;
std::map<std::string, int> multinomialSums;
std::map<std::string, Entry > sumX;
std::map<std::string, std::vector<double> > means;
std::map<std::string, std::vector<double> > variances;
auto classify = [&](const std::string& label, const Entry& entry)
{
std::string predlabel;
double maxlikelihood = 0.0;
double denom = 0.0;
std::vector<double> probs;
for (auto it = priors.begin(); it != priors.end(); it++)
{
double numer = priors[it->first];
const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
const auto& firstMean = means[it->first];
const auto& firstVariance = variances[it->first];
for (int j = 0; j < NUM_FIELDS; j++)
switch (decision)
{
case 2:
// Multinomial
if (entry[j])
numer *= pow(firstMultinomialLikelihood[j], entry[j]);
break;
case 3:
// Bernoulli
numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
break;
default:
// Gaussian
numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
break;
}
if (numer > maxlikelihood)
{
maxlikelihood = numer;
predlabel = it->first;
}
denom += numer;
probs.push_back(numer);
}
std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
if ("" == label)
std::cout << "<no label>" << std::endl;
else if (predlabel == label)
{
std::cout << "correct" << std::endl;
correct++;
}
else
std::cout << "incorrect" << std::endl;
totalClassified++;
};
auto readFromFile = [&](const char* filename, bool isClassification)
{
std::ifstream file(argv[1]);
if (!file.is_open())
return 1;
while (!file.eof())
{
std::string line;
std::getline(file, line);
if ("" == line)
continue;
std::istringstream linein(std::move(line));
std::string label;
std::getline(linein, label, ',');
Entry entry;
auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
{
switch (field[0])
{
case 'y':
entry[i] = 1.0;
break;
case 'n':
entry[i] = 0.0;
break;
case '?':
entry[i] = 0.5;
break;
}
if (!isClassification)
{
sumX[label][i] += entry[i];
multinomialSums[label] += entry[i];
}
};
for (int i = 0; i < NUM_FIELDS; i++)
{
std::string field;
std::getline(linein, field, ',');
setField(i, field);
}
std::string field;
std::getline(linein, field);
setField(NUM_FIELDS - 1, field);
if (!isClassification)
{
data[label].push_back(std::move(entry));
n[label]++;
total++;
}
else
classify(label, entry);
}
return 0;
};
int errcode = readFromFile(argv[1], false);
if (errcode)
return errcode;
for (auto it = sumX.begin(); it != sumX.end(); it++)
{
priors[it->first] = (double)n[it->first] / total;
std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;
// calculate means
std::vector<double> featureMeans(NUM_FIELDS);
for (int i = 0; i < NUM_FIELDS; i++)
featureMeans[i] = sumX[it->first][i] / n[it->first];
// calculate variances
std::vector<double> featureVariances(NUM_FIELDS);
const auto& firstData = data[it->first];
for (int i = 0; i < (int)firstData.size(); i++)
for (int j = 0; j < NUM_FIELDS; j++)
featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
for (int i = 0; i < NUM_FIELDS; i++)
featureVariances[i] /= firstData.size();
const auto& firstSumX = sumX[it->first];
auto firstMultinomialSum = multinomialSums[it->first];
auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
// calculate multinomial likelihoods
for (int i = 0; i < NUM_FIELDS; i++)
{
double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
firstMultinomialLikelihood.push_back(mnl);
}
for (unsigned int i = 0; i < NUM_FIELDS; i++)
printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);
means[it->first] = std::move(featureMeans);
variances[it->first] = std::move(featureVariances);
}
// classify
std::cout << "Classifying:" << std::endl;
std::cout << "class\tprob\tresult" << std::endl;
errcode = readFromFile(argv[2], true);
if (errcode)
return errcode;
printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);
return 0;
}
<commit_msg>bayes: dropped some redundant types<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>
#include <cmath>
#define NUM_FIELDS 16
using Entry = std::array<double, NUM_FIELDS>;
int main(int argc, char** argv)
{
// smoothing factor
const double alpha = 1.0;
// decision rule
const int decision = 1;
if (argc < 2)
return 1;
// preparing data
int total = 0, correct = 0, totalClassified = 0;
std::map<std::string, std::vector<Entry> > data;
std::map<std::string, int> n;
std::map<std::string, double> priors;
std::map<std::string, std::vector<double> > multinomialLikelihoods;
std::map<std::string, int> multinomialSums;
std::map<std::string, Entry > sumX;
std::map<std::string, std::vector<double> > means;
std::map<std::string, std::vector<double> > variances;
auto classify = [&](const std::string& label, const Entry& entry)
{
std::string predlabel;
double maxlikelihood = 0.0;
double denom = 0.0;
std::vector<double> probs;
for (auto it = priors.begin(); it != priors.end(); it++)
{
double numer = priors[it->first];
const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
const auto& firstMean = means[it->first];
const auto& firstVariance = variances[it->first];
for (int j = 0; j < NUM_FIELDS; j++)
switch (decision)
{
case 2:
// Multinomial
if (entry[j])
numer *= pow(firstMultinomialLikelihood[j], entry[j]);
break;
case 3:
// Bernoulli
numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
break;
default:
// Gaussian
numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
break;
}
if (numer > maxlikelihood)
{
maxlikelihood = numer;
predlabel = it->first;
}
denom += numer;
probs.push_back(numer);
}
std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
if ("" == label)
std::cout << "<no label>" << std::endl;
else if (predlabel == label)
{
std::cout << "correct" << std::endl;
correct++;
}
else
std::cout << "incorrect" << std::endl;
totalClassified++;
};
auto readFromFile = [&](const char* filename, bool isClassification)
{
std::ifstream file(argv[1]);
if (!file.is_open())
return 1;
while (!file.eof())
{
std::string line;
std::getline(file, line);
if ("" == line)
continue;
std::istringstream linein(std::move(line));
std::string label;
std::getline(linein, label, ',');
Entry entry;
auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
{
switch (field[0])
{
case 'y':
entry[i] = 1.0;
break;
case 'n':
entry[i] = 0.0;
break;
case '?':
entry[i] = 0.5;
break;
}
if (!isClassification)
{
sumX[label][i] += entry[i];
multinomialSums[label] += entry[i];
}
};
for (int i = 0; i < NUM_FIELDS; i++)
{
std::string field;
std::getline(linein, field, ',');
setField(i, field);
}
std::string field;
std::getline(linein, field);
setField(NUM_FIELDS - 1, field);
if (!isClassification)
{
data[label].push_back(std::move(entry));
n[label]++;
total++;
}
else
classify(label, entry);
}
return 0;
};
int errcode = readFromFile(argv[1], false);
if (errcode)
return errcode;
for (auto it = sumX.begin(); it != sumX.end(); it++)
{
priors[it->first] = (double)n[it->first] / total;
std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;
// calculate means
std::vector<double> featureMeans(NUM_FIELDS);
for (int i = 0; i < NUM_FIELDS; i++)
featureMeans[i] = sumX[it->first][i] / n[it->first];
// calculate variances
std::vector<double> featureVariances(NUM_FIELDS);
const auto& firstData = data[it->first];
for (int i = 0; i < (int)firstData.size(); i++)
for (int j = 0; j < NUM_FIELDS; j++)
featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
for (int i = 0; i < NUM_FIELDS; i++)
featureVariances[i] /= firstData.size();
const auto& firstSumX = sumX[it->first];
auto firstMultinomialSum = multinomialSums[it->first];
auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
// calculate multinomial likelihoods
for (int i = 0; i < NUM_FIELDS; i++)
{
double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
firstMultinomialLikelihood.push_back(mnl);
}
for (unsigned int i = 0; i < NUM_FIELDS; i++)
printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);
means[it->first] = std::move(featureMeans);
variances[it->first] = std::move(featureVariances);
}
// classify
std::cout << "Classifying:" << std::endl;
std::cout << "class\tprob\tresult" << std::endl;
errcode = readFromFile(argv[2], true);
if (errcode)
return errcode;
printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);
return 0;
}
<|endoftext|> |
<commit_before>#include "SerialController.h"
#include <utils/AnyCollection.h>
SerialController::SerialController(Robot& robot,const string& _servAddr,Real _writeRate)
:RobotController(robot),servAddr(_servAddr),writeRate(_writeRate),lastWriteTime(0)
{
if(!servAddr.empty())
OpenConnection(servAddr);
}
void SerialController::PackSensorData(AnyCollection& data) const
{
data["t"] = time;
data["dt"] = 1.0/writeRate;
for(size_t i=0;i<sensors->sensors.size();i++) {
vector<double> values;
sensors->sensors[i]->GetMeasurements(values);
data[sensors->sensors[i]->name] = AnyCollection(values);
}
}
void SerialController::Update(Real dt)
{
RobotController::Update(dt);
#ifndef WIN32
if(time >= lastWriteTime + 1.0/writeRate) {
lastWriteTime += 1.0/writeRate;
if(time >= lastWriteTime + 1.0/writeRate) {
printf("Warning, next write time %g is less than controller update time %g\n",lastWriteTime+1.0/writeRate,time);
lastWriteTime = time;
}
AnyCollection sensorData;
PackSensorData(sensorData);
stringstream ss;
ss << sensorData;
if(controllerPipe) {
controllerPipe->SendMessage(ss.str());
}
}
if(controllerPipe && controllerPipe->NewMessageCount() > 0) {
string scmd = controllerPipe->NewestMessage();
AnyCollection cmd;
if(!cmd.read(scmd.c_str())) {
fprintf(stderr,"SerialController: Unable to parse incoming message %s\n",scmd.c_str());
return;
}
SmartPointer<AnyCollection> qcmdptr = cmd.find("qcmd");
SmartPointer<AnyCollection> dqcmdptr = cmd.find("dqcmd");
SmartPointer<AnyCollection> torquecmdptr = cmd.find("torquecmd");
SmartPointer<AnyCollection> tcmdptr = cmd.find("tcmd");
if(qcmdptr) {
vector<Real> qcmd,dqcmd,torquecmd;
if(!qcmdptr->asvector(qcmd)) {
fprintf(stderr,"SerialController: qcmd not of proper type\n");
return;
}
if(dqcmdptr) {
if(!dqcmdptr->asvector(dqcmd)) {
fprintf(stderr,"SerialController: dqcmd not of proper type\n");
return;
}
}
else
dqcmd.resize(qcmd.size(),0);
if(torquecmdptr) {
if(!torquecmdptr->asvector(torquecmd)) {
fprintf(stderr,"SerialController: torquecmd not of proper type\n");
return;
}
}
if(torquecmd.empty()) {
SetPIDCommand(qcmd,dqcmd);
}
else
SetFeedforwardPIDCommand(qcmd,dqcmd,torquecmd);
}
else if(dqcmdptr) {
if(tcmdptr == NULL) {
fprintf(stderr,"SerialController: dqcmd not given with tcmd\n");
return;
}
FatalError("Velocity commands not implemented yet");
}
else if(torquecmdptr) {
vector<Real> torquecmd;
if(!torquecmdptr->asvector(torquecmd)) {
fprintf(stderr,"SerialController: torquecmd not of proper type\n");
return;
}
SetTorqueCommand(torquecmd);
}
else {
fprintf(stderr,"SerialController: message doesn't contain proper command type\n");
return;
}
}
#endif //WIN32
}
void SerialController::Reset()
{
RobotController::Reset();
lastWriteTime = 0;
}
map<string,string> SerialController::Settings() const
{
map<string,string> settings;
FILL_CONTROLLER_SETTING(settings,servAddr);
FILL_CONTROLLER_SETTING(settings,writeRate);
if(controllerPipe)
settings["connected"]="1";
else
settings["connected"]="0";
return settings;
}
bool SerialController::GetSetting(const string& name,string& str) const
{
READ_CONTROLLER_SETTING(servAddr)
READ_CONTROLLER_SETTING(writeRate)
return false;
}
bool SerialController::SetSetting(const string& name,const string& str)
{
if(name == "servAddr") {
OpenConnection(str);
return true;
}
WRITE_CONTROLLER_SETTING(writeRate)
return false;
}
bool SerialController::OpenConnection(const string& addr)
{
servAddr = addr;
if(addr.empty()) {
CloseConnection();
return true;
}
controllerPipe = new SocketPipeWorker(addr.c_str(),true);
if(!controllerPipe->Start()) {
cout<<"Controller could not be opened on address "<<addr<<endl;
return false;
}
return true;
}
bool SerialController::CloseConnection()
{
if(controllerPipe) {
controllerPipe->Stop();
controllerPipe = NULL;
return true;
}
return false;
}
<commit_msg>Doesn't queue up messages if no client is connected<commit_after>#include "SerialController.h"
#include <utils/AnyCollection.h>
SerialController::SerialController(Robot& robot,const string& _servAddr,Real _writeRate)
:RobotController(robot),servAddr(_servAddr),writeRate(_writeRate),lastWriteTime(0)
{
if(!servAddr.empty())
OpenConnection(servAddr);
}
void SerialController::PackSensorData(AnyCollection& data) const
{
data["t"] = time;
data["dt"] = 1.0/writeRate;
for(size_t i=0;i<sensors->sensors.size();i++) {
vector<double> values;
sensors->sensors[i]->GetMeasurements(values);
data[sensors->sensors[i]->name] = AnyCollection(values);
}
}
void SerialController::Update(Real dt)
{
RobotController::Update(dt);
#ifndef WIN32
if(time >= lastWriteTime + 1.0/writeRate) {
lastWriteTime += 1.0/writeRate;
if(time >= lastWriteTime + 1.0/writeRate) {
printf("Warning, next write time %g is less than controller update time %g\n",lastWriteTime+1.0/writeRate,time);
lastWriteTime = time;
}
AnyCollection sensorData;
PackSensorData(sensorData);
stringstream ss;
ss << sensorData;
if(controllerPipe && controllerPipe->transport->WriteReady()) {
controllerPipe->SendMessage(ss.str());
}
}
if(controllerPipe && controllerPipe->NewMessageCount() > 0) {
string scmd = controllerPipe->NewestMessage();
AnyCollection cmd;
if(!cmd.read(scmd.c_str())) {
fprintf(stderr,"SerialController: Unable to parse incoming message %s\n",scmd.c_str());
return;
}
SmartPointer<AnyCollection> qcmdptr = cmd.find("qcmd");
SmartPointer<AnyCollection> dqcmdptr = cmd.find("dqcmd");
SmartPointer<AnyCollection> torquecmdptr = cmd.find("torquecmd");
SmartPointer<AnyCollection> tcmdptr = cmd.find("tcmd");
if(qcmdptr) {
vector<Real> qcmd,dqcmd,torquecmd;
if(!qcmdptr->asvector(qcmd)) {
fprintf(stderr,"SerialController: qcmd not of proper type\n");
return;
}
if(dqcmdptr) {
if(!dqcmdptr->asvector(dqcmd)) {
fprintf(stderr,"SerialController: dqcmd not of proper type\n");
return;
}
}
else
dqcmd.resize(qcmd.size(),0);
if(torquecmdptr) {
if(!torquecmdptr->asvector(torquecmd)) {
fprintf(stderr,"SerialController: torquecmd not of proper type\n");
return;
}
}
if(torquecmd.empty()) {
SetPIDCommand(qcmd,dqcmd);
}
else
SetFeedforwardPIDCommand(qcmd,dqcmd,torquecmd);
}
else if(dqcmdptr) {
if(tcmdptr == NULL) {
fprintf(stderr,"SerialController: dqcmd not given with tcmd\n");
return;
}
FatalError("Velocity commands not implemented yet");
}
else if(torquecmdptr) {
vector<Real> torquecmd;
if(!torquecmdptr->asvector(torquecmd)) {
fprintf(stderr,"SerialController: torquecmd not of proper type\n");
return;
}
SetTorqueCommand(torquecmd);
}
else {
fprintf(stderr,"SerialController: message doesn't contain proper command type\n");
return;
}
}
#endif //WIN32
}
void SerialController::Reset()
{
RobotController::Reset();
lastWriteTime = 0;
}
map<string,string> SerialController::Settings() const
{
map<string,string> settings;
FILL_CONTROLLER_SETTING(settings,servAddr);
FILL_CONTROLLER_SETTING(settings,writeRate);
if(controllerPipe)
settings["connected"]="1";
else
settings["connected"]="0";
return settings;
}
bool SerialController::GetSetting(const string& name,string& str) const
{
READ_CONTROLLER_SETTING(servAddr)
READ_CONTROLLER_SETTING(writeRate)
if(name=="connected") {
if(controllerPipe)
str = "1";
else
str = "0";
}
return false;
}
bool SerialController::SetSetting(const string& name,const string& str)
{
if(name == "servAddr") {
OpenConnection(str);
return true;
}
WRITE_CONTROLLER_SETTING(writeRate)
return false;
}
bool SerialController::OpenConnection(const string& addr)
{
servAddr = addr;
if(addr.empty()) {
CloseConnection();
return true;
}
controllerPipe = new SocketPipeWorker(addr.c_str(),true);
if(!controllerPipe->Start()) {
cout<<"Controller could not be opened on address "<<addr<<endl;
return false;
}
return true;
}
bool SerialController::CloseConnection()
{
if(controllerPipe) {
controllerPipe->Stop();
controllerPipe = NULL;
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#ifndef SURFACE_H
#define SURFACE_H
#include "scene.hpp"
#include "ray.hpp"
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <vector>
class Surface {
Scene& scene;
int width;
int height;
bool rendered;
cairo_surface_t* cairo_surface;
cairo_t* cr;
Display *dsp;
std::vector<std::vector<Color> > buffer;
public:
Ray get_ray(int x, int y) {
return scene.get_ray((x - width/2.0) / width, (y - height/2.0) / width);
}
std::pair<int, int> get_coord(Point p) {
auto pair = scene.get_coord(p);
return {(pair.first*width + width)/2, (pair.second*width + height)/2};
}
void draw_pixel(int x, int y, Color c) {
cairo_set_source_rgb(cr, c.x, c.y, c.z);
cairo_rectangle(cr, x, y, 1, 1);
cairo_fill(cr);
}
void enchance_balance() {
double factor = -INFINITY;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
for (int comp = 0; comp < 3; ++comp) {
double cur = buffer[x][y].coord[comp];
if (cur > factor) {
factor = cur;
}
}
}
}
if (almost_zero(factor)) {
return;
}
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
buffer[x][y] /= factor;
}
}
};
void render() {
if (width == 0 || rendered) {
printf("skip");
return;
}
printf("(%i %i)\n", width, height);
buffer = std::vector<std::vector<Color> >(width, std::vector<Color>(height));
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
Color c = scene.trace_ray(get_ray(x, y));
buffer[x][y] = c;
}
}
enchance_balance();
rendered = true;
}
void draw() {
printf("draw");
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
draw_pixel(x, y, buffer[x][y]);
}
}
}
Surface(Scene& scene, int width = 0, int height = 0) : scene(scene), width(width), height(height), rendered(false) {
Drawable da;
Screen *scr;
int screen;
cairo_surface_t *sfc;
if ((dsp = XOpenDisplay(NULL)) == NULL) {
exit(1);
}
screen = DefaultScreen(dsp);
scr = DefaultScreenOfDisplay(dsp);
width = WidthOfScreen(scr), height = HeightOfScreen(scr);
da = XCreateSimpleWindow(dsp, DefaultRootWindow(dsp), 0, 0, width, height, 0, 0, 0);
XSelectInput(dsp, da, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask);
XMapWindow(dsp, da);
sfc = cairo_xlib_surface_create(dsp, da, DefaultVisual(dsp, screen), width, height);
cairo_xlib_surface_set_size(sfc, width, height);
cairo_surface = sfc;
cr = cairo_create(sfc);
render();
}
void event_loop() {
double angle = 0;
while (1) {
XEvent report;
XNextEvent(dsp, &report);
switch (report.type) {
case Expose:
if (report.xexpose.count != 0) {
break;
}
render();
draw();
break;
case ConfigureNotify:
/* Window has been resized; change width
* and height to send to place_text and
* place_graphics in next Expose */
if (width == report.xconfigure.width && height == report.xconfigure.height) {
break;
}
width = report.xconfigure.width;
height = report.xconfigure.height;
render();
draw();
break;
case ButtonPress:
case KeyPress:
printf("ok");
switch (report.xkey.keycode) {
case 113:
angle += 0.6;
break;
case 114:
angle -= 0.6;
break;
default:
continue;
}
scene.find_best_view(angle);
rendered = false;
render();
draw();
default:
/* All events selected by StructureNotifyMask
* except ConfigureNotify are thrown away here,
* since nothing is done with them */
break;
} /* End switch */
}
}
~Surface() {
cairo_destroy(cr);
cairo_surface_destroy(cairo_surface);
XCloseDisplay(dsp);
}
};
#endif
<commit_msg>add debug printfs<commit_after>#ifndef SURFACE_H
#define SURFACE_H
#include "scene.hpp"
#include "ray.hpp"
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <vector>
class Surface {
Scene& scene;
int width;
int height;
bool rendered;
cairo_surface_t* cairo_surface;
cairo_t* cr;
Display *dsp;
std::vector<std::vector<Color> > buffer;
public:
Ray get_ray(int x, int y) {
return scene.get_ray((x - width/2.0) / width, (y - height/2.0) / width);
}
std::pair<int, int> get_coord(Point p) {
auto pair = scene.get_coord(p);
return {(pair.first*width + width)/2, (pair.second*width + height)/2};
}
void draw_pixel(int x, int y, Color c) {
cairo_set_source_rgb(cr, c.x, c.y, c.z);
cairo_rectangle(cr, x, y, 1, 1);
cairo_fill(cr);
}
void enchance_balance() {
double factor = -INFINITY;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
for (int comp = 0; comp < 3; ++comp) {
double cur = buffer[x][y].coord[comp];
if (cur > factor) {
factor = cur;
}
}
}
}
if (almost_zero(factor)) {
return;
}
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
buffer[x][y] /= factor;
}
}
};
void render() {
if (width == 0 || rendered) {
return;
}
buffer = std::vector<std::vector<Color> >(width, std::vector<Color>(height));
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
Color c = scene.trace_ray(get_ray(x, y));
buffer[x][y] = c;
}
}
enchance_balance();
rendered = true;
}
void draw() {
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
draw_pixel(x, y, buffer[x][y]);
}
}
}
Surface(Scene& scene, int width = 0, int height = 0) : scene(scene), width(width), height(height), rendered(false) {
Drawable da;
Screen *scr;
int screen;
cairo_surface_t *sfc;
if ((dsp = XOpenDisplay(NULL)) == NULL) {
exit(1);
}
screen = DefaultScreen(dsp);
scr = DefaultScreenOfDisplay(dsp);
width = WidthOfScreen(scr), height = HeightOfScreen(scr);
da = XCreateSimpleWindow(dsp, DefaultRootWindow(dsp), 0, 0, width, height, 0, 0, 0);
XSelectInput(dsp, da, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask);
XMapWindow(dsp, da);
sfc = cairo_xlib_surface_create(dsp, da, DefaultVisual(dsp, screen), width, height);
cairo_xlib_surface_set_size(sfc, width, height);
cairo_surface = sfc;
cr = cairo_create(sfc);
render();
}
void event_loop() {
double angle = 0;
while (1) {
XEvent report;
XNextEvent(dsp, &report);
switch (report.type) {
case Expose:
if (report.xexpose.count != 0) {
break;
}
render();
draw();
break;
case ConfigureNotify:
/* Window has been resized; change width
* and height to send to place_text and
* place_graphics in next Expose */
if (width == report.xconfigure.width && height == report.xconfigure.height) {
break;
}
width = report.xconfigure.width;
height = report.xconfigure.height;
render();
draw();
break;
case ButtonPress:
case KeyPress:
switch (report.xkey.keycode) {
case 113:
angle += 0.6;
break;
case 114:
angle -= 0.6;
break;
default:
continue;
}
scene.find_best_view(angle);
rendered = false;
render();
draw();
default:
/* All events selected by StructureNotifyMask
* except ConfigureNotify are thrown away here,
* since nothing is done with them */
break;
} /* End switch */
}
}
~Surface() {
cairo_destroy(cr);
cairo_surface_destroy(cairo_surface);
XCloseDisplay(dsp);
}
};
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
static bool DONE = false;
static int CLIENT_PID = false;
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor; commanding client [" << CLIENT_PID << "] to shut down.";
int rc = kill(CLIENT_PID, SIGTERM);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to shut down failed: [" << errno << "] " << strerror(errno);
}
DONE = true;
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG(FATAL) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
LOG_TOPIC(INFO, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(INFO, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child " << _clientPid
<< " died of natural causes";
done = true;
horrible = false;
} else {
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, exit status " << WEXITSTATUS(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the error "
"first";
done = true;
} else {
done = false;
}
}
} else if (WIFSIGNALED(status)) {
switch (WTERMSIG(status)) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child " << _clientPid
<< " died of natural causes, exit status " << WTERMSIG(status);
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP) << "child " << _clientPid
<< " died a horrible death, signal "
<< WTERMSIG(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the "
"error first";
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " produced a core dump";
}
#endif
} else {
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, unknown cause";
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<commit_msg>forward SIG_HUP from supervisor<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
static bool DONE = false;
static int CLIENT_PID = false;
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor; commanding client [" << CLIENT_PID << "] to shut down.";
int rc = kill(CLIENT_PID, SIGTERM);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to shut down failed: [" << errno << "] " << strerror(errno);
}
DONE = true;
}
static void HUPHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGHUP for supervisor; commanding client [" << CLIENT_PID << "] to logrotate.";
int rc = kill(CLIENT_PID, SIGHUP);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to logrotate failed: [" << errno << "] " << strerror(errno);
}
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG(FATAL) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
signal(SIGHUP, HUPHandler);
LOG_TOPIC(INFO, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(INFO, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child " << _clientPid
<< " died of natural causes";
done = true;
horrible = false;
} else {
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, exit status " << WEXITSTATUS(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the error "
"first";
done = true;
} else {
done = false;
}
}
} else if (WIFSIGNALED(status)) {
switch (WTERMSIG(status)) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child " << _clientPid
<< " died of natural causes, exit status " << WTERMSIG(status);
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP) << "child " << _clientPid
<< " died a horrible death, signal "
<< WTERMSIG(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the "
"error first";
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " produced a core dump";
}
#endif
} else {
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, unknown cause";
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: workingsetoptions.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-11-11 08:55:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef GCC
#pragma hdrstop
#endif
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "workingsetoptions.hxx"
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#include <itemholder1.hxx>
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl ;
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::com::sun::star::uno ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_WORKINGSET OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/WorkingSet"))
#define DEFAULT_WINDOWLIST Sequence< OUString >()
#define PROPERTYNAME_WINDOWLIST OUString(RTL_CONSTASCII_USTRINGPARAM("WindowList" ))
#define PROPERTYHANDLE_WINDOWLIST 0
#define PROPERTYCOUNT 1
//_________________________________________________________________________________________________________________
// private declarations!
//_________________________________________________________________________________________________________________
class SvtWorkingSetOptions_Impl : public ConfigItem
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtWorkingSetOptions_Impl();
~SvtWorkingSetOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short called for notify of configmanager
@descr These method is called from the ConfigManager before application ends or from the
PropertyChangeListener if the sub tree broadcasts changes. You must update your
internal values.
@seealso baseclass ConfigItem
@param "seqPropertyNames" is the list of properties which should be updated.
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Notify( const Sequence< OUString >& seqPropertyNames );
/*-****************************************************************************************************//**
@short write changes to configuration
@descr These method writes the changed values into the sub tree
and should always called in our destructor to guarantee consistency of config data.
@seealso baseclass ConfigItem
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short access method to get internal values
@descr These method give us a chance to regulate acces to ouer internal values.
It's not used in the moment - but it's possible for the feature!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
Sequence< OUString > GetWindowList( ) const ;
void SetWindowList( const Sequence< OUString >& seqWindowList ) ;
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return list of key names of ouer configuration management which represent oue module tree
@descr These methods return a static const list of key names. We need it to get needed values from our
configuration management.
@seealso -
@param -
@return A list of needed configuration keys is returned.
@onerror -
*//*-*****************************************************************************************************/
static Sequence< OUString > GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
Sequence< OUString > m_seqWindowList ;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()
// Init baseclasses first
: ConfigItem ( ROOTNODE_WORKINGSET )
// Init member then.
, m_seqWindowList ( DEFAULT_WINDOWLIST )
{
// Use our static list of configuration keys to get his values.
Sequence< OUString > seqNames = GetPropertyNames ( );
Sequence< Any > seqValues = GetProperties ( seqNames );
// Safe impossible cases.
// We need values from ALL configuration keys.
// Follow assignment use order of values in relation to our list of key names!
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to ouer internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
// Safe impossible cases.
// Check any for valid value.
DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nInvalid property value detected!\n" );
switch( nProperty )
{
case PROPERTYHANDLE_WINDOWLIST : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" );
seqValues[nProperty] >>= m_seqWindowList;
}
break;
}
}
// Enable notification mechanism of ouer baseclass.
// We need it to get information about changes outside these class on ouer used configuration keys!
EnableNotification( seqNames );
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl::~SvtWorkingSetOptions_Impl()
{
// We must save our current values .. if user forget it!
if( IsModified() == sal_True )
{
Commit();
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
// Use given list of updated properties to get his values from configuration directly!
Sequence< Any > seqValues = GetProperties( seqPropertyNames );
// Safe impossible cases.
// We need values from ALL notified configuration keys.
DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
// Step over list of property names and get right value from coreesponding value list to set it on internal members!
sal_Int32 nCount = seqPropertyNames.getLength();
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
if( seqPropertyNames[nProperty] == PROPERTYNAME_WINDOWLIST )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" );
seqValues[nProperty] >>= m_seqWindowList;
}
#if OSL_DEBUG_LEVEL > 1
else DBG_ASSERT( sal_False, "SvtWorkingSetOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
#endif
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::Commit()
{
// Get names of supported properties, create a list for values and copy current values to it.
Sequence< OUString > seqNames = GetPropertyNames ();
sal_Int32 nCount = seqNames.getLength();
Sequence< Any > seqValues ( nCount );
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_WINDOWLIST : {
seqValues[nProperty] <<= m_seqWindowList;
}
break;
}
}
// Set properties in configuration.
PutProperties( seqNames, seqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions_Impl::GetWindowList() const
{
return m_seqWindowList;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::SetWindowList( const Sequence< OUString >& seqWindowList )
{
m_seqWindowList = seqWindowList;
SetModified();
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions_Impl::GetPropertyNames()
{
// Build static list of configuration key names.
static const OUString pProperties[] =
{
PROPERTYNAME_WINDOWLIST ,
};
// Initialize return sequence with these list ...
static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl* SvtWorkingSetOptions::m_pDataContainer = NULL ;
sal_Int32 SvtWorkingSetOptions::m_nRefCount = 0 ;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtWorkingSetOptions::SvtWorkingSetOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already exist!
if( m_pDataContainer == NULL )
{
m_pDataContainer = new SvtWorkingSetOptions_Impl;
ItemHolder1::holdConfigItem(E_WORKINGSETOPTIONS);
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtWorkingSetOptions::~SvtWorkingSetOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions::GetWindowList() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetWindowList();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions::SetWindowList( const Sequence< OUString >& seqWindowList )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetWindowList( seqWindowList );
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtWorkingSetOptions::GetOwnStaticMutex()
{
// Initialize static mutex only for one time!
static Mutex* pMutex = NULL;
// If these method first called (Mutex not already exist!) ...
if( pMutex == NULL )
{
// ... we must create a new one. Protect follow code with the global mutex -
// It must be - we create a static variable!
MutexGuard aGuard( Mutex::getGlobalMutex() );
// We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!
if( pMutex == NULL )
{
// Create the new mutex and set it for return on static variable.
static Mutex aMutex;
pMutex = &aMutex;
}
}
// Return new created or already existing mutex object.
return *pMutex;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.276); FILE MERGED 2006/09/01 17:42:51 kaib 1.7.276.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: workingsetoptions.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:31:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef GCC
#endif
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "workingsetoptions.hxx"
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#include <itemholder1.hxx>
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl ;
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::com::sun::star::uno ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_WORKINGSET OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/WorkingSet"))
#define DEFAULT_WINDOWLIST Sequence< OUString >()
#define PROPERTYNAME_WINDOWLIST OUString(RTL_CONSTASCII_USTRINGPARAM("WindowList" ))
#define PROPERTYHANDLE_WINDOWLIST 0
#define PROPERTYCOUNT 1
//_________________________________________________________________________________________________________________
// private declarations!
//_________________________________________________________________________________________________________________
class SvtWorkingSetOptions_Impl : public ConfigItem
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtWorkingSetOptions_Impl();
~SvtWorkingSetOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short called for notify of configmanager
@descr These method is called from the ConfigManager before application ends or from the
PropertyChangeListener if the sub tree broadcasts changes. You must update your
internal values.
@seealso baseclass ConfigItem
@param "seqPropertyNames" is the list of properties which should be updated.
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Notify( const Sequence< OUString >& seqPropertyNames );
/*-****************************************************************************************************//**
@short write changes to configuration
@descr These method writes the changed values into the sub tree
and should always called in our destructor to guarantee consistency of config data.
@seealso baseclass ConfigItem
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short access method to get internal values
@descr These method give us a chance to regulate acces to ouer internal values.
It's not used in the moment - but it's possible for the feature!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
Sequence< OUString > GetWindowList( ) const ;
void SetWindowList( const Sequence< OUString >& seqWindowList ) ;
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return list of key names of ouer configuration management which represent oue module tree
@descr These methods return a static const list of key names. We need it to get needed values from our
configuration management.
@seealso -
@param -
@return A list of needed configuration keys is returned.
@onerror -
*//*-*****************************************************************************************************/
static Sequence< OUString > GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
Sequence< OUString > m_seqWindowList ;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()
// Init baseclasses first
: ConfigItem ( ROOTNODE_WORKINGSET )
// Init member then.
, m_seqWindowList ( DEFAULT_WINDOWLIST )
{
// Use our static list of configuration keys to get his values.
Sequence< OUString > seqNames = GetPropertyNames ( );
Sequence< Any > seqValues = GetProperties ( seqNames );
// Safe impossible cases.
// We need values from ALL configuration keys.
// Follow assignment use order of values in relation to our list of key names!
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to ouer internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
// Safe impossible cases.
// Check any for valid value.
DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nInvalid property value detected!\n" );
switch( nProperty )
{
case PROPERTYHANDLE_WINDOWLIST : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" );
seqValues[nProperty] >>= m_seqWindowList;
}
break;
}
}
// Enable notification mechanism of ouer baseclass.
// We need it to get information about changes outside these class on ouer used configuration keys!
EnableNotification( seqNames );
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl::~SvtWorkingSetOptions_Impl()
{
// We must save our current values .. if user forget it!
if( IsModified() == sal_True )
{
Commit();
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
// Use given list of updated properties to get his values from configuration directly!
Sequence< Any > seqValues = GetProperties( seqPropertyNames );
// Safe impossible cases.
// We need values from ALL notified configuration keys.
DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
// Step over list of property names and get right value from coreesponding value list to set it on internal members!
sal_Int32 nCount = seqPropertyNames.getLength();
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
if( seqPropertyNames[nProperty] == PROPERTYNAME_WINDOWLIST )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" );
seqValues[nProperty] >>= m_seqWindowList;
}
#if OSL_DEBUG_LEVEL > 1
else DBG_ASSERT( sal_False, "SvtWorkingSetOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
#endif
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::Commit()
{
// Get names of supported properties, create a list for values and copy current values to it.
Sequence< OUString > seqNames = GetPropertyNames ();
sal_Int32 nCount = seqNames.getLength();
Sequence< Any > seqValues ( nCount );
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_WINDOWLIST : {
seqValues[nProperty] <<= m_seqWindowList;
}
break;
}
}
// Set properties in configuration.
PutProperties( seqNames, seqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions_Impl::GetWindowList() const
{
return m_seqWindowList;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions_Impl::SetWindowList( const Sequence< OUString >& seqWindowList )
{
m_seqWindowList = seqWindowList;
SetModified();
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions_Impl::GetPropertyNames()
{
// Build static list of configuration key names.
static const OUString pProperties[] =
{
PROPERTYNAME_WINDOWLIST ,
};
// Initialize return sequence with these list ...
static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtWorkingSetOptions_Impl* SvtWorkingSetOptions::m_pDataContainer = NULL ;
sal_Int32 SvtWorkingSetOptions::m_nRefCount = 0 ;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtWorkingSetOptions::SvtWorkingSetOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already exist!
if( m_pDataContainer == NULL )
{
m_pDataContainer = new SvtWorkingSetOptions_Impl;
ItemHolder1::holdConfigItem(E_WORKINGSETOPTIONS);
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtWorkingSetOptions::~SvtWorkingSetOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
Sequence< OUString > SvtWorkingSetOptions::GetWindowList() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetWindowList();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtWorkingSetOptions::SetWindowList( const Sequence< OUString >& seqWindowList )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetWindowList( seqWindowList );
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtWorkingSetOptions::GetOwnStaticMutex()
{
// Initialize static mutex only for one time!
static Mutex* pMutex = NULL;
// If these method first called (Mutex not already exist!) ...
if( pMutex == NULL )
{
// ... we must create a new one. Protect follow code with the global mutex -
// It must be - we create a static variable!
MutexGuard aGuard( Mutex::getGlobalMutex() );
// We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!
if( pMutex == NULL )
{
// Create the new mutex and set it for return on static variable.
static Mutex aMutex;
pMutex = &aMutex;
}
}
// Return new created or already existing mutex object.
return *pMutex;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
#include <boost/program_options.hpp>
#include <llvm/ADT/STLExtras.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include "AST.h"
#include "Error.h"
#include "BuiltinFunctions.h"
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/IPO.h>
namespace po = boost::program_options;
using namespace Helen;
using namespace std;
int yyparse(AST*& ast);
extern FILE* yyin;
int main(int argc, char** argv)
{
// Boost Program Options setup
po::options_description desc("Compiler options");
desc.add_options()
("help,h", "display this help")
("version,v", "display version")
("input-file", po::value<string>(), "input file")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.empty()) {
cout << desc << "\n";
return 1;
}
AST::module = llvm::make_unique<Module>("__helenmodule__", getGlobalContext());
AST::fpm = llvm::make_unique<legacy::FunctionPassManager>(AST::module.get());
AST::dataLayout = llvm::make_unique<DataLayout>(AST::module.get());
AST::fpm->add(createBasicAliasAnalysisPass());
AST::fpm->add(createPromoteMemoryToRegisterPass());
AST::fpm->add(createInstructionCombiningPass());
AST::fpm->add(createReassociatePass());
AST::fpm->add(createGVNPass());
AST::fpm->add(createCFGSimplificationPass());
//AST::fpm->add(createFunctionInliningPass());
legacy::PassManager pm;
pm.add(createAlwaysInlinerPass());
AST::fpm->doInitialization();
yyin = fopen(vm["input-file"].as<string>().c_str(), "r");
AST::isMainModule = false;
AST* result;
yyparse(result);
if (Error::errorFlag) { // don't even try to compile if syntax errors present
fprintf(stderr, "Fatal errors detected: translation terminated\n");
return 1;
}
BuiltinFunctions::createMainFunction(AST::isMainModule);
result->codegen();
if (Error::errorFlag) {
fprintf(stderr, "Fatal errors detected: translation terminated\n");
return 1;
}
AST::builder.CreateRet(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0));
pm.run(*(AST::module.get()));
AST::module->dump();
//TODO: Add output file to program options
string filename = (argc >= 3) ? argv[2] : (argv[1] + string(".bc"));
std::error_code ec;
raw_fd_ostream fdos(filename, ec, sys::fs::OpenFlags::F_None);
WriteBitcodeToFile(AST::module.get(), fdos);
return 0;
}
<commit_msg>added include paths options<commit_after>#include <stdio.h>
#include <iostream>
#include <boost/program_options.hpp>
#include <llvm/ADT/STLExtras.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include "AST.h"
#include "Error.h"
#include "BuiltinFunctions.h"
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/IPO.h>
namespace po = boost::program_options;
using namespace Helen;
using namespace std;
vector<string> includePaths;
int yyparse(AST*& ast);
extern FILE* yyin;
int main(int argc, char** argv)
{
// Boost Program Options setup
po::options_description desc("Compiler options");
desc.add_options()
("help,h", "display this help")
("version,v", "display version")
("input-file", po::value<string>(), "input file")
("include-path,I", po::value<vector<string> >(), "path to include files")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.empty()) {
cout << desc << "\n";
return 1;
}
if(vm.count("include-path"))
includePaths = vm["include-path"].as<vector<string> >();
includePaths.push_back(".");
//TODO: add stdlib dirs to include paths
AST::module = llvm::make_unique<Module>("__helenmodule__", getGlobalContext());
AST::fpm = llvm::make_unique<legacy::FunctionPassManager>(AST::module.get());
AST::dataLayout = llvm::make_unique<DataLayout>(AST::module.get());
AST::fpm->add(createBasicAliasAnalysisPass());
AST::fpm->add(createPromoteMemoryToRegisterPass());
AST::fpm->add(createInstructionCombiningPass());
AST::fpm->add(createReassociatePass());
AST::fpm->add(createGVNPass());
AST::fpm->add(createCFGSimplificationPass());
//AST::fpm->add(createFunctionInliningPass());
legacy::PassManager pm;
pm.add(createAlwaysInlinerPass());
AST::fpm->doInitialization();
yyin = fopen(vm["input-file"].as<string>().c_str(), "r");
AST::isMainModule = false;
AST* result;
yyparse(result);
if (Error::errorFlag) { // don't even try to compile if syntax errors present
fprintf(stderr, "Fatal errors detected: translation terminated\n");
return 1;
}
BuiltinFunctions::createMainFunction(AST::isMainModule);
result->codegen();
if (Error::errorFlag) {
fprintf(stderr, "Fatal errors detected: translation terminated\n");
return 1;
}
AST::builder.CreateRet(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0));
pm.run(*(AST::module.get()));
AST::module->dump();
//TODO: Add output file to program options
string filename = (argc >= 3) ? argv[2] : (argv[1] + string(".bc"));
std::error_code ec;
raw_fd_ostream fdos(filename, ec, sys::fs::OpenFlags::F_None);
WriteBitcodeToFile(AST::module.get(), fdos);
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************\
**
** tRunTimer.cpp: functions for tRunTimer objects.
**
** tRunTimer objects are used to keep track of time in a time-evolving
** simulation model. Their services include keeping track of when it's
** time to write output, printing the current time to standard output if
** desired, and writing the current time to a file every so often.
**
** Version 1.0, Greg Tucker, November 1997
**
** Potential additions/improvements:
** - add functions to set output interval and time status notification
** interval
**
** $Id: tRunTimer.cpp,v 1.11 2000-06-05 22:13:27 daniel Exp $
\***************************************************************************/
#include <iostream.h>
#include <fstream.h>
#include <assert.h>
#include "../tInputFile/tInputFile.h"
#include "tRunTimer.h"
//****************************************************
// Constructors
//
// - A default constructor
// - A constructor that sets the run duration and
// output interval (and if desired sets the option
// to print time steps to stdout; default is 1,
// see header file)
// - A constructor that reads run duration and
// output interval from a tInputFile object (and
// if desired sets the option
// to print time steps to stdout; default is 1,
// see header file)
// NG changed this constructor so that if layering
// info is read in, the start time is set to the
// time which layers are read in. Must have this
// for the layering to make sense, but might also
// want this if reading in any type of input other
// than the standard parameters. (OPTREADINPUT>0)
// Wasn't changed because I don't know how other
// people want this handled. Bad practice to have
// something about layering in here though.
//
// Note that the notifyInterval is always initialized
// at 1000, but of course this could be changed.
//****************************************************
tRunTimer::tRunTimer()
{
currentTime = 0;
endTime = 1;
outputInterval = 1;
nextOutputTime = 0;
optPrintEachTime = 1;
notifyInterval = 1000;
nextNotify = 0;
TSOutputInterval = 1;
nextTSOutputTime = 0;
}
tRunTimer::tRunTimer( double duration, double opint, int optprint )
{
currentTime = 0;
endTime = duration;
outputInterval = opint;
nextOutputTime = 0;
optPrintEachTime = optprint;
notifyInterval = 1000;
nextNotify = 0;
nextTSOutputTime = 999999999
}
tRunTimer::tRunTimer( tInputFile &infile, int optprint )
{
endTime = infile.ReadItem( endTime, "RUNTIME" );
outputInterval = infile.ReadItem( outputInterval, "OPINTRVL" );
optPrintEachTime = optprint;
notifyInterval = 1000;
optTSOutput = infile.ReadItem( optTSOutput, "OPTTSOUTPUT" );
if( optTSOutput )
TSOutput = infile.ReadItem( TSOutputInterval, "TSOPINTRVL" );
double help;
//If you are reading in layering information, the timer should
//be set to the time in which the layers were output, since
//time is tracked in the layers and restarting at time zero
//would make the layer times non-sensical.
help = infile.ReadItem( help, "OPTREADINPUT" );
if(help>0){
help = infile.ReadItem( help, "INPUTTIME" );
currentTime = help;
endTime += help;
nextOutputTime = help;
nextNotify = help;
}
else{
nextOutputTime = 0;
nextNotify = 0;
currentTime = 0;
}
}
//****************************************************
// Start
//
// Sets the current time and run duration.
//****************************************************
void tRunTimer::Start( double start, double end )
{
currentTime = start;
if( end>0.0 ) endTime = end;
}
//****************************************************
// getCurrentTime
//
// Returns the current time.
//****************************************************
double tRunTimer::getCurrentTime()
{
return currentTime;
}
//****************************************************
// RemainingTime
//
// Returns the remaining time.
//****************************************************
double tRunTimer::RemainingTime()
{
return endTime - currentTime;
}
//****************************************************
// Advance
//
// Increments the current time by dt.
// Returns 1 if there is still time
// remaining, 0 if the time is up.
//****************************************************
int tRunTimer::Advance( double dt )
{
currentTime += dt;
return( currentTime < endTime );
}
//****************************************************
// ReportTimeStatus
//
// Reports the current time to a file and to
// standard output if desired. Output to file is
// only done at selected intervals.
// Compares currentTime with nextNotify to see
// whether it's time to update the time status file,
// and if so opens the file and writes the current
// time (overwriting any previous contents).
// Regardless of the status of nextNotify, if
// optPrintEachTime is selected, the current time is
// reported to cout.
//****************************************************
void tRunTimer::ReportTimeStatus()
{
if( optPrintEachTime ) cout << currentTime << endl;
if( currentTime >= nextNotify )
{
timeStatusFile.open( "run.time" );
assert( timeStatusFile.good() );
timeStatusFile << currentTime << endl;
timeStatusFile.close();
nextNotify += notifyInterval;
}
}
//*************************************************
// CheckOutputTime
//
// Checks to see whether it's time to write output
// yet.
//*************************************************
int tRunTimer::CheckOutputTime()
{
if( currentTime>=nextOutputTime )
{
nextOutputTime += outputInterval;
return 1;
}
else return 0;
}
//*************************************************
// CheckTSOutputTime
//
// Checks to see weather it's time to write time
// series output yet.
//*************************************************
int tRunTimer::CheckTSOutputTime()
{
if( currentTime >= nextTSOutputTime )
{
nextTSOutputTime += TSoutputInterval;
return 1;
}
else return 0;
}
//*************************************************
// IsFinished
//
// Checks to see whether the run is finished.
//*************************************************
int tRunTimer::IsFinished()
{
return( currentTime >= endTime );
}
<commit_msg>*** empty log message ***<commit_after>/***************************************************************************\
**
** tRunTimer.cpp: functions for tRunTimer objects.
**
** tRunTimer objects are used to keep track of time in a time-evolving
** simulation model. Their services include keeping track of when it's
** time to write output, printing the current time to standard output if
** desired, and writing the current time to a file every so often.
**
** Version 1.0, Greg Tucker, November 1997
**
** Potential additions/improvements:
** - add functions to set output interval and time status notification
** interval
**
** $Id: tRunTimer.cpp,v 1.12 2000-06-05 22:18:17 daniel Exp $
\***************************************************************************/
#include <iostream.h>
#include <fstream.h>
#include <assert.h>
#include "../tInputFile/tInputFile.h"
#include "tRunTimer.h"
//****************************************************
// Constructors
//
// - A default constructor
// - A constructor that sets the run duration and
// output interval (and if desired sets the option
// to print time steps to stdout; default is 1,
// see header file)
// - A constructor that reads run duration and
// output interval from a tInputFile object (and
// if desired sets the option
// to print time steps to stdout; default is 1,
// see header file)
// NG changed this constructor so that if layering
// info is read in, the start time is set to the
// time which layers are read in. Must have this
// for the layering to make sense, but might also
// want this if reading in any type of input other
// than the standard parameters. (OPTREADINPUT>0)
// Wasn't changed because I don't know how other
// people want this handled. Bad practice to have
// something about layering in here though.
//
// Note that the notifyInterval is always initialized
// at 1000, but of course this could be changed.
//****************************************************
tRunTimer::tRunTimer()
{
currentTime = 0;
endTime = 1;
outputInterval = 1;
nextOutputTime = 0;
optPrintEachTime = 1;
notifyInterval = 1000;
nextNotify = 0;
TSOutputInterval = 1;
nextTSOutputTime = 0;
}
tRunTimer::tRunTimer( double duration, double opint, int optprint )
{
currentTime = 0;
endTime = duration;
outputInterval = opint;
nextOutputTime = 0;
optPrintEachTime = optprint;
notifyInterval = 1000;
nextNotify = 0;
nextTSOutputTime = 999999999
}
tRunTimer::tRunTimer( tInputFile &infile, int optprint )
{
endTime = infile.ReadItem( endTime, "RUNTIME" );
outputInterval = infile.ReadItem( outputInterval, "OPINTRVL" );
optPrintEachTime = optprint;
notifyInterval = 1000;
optTSOutput = infile.ReadItem( optTSOutput, "OPTTSOUTPUT" );
if( optTSOutput )
TSOutput = infile.ReadItem( TSOutputInterval, "TSOPINTRVL" );
double help;
//If you are reading in layering information, the timer should
//be set to the time in which the layers were output, since
//time is tracked in the layers and restarting at time zero
//would make the layer times non-sensical.
help = infile.ReadItem( help, "OPTREADINPUT" );
if(help>0){
help = infile.ReadItem( help, "INPUTTIME" );
currentTime = help;
endTime += help;
nextOutputTime = help;
nextNotify = help;
}
else{
nextOutputTime = 0;
nextNotify = 0;
currentTime = 0;
}
}
//****************************************************
// Start
//
// Sets the current time and run duration.
//****************************************************
void tRunTimer::Start( double start, double end )
{
currentTime = start;
if( end>0.0 ) endTime = end;
}
//****************************************************
// getCurrentTime
//
// Returns the current time.
//****************************************************
double tRunTimer::getCurrentTime()
{
return currentTime;
}
//****************************************************
// RemainingTime
//
// Returns the remaining time.
//****************************************************
double tRunTimer::RemainingTime()
{
return endTime - currentTime;
}
//****************************************************
// Advance
//
// Increments the current time by dt.
// Returns 1 if there is still time
// remaining, 0 if the time is up.
//****************************************************
int tRunTimer::Advance( double dt )
{
currentTime += dt;
return( currentTime < endTime );
}
//****************************************************
// ReportTimeStatus
//
// Reports the current time to a file and to
// standard output if desired. Output to file is
// only done at selected intervals.
// Compares currentTime with nextNotify to see
// whether it's time to update the time status file,
// and if so opens the file and writes the current
// time (overwriting any previous contents).
// Regardless of the status of nextNotify, if
// optPrintEachTime is selected, the current time is
// reported to cout.
//****************************************************
void tRunTimer::ReportTimeStatus()
{
if( optPrintEachTime ) cout << currentTime << endl;
if( currentTime >= nextNotify )
{
timeStatusFile.open( "run.time" );
assert( timeStatusFile.good() );
timeStatusFile << currentTime << endl;
timeStatusFile.close();
nextNotify += notifyInterval;
}
}
//*************************************************
// CheckOutputTime
//
// Checks to see whether it's time to write output
// yet.
//*************************************************
int tRunTimer::CheckOutputTime()
{
if( currentTime>=nextOutputTime )
{
nextOutputTime += outputInterval;
return 1;
}
else return 0;
}
//*************************************************
// CheckTSOutputTime
//
// Checks to see weather it's time to write time
// series output yet.
//*************************************************
int tRunTimer::CheckTSOutputTime()
{
if( currentTime >= nextTSOutputTime )
{
nextTSOutputTime += TSOutputInterval;
return 1;
}
else return 0;
}
//*************************************************
// IsFinished
//
// Checks to see whether the run is finished.
//*************************************************
int tRunTimer::IsFinished()
{
return( currentTime >= endTime );
}
<|endoftext|> |
<commit_before>// StdLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "StdLib.h"
#include "../EScript/EScript.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Compiler/Parser.h"
#include "../EScript/Utils/IO/IO.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
#include <unistd.h>
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if (!o) return;
if (level>maxLevel) {
std::cout << " ... \n";
return;
}
if (Array * a=dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef=a->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "]";
} else if (Map * m=dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef=m->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)
std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "}";
} else {
if (dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef=searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m=dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m=Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj=m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(String::create(condensedFilename),Bool::create(true));
return _loadAndExecute(runtime,condensedFilename);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION_DECLARE(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
runtime.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return Void::get();
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION_DECLARE(globals,"assert",1,2, {
assertParamCount(runtime,parameter.count(),1,2);
if(!parameter[0]->toBool()){
runtime.setException(parameter.count()>1?parameter[1]->toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUNCTION_DECLARE(globals,"chr",1,1,{
std::ostringstream s;
s<< static_cast<char>(parameter[0]->toInt());
return String::create(s.str());
})
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION_DECLARE(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return Number::create( static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart) );
})
#else
//! [ESF] number clock()
ESF_DECLARE(globals,"clock",0,0,Number::create( static_cast<double>(clock())/CLOCKS_PER_SEC))
#endif
}
//! [ESF] Object eval(string)
ESF_DECLARE(globals,"eval",1,1,
_eval(runtime,CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString()))).detachAndDecrease())
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION_DECLARE(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0]->toInt());
tm d;
localtime_r(&t, &d);
Map * m=Map::create();
m->setValue(String::create("seconds"),Number::create(d.tm_sec));
m->setValue(String::create("minutes"),Number::create(d.tm_min));
m->setValue(String::create("hours"),Number::create(d.tm_hour));
m->setValue(String::create("mday"),Number::create(d.tm_mday));
m->setValue(String::create("mon"),Number::create(d.tm_mon+1));
m->setValue(String::create("year"),Number::create(d.tm_year+1900));
m->setValue(String::create("wday"),Number::create(d.tm_wday));
m->setValue(String::create("yday"),Number::create(d.tm_yday));
m->setValue(String::create("isdst"),Number::create(d.tm_isdst));
return m;
})
//! [ESF] string getOS()
ESF_DECLARE(globals,"getOS",0,0,String::create(StdLib::getOS()))
//! [ESF] Runtime getRuntime( )
ESF_DECLARE(globals,"getRuntime",0,0, &runtime)
//! [ESF] mixed load(string filename)
ESF_DECLARE(globals,"load",1,1,_loadAndExecute(runtime,findFile(runtime,parameter[0].toString())).detachAndDecrease())
//! [ESF] mixed loadOnce(string filename)
ESF_DECLARE(globals,"loadOnce",1,1,StdLib::loadOnce(runtime,parameter[0].toString()).detachAndDecrease())
//! [ESF] void out(...)
ES_FUNCTION_DECLARE(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION_DECLARE(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION_DECLARE(globals,"parse",1,1, {
ERef<UserFunction> script;
Compiler compiler(runtime.getLogger());
script = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())));
return script.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ESF_DECLARE(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION_DECLARE(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ESF_DECLARE(globals,"system",1,1,Number::create(system(parameter[0]->toString().c_str())))
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION_DECLARE(globals, "exec", 2, 2, {
Array * array = assertType<Array>(runtime, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = Number::create(execv(parameter[0]->toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
//! [ESF] number time()
ESF_DECLARE(globals,"time",0,0,Number::create(static_cast<double>(time(nullptr))))
//! [ESF] string toJSON(obj[,formatted=true])
ESF_DECLARE(globals,"toJSON",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))
}
}
<commit_msg>Revert changeset 405 (localtime_r is not available on all platforms)<commit_after>// StdLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "StdLib.h"
#include "../EScript/EScript.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Compiler/Parser.h"
#include "../EScript/Utils/IO/IO.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
#include <unistd.h>
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if (!o) return;
if (level>maxLevel) {
std::cout << " ... \n";
return;
}
if (Array * a=dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef=a->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "]";
} else if (Map * m=dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef=m->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)
std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "}";
} else {
if (dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef=searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m=dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m=Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj=m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(String::create(condensedFilename),Bool::create(true));
return _loadAndExecute(runtime,condensedFilename);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION_DECLARE(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
runtime.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return Void::get();
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION_DECLARE(globals,"assert",1,2, {
assertParamCount(runtime,parameter.count(),1,2);
if(!parameter[0]->toBool()){
runtime.setException(parameter.count()>1?parameter[1]->toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUNCTION_DECLARE(globals,"chr",1,1,{
std::ostringstream s;
s<< static_cast<char>(parameter[0]->toInt());
return String::create(s.str());
})
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION_DECLARE(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return Number::create( static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart) );
})
#else
//! [ESF] number clock()
ESF_DECLARE(globals,"clock",0,0,Number::create( static_cast<double>(clock())/CLOCKS_PER_SEC))
#endif
}
//! [ESF] Object eval(string)
ESF_DECLARE(globals,"eval",1,1,
_eval(runtime,CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString()))).detachAndDecrease())
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION_DECLARE(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0]->toInt());
tm *d=localtime (& t );
Map * m=Map::create();
m->setValue(String::create("seconds"),Number::create(d->tm_sec));
m->setValue(String::create("minutes"),Number::create(d->tm_min));
m->setValue(String::create("hours"),Number::create(d->tm_hour));
m->setValue(String::create("mday"),Number::create(d->tm_mday));
m->setValue(String::create("mon"),Number::create(d->tm_mon+1));
m->setValue(String::create("year"),Number::create(d->tm_year+1900));
m->setValue(String::create("wday"),Number::create(d->tm_wday));
m->setValue(String::create("yday"),Number::create(d->tm_yday));
m->setValue(String::create("isdst"),Number::create(d->tm_isdst));
return m;
})
//! [ESF] string getOS()
ESF_DECLARE(globals,"getOS",0,0,String::create(StdLib::getOS()))
//! [ESF] Runtime getRuntime( )
ESF_DECLARE(globals,"getRuntime",0,0, &runtime)
//! [ESF] mixed load(string filename)
ESF_DECLARE(globals,"load",1,1,_loadAndExecute(runtime,findFile(runtime,parameter[0].toString())).detachAndDecrease())
//! [ESF] mixed loadOnce(string filename)
ESF_DECLARE(globals,"loadOnce",1,1,StdLib::loadOnce(runtime,parameter[0].toString()).detachAndDecrease())
//! [ESF] void out(...)
ES_FUNCTION_DECLARE(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION_DECLARE(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION_DECLARE(globals,"parse",1,1, {
ERef<UserFunction> script;
Compiler compiler(runtime.getLogger());
script = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())));
return script.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ESF_DECLARE(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION_DECLARE(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ESF_DECLARE(globals,"system",1,1,Number::create(system(parameter[0]->toString().c_str())))
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION_DECLARE(globals, "exec", 2, 2, {
Array * array = assertType<Array>(runtime, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = Number::create(execv(parameter[0]->toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
//! [ESF] number time()
ESF_DECLARE(globals,"time",0,0,Number::create(static_cast<double>(time(nullptr))))
//! [ESF] string toJSON(obj[,formatted=true])
ESF_DECLARE(globals,"toJSON",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Eservices.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:02:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_
#include "flat/EDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::flat;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "FILE::component_writeInfo : could not create a registry key !");
for (sal_Int32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "FILE::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(),
ODriver_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<commit_msg>INTEGRATION: CWS warnings01 (1.5.30); FILE MERGED 2005/12/22 11:44:47 fs 1.5.30.2: #i57457# warning-free code 2005/11/16 12:59:05 fs 1.5.30.1: #i57457# warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Eservices.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:29:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_
#include "flat/EDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::flat;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "FILE::component_writeInfo : could not create a registry key !");
for (sal_Int32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment ** /*ppEnv*/
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* /*pServiceManager*/,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "FILE::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* /*pRegistryKey*/)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(),
ODriver_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<|endoftext|> |
<commit_before>/*!
* \file vectors.hpp
* \author Nathan Eloe
* \brief array template specializations
*/
#include "../typeinfo.h"
#include "convert_utils.h"
#include "../element.h"
#include <string>
#include <vector>
namespace bson
{
template<>
TypeInfo default_type<array>()
{
return ARRAY;
}
template<>
std::string to_string<array>()
{
return "std::vector<bson::Element>";
}
template<>
bool Element::check_convert<array>() const
{
return m_type == ARRAY;
}
template<>
unsigned Element::deserialize_bytes<array>(const unsigned char* bytes)
{
Document d;
TypeInfo ti;
Element e;
int32_t size, consumed = 4;
memcpy(&size, bytes, 4);
size --;
m_data = std::shared_ptr<array>(new array);
while (consumed < size)
{
ti = static_cast<TypeInfo>(*(bytes + consumed));
std::string name((char*)bytes + (++consumed));
consumed += name.size() + 1;
consumed += e.decode(bytes + consumed, ti);
std::static_pointer_cast<array>(m_data) -> push_back(e);
}
return consumed + 1;
}
template<>
void Element::serialize_bson<array>(std::ostringstream& oss) const
{
int size = std::static_pointer_cast<array>(m_data) -> size();
int index = 0;
std::ostringstream data_ser;
for (const Element & e: *(std::static_pointer_cast<array>(m_data)))
{
data_ser << to_char(e.m_type) << itos(index++) << X00;
e.encode(data_ser);
}
_to_stream(oss, static_cast<int>(5 + data_ser.tellp()));
oss << data_ser.str() << X00;
return;
}
template <>
std::string Element::_to_std_str<array>() const
{
std::ostringstream oss;
int size = std::static_pointer_cast<array>(m_data) -> size();
oss << "[ ";
if (size > 0)
oss << static_cast<std::string>((*(std::static_pointer_cast<array>(m_data)))[0]);
for (int i=0; i < size; i++)
{
oss << ", " << static_cast<std::string>((*(std::static_pointer_cast<array>(m_data)))[i]);
}
oss << " ]";
return oss.str();
}
}<commit_msg>silly bug in outputting an array to a string<commit_after>/*!
* \file vectors.hpp
* \author Nathan Eloe
* \brief array template specializations
*/
#include "../typeinfo.h"
#include "convert_utils.h"
#include "../element.h"
#include <string>
#include <vector>
namespace bson
{
template<>
TypeInfo default_type<array>()
{
return ARRAY;
}
template<>
std::string to_string<array>()
{
return "std::vector<bson::Element>";
}
template<>
bool Element::check_convert<array>() const
{
return m_type == ARRAY;
}
template<>
unsigned Element::deserialize_bytes<array>(const unsigned char* bytes)
{
Document d;
TypeInfo ti;
Element e;
int32_t size, consumed = 4;
memcpy(&size, bytes, 4);
size --;
m_data = std::shared_ptr<array>(new array);
while (consumed < size)
{
ti = static_cast<TypeInfo>(*(bytes + consumed));
std::string name((char*)bytes + (++consumed));
consumed += name.size() + 1;
consumed += e.decode(bytes + consumed, ti);
std::static_pointer_cast<array>(m_data) -> push_back(e);
}
return consumed + 1;
}
template<>
void Element::serialize_bson<array>(std::ostringstream& oss) const
{
int size = std::static_pointer_cast<array>(m_data) -> size();
int index = 0;
std::ostringstream data_ser;
for (const Element & e: *(std::static_pointer_cast<array>(m_data)))
{
data_ser << to_char(e.m_type) << itos(index++) << X00;
e.encode(data_ser);
}
_to_stream(oss, static_cast<int>(5 + data_ser.tellp()));
oss << data_ser.str() << X00;
return;
}
template <>
std::string Element::_to_std_str<array>() const
{
std::ostringstream oss;
int size = std::static_pointer_cast<array>(m_data) -> size();
oss << "[ ";
if (size > 0)
oss << static_cast<std::string>((*(std::static_pointer_cast<array>(m_data)))[0]);
for (int i=1; i < size; i++)
{
oss << ", " << static_cast<std::string>((*(std::static_pointer_cast<array>(m_data)))[i]);
}
oss << " ]";
return oss.str();
}
}<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TStopwatch.cxx,v 1.4 2000/12/13 15:13:46 brun Exp $
// Author: Fons Rademakers 11/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStopwatch //
// //
// Stopwatch class. This class returns the real and cpu time between //
// the start and stop events. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStopwatch.h"
#include "TString.h"
#if defined(R__MAC)
# include <time.h>
static clock_t gTicks = CLOCKS_PER_SEC;
#elif defined(R__UNIX)
# include <sys/times.h>
# include <unistd.h>
static clock_t gTicks = 0;
#elif defined(R__VMS)
# include <time.h>
# include <unistd.h>
static clock_t gTicks = 1000;
#elif defined(WIN32)
# include "TError.h"
const Double_t gTicks = 1.0e-7;
# include "Windows4Root.h"
#endif
ClassImp(TStopwatch)
//______________________________________________________________________________
TStopwatch::TStopwatch()
{
// Create a stopwatch and start it.
#ifdef R__UNIX
if (!gTicks) gTicks = (clock_t)sysconf(_SC_CLK_TCK);
#endif
fState = kUndefined;
fTotalCpuTime = 0;
fTotalRealTime = 0;
fCounter = 0;
Start();
}
//______________________________________________________________________________
void TStopwatch::Start(Bool_t reset)
{
// Start the stopwatch. If reset is kTRUE reset the stopwatch before
// starting it (including the stopwatch counter).
// Use kFALSE to continue timing after a Stop() without
// resetting the stopwatch.
if (reset) {
fTotalCpuTime = 0;
fTotalRealTime = 0;
fCounter = 0;
}
if (fState != kRunning) {
#ifndef R__UNIX
fStartRealTime = GetRealTime();
fStartCpuTime = GetCPUTime();
#else
struct tms cpt;
fStartRealTime = (Double_t)times(&cpt) / gTicks;
fStartCpuTime = (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#endif
}
fState = kRunning;
fCounter++;
}
//______________________________________________________________________________
void TStopwatch::Stop()
{
// Stop the stopwatch.
#ifndef R__UNIX
fStopRealTime = GetRealTime();
fStopCpuTime = GetCPUTime();
#else
struct tms cpt;
fStopRealTime = (Double_t)times(&cpt) / gTicks;
fStopCpuTime = (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#endif
if (fState == kRunning) {
fTotalCpuTime += fStopCpuTime - fStartCpuTime;
fTotalRealTime += fStopRealTime - fStartRealTime;
}
fState = kStopped;
}
//______________________________________________________________________________
void TStopwatch::Continue()
{
// Resume a stopped stopwatch. The stopwatch continues counting from the last
// Start() onwards (this is like the laptimer function).
if (fState == kUndefined)
Error("Continue", "stopwatch not started");
if (fState == kStopped) {
fTotalCpuTime -= fStopCpuTime - fStartCpuTime;
fTotalRealTime -= fStopRealTime - fStartRealTime;
}
fState = kRunning;
}
//______________________________________________________________________________
Double_t TStopwatch::RealTime()
{
// Return the realtime passed between the start and stop events. If the
// stopwatch was still running stop it first.
if (fState == kUndefined)
Error("RealTime", "stopwatch not started");
if (fState == kRunning)
Stop();
return fTotalRealTime;
}
//______________________________________________________________________________
Double_t TStopwatch::CpuTime()
{
// Return the cputime passed between the start and stop events. If the
// stopwatch was still running stop it first.
if (fState == kUndefined)
Error("RealTime", "stopwatch not started");
if (fState == kRunning)
Stop();
return fTotalCpuTime;
}
//______________________________________________________________________________
Double_t TStopwatch::GetRealTime()
{
// Private static method returning system realtime.
#if defined(R__MAC)
return (Double_t)clock() / gTicks;
#elif defined(R__UNIX)
struct tms cpt;
Double_t trt = (Double_t)times(&cpt);
return trt / (Double_t) gTicks;
#elif defined(R__VMS)
return (Double_t)clock() / gTicks;
#elif defined(WIN32)
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftRealTime; // time the process has spent in kernel mode
SYSTEMTIME st;
GetSystemTime(&st);
SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);
return (Double_t)ftRealTime.ftInt64 * gTicks;
#endif
}
//______________________________________________________________________________
Double_t TStopwatch::GetCPUTime()
{
// Private static method returning system CPU time.
#if defined(R__MAC)
return (Double_t)clock() / gTicks;
#elif defined(R__UNIX)
struct tms cpt;
times(&cpt);
return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#elif defined(R__VMS)
return (Double_t)clock() / gTicks;
#elif defined(WIN32)
OSVERSIONINFO OsVersionInfo;
// Value Platform
//----------------------------------------------------
// VER_PLATFORM_WIN32s Win32s on Windows 3.1
// VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95
// VER_PLATFORM_WIN32_NT Windows NT
//
OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
GetVersionEx(&OsVersionInfo);
if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
DWORD ret;
FILETIME ftCreate, // when the process was created
ftExit; // when the process exited
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftKernel; // time the process has spent in kernel mode
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftUser; // time the process has spent in user mode
HANDLE hProcess = GetCurrentProcess();
ret = GetProcessTimes (hProcess, &ftCreate, &ftExit,
&ftKernel.ftFileTime,
&ftUser.ftFileTime);
if (ret != TRUE) {
ret = GetLastError ();
::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret);
}
// Process times are returned in a 64-bit structure, as the number of
// 100 nanosecond ticks since 1 January 1601. User mode and kernel mode
// times for this process are in separate 64-bit structures.
// To convert to floating point seconds, we will:
//
// Convert sum of high 32-bit quantities to 64-bit int
return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;
} else
return GetRealTime();
#endif
}
//______________________________________________________________________________
void TStopwatch::Print(Option_t *) const
{
// Print the real and cpu time passed between the start and stop events.
// and the number of times (slices) this TStopwatch was called
// (if this number > 1)
Double_t realt = ((TStopwatch*)this)->RealTime();
Int_t hours = Int_t(realt / 3600);
realt -= hours * 3600;
Int_t min = Int_t(realt / 60);
realt -= min * 60;
Int_t sec = Int_t(realt);
Int_t counter = Counter();
if (counter <= 1 )
Printf("Real time %d:%d:%d, CP time %.3f", hours, min, sec, ((TStopwatch*)this)->CpuTime());
else
Printf("Real time %d:%d:%d, CP time %.3f, %d slices", hours, min, sec, ((TStopwatch*)this)->CpuTime(),counter);
}
<commit_msg>added option "m" to Print() to allow millisecond precision in the real time reporting. By Maarten.<commit_after>// @(#)root/base:$Name: $:$Id: TStopwatch.cxx,v 1.5 2002/06/13 13:42:55 rdm Exp $
// Author: Fons Rademakers 11/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStopwatch //
// //
// Stopwatch class. This class returns the real and cpu time between //
// the start and stop events. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStopwatch.h"
#include "TString.h"
#if defined(R__MAC)
# include <time.h>
static clock_t gTicks = CLOCKS_PER_SEC;
#elif defined(R__UNIX)
# include <sys/times.h>
# include <unistd.h>
static clock_t gTicks = 0;
#elif defined(R__VMS)
# include <time.h>
# include <unistd.h>
static clock_t gTicks = 1000;
#elif defined(WIN32)
# include "TError.h"
const Double_t gTicks = 1.0e-7;
# include "Windows4Root.h"
#endif
ClassImp(TStopwatch)
//______________________________________________________________________________
TStopwatch::TStopwatch()
{
// Create a stopwatch and start it.
#ifdef R__UNIX
if (!gTicks) gTicks = (clock_t)sysconf(_SC_CLK_TCK);
#endif
fState = kUndefined;
fTotalCpuTime = 0;
fTotalRealTime = 0;
fCounter = 0;
Start();
}
//______________________________________________________________________________
void TStopwatch::Start(Bool_t reset)
{
// Start the stopwatch. If reset is kTRUE reset the stopwatch before
// starting it (including the stopwatch counter).
// Use kFALSE to continue timing after a Stop() without
// resetting the stopwatch.
if (reset) {
fTotalCpuTime = 0;
fTotalRealTime = 0;
fCounter = 0;
}
if (fState != kRunning) {
#ifndef R__UNIX
fStartRealTime = GetRealTime();
fStartCpuTime = GetCPUTime();
#else
struct tms cpt;
fStartRealTime = (Double_t)times(&cpt) / gTicks;
fStartCpuTime = (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#endif
}
fState = kRunning;
fCounter++;
}
//______________________________________________________________________________
void TStopwatch::Stop()
{
// Stop the stopwatch.
#ifndef R__UNIX
fStopRealTime = GetRealTime();
fStopCpuTime = GetCPUTime();
#else
struct tms cpt;
fStopRealTime = (Double_t)times(&cpt) / gTicks;
fStopCpuTime = (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#endif
if (fState == kRunning) {
fTotalCpuTime += fStopCpuTime - fStartCpuTime;
fTotalRealTime += fStopRealTime - fStartRealTime;
}
fState = kStopped;
}
//______________________________________________________________________________
void TStopwatch::Continue()
{
// Resume a stopped stopwatch. The stopwatch continues counting from the last
// Start() onwards (this is like the laptimer function).
if (fState == kUndefined)
Error("Continue", "stopwatch not started");
if (fState == kStopped) {
fTotalCpuTime -= fStopCpuTime - fStartCpuTime;
fTotalRealTime -= fStopRealTime - fStartRealTime;
}
fState = kRunning;
}
//______________________________________________________________________________
Double_t TStopwatch::RealTime()
{
// Return the realtime passed between the start and stop events. If the
// stopwatch was still running stop it first.
if (fState == kUndefined)
Error("RealTime", "stopwatch not started");
if (fState == kRunning)
Stop();
return fTotalRealTime;
}
//______________________________________________________________________________
Double_t TStopwatch::CpuTime()
{
// Return the cputime passed between the start and stop events. If the
// stopwatch was still running stop it first.
if (fState == kUndefined)
Error("CpuTime", "stopwatch not started");
if (fState == kRunning)
Stop();
return fTotalCpuTime;
}
//______________________________________________________________________________
Double_t TStopwatch::GetRealTime()
{
// Private static method returning system realtime.
#if defined(R__MAC)
return (Double_t)clock() / gTicks;
#elif defined(R__UNIX)
struct tms cpt;
Double_t trt = (Double_t)times(&cpt);
return trt / (Double_t) gTicks;
#elif defined(R__VMS)
return (Double_t)clock() / gTicks;
#elif defined(WIN32)
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftRealTime; // time the process has spent in kernel mode
SYSTEMTIME st;
GetSystemTime(&st);
SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);
return (Double_t)ftRealTime.ftInt64 * gTicks;
#endif
}
//______________________________________________________________________________
Double_t TStopwatch::GetCPUTime()
{
// Private static method returning system CPU time.
#if defined(R__MAC)
return (Double_t)clock() / gTicks;
#elif defined(R__UNIX)
struct tms cpt;
times(&cpt);
return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#elif defined(R__VMS)
return (Double_t)clock() / gTicks;
#elif defined(WIN32)
OSVERSIONINFO OsVersionInfo;
// Value Platform
//----------------------------------------------------
// VER_PLATFORM_WIN32s Win32s on Windows 3.1
// VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95
// VER_PLATFORM_WIN32_NT Windows NT
//
OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
GetVersionEx(&OsVersionInfo);
if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
DWORD ret;
FILETIME ftCreate, // when the process was created
ftExit; // when the process exited
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftKernel; // time the process has spent in kernel mode
union {
FILETIME ftFileTime;
__int64 ftInt64;
} ftUser; // time the process has spent in user mode
HANDLE hProcess = GetCurrentProcess();
ret = GetProcessTimes (hProcess, &ftCreate, &ftExit,
&ftKernel.ftFileTime,
&ftUser.ftFileTime);
if (ret != TRUE) {
ret = GetLastError ();
::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret);
}
// Process times are returned in a 64-bit structure, as the number of
// 100 nanosecond ticks since 1 January 1601. User mode and kernel mode
// times for this process are in separate 64-bit structures.
// To convert to floating point seconds, we will:
//
// Convert sum of high 32-bit quantities to 64-bit int
return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;
} else
return GetRealTime();
#endif
}
//______________________________________________________________________________
void TStopwatch::Print(Option_t *opt) const
{
// Print the real and cpu time passed between the start and stop events.
// and the number of times (slices) this TStopwatch was called
// (if this number > 1). If opt="m" printout realtime in milli second
// precision.
Double_t realt = const_cast<TStopwatch*>(this)->RealTime();
Double_t cput = const_cast<TStopwatch*>(this)->CpuTime();
Int_t hours = Int_t(realt / 3600);
realt -= hours * 3600;
Int_t min = Int_t(realt / 60);
realt -= min * 60;
Int_t sec = Int_t(realt);
realt = TMath::Max(realt, 0.);
cput = TMath::Max(cput, 0.);
if (opt && *opt == 'm') {
if (Counter() > 1) {
Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter());
} else {
Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput);
}
} else {
if (Counter() > 1) {
Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter());
} else {
Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput);
}
}
}
<|endoftext|> |
<commit_before>#include "Session.h"
#include <string>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/DataMatrices/DataCreator.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
using namespace smurff;
void Session::setFromRootPath(std::string rootPath)
{
// assign config
m_rootFile = std::make_shared<RootFile>(rootPath);
m_rootFile->restoreConfig(m_config);
m_config.validate();
//base functionality
setFromBase();
}
void Session::setFromConfig(const Config& cfg)
{
// assign config
cfg.validate();
m_config = cfg;
m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension());
m_rootFile->saveConfig(m_config);
//base functionality
setFromBase();
//flush record about options.ini
m_rootFile->flushLast();
}
void Session::setFromBase()
{
std::shared_ptr<Session> this_session = shared_from_this();
// initialize pred
if (m_config.getClassify())
m_pred->setThreshold(m_config.getThreshold());
if (m_config.getTest())
m_pred->set(m_config.getTest());
// initialize data
data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session));
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++)
this->addPrior(priorFactory->create_prior(this_session, i));
}
void Session::init()
{
//init omp
threads_init();
//initialize random generator
initRng();
//initialize train matrix (centring and noise model)
data()->init();
//initialize model (samples)
m_model->init(m_config.getNumLatent(), data()->dim(), m_config.getModelInitType());
//initialize priors
for(auto &p : m_priors)
p->init();
//write header to status file
if (m_config.getCsvStatus().size())
{
auto f = fopen(m_config.getCsvStatus().c_str(), "w");
fprintf(f, "phase;iter;phase_len;globmean_rmse;colmean_rmse;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;U0;U1;elapsed\n");
fclose(f);
}
//write info to console
if (m_config.getVerbose())
info(std::cout, "");
//restore session (model, priors)
bool resume = restore(m_iter);
//print session status to console
if (m_config.getVerbose())
{
printStatus(0, resume, m_iter);
printf(" ====== Sampling (burning phase) ====== \n");
}
//restore will either start from initial iteration (-1) that should be printed with printStatus
//or it will start with last iteration that was previously saved
//in any case - we have to move to next iteration
m_iter++; //go to next iteration
is_init = true;
}
void Session::run()
{
init();
while (m_iter < m_config.getBurnin() + m_config.getNSamples())
step();
}
void Session::step()
{
THROWERROR_ASSERT(is_init);
if (m_config.getVerbose() && m_iter == m_config.getBurnin())
{
printf(" ====== Burn-in complete, averaging samples ====== \n");
}
auto starti = tick();
BaseSession::step();
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred->update(m_model, m_iter < m_config.getBurnin());
printStatus(endi - starti, false, m_iter);
save(m_iter);
m_iter++;
}
std::ostream& Session::info(std::ostream &os, std::string indent)
{
os << indent << name << " {\n";
BaseSession::info(os, indent);
os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ;
os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n";
if (m_config.getSaveFreq() != 0)
{
if (m_config.getSaveFreq() > 0)
{
os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n";
}
else
{
os << indent << " Save model after last iteration\n";
}
os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n";
os << indent << " Save extension: " << m_config.getSaveExtension() << "\n";
}
else
{
os << indent << " Save model: never\n";
}
os << indent << "}\n";
return os;
}
void Session::save(int iteration) const
{
//do not save if 'never save' mode is selected
if (!m_config.getSaveFreq())
return;
std::int32_t isample = iteration - m_config.getBurnin() + 1;
//save if burnin
if (isample <= 0)
{
std::int32_t iburninPrev = iteration;
if (iburninPrev > 0)
{
//remove previous iteration
m_rootFile->removeBurninStepFile(iburninPrev);
//flush last item in a root file
m_rootFile->flushLast();
}
std::int32_t iburnin = iteration + 1;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createBurninStepFile(iburnin);
saveInternal(stepFile);
}
else
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (m_config.getSaveFreq() > 0 && (isample % m_config.getSaveFreq()) != 0)
return;
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples())
return;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample);
saveInternal(stepFile);
}
}
void Session::saveInternal(std::shared_ptr<StepFile> stepFile) const
{
if (m_config.getVerbose())
printf("-- Saving model, predictions,... into '%s'.\n", stepFile->getStepFileName().c_str());
BaseSession::save(stepFile);
//flush last item in a root file
m_rootFile->flushLast();
}
bool Session::restore(int& iteration)
{
std::shared_ptr<StepFile> stepFile = m_rootFile->openLastStepFile();
if (!stepFile)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
return false;
}
else
{
if (m_config.getVerbose())
printf("-- Restoring model, predictions,... from '%s'.\n", stepFile->getStepFileName().c_str());
BaseSession::restore(stepFile);
//restore last iteration index
if (stepFile->getBurnin())
{
iteration = stepFile->getIsample() - 1; //restore original state
}
else
{
iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state
}
return true;
}
}
void Session::printStatus(double elapsedi, bool resume, int iteration)
{
if(!m_config.getVerbose())
return;
double snorm0 = m_model->U(0).norm();
double snorm1 = m_model->U(1).norm();
auto nnz_per_sec = (data()->nnz()) / elapsedi;
auto samples_per_sec = (m_model->nsamples()) / elapsedi;
std::string resumeString = resume ? "Continue from " : std::string();
std::string phase;
int i, from;
if (iteration < 0)
{
phase = "Initial";
i = iteration + 1;
from = 0;
}
else if (iteration < m_config.getBurnin())
{
phase = "Burnin";
i = iteration + 1;
from = m_config.getBurnin();
}
else
{
phase = "Sample";
i = iteration - m_config.getBurnin() + 1;
from = m_config.getNSamples();
}
printf("%s%s %3d/%3d: RMSE: %.4f (1samp: %.4f)", resumeString.c_str(), phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample);
if (m_config.getClassify())
printf(" AUC:%.4f (1samp: %.4f)", m_pred->auc_avg, m_pred->auc_1sample);
printf(" U:[%1.2e, %1.2e] [took: %0.1fs]\n", snorm0, snorm1, elapsedi);
// avoid computing train_rmse twice
double train_rmse = NAN;
if (m_config.getVerbose() > 1)
{
train_rmse = data()->train_rmse(m_model);
printf(" RMSE train: %.4f\n", train_rmse);
printf(" Priors:\n");
for(const auto &p : m_priors)
p->status(std::cout, " ");
printf(" Model:\n");
m_model->status(std::cout, " ");
printf(" Noise:\n");
data()->status(std::cout, " ");
}
if (m_config.getVerbose() > 2)
{
printf(" Compute Performance: %.0f samples/sec, %.0f nnz/sec\n", samples_per_sec, nnz_per_sec);
}
if (m_config.getCsvStatus().size())
{
// train_rmse is printed as NAN, unless verbose > 1
auto f = fopen(m_config.getCsvStatus().c_str(), "a");
fprintf(f, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%1.2e;%1.2e;%0.1f\n",
phase.c_str(), i, from,
m_pred->rmse_avg, m_pred->rmse_1sample, train_rmse, m_pred->auc_1sample, m_pred->auc_avg, snorm0, snorm1, elapsedi);
fclose(f);
}
}
void Session::initRng()
{
//init random generator
if (m_config.getRandomSeedSet())
init_bmrng(m_config.getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> Session::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}<commit_msg>Write CsvStatus file, even if verbose == 0<commit_after>#include "Session.h"
#include <string>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/DataMatrices/DataCreator.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
using namespace smurff;
void Session::setFromRootPath(std::string rootPath)
{
// assign config
m_rootFile = std::make_shared<RootFile>(rootPath);
m_rootFile->restoreConfig(m_config);
m_config.validate();
//base functionality
setFromBase();
}
void Session::setFromConfig(const Config& cfg)
{
// assign config
cfg.validate();
m_config = cfg;
m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension());
m_rootFile->saveConfig(m_config);
//base functionality
setFromBase();
//flush record about options.ini
m_rootFile->flushLast();
}
void Session::setFromBase()
{
std::shared_ptr<Session> this_session = shared_from_this();
// initialize pred
if (m_config.getClassify())
m_pred->setThreshold(m_config.getThreshold());
if (m_config.getTest())
m_pred->set(m_config.getTest());
// initialize data
data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session));
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++)
this->addPrior(priorFactory->create_prior(this_session, i));
}
void Session::init()
{
//init omp
threads_init();
//initialize random generator
initRng();
//initialize train matrix (centring and noise model)
data()->init();
//initialize model (samples)
m_model->init(m_config.getNumLatent(), data()->dim(), m_config.getModelInitType());
//initialize priors
for(auto &p : m_priors)
p->init();
//write header to status file
if (m_config.getCsvStatus().size())
{
auto f = fopen(m_config.getCsvStatus().c_str(), "w");
fprintf(f, "phase;iter;phase_len;globmean_rmse;colmean_rmse;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;U0;U1;elapsed\n");
fclose(f);
}
//write info to console
if (m_config.getVerbose())
info(std::cout, "");
//restore session (model, priors)
bool resume = restore(m_iter);
//print session status to console
if (m_config.getVerbose())
{
printStatus(0, resume, m_iter);
printf(" ====== Sampling (burning phase) ====== \n");
}
//restore will either start from initial iteration (-1) that should be printed with printStatus
//or it will start with last iteration that was previously saved
//in any case - we have to move to next iteration
m_iter++; //go to next iteration
is_init = true;
}
void Session::run()
{
init();
while (m_iter < m_config.getBurnin() + m_config.getNSamples())
step();
}
void Session::step()
{
THROWERROR_ASSERT(is_init);
if (m_config.getVerbose() && m_iter == m_config.getBurnin())
{
printf(" ====== Burn-in complete, averaging samples ====== \n");
}
auto starti = tick();
BaseSession::step();
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred->update(m_model, m_iter < m_config.getBurnin());
printStatus(endi - starti, false, m_iter);
save(m_iter);
m_iter++;
}
std::ostream& Session::info(std::ostream &os, std::string indent)
{
os << indent << name << " {\n";
BaseSession::info(os, indent);
os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ;
os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n";
if (m_config.getSaveFreq() != 0)
{
if (m_config.getSaveFreq() > 0)
{
os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n";
}
else
{
os << indent << " Save model after last iteration\n";
}
os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n";
os << indent << " Save extension: " << m_config.getSaveExtension() << "\n";
}
else
{
os << indent << " Save model: never\n";
}
os << indent << "}\n";
return os;
}
void Session::save(int iteration) const
{
//do not save if 'never save' mode is selected
if (!m_config.getSaveFreq() && !m_config.getCsvStatus().size())
return;
std::int32_t isample = iteration - m_config.getBurnin() + 1;
//save if burnin
if (isample <= 0)
{
std::int32_t iburninPrev = iteration;
if (iburninPrev > 0)
{
//remove previous iteration
m_rootFile->removeBurninStepFile(iburninPrev);
//flush last item in a root file
m_rootFile->flushLast();
}
std::int32_t iburnin = iteration + 1;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createBurninStepFile(iburnin);
saveInternal(stepFile);
}
else
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (m_config.getSaveFreq() > 0 && (isample % m_config.getSaveFreq()) != 0)
return;
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples())
return;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample);
saveInternal(stepFile);
}
}
void Session::saveInternal(std::shared_ptr<StepFile> stepFile) const
{
if (m_config.getVerbose())
printf("-- Saving model, predictions,... into '%s'.\n", stepFile->getStepFileName().c_str());
BaseSession::save(stepFile);
//flush last item in a root file
m_rootFile->flushLast();
}
bool Session::restore(int& iteration)
{
std::shared_ptr<StepFile> stepFile = m_rootFile->openLastStepFile();
if (!stepFile)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
return false;
}
else
{
if (m_config.getVerbose())
printf("-- Restoring model, predictions,... from '%s'.\n", stepFile->getStepFileName().c_str());
BaseSession::restore(stepFile);
//restore last iteration index
if (stepFile->getBurnin())
{
iteration = stepFile->getIsample() - 1; //restore original state
}
else
{
iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state
}
return true;
}
}
void Session::printStatus(double elapsedi, bool resume, int iteration)
{
if(!m_config.getVerbose())
return;
double snorm0 = m_model->U(0).norm();
double snorm1 = m_model->U(1).norm();
auto nnz_per_sec = (data()->nnz()) / elapsedi;
auto samples_per_sec = (m_model->nsamples()) / elapsedi;
std::string resumeString = resume ? "Continue from " : std::string();
std::string phase;
int i, from;
if (iteration < 0)
{
phase = "Initial";
i = iteration + 1;
from = 0;
}
else if (iteration < m_config.getBurnin())
{
phase = "Burnin";
i = iteration + 1;
from = m_config.getBurnin();
}
else
{
phase = "Sample";
i = iteration - m_config.getBurnin() + 1;
from = m_config.getNSamples();
}
printf("%s%s %3d/%3d: RMSE: %.4f (1samp: %.4f)", resumeString.c_str(), phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample);
if (m_config.getClassify())
printf(" AUC:%.4f (1samp: %.4f)", m_pred->auc_avg, m_pred->auc_1sample);
printf(" U:[%1.2e, %1.2e] [took: %0.1fs]\n", snorm0, snorm1, elapsedi);
// avoid computing train_rmse twice
double train_rmse = NAN;
if (m_config.getVerbose() > 1)
{
train_rmse = data()->train_rmse(m_model);
printf(" RMSE train: %.4f\n", train_rmse);
printf(" Priors:\n");
for(const auto &p : m_priors)
p->status(std::cout, " ");
printf(" Model:\n");
m_model->status(std::cout, " ");
printf(" Noise:\n");
data()->status(std::cout, " ");
}
if (m_config.getVerbose() > 2)
{
printf(" Compute Performance: %.0f samples/sec, %.0f nnz/sec\n", samples_per_sec, nnz_per_sec);
}
if (m_config.getCsvStatus().size())
{
// train_rmse is printed as NAN, unless verbose > 1
auto f = fopen(m_config.getCsvStatus().c_str(), "a");
fprintf(f, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%1.2e;%1.2e;%0.1f\n",
phase.c_str(), i, from,
m_pred->rmse_avg, m_pred->rmse_1sample, train_rmse, m_pred->auc_1sample, m_pred->auc_avg, snorm0, snorm1, elapsedi);
fclose(f);
}
}
void Session::initRng()
{
//init random generator
if (m_config.getRandomSeedSet())
init_bmrng(m_config.getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> Session::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}<|endoftext|> |
<commit_before>/**
* @file Zip.cpp
* @brief Zip class implementation.
* @author zer0
* @date 2016-11-17
*/
#include <libtbag/archive/Zip.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/filesystem/details/FsCommon.hpp>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <zlib.h>
#include <zip.h>
#include <unzip.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace archive {
Zip::Zip()
{
// EMPTY.
}
Zip::~Zip()
{
// EMPTY.
}
Zip::ResultCode Zip::coding(Buffer & output, uint8_t const * input, std::size_t size, int level)
{
bool const ENCODE = (level != DECODE_LEVEL);
z_stream stream = {0,};
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
int result = Z_OK;
if (ENCODE) {
result = deflateInit(&stream, level);
} else {
result = inflateInit(&stream);
}
if (result != Z_OK) {
return ResultCode::FAILURE;
}
std::size_t const BUFFER_SIZE = 2048; // TODO: CHANGE PAGE SIZE.
Bytef in[BUFFER_SIZE] = {0,};
Bytef out[BUFFER_SIZE] = {0,};
std::size_t read_index = 0;
int flush = Z_NO_FLUSH;
do {
// Update input buffer.
stream.next_in = in;
if (size - read_index > BUFFER_SIZE) {
stream.avail_in = BUFFER_SIZE;
flush = Z_NO_FLUSH;
} else {
stream.avail_in = static_cast<uInt>(size - read_index);
flush = Z_FINISH; // EOF.
}
memcpy(in, input + read_index, stream.avail_in);
read_index += stream.avail_in;
do {
// Update output buffer.
stream.avail_out = BUFFER_SIZE;
stream.next_out = out;
if (ENCODE) {
result = deflate(&stream, flush);
} else {
result = inflate(&stream, flush);
}
assert(result != Z_STREAM_ERROR);
std::size_t dsize = BUFFER_SIZE - stream.avail_out;
output.insert(output.end(), out, out + dsize);
} while (stream.avail_out == 0);
assert(stream.avail_in == 0);
} while (flush != Z_FINISH);
assert(result == Z_STREAM_END);
if (ENCODE) {
deflateEnd(&stream);
} else {
inflateEnd(&stream);
}
return ResultCode::SUCCESS;
}
Zip::ResultCode Zip::encode(Buffer & output, uint8_t const * input, std::size_t size, int level)
{
if (level < MIN_ENCODE_LEVEL || level > MAX_ENCODE_LEVEL) {
level = Z_DEFAULT_COMPRESSION;
}
return coding(output, input, size, level);
}
Zip::ResultCode Zip::decode(Buffer & output, uint8_t const * input, std::size_t size)
{
return coding(output, input, size, DECODE_LEVEL);
}
Zip::ResultCode Zip::zip(std::string const & file, std::string const & dir)
{
return ResultCode::FAILURE;
}
Zip::ResultCode Zip::unzip(std::string const & file, std::string const & dir)
{
using Path = filesystem::Path;
unzFile uf = unzOpen(file.c_str());
if (uf == nullptr) {
return ResultCode::OPEN_ERROR;
}
if (unzGoToFirstFile(uf) != UNZ_OK) {
unzClose(uf);
return ResultCode::GO_TO_FIRST_FILE_ERROR;
}
std::size_t const MAX_PATH = 256;
std::size_t const MAX_COMMENT = 256;
char filename[MAX_PATH] = {0,};
char comment[MAX_COMMENT] = {0,};
std::size_t const INPUT_BUFFER = 2048;
Bytef in[INPUT_BUFFER] = {0,};
unz_file_info info;
do {
unzGetCurrentFileInfo(uf, &info, filename, MAX_PATH, nullptr, 0, comment, MAX_COMMENT);
//std::cout << "NAME(" << filename
// << ") COMP_SIZE(" << info.compressed_size
// << ") ORI_SIZE(" << info.uncompressed_size
// << ")\n";
std::string const OUTPUT_NODE_PATH = dir + filesystem::details::PATH_SEPARATOR + filename;
if (info.compressed_size == 0 && info.uncompressed_size == 0) {
// Directory.
//OUTPUT_NODE_PATH.createDirWithRecursive();
libtbag::filesystem::details::createDirectory(OUTPUT_NODE_PATH);
} else {
// Regular file.
if (unzOpenCurrentFile(uf) == UNZ_OK) {
std::ofstream op(OUTPUT_NODE_PATH, std::ios_base::binary);
int readsize = 0;
do {
readsize = unzReadCurrentFile(uf, (void*)in, INPUT_BUFFER);
op.write((char const *) in, readsize);
} while (readsize != 0);
op.close();
}
unzCloseCurrentFile(uf);
}
} while (unzGoToNextFile(uf) == UNZ_OK);
unzClose(uf);
return ResultCode::SUCCESS;
}
} // namespace archive
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<commit_msg>Trivial commit.<commit_after>/**
* @file Zip.cpp
* @brief Zip class implementation.
* @author zer0
* @date 2016-11-17
*/
#include <libtbag/archive/Zip.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/filesystem/details/FsCommon.hpp>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <zlib.h>
#include <zip.h>
#include <unzip.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace archive {
Zip::Zip()
{
// EMPTY.
}
Zip::~Zip()
{
// EMPTY.
}
Zip::ResultCode Zip::coding(Buffer & output, uint8_t const * input, std::size_t size, int level)
{
bool const ENCODE = (level != DECODE_LEVEL);
z_stream stream = {0,};
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
int result = Z_OK;
if (ENCODE) {
result = deflateInit(&stream, level);
} else {
result = inflateInit(&stream);
}
if (result != Z_OK) {
return ResultCode::FAILURE;
}
std::size_t const BUFFER_SIZE = 2048; // TODO: CHANGE PAGE SIZE.
Bytef in[BUFFER_SIZE] = {0,};
Bytef out[BUFFER_SIZE] = {0,};
std::size_t read_index = 0;
int flush = Z_NO_FLUSH;
do {
// Update input buffer.
stream.next_in = in;
if (size - read_index > BUFFER_SIZE) {
stream.avail_in = BUFFER_SIZE;
flush = Z_NO_FLUSH;
} else {
stream.avail_in = static_cast<uInt>(size - read_index);
flush = Z_FINISH; // EOF.
}
memcpy(in, input + read_index, stream.avail_in);
read_index += stream.avail_in;
do {
// Update output buffer.
stream.avail_out = BUFFER_SIZE;
stream.next_out = out;
if (ENCODE) {
result = deflate(&stream, flush);
} else {
result = inflate(&stream, flush);
}
assert(result != Z_STREAM_ERROR);
std::size_t dsize = BUFFER_SIZE - stream.avail_out;
output.insert(output.end(), out, out + dsize);
} while (stream.avail_out == 0);
assert(stream.avail_in == 0);
} while (flush != Z_FINISH);
assert(result == Z_STREAM_END);
if (ENCODE) {
deflateEnd(&stream);
} else {
inflateEnd(&stream);
}
return ResultCode::SUCCESS;
}
Zip::ResultCode Zip::encode(Buffer & output, uint8_t const * input, std::size_t size, int level)
{
if (level < MIN_ENCODE_LEVEL || level > MAX_ENCODE_LEVEL) {
level = Z_DEFAULT_COMPRESSION;
}
return coding(output, input, size, level);
}
Zip::ResultCode Zip::decode(Buffer & output, uint8_t const * input, std::size_t size)
{
return coding(output, input, size, DECODE_LEVEL);
}
Zip::ResultCode Zip::zip(std::string const & file, std::string const & dir)
{
return ResultCode::FAILURE;
}
Zip::ResultCode Zip::unzip(std::string const & file, std::string const & dir)
{
using Path = filesystem::Path;
unzFile uf = unzOpen(file.c_str());
if (uf == nullptr) {
return ResultCode::OPEN_ERROR;
}
if (unzGoToFirstFile(uf) != UNZ_OK) {
unzClose(uf);
return ResultCode::GO_TO_FIRST_FILE_ERROR;
}
std::size_t const MAX_PATH_LENGTH = 256;
std::size_t const MAX_COMMENT = 256;
char filename[MAX_PATH_LENGTH] = {0,};
char comment[MAX_COMMENT] = {0,};
std::size_t const INPUT_BUFFER = 2048;
Bytef in[INPUT_BUFFER] = {0,};
unz_file_info info;
do {
unzGetCurrentFileInfo(uf, &info, filename, MAX_PATH_LENGTH, nullptr, 0, comment, MAX_COMMENT);
//std::cout << "NAME(" << filename
// << ") COMP_SIZE(" << info.compressed_size
// << ") ORI_SIZE(" << info.uncompressed_size
// << ")\n";
std::string const OUTPUT_NODE_PATH = dir + filesystem::details::PATH_SEPARATOR + filename;
if (info.compressed_size == 0 && info.uncompressed_size == 0) {
// Directory.
//OUTPUT_NODE_PATH.createDirWithRecursive();
libtbag::filesystem::details::createDirectory(OUTPUT_NODE_PATH);
} else {
// Regular file.
if (unzOpenCurrentFile(uf) == UNZ_OK) {
std::ofstream op(OUTPUT_NODE_PATH, std::ios_base::binary);
int readsize = 0;
do {
readsize = unzReadCurrentFile(uf, (void*)in, INPUT_BUFFER);
op.write((char const *) in, readsize);
} while (readsize != 0);
op.close();
}
unzCloseCurrentFile(uf);
}
} while (unzGoToNextFile(uf) == UNZ_OK);
unzClose(uf);
return ResultCode::SUCCESS;
}
} // namespace archive
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<|endoftext|> |
<commit_before>#include "Session.h"
#include <fstream>
#include <string>
#include <iomanip>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/DataMatrices/DataCreator.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
#include <SmurffCpp/StatusItem.h>
using namespace smurff;
void Session::setRestoreFromRootPath(std::string rootPath)
{
// open root file
m_rootFile = std::make_shared<RootFile>(rootPath);
//restore config
m_rootFile->restoreConfig(m_config);
m_config.validate();
//base functionality
setFromBase();
}
void Session::setRestoreFromConfig(const Config& cfg, std::string rootPath)
{
cfg.validate();
// assign config
m_config = cfg;
// open root file
m_rootFile = std::make_shared<RootFile>(rootPath);
//base functionality
setFromBase();
}
void Session::setCreateFromConfig(const Config& cfg)
{
cfg.validate();
// assign config
m_config = cfg;
if (m_config.getSaveFreq() || m_config.getCheckpointFreq())
{
// create root file
m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension());
//save config
m_rootFile->saveConfig(m_config);
//flush record about options.ini
m_rootFile->flushLast();
}
//base functionality
setFromBase();
}
void Session::setFromBase()
{
std::shared_ptr<Session> this_session = shared_from_this();
// initialize pred
if (m_config.getClassify())
m_pred->setThreshold(m_config.getThreshold());
if (m_config.getTest())
m_pred->set(m_config.getTest());
// initialize data
data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session));
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++)
this->addPrior(priorFactory->create_prior(this_session, i));
}
void Session::init()
{
//init omp
threads::init(m_config.getVerbose(), m_config.getNumThreads());
//initialize random generator
initRng();
//initialize train matrix (centring and noise model)
data().init();
//initialize model (samples)
model().init(m_config.getNumLatent(), data().dim(), m_config.getModelInitType());
//initialize priors
for(auto &p : m_priors)
p->init();
//write header to status file
if (m_config.getCsvStatus().size())
{
std::ofstream f(m_config.getCsvStatus(), std::ofstream::out);
THROWERROR_ASSERT_MSG(f, "Could not open status csv file: " + m_config.getCsvStatus());
f << StatusItem::getCsvHeader() << std::endl;
}
//write info to console
if (m_config.getVerbose())
info(std::cout, "");
//restore session (model, priors)
bool resume = restore(m_iter);
//print session status to console
if (m_config.getVerbose())
{
printStatus(std::cout, resume);
}
is_init = true;
}
void Session::run()
{
init();
while (step());
}
bool Session::step()
{
THROWERROR_ASSERT_MSG(is_init, "Session::init() needs to be called before ::step()")
// go to the next iteration
m_iter++;
bool isStep = m_iter < m_config.getBurnin() + m_config.getNSamples();
if (isStep)
{
//init omp
threads::enable();
THROWERROR_ASSERT(is_init);
auto starti = tick();
BaseSession::step();
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred->update(m_model, m_iter < m_config.getBurnin());
m_secs_per_iter = endi - starti;
printStatus(std::cout);
save(m_iter);
threads::disable();
}
return isStep;
}
std::ostream& Session::info(std::ostream &os, std::string indent)
{
os << indent << name << " {\n";
BaseSession::info(os, indent);
os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ;
os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n";
if (m_config.getSaveFreq() != 0 || m_config.getCheckpointFreq() != 0)
{
if (m_config.getSaveFreq() > 0)
{
os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n";
}
else if (m_config.getSaveFreq() < 0)
{
os << indent << " Save model after last iteration\n";
}
if (m_config.getCheckpointFreq() > 0)
{
os << indent << " Checkpoint state: every " << m_config.getCheckpointFreq() << " seconds\n";
}
os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n";
os << indent << " Save extension: " << m_config.getSaveExtension() << "\n";
}
else
{
os << indent << " Save model: never\n";
}
os << indent << "}\n";
return os;
}
void Session::save(int iteration)
{
//do not save if 'never save' mode is selected
if (!m_config.getSaveFreq() &&
!m_config.getCheckpointFreq() &&
!m_config.getCsvStatus().size())
return;
std::int32_t isample = iteration - m_config.getBurnin() + 1;
//save if checkpoint threshold overdue
if (m_config.getCheckpointFreq() && (tick() - m_lastCheckpointTime) >= m_config.getCheckpointFreq())
{
std::int32_t icheckpoint = iteration + 1;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createCheckpointStepFile(icheckpoint);
saveInternal(stepFile);
//remove previous iteration if required (initial m_lastCheckpointIter is -1 which means that it does not exist)
if (m_lastCheckpointIter >= 0)
{
std::int32_t icheckpointPrev = m_lastCheckpointIter + 1;
//remove previous iteration
m_rootFile->removeCheckpointStepFile(icheckpointPrev);
//flush last item in a root file
m_rootFile->flushLast();
}
//upddate counters
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
//save model during sampling stage
if (m_config.getSaveFreq() && isample > 0)
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (m_config.getSaveFreq() > 0 && (isample % m_config.getSaveFreq()) != 0)
{
// don't save
}
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
else if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples())
{
// don't save
}
else
{
//do save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample);
saveInternal(stepFile);
}
}
}
void Session::saveInternal(std::shared_ptr<StepFile> stepFile)
{
if (m_config.getVerbose())
{
std::cout << "-- Saving model, predictions,... into '" << stepFile->getStepFileName() << "'." << std::endl;
}
BaseSession::save(stepFile);
//flush last item in a root file
m_rootFile->flushLast();
}
bool Session::restore(int& iteration)
{
std::shared_ptr<StepFile> stepFile = nullptr;
if (m_rootFile)
{
stepFile = m_rootFile->openLastStepFile();
}
if (!stepFile)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = -1;
return false;
}
else
{
if (m_config.getVerbose())
{
std::cout << "-- Restoring model, predictions,... from '" << stepFile->getStepFileName() << "'." << std::endl;
}
BaseSession::restore(stepFile);
//restore last iteration index
if (stepFile->getCheckpoint())
{
iteration = stepFile->getIsample() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
else
{
iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
return true;
}
}
std::shared_ptr<StatusItem> Session::getStatus() const
{
std::shared_ptr<StatusItem> ret = std::make_shared<StatusItem>();
if (m_iter < 0)
{
ret->phase = "Initial";
ret->iter = m_iter + 1;
ret->phase_iter = 0;
}
else if (m_iter < m_config.getBurnin())
{
ret->phase = "Burnin";
ret->iter = m_iter + 1;
ret->phase_iter = m_config.getBurnin();
}
else
{
ret->phase = "Sample";
ret->iter = m_iter - m_config.getBurnin() + 1;
ret->phase_iter = m_config.getNSamples();
}
for (int i = 0; i < (int)model().nmodes(); ++i)
{
ret->model_norms.push_back(model().U(i).norm());
}
ret->train_rmse = data().train_rmse(model());
ret->rmse_avg = m_pred->rmse_avg;
ret->rmse_1sample = m_pred->rmse_1sample;
ret->auc_avg = m_pred->auc_avg;
ret->auc_1sample = m_pred->auc_1sample;
ret->elapsed_iter = m_secs_per_iter;
ret->nnz_per_sec = (double)(data().nnz()) / m_secs_per_iter;
ret->samples_per_sec = (double)(model().nsamples()) / m_secs_per_iter;
return ret;
}
void Session::printStatus(std::ostream& output, bool resume)
{
if(!m_config.getVerbose() &&
!m_config.getCsvStatus().size())
return;
auto status_item = getStatus();
std::string resumeString = resume ? "Continue from " : std::string();
if (m_config.getVerbose() > 0)
{
if (m_iter < 0)
{
output << " ====== Initial phase ====== " << std::endl;
}
else if (m_iter < m_config.getBurnin() && m_iter == 0)
{
output << " ====== Sampling (burning phase) ====== " << std::endl;
}
else if (m_iter == m_config.getBurnin())
{
output << " ====== Burn-in complete, averaging samples ====== " << std::endl;
}
output << resumeString
<< status_item->phase
<< " "
<< std::setfill(' ') << std::setw(3) << status_item->iter
<< "/"
<< std::setfill(' ') << std::setw(3) << status_item->phase_iter
<< ": RMSE: "
<< std::fixed << std::setprecision(4) << status_item->rmse_avg
<< " (1samp: "
<< std::fixed << std::setprecision(4) << status_item->rmse_1sample
<< ")";
if (m_config.getClassify())
{
output << " AUC:"
<< std::fixed << std::setprecision(4) << status_item->auc_avg
<< " (1samp: "
<< std::fixed << std::setprecision(4) << status_item->auc_1sample
<< ")"
<< std::endl;
}
output << " U:[";
for(double n: status_item->model_norms)
{
output << std::scientific << std::setprecision(2) << n << ", ";
}
output << "] [took: "
<< std::fixed << std::setprecision(1) << status_item->elapsed_iter
<< "s]"
<< std::endl;
if (m_config.getVerbose() > 1)
{
output << std::fixed << std::setprecision(4) << " RMSE train: " << status_item->train_rmse << std::endl;
output << " Priors:" << std::endl;
for(const auto &p : m_priors)
p->status(output, " ");
output << " Model:" << std::endl;
model().status(output, " ");
output << " Noise:" << std::endl;
data().status(output, " ");
}
if (m_config.getVerbose() > 2)
{
output << " Compute Performance: " << status_item->samples_per_sec << " samples/sec, " << status_item->nnz_per_sec << " nnz/sec" << std::endl;
}
}
if (m_config.getCsvStatus().size())
{
std::ofstream f(m_config.getCsvStatus(), std::ofstream::out | std::ofstream::app);
THROWERROR_ASSERT_MSG(f, "Could not open status csv file: " + m_config.getCsvStatus());
f << status_item->asCsvString() << std::endl;
}
}
std::string StatusItem::getCsvHeader()
{
return "phase;iter;phase_len;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;elapsed";
}
std::string StatusItem::asCsvString() const
{
char ret[1024];
snprintf(ret, 1024, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%0.1f",
phase.c_str(), iter, phase_iter, rmse_avg, rmse_1sample, train_rmse,
auc_1sample, auc_avg, elapsed_iter);
return ret;
}
void Session::initRng()
{
//init random generator
if (m_config.getRandomSeedSet())
init_bmrng(m_config.getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> Session::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}
<commit_msg>Print how long it took to save<commit_after>#include "Session.h"
#include <fstream>
#include <string>
#include <iomanip>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/DataMatrices/DataCreator.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
#include <SmurffCpp/StatusItem.h>
using namespace smurff;
void Session::setRestoreFromRootPath(std::string rootPath)
{
// open root file
m_rootFile = std::make_shared<RootFile>(rootPath);
//restore config
m_rootFile->restoreConfig(m_config);
m_config.validate();
//base functionality
setFromBase();
}
void Session::setRestoreFromConfig(const Config& cfg, std::string rootPath)
{
cfg.validate();
// assign config
m_config = cfg;
// open root file
m_rootFile = std::make_shared<RootFile>(rootPath);
//base functionality
setFromBase();
}
void Session::setCreateFromConfig(const Config& cfg)
{
cfg.validate();
// assign config
m_config = cfg;
if (m_config.getSaveFreq() || m_config.getCheckpointFreq())
{
// create root file
m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension());
//save config
m_rootFile->saveConfig(m_config);
//flush record about options.ini
m_rootFile->flushLast();
}
//base functionality
setFromBase();
}
void Session::setFromBase()
{
std::shared_ptr<Session> this_session = shared_from_this();
// initialize pred
if (m_config.getClassify())
m_pred->setThreshold(m_config.getThreshold());
if (m_config.getTest())
m_pred->set(m_config.getTest());
// initialize data
data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session));
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++)
this->addPrior(priorFactory->create_prior(this_session, i));
}
void Session::init()
{
//init omp
threads::init(m_config.getVerbose(), m_config.getNumThreads());
//initialize random generator
initRng();
//initialize train matrix (centring and noise model)
data().init();
//initialize model (samples)
model().init(m_config.getNumLatent(), data().dim(), m_config.getModelInitType());
//initialize priors
for(auto &p : m_priors)
p->init();
//write header to status file
if (m_config.getCsvStatus().size())
{
std::ofstream f(m_config.getCsvStatus(), std::ofstream::out);
THROWERROR_ASSERT_MSG(f, "Could not open status csv file: " + m_config.getCsvStatus());
f << StatusItem::getCsvHeader() << std::endl;
}
//write info to console
if (m_config.getVerbose())
info(std::cout, "");
//restore session (model, priors)
bool resume = restore(m_iter);
//print session status to console
if (m_config.getVerbose())
{
printStatus(std::cout, resume);
}
is_init = true;
}
void Session::run()
{
init();
while (step());
}
bool Session::step()
{
THROWERROR_ASSERT_MSG(is_init, "Session::init() needs to be called before ::step()")
// go to the next iteration
m_iter++;
bool isStep = m_iter < m_config.getBurnin() + m_config.getNSamples();
if (isStep)
{
//init omp
threads::enable();
THROWERROR_ASSERT(is_init);
auto starti = tick();
BaseSession::step();
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred->update(m_model, m_iter < m_config.getBurnin());
m_secs_per_iter = endi - starti;
printStatus(std::cout);
save(m_iter);
threads::disable();
}
return isStep;
}
std::ostream& Session::info(std::ostream &os, std::string indent)
{
os << indent << name << " {\n";
BaseSession::info(os, indent);
os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ;
os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n";
if (m_config.getSaveFreq() != 0 || m_config.getCheckpointFreq() != 0)
{
if (m_config.getSaveFreq() > 0)
{
os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n";
}
else if (m_config.getSaveFreq() < 0)
{
os << indent << " Save model after last iteration\n";
}
if (m_config.getCheckpointFreq() > 0)
{
os << indent << " Checkpoint state: every " << m_config.getCheckpointFreq() << " seconds\n";
}
os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n";
os << indent << " Save extension: " << m_config.getSaveExtension() << "\n";
}
else
{
os << indent << " Save model: never\n";
}
os << indent << "}\n";
return os;
}
void Session::save(int iteration)
{
//do not save if 'never save' mode is selected
if (!m_config.getSaveFreq() &&
!m_config.getCheckpointFreq() &&
!m_config.getCsvStatus().size())
return;
std::int32_t isample = iteration - m_config.getBurnin() + 1;
//save if checkpoint threshold overdue
if (m_config.getCheckpointFreq() && (tick() - m_lastCheckpointTime) >= m_config.getCheckpointFreq())
{
std::int32_t icheckpoint = iteration + 1;
//save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createCheckpointStepFile(icheckpoint);
saveInternal(stepFile);
//remove previous iteration if required (initial m_lastCheckpointIter is -1 which means that it does not exist)
if (m_lastCheckpointIter >= 0)
{
std::int32_t icheckpointPrev = m_lastCheckpointIter + 1;
//remove previous iteration
m_rootFile->removeCheckpointStepFile(icheckpointPrev);
//flush last item in a root file
m_rootFile->flushLast();
}
//upddate counters
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
//save model during sampling stage
if (m_config.getSaveFreq() && isample > 0)
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (m_config.getSaveFreq() > 0 && (isample % m_config.getSaveFreq()) != 0)
{
// don't save
}
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
else if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples())
{
// don't save
}
else
{
//do save this iteration
std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample);
saveInternal(stepFile);
}
}
}
void Session::saveInternal(std::shared_ptr<StepFile> stepFile)
{
if (m_config.getVerbose())
{
std::cout << "-- Saving model, predictions,... into '" << stepFile->getStepFileName() << "'." << std::endl;
}
double start = tick();
BaseSession::save(stepFile);
//flush last item in a root file
m_rootFile->flushLast();
double stop = tick();
if (m_config.getVerbose())
{
std::cout << "-- Done saving model. Took " << stop - start << " seconds." << std::endl;
}
}
bool Session::restore(int& iteration)
{
std::shared_ptr<StepFile> stepFile = nullptr;
if (m_rootFile)
{
stepFile = m_rootFile->openLastStepFile();
}
if (!stepFile)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = -1;
return false;
}
else
{
if (m_config.getVerbose())
{
std::cout << "-- Restoring model, predictions,... from '" << stepFile->getStepFileName() << "'." << std::endl;
}
BaseSession::restore(stepFile);
//restore last iteration index
if (stepFile->getCheckpoint())
{
iteration = stepFile->getIsample() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
else
{
iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
return true;
}
}
std::shared_ptr<StatusItem> Session::getStatus() const
{
std::shared_ptr<StatusItem> ret = std::make_shared<StatusItem>();
if (m_iter < 0)
{
ret->phase = "Initial";
ret->iter = m_iter + 1;
ret->phase_iter = 0;
}
else if (m_iter < m_config.getBurnin())
{
ret->phase = "Burnin";
ret->iter = m_iter + 1;
ret->phase_iter = m_config.getBurnin();
}
else
{
ret->phase = "Sample";
ret->iter = m_iter - m_config.getBurnin() + 1;
ret->phase_iter = m_config.getNSamples();
}
for (int i = 0; i < (int)model().nmodes(); ++i)
{
ret->model_norms.push_back(model().U(i).norm());
}
ret->train_rmse = data().train_rmse(model());
ret->rmse_avg = m_pred->rmse_avg;
ret->rmse_1sample = m_pred->rmse_1sample;
ret->auc_avg = m_pred->auc_avg;
ret->auc_1sample = m_pred->auc_1sample;
ret->elapsed_iter = m_secs_per_iter;
ret->nnz_per_sec = (double)(data().nnz()) / m_secs_per_iter;
ret->samples_per_sec = (double)(model().nsamples()) / m_secs_per_iter;
return ret;
}
void Session::printStatus(std::ostream& output, bool resume)
{
if(!m_config.getVerbose() &&
!m_config.getCsvStatus().size())
return;
auto status_item = getStatus();
std::string resumeString = resume ? "Continue from " : std::string();
if (m_config.getVerbose() > 0)
{
if (m_iter < 0)
{
output << " ====== Initial phase ====== " << std::endl;
}
else if (m_iter < m_config.getBurnin() && m_iter == 0)
{
output << " ====== Sampling (burning phase) ====== " << std::endl;
}
else if (m_iter == m_config.getBurnin())
{
output << " ====== Burn-in complete, averaging samples ====== " << std::endl;
}
output << resumeString
<< status_item->phase
<< " "
<< std::setfill(' ') << std::setw(3) << status_item->iter
<< "/"
<< std::setfill(' ') << std::setw(3) << status_item->phase_iter
<< ": RMSE: "
<< std::fixed << std::setprecision(4) << status_item->rmse_avg
<< " (1samp: "
<< std::fixed << std::setprecision(4) << status_item->rmse_1sample
<< ")";
if (m_config.getClassify())
{
output << " AUC:"
<< std::fixed << std::setprecision(4) << status_item->auc_avg
<< " (1samp: "
<< std::fixed << std::setprecision(4) << status_item->auc_1sample
<< ")"
<< std::endl;
}
output << " U:[";
for(double n: status_item->model_norms)
{
output << std::scientific << std::setprecision(2) << n << ", ";
}
output << "] [took: "
<< std::fixed << std::setprecision(1) << status_item->elapsed_iter
<< "s]"
<< std::endl;
if (m_config.getVerbose() > 1)
{
output << std::fixed << std::setprecision(4) << " RMSE train: " << status_item->train_rmse << std::endl;
output << " Priors:" << std::endl;
for(const auto &p : m_priors)
p->status(output, " ");
output << " Model:" << std::endl;
model().status(output, " ");
output << " Noise:" << std::endl;
data().status(output, " ");
}
if (m_config.getVerbose() > 2)
{
output << " Compute Performance: " << status_item->samples_per_sec << " samples/sec, " << status_item->nnz_per_sec << " nnz/sec" << std::endl;
}
}
if (m_config.getCsvStatus().size())
{
std::ofstream f(m_config.getCsvStatus(), std::ofstream::out | std::ofstream::app);
THROWERROR_ASSERT_MSG(f, "Could not open status csv file: " + m_config.getCsvStatus());
f << status_item->asCsvString() << std::endl;
}
}
std::string StatusItem::getCsvHeader()
{
return "phase;iter;phase_len;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;elapsed";
}
std::string StatusItem::asCsvString() const
{
char ret[1024];
snprintf(ret, 1024, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%0.1f",
phase.c_str(), iter, phase_iter, rmse_avg, rmse_1sample, train_rmse,
auc_1sample, auc_avg, elapsed_iter);
return ret;
}
void Session::initRng()
{
//init random generator
if (m_config.getRandomSeedSet())
init_bmrng(m_config.getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> Session::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}
<|endoftext|> |
<commit_before>// This file is part of the VroomJs library.
//
// Author:
// Federico Di Gregorio <[email protected]>
//
// Copyright © 2013 Federico Di Gregorio <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "vroomjs.h"
using namespace v8;
extern "C" jsvalue jsvalue_alloc_array(const int32_t length);
static Handle<Value> managed_prop_get(Local<String> name, const AccessorInfo& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->GetPropertyValue(name);
}
static Handle<Value> managed_prop_set(Local<String> name, Local<Value> value, const AccessorInfo& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->SetPropertyValue(name, value);
}
static Handle<Value> managed_call(const Arguments& args)
{
Local<Object> self = args.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->Invoke(args);
}
JsEngine* JsEngine::New()
{
JsEngine* engine = new JsEngine();
if (engine != NULL) {
engine->isolate_ = Isolate::New();
Locker locker(engine->isolate_);
Isolate::Scope isolate_scope(engine->isolate_);
engine->context_ = new Persistent<Context>(Context::New());
(*(engine->context_))->Enter();
// Setup the template we'll use for all managed object references.
HandleScope scope;
Handle<ObjectTemplate> o = ObjectTemplate::New();
o->SetInternalFieldCount(1);
o->SetNamedPropertyHandler(managed_prop_get, managed_prop_set);
o->SetCallAsFunctionHandler(managed_call);
Persistent<ObjectTemplate> p = Persistent<ObjectTemplate>::New(o);
engine->managed_template_ = new Persistent<ObjectTemplate>(p);
}
return engine;
}
void JsEngine::Dispose()
{
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
managed_template_->Dispose();
delete managed_template_;
context_->Dispose();
delete context_;
}
isolate_->Dispose();
}
jsvalue JsEngine::Execute(const uint16_t* str)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Handle<String> source = String::New(str);
Handle<Script> script = Script::Compile(source);
if (!script.IsEmpty()) {
Local<Value> result = script->Run();
if (result.IsEmpty())
v = ErrorFromV8(trycatch);
else
v = AnyFromV8(result);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::SetVariable(const uint16_t* name, jsvalue value)
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
Handle<Value> v = AnyToV8(value);
if ((*context_)->Global()->Set(String::New(name), v) == false) {
// TODO: Return an error if set failed.
}
(*context_)->Exit();
return AnyFromV8(Null());
}
jsvalue JsEngine::GetVariable(const uint16_t* name)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> value = (*context_)->Global()->Get(String::New(name));
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::GetPropertyValue(Persistent<Object>* obj, const uint16_t* name)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> value = (*obj)->Get(String::New(name));
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::SetPropertyValue(Persistent<Object>* obj, const uint16_t* name, jsvalue value)
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
Handle<Value> v = AnyToV8(value);
if ((*obj)->Set(String::New(name), v) == false) {
// TODO: Return an error if set failed.
}
(*context_)->Exit();
return AnyFromV8(Null());
}
jsvalue JsEngine::InvokeProperty(Persistent<Object>* obj, const uint16_t* name, jsvalue args)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> prop = (*obj)->Get(String::New(name));
if (prop.IsEmpty() || !prop->IsFunction()) {
v = StringFromV8(String::New("property not found or isn't a function"));
v.type = JSVALUE_TYPE_ERROR;
}
else {
Local<Value> argv[args.length];
ArrayToV8Args(args, argv);
// TODO: Check ArrayToV8Args return value (but right now can't fail, right?)
Local<Function> func = Local<Function>::Cast(prop);
Local<Value> value = func->Call(*obj, args.length, argv);
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::ErrorFromV8(TryCatch& trycatch)
{
jsvalue v;
Local<Value> exception = trycatch.Exception();
v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
v.value.str = 0;
v.length = 0;
// If this is a managed exception we need to place its ID inside the jsvalue
// and set the type JSVALUE_TYPE_MANAGED_ERROR to make sure the CLR side will
// throw on it. Else we just wrap and return the exception Object. Note that
// this is far from perfect because we ignore both the Message object and the
// stack stack trace. If the exception is not an object (but just a string,
// for example) we convert it with toString() and return that as an Exception.
// TODO: return a composite/special object with stack trace information.
if (exception->IsObject()) {
Local<Object> obj = Local<Object>::Cast(exception);
if (obj->InternalFieldCount() == 1) {
ManagedRef* ref = (ManagedRef*)obj->GetPointerFromInternalField(0);
v.type = JSVALUE_TYPE_MANAGED_ERROR;
v.length = ref->Id();
}
else {
v = WrappedFromV8(obj);
v.type = JSVALUE_TYPE_WRAPPED_ERROR;
}
}
else if (!exception.IsEmpty()) {
v = StringFromV8(exception);
v.type = JSVALUE_TYPE_ERROR;
}
return v;
}
jsvalue JsEngine::StringFromV8(Handle<Value> value)
{
jsvalue v;
Local<String> s = value->ToString();
v.length = s->Length();
v.value.str = new uint16_t[v.length+1];
if (v.value.str != NULL) {
s->Write(v.value.str);
v.type = JSVALUE_TYPE_STRING;
}
return v;
}
jsvalue JsEngine::WrappedFromV8(Handle<Object> obj)
{
jsvalue v;
v.type = JSVALUE_TYPE_WRAPPED;
v.length = 0;
v.value.ptr = new Persistent<Object>(Persistent<Object>::New(obj));
return v;
}
jsvalue JsEngine::ManagedFromV8(Handle<Object> obj)
{
jsvalue v;
ManagedRef* ref = (ManagedRef*)obj->GetPointerFromInternalField(0);
v.type = JSVALUE_TYPE_MANAGED;
v.length = ref->Id();
v.value.str = 0;
return v;
}
jsvalue JsEngine::AnyFromV8(Handle<Value> value)
{
jsvalue v;
// Initialize to a generic error.
v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
v.length = 0;
v.value.str = 0;
if (value->IsNull() || value->IsUndefined()) {
v.type = JSVALUE_TYPE_NULL;
}
else if (value->IsBoolean()) {
v.type = JSVALUE_TYPE_BOOLEAN;
v.value.i32 = value->BooleanValue() ? 1 : 0;
}
else if (value->IsInt32()) {
v.type = JSVALUE_TYPE_INTEGER;
v.value.i32 = value->Int32Value();
}
else if (value->IsUint32()) {
v.type = JSVALUE_TYPE_INDEX;
v.value.i64 = value->Uint32Value();
}
else if (value->IsNumber()) {
v.type = JSVALUE_TYPE_NUMBER;
v.value.num = value->NumberValue();
}
else if (value->IsString()) {
v = StringFromV8(value);
}
else if (value->IsDate()) {
v.type = JSVALUE_TYPE_DATE;
v.value.num = value->NumberValue();
}
else if (value->IsArray()) {
Handle<Array> object = Handle<Array>::Cast(value->ToObject());
v.length = object->Length();
jsvalue* array = new jsvalue[v.length];
if (array != NULL) {
for(int i = 0; i < v.length; i++) {
array[i] = AnyFromV8(object->Get(i));
}
v.type = JSVALUE_TYPE_ARRAY;
v.value.arr = array;
}
}
else if (value->IsFunction()) {
}
else if (value->IsObject()) {
Handle<Object> obj = Handle<Object>::Cast(value);
if (obj->InternalFieldCount() == 1)
v = ManagedFromV8(obj);
else
v = WrappedFromV8(obj);
}
return v;
}
Handle<Value> JsEngine::AnyToV8(jsvalue v)
{
if (v.type == JSVALUE_TYPE_NULL) {
return Null();
}
if (v.type == JSVALUE_TYPE_BOOLEAN) {
return Boolean::New(v.value.i32);
}
if (v.type == JSVALUE_TYPE_INTEGER) {
return Int32::New(v.value.i32);
}
if (v.type == JSVALUE_TYPE_NUMBER) {
return Number::New(v.value.num);
}
if (v.type == JSVALUE_TYPE_STRING) {
return String::New(v.value.str);
}
if (v.type == JSVALUE_TYPE_DATE) {
return Date::New(v.value.num);
}
// This is an ID to a managed object that lives inside the JsEngine keep-alive
// cache. We just wrap it and the pointer to the engine inside an External. A
// managed error is still a CLR object so it is wrapped exactly as a normal
// managed object.
if (v.type == JSVALUE_TYPE_MANAGED || v.type == JSVALUE_TYPE_MANAGED_ERROR) {
ManagedRef* ref = new ManagedRef(this, v.length);
Local<Object> obj = (*(managed_template_))->NewInstance();
obj->SetInternalField(0, External::New(ref));
return obj;
}
return Null();
}
int32_t JsEngine::ArrayToV8Args(jsvalue value, Handle<Value> preallocatedArgs[])
{
if (value.type != JSVALUE_TYPE_ARRAY)
return -1;
for (int i=0 ; i < value.length ; i++) {
preallocatedArgs[i] = AnyToV8(value.value.arr[i]);
}
return value.length;
}
jsvalue JsEngine::ArrayFromArguments(const Arguments& args)
{
jsvalue v = jsvalue_alloc_array(args.Length());
for (int i=0 ; i < v.length ; i++) {
v.value.arr[i] = AnyFromV8(args[i]);
}
return v;
}<commit_msg>[libvroomjs] Added callback to dispose of managed references<commit_after>// This file is part of the VroomJs library.
//
// Author:
// Federico Di Gregorio <[email protected]>
//
// Copyright © 2013 Federico Di Gregorio <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "vroomjs.h"
using namespace v8;
extern "C" jsvalue jsvalue_alloc_array(const int32_t length);
static Handle<Value> managed_prop_get(Local<String> name, const AccessorInfo& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->GetPropertyValue(name);
}
static Handle<Value> managed_prop_set(Local<String> name, Local<Value> value, const AccessorInfo& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->SetPropertyValue(name, value);
}
static Handle<Value> managed_call(const Arguments& args)
{
Local<Object> self = args.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
ManagedRef* ref = (ManagedRef*)wrap->Value();
return ref->Invoke(args);
}
static void managed_destroy(Persistent<Value> object, void* parameter)
{
Persistent<Object> self = Persistent<Object>::Cast(object);
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
delete (ManagedRef*)wrap->Value();
object.Dispose();
}
JsEngine* JsEngine::New()
{
JsEngine* engine = new JsEngine();
if (engine != NULL) {
engine->isolate_ = Isolate::New();
Locker locker(engine->isolate_);
Isolate::Scope isolate_scope(engine->isolate_);
engine->context_ = new Persistent<Context>(Context::New());
(*(engine->context_))->Enter();
// Setup the template we'll use for all managed object references.
HandleScope scope;
Handle<ObjectTemplate> o = ObjectTemplate::New();
o->SetInternalFieldCount(1);
o->SetNamedPropertyHandler(managed_prop_get, managed_prop_set);
o->SetCallAsFunctionHandler(managed_call);
Persistent<ObjectTemplate> p = Persistent<ObjectTemplate>::New(o);
engine->managed_template_ = new Persistent<ObjectTemplate>(p);
}
return engine;
}
void JsEngine::Dispose()
{
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
managed_template_->Dispose();
delete managed_template_;
context_->Dispose();
delete context_;
}
isolate_->Dispose();
}
jsvalue JsEngine::Execute(const uint16_t* str)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Handle<String> source = String::New(str);
Handle<Script> script = Script::Compile(source);
if (!script.IsEmpty()) {
Local<Value> result = script->Run();
if (result.IsEmpty())
v = ErrorFromV8(trycatch);
else
v = AnyFromV8(result);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::SetVariable(const uint16_t* name, jsvalue value)
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
Handle<Value> v = AnyToV8(value);
if ((*context_)->Global()->Set(String::New(name), v) == false) {
// TODO: Return an error if set failed.
}
(*context_)->Exit();
return AnyFromV8(Null());
}
jsvalue JsEngine::GetVariable(const uint16_t* name)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> value = (*context_)->Global()->Get(String::New(name));
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::GetPropertyValue(Persistent<Object>* obj, const uint16_t* name)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> value = (*obj)->Get(String::New(name));
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::SetPropertyValue(Persistent<Object>* obj, const uint16_t* name, jsvalue value)
{
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
Handle<Value> v = AnyToV8(value);
if ((*obj)->Set(String::New(name), v) == false) {
// TODO: Return an error if set failed.
}
(*context_)->Exit();
return AnyFromV8(Null());
}
jsvalue JsEngine::InvokeProperty(Persistent<Object>* obj, const uint16_t* name, jsvalue args)
{
jsvalue v;
Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
(*context_)->Enter();
HandleScope scope;
TryCatch trycatch;
Local<Value> prop = (*obj)->Get(String::New(name));
if (prop.IsEmpty() || !prop->IsFunction()) {
v = StringFromV8(String::New("property not found or isn't a function"));
v.type = JSVALUE_TYPE_ERROR;
}
else {
Local<Value> argv[args.length];
ArrayToV8Args(args, argv);
// TODO: Check ArrayToV8Args return value (but right now can't fail, right?)
Local<Function> func = Local<Function>::Cast(prop);
Local<Value> value = func->Call(*obj, args.length, argv);
if (!value.IsEmpty()) {
v = AnyFromV8(value);
}
else {
v = ErrorFromV8(trycatch);
}
}
(*context_)->Exit();
return v;
}
jsvalue JsEngine::ErrorFromV8(TryCatch& trycatch)
{
jsvalue v;
Local<Value> exception = trycatch.Exception();
v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
v.value.str = 0;
v.length = 0;
// If this is a managed exception we need to place its ID inside the jsvalue
// and set the type JSVALUE_TYPE_MANAGED_ERROR to make sure the CLR side will
// throw on it. Else we just wrap and return the exception Object. Note that
// this is far from perfect because we ignore both the Message object and the
// stack stack trace. If the exception is not an object (but just a string,
// for example) we convert it with toString() and return that as an Exception.
// TODO: return a composite/special object with stack trace information.
if (exception->IsObject()) {
Local<Object> obj = Local<Object>::Cast(exception);
if (obj->InternalFieldCount() == 1) {
ManagedRef* ref = (ManagedRef*)obj->GetPointerFromInternalField(0);
v.type = JSVALUE_TYPE_MANAGED_ERROR;
v.length = ref->Id();
}
else {
v = WrappedFromV8(obj);
v.type = JSVALUE_TYPE_WRAPPED_ERROR;
}
}
else if (!exception.IsEmpty()) {
v = StringFromV8(exception);
v.type = JSVALUE_TYPE_ERROR;
}
return v;
}
jsvalue JsEngine::StringFromV8(Handle<Value> value)
{
jsvalue v;
Local<String> s = value->ToString();
v.length = s->Length();
v.value.str = new uint16_t[v.length+1];
if (v.value.str != NULL) {
s->Write(v.value.str);
v.type = JSVALUE_TYPE_STRING;
}
return v;
}
jsvalue JsEngine::WrappedFromV8(Handle<Object> obj)
{
jsvalue v;
v.type = JSVALUE_TYPE_WRAPPED;
v.length = 0;
v.value.ptr = new Persistent<Object>(Persistent<Object>::New(obj));
return v;
}
jsvalue JsEngine::ManagedFromV8(Handle<Object> obj)
{
jsvalue v;
ManagedRef* ref = (ManagedRef*)obj->GetPointerFromInternalField(0);
v.type = JSVALUE_TYPE_MANAGED;
v.length = ref->Id();
v.value.str = 0;
return v;
}
jsvalue JsEngine::AnyFromV8(Handle<Value> value)
{
jsvalue v;
// Initialize to a generic error.
v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
v.length = 0;
v.value.str = 0;
if (value->IsNull() || value->IsUndefined()) {
v.type = JSVALUE_TYPE_NULL;
}
else if (value->IsBoolean()) {
v.type = JSVALUE_TYPE_BOOLEAN;
v.value.i32 = value->BooleanValue() ? 1 : 0;
}
else if (value->IsInt32()) {
v.type = JSVALUE_TYPE_INTEGER;
v.value.i32 = value->Int32Value();
}
else if (value->IsUint32()) {
v.type = JSVALUE_TYPE_INDEX;
v.value.i64 = value->Uint32Value();
}
else if (value->IsNumber()) {
v.type = JSVALUE_TYPE_NUMBER;
v.value.num = value->NumberValue();
}
else if (value->IsString()) {
v = StringFromV8(value);
}
else if (value->IsDate()) {
v.type = JSVALUE_TYPE_DATE;
v.value.num = value->NumberValue();
}
else if (value->IsArray()) {
Handle<Array> object = Handle<Array>::Cast(value->ToObject());
v.length = object->Length();
jsvalue* array = new jsvalue[v.length];
if (array != NULL) {
for(int i = 0; i < v.length; i++) {
array[i] = AnyFromV8(object->Get(i));
}
v.type = JSVALUE_TYPE_ARRAY;
v.value.arr = array;
}
}
else if (value->IsFunction()) {
// TODO: how do we represent this on the CLR side? Delegate?
}
else if (value->IsObject()) {
Handle<Object> obj = Handle<Object>::Cast(value);
if (obj->InternalFieldCount() == 1)
v = ManagedFromV8(obj);
else
v = WrappedFromV8(obj);
}
return v;
}
Handle<Value> JsEngine::AnyToV8(jsvalue v)
{
if (v.type == JSVALUE_TYPE_NULL) {
return Null();
}
if (v.type == JSVALUE_TYPE_BOOLEAN) {
return Boolean::New(v.value.i32);
}
if (v.type == JSVALUE_TYPE_INTEGER) {
return Int32::New(v.value.i32);
}
if (v.type == JSVALUE_TYPE_NUMBER) {
return Number::New(v.value.num);
}
if (v.type == JSVALUE_TYPE_STRING) {
return String::New(v.value.str);
}
if (v.type == JSVALUE_TYPE_DATE) {
return Date::New(v.value.num);
}
// This is an ID to a managed object that lives inside the JsEngine keep-alive
// cache. We just wrap it and the pointer to the engine inside an External. A
// managed error is still a CLR object so it is wrapped exactly as a normal
// managed object.
if (v.type == JSVALUE_TYPE_MANAGED || v.type == JSVALUE_TYPE_MANAGED_ERROR) {
ManagedRef* ref = new ManagedRef(this, v.length);
Persistent<Object> obj = Persistent<Object>::New((*(managed_template_))->NewInstance());
obj->SetInternalField(0, External::New(ref));
obj.MakeWeak(NULL, managed_destroy);
return obj;
}
return Null();
}
int32_t JsEngine::ArrayToV8Args(jsvalue value, Handle<Value> preallocatedArgs[])
{
if (value.type != JSVALUE_TYPE_ARRAY)
return -1;
for (int i=0 ; i < value.length ; i++) {
preallocatedArgs[i] = AnyToV8(value.value.arr[i]);
}
return value.length;
}
jsvalue JsEngine::ArrayFromArguments(const Arguments& args)
{
jsvalue v = jsvalue_alloc_array(args.Length());
for (int i=0 ; i < v.length ; i++) {
v.value.arr[i] = AnyFromV8(args[i]);
}
return v;
}<|endoftext|> |
<commit_before>#ifndef HEADERLIB_HDR_MATH_HPP
#define HEADERLIB_HDR_MATH_HPP
/*
* math.hpp
* Common mathematical constructs
*
* Created on: 04.04.2016
* Author: andreas
*/
#include "hdr/core.hpp"
namespace hdr::math {
using ::hdr::std::Apply;
using ::hdr::std::False;
using ::hdr::std::True;
using ::hdr::std::flip;
using ::hdr::lambda::_0;
using ::hdr::lambda::_1;
using ::hdr::lambda::Lambda;
using ::hdr::lambda::IApply;
/** Utility to convert integers to types
*/
template<unsigned u> using Unsigned = Value<u>;
template<signed s> using Signed = Value<s>;
template<bool b> using Bool = Value<b>;
template<typename _Tp, _Tp a, _Tp b>
struct Plus<Value<a>, Value<b>> { using type = Value<a+b>; };
template<bool a, bool b>
struct Plus<Bool<a>, Bool<b>> { using type = Bool<a || b>; };
template<typename _Tp, _Tp a, _Tp b>
struct Mult<Value<a>, Value<b>> { using type = Value<a*b>; };
template<bool a, bool b>
struct Mult<Bool<a>, Bool<b>> { using type = Bool<a && b>; };
template<typename _Tp, _Tp a, _Tp b>
struct Minus<Value<a>, Value<b>> { using type = Value<a-b>; };
template<bool a, bool b>
struct Minus<Bool<a>, Bool<b>>;
template<typename _Tp, _Tp a, _Tp b>
struct Div<Value<a>, Value<b>> { using type = Value<a/b>; };
template<typename _Tp, _Tp a>
struct Div<Value<a>, Value<0>>;
template<bool a, bool b>
struct Div<Bool<a>, Bool<b>>;
template<typename _Tp, _Tp a, _Tp b>
struct Compare<Value<a>, Value<b>> { using type = Value<(a < b)>; };
/// Boolean manipulators
using not_ = Lambda<_0, False, True>;
using and_ = Lambda<_0, _1, False>;
using or_ = Lambda<_0, True, _1>;
using xor_ = Lambda<_0, IApply<not_, _1>, _1>;
template<typename Smaller>
struct TotalOrder {
using smaller = Smaller;
using greater = Apply<flip, smaller>;
using unequal = Lambda<or_, IApply<compare, _0, _1>, IApply<compare, _1, _0>>;
using equal = Lambda<not_, IApply<unequal, _0, _1>>;
};
using natural_order = TotalOrder<compare>;
} // hdrstd::math
#endif //HEADERLIB_HDR_MATH_HPP
<commit_msg>Fix bug in math comparison<commit_after>#ifndef HEADERLIB_HDR_MATH_HPP
#define HEADERLIB_HDR_MATH_HPP
/*
* math.hpp
* Common mathematical constructs
*
* Created on: 04.04.2016
* Author: andreas
*/
#include "hdr/core.hpp"
namespace hdr::math {
using ::hdr::std::Apply;
using ::hdr::std::False;
using ::hdr::std::True;
using ::hdr::std::flip;
using ::hdr::lambda::_0;
using ::hdr::lambda::_1;
using ::hdr::lambda::Lambda;
using ::hdr::lambda::IApply;
/** Utility to convert integers to types
*/
template<unsigned u> using Unsigned = Value<u>;
template<signed s> using Signed = Value<s>;
template<bool b> using Bool = Value<b>;
template<typename _Tp, _Tp a, _Tp b>
struct Plus<Value<a>, Value<b>> { using type = Value<a+b>; };
template<bool a, bool b>
struct Plus<Bool<a>, Bool<b>> { using type = Bool<a || b>; };
template<typename _Tp, _Tp a, _Tp b>
struct Mult<Value<a>, Value<b>> { using type = Value<a*b>; };
template<bool a, bool b>
struct Mult<Bool<a>, Bool<b>> { using type = Bool<a && b>; };
template<typename _Tp, _Tp a, _Tp b>
struct Minus<Value<a>, Value<b>> { using type = Value<a-b>; };
template<bool a, bool b>
struct Minus<Bool<a>, Bool<b>>;
template<typename _Tp, _Tp a, _Tp b>
struct Div<Value<a>, Value<b>> { using type = Value<a/b>; };
template<typename _Tp, _Tp a>
struct Div<Value<a>, Value<0>>;
template<bool a, bool b>
struct Div<Bool<a>, Bool<b>>;
template<typename _Tp, _Tp a, _Tp b>
struct Compare<Value<a>, Value<b>> { using type = ::hdr::std::FromStdBool<(a < b)>; };
/// Boolean manipulators
using not_ = Lambda<_0, False, True>;
using and_ = Lambda<_0, _1, False>;
using or_ = Lambda<_0, True, _1>;
using xor_ = Lambda<_0, IApply<not_, _1>, _1>;
template<typename Smaller>
struct TotalOrder {
using smaller = Smaller;
using greater = Apply<flip, smaller>;
using unequal = Lambda<or_, IApply<compare, _0, _1>, IApply<compare, _1, _0>>;
using equal = Lambda<not_, IApply<unequal, _0, _1>>;
};
using natural_order = TotalOrder<compare>;
} // hdrstd::math
#endif //HEADERLIB_HDR_MATH_HPP
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/pjrt/mlir_to_hlo.h"
#include <utility>
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/Parser.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/chlo_ops.h"
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h"
namespace xla {
Status MlirToXlaComputation(mlir::ModuleOp module,
XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::StatusScopedDiagnosticHandler diagnostic_handler(module->getContext());
{
mlir::PassManager pm(module->getContext());
pm.addNestedPass<mlir::FuncOp>(mlir::mhlo::createChloLegalizeToHloPass(
/*legalize_broadcasts=*/true, /*expand_compositions=*/true));
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
// In order to export to XLA, we must sink constants to control flow
// regions, since XLA uses functional control flow.
pm.addNestedPass<mlir::FuncOp>(
mlir::mhlo::createSinkConstantsToControlFlowPass());
if (failed(pm.run(module))) {
VLOG(1) << "MHLO->HLO lowering passes failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
VLOG(5) << "MHLO module after lowering, before HLO import ";
if (VLOG_IS_ON(5)) {
module->dump();
}
}
HloProto proto;
TF_RETURN_IF_ERROR(
ConvertMlirHloToHlo(module, &proto, use_tuple_args, return_tuple));
xla_computation = XlaComputation(std::move(*proto.mutable_hlo_module()));
return Status::OK();
}
StatusOr<mlir::OwningModuleRef> ParseMlirModuleString(
absl::string_view mlir_module_str, mlir::MLIRContext& context) {
mlir::OwningModuleRef module;
context.loadDialect<mlir::StandardOpsDialect>();
context.loadDialect<mlir::mhlo::MhloDialect>();
context.loadDialect<mlir::chlo::HloClientDialect>();
mlir::StatusScopedDiagnosticHandler diagnostic_handler(&context);
module = mlir::parseSourceString(
llvm::StringRef(mlir_module_str.data(), mlir_module_str.size()),
&context);
if (!module) {
return diagnostic_handler.ConsumeStatus();
}
if (failed(module->verify())) {
VLOG(1) << "MLIR verification failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
return std::move(module);
}
Status ParseMlirModuleStringAndConvertToXlaComputation(
absl::string_view mlir_module_str, XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::MLIRContext context;
TF_ASSIGN_OR_RETURN(mlir::OwningModuleRef module,
xla::ParseMlirModuleString(mlir_module_str, context));
return xla::MlirToXlaComputation(*module, xla_computation, use_tuple_args,
return_tuple);
}
} // namespace xla
<commit_msg>[JAX] Include JAX operator type in MHLO locations.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/pjrt/mlir_to_hlo.h"
#include <utility>
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/Parser.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/chlo_ops.h"
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h"
namespace xla {
Status MlirToXlaComputation(mlir::ModuleOp module,
XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::StatusScopedDiagnosticHandler diagnostic_handler(module->getContext());
{
mlir::PassManager pm(module->getContext());
pm.addNestedPass<mlir::FuncOp>(mlir::mhlo::createChloLegalizeToHloPass(
/*legalize_broadcasts=*/true, /*expand_compositions=*/true));
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
// In order to export to XLA, we must sink constants to control flow
// regions, since XLA uses functional control flow.
pm.addNestedPass<mlir::FuncOp>(
mlir::mhlo::createSinkConstantsToControlFlowPass());
if (failed(pm.run(module))) {
VLOG(1) << "MHLO->HLO lowering passes failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
VLOG(5) << "MHLO module after lowering, before HLO import ";
if (VLOG_IS_ON(5)) {
module->dump();
}
}
HloProto proto;
mlir::MlirToHloConversionOptions options;
// We don't want the conversion to muck with our operator names.
options.legalize_node_names = false;
TF_RETURN_IF_ERROR(
ConvertMlirHloToHlo(module, &proto, use_tuple_args, return_tuple,
/*shape_representation_fn=*/nullptr, options));
xla_computation = XlaComputation(std::move(*proto.mutable_hlo_module()));
return Status::OK();
}
StatusOr<mlir::OwningModuleRef> ParseMlirModuleString(
absl::string_view mlir_module_str, mlir::MLIRContext& context) {
mlir::OwningModuleRef module;
context.loadDialect<mlir::StandardOpsDialect>();
context.loadDialect<mlir::mhlo::MhloDialect>();
context.loadDialect<mlir::chlo::HloClientDialect>();
mlir::StatusScopedDiagnosticHandler diagnostic_handler(&context);
module = mlir::parseSourceString(
llvm::StringRef(mlir_module_str.data(), mlir_module_str.size()),
&context);
if (!module) {
return diagnostic_handler.ConsumeStatus();
}
if (failed(module->verify())) {
VLOG(1) << "MLIR verification failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
return std::move(module);
}
Status ParseMlirModuleStringAndConvertToXlaComputation(
absl::string_view mlir_module_str, XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::MLIRContext context;
TF_ASSIGN_OR_RETURN(mlir::OwningModuleRef module,
xla::ParseMlirModuleString(mlir_module_str, context));
return xla::MlirToXlaComputation(*module, xla_computation, use_tuple_args,
return_tuple);
}
} // namespace xla
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <string>
#include <utility>
#include "../fpdfsdk/include/fpdf_dataavail.h"
#include "../fpdfsdk/include/fpdf_ext.h"
#include "../fpdfsdk/include/fpdfformfill.h"
#include "../fpdfsdk/include/fpdftext.h"
#include "../fpdfsdk/include/fpdfview.h"
#include "v8/include/v8.h"
#ifdef _WIN32
#define snprintf _snprintf
#endif
enum OutputFormat {
OUTPUT_NONE,
OUTPUT_PPM,
#ifdef _WIN32
OUTPUT_BMP,
OUTPUT_EMF,
#endif
};
static void WritePpm(const char* pdf_name, int num, const void* buffer_void,
int stride, int width, int height) {
const char* buffer = reinterpret_cast<const char*>(buffer_void);
if (stride < 0 || width < 0 || height < 0)
return;
if (height > 0 && width > INT_MAX / height)
return;
int out_len = width * height;
if (out_len > INT_MAX / 3)
return;
out_len *= 3;
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num);
FILE* fp = fopen(filename, "wb");
if (!fp)
return;
fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height);
// Source data is B, G, R, unused.
// Dest data is R, G, B.
char* result = new char[out_len];
if (result) {
for (int h = 0; h < height; ++h) {
const char* src_line = buffer + (stride * h);
char* dest_line = result + (width * h * 3);
for (int w = 0; w < width; ++w) {
// R
dest_line[w * 3] = src_line[(w * 4) + 2];
// G
dest_line[(w * 3) + 1] = src_line[(w * 4) + 1];
// B
dest_line[(w * 3) + 2] = src_line[w * 4];
}
}
fwrite(result, out_len, 1, fp);
delete [] result;
}
fclose(fp);
}
#ifdef _WIN32
static void WriteBmp(const char* pdf_name, int num, const void* buffer,
int stride, int width, int height) {
if (stride < 0 || width < 0 || height < 0)
return;
if (height > 0 && width > INT_MAX / height)
return;
int out_len = stride * height;
if (out_len > INT_MAX / 3)
return;
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.bmp", pdf_name, num);
FILE* fp = fopen(filename, "wb");
if (!fp)
return;
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi) - sizeof(RGBQUAD);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height; // top-down image
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
BITMAPFILEHEADER file_header = {0};
file_header.bfType = 0x4d42;
file_header.bfSize = sizeof(file_header) + bmi.bmiHeader.biSize + out_len;
file_header.bfOffBits = file_header.bfSize - out_len;
fwrite(&file_header, sizeof(file_header), 1, fp);
fwrite(&bmi, bmi.bmiHeader.biSize, 1, fp);
fwrite(buffer, out_len, 1, fp);
fclose(fp);
}
void WriteEmf(FPDF_PAGE page, const char* pdf_name, int num) {
int width = static_cast<int>(FPDF_GetPageWidth(page));
int height = static_cast<int>(FPDF_GetPageHeight(page));
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.emf", pdf_name, num);
HDC dc = CreateEnhMetaFileA(NULL, filename, NULL, NULL);
HRGN rgn = CreateRectRgn(0, 0, width, height);
SelectClipRgn(dc, rgn);
DeleteObject(rgn);
SelectObject(dc, GetStockObject(NULL_PEN));
SelectObject(dc, GetStockObject(WHITE_BRUSH));
// If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less.
Rectangle(dc, 0, 0, width + 1, height + 1);
FPDF_RenderPage(dc, page, 0, 0, width, height, 0,
FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
DeleteEnhMetaFile(CloseEnhMetaFile(dc));
}
#endif
int Form_Alert(IPDF_JSPLATFORM*, FPDF_WIDESTRING, FPDF_WIDESTRING, int, int) {
printf("Form_Alert called.\n");
return 0;
}
void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
std::string feature = "Unknown";
switch (type) {
case FPDF_UNSP_DOC_XFAFORM:
feature = "XFA";
break;
case FPDF_UNSP_DOC_PORTABLECOLLECTION:
feature = "Portfolios_Packages";
break;
case FPDF_UNSP_DOC_ATTACHMENT:
case FPDF_UNSP_ANNOT_ATTACHMENT:
feature = "Attachment";
break;
case FPDF_UNSP_DOC_SECURITY:
feature = "Rights_Management";
break;
case FPDF_UNSP_DOC_SHAREDREVIEW:
feature = "Shared_Review";
break;
case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
feature = "Shared_Form";
break;
case FPDF_UNSP_ANNOT_3DANNOT:
feature = "3D";
break;
case FPDF_UNSP_ANNOT_MOVIE:
feature = "Movie";
break;
case FPDF_UNSP_ANNOT_SOUND:
feature = "Sound";
break;
case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
feature = "Screen";
break;
case FPDF_UNSP_ANNOT_SIG:
feature = "Digital_Signature";
break;
}
printf("Unsupported feature: %s.\n", feature.c_str());
}
bool ParseCommandLine(int argc, const char* argv[], OutputFormat* output_format,
std::list<const char*>* files) {
*output_format = OUTPUT_NONE;
files->clear();
int cur_arg = 1;
for (; cur_arg < argc; ++cur_arg) {
if (strcmp(argv[cur_arg], "--ppm") == 0)
*output_format = OUTPUT_PPM;
#ifdef _WIN32
else if (strcmp(argv[cur_arg], "--emf") == 0)
*output_format = OUTPUT_EMF;
else if (strcmp(argv[cur_arg], "--bmp") == 0)
*output_format = OUTPUT_BMP;
#endif
else
break;
}
if (cur_arg > 2) // Multiple options.
return false;
if (cur_arg >= argc) // No input files.
return false;
for (int i = cur_arg; i < argc; i++)
files->push_back(argv[i]);
return true;
}
class TestLoader {
public:
TestLoader(const char* pBuf, size_t len);
const char* m_pBuf;
size_t m_Len;
};
TestLoader::TestLoader(const char* pBuf, size_t len)
: m_pBuf(pBuf), m_Len(len) {
}
int Get_Block(void* param, unsigned long pos, unsigned char* pBuf,
unsigned long size) {
TestLoader* pLoader = (TestLoader*) param;
if (pos + size < pos || pos + size > pLoader->m_Len) return 0;
memcpy(pBuf, pLoader->m_pBuf + pos, size);
return 1;
}
bool Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
return true;
}
void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {
}
void RenderPdf(const char* name, const char* pBuf, size_t len,
OutputFormat format) {
printf("Rendering PDF file %s.\n", name);
IPDF_JSPLATFORM platform_callbacks;
memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
platform_callbacks.version = 1;
platform_callbacks.app_alert = Form_Alert;
FPDF_FORMFILLINFO form_callbacks;
memset(&form_callbacks, '\0', sizeof(form_callbacks));
form_callbacks.version = 1;
form_callbacks.m_pJsPlatform = &platform_callbacks;
TestLoader loader(pBuf, len);
FPDF_FILEACCESS file_access;
memset(&file_access, '\0', sizeof(file_access));
file_access.m_FileLen = static_cast<unsigned long>(len);
file_access.m_GetBlock = Get_Block;
file_access.m_Param = &loader;
FX_FILEAVAIL file_avail;
memset(&file_avail, '\0', sizeof(file_avail));
file_avail.version = 1;
file_avail.IsDataAvail = Is_Data_Avail;
FX_DOWNLOADHINTS hints;
memset(&hints, '\0', sizeof(hints));
hints.version = 1;
hints.AddSegment = Add_Segment;
FPDF_DOCUMENT doc;
FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
(void) FPDFAvail_IsDocAvail(pdf_avail, &hints);
if (!FPDFAvail_IsLinearized(pdf_avail)) {
printf("Non-linearized path...\n");
doc = FPDF_LoadCustomDocument(&file_access, NULL);
} else {
printf("Linearized path...\n");
doc = FPDFAvail_GetDocument(pdf_avail, NULL);
}
(void) FPDF_GetDocPermissions(doc);
(void) FPDFAvail_IsFormAvail(pdf_avail, &hints);
FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnviroument(doc, &form_callbacks);
FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
FPDF_SetFormFieldHighlightAlpha(form, 100);
int first_page = FPDFAvail_GetFirstPageNum(doc);
(void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints);
int page_count = FPDF_GetPageCount(doc);
for (int i = 0; i < page_count; ++i) {
(void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
}
FORM_DoDocumentJSAction(form);
FORM_DoDocumentOpenAction(form);
size_t rendered_pages = 0;
size_t bad_pages = 0;
for (int i = 0; i < page_count; ++i) {
FPDF_PAGE page = FPDF_LoadPage(doc, i);
if (!page) {
bad_pages ++;
continue;
}
FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
FORM_OnAfterLoadPage(page, form);
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
int width = static_cast<int>(FPDF_GetPageWidth(page));
int height = static_cast<int>(FPDF_GetPageHeight(page));
FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
rendered_pages ++;
FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
int stride = FPDFBitmap_GetStride(bitmap);
const char* buffer =
reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bitmap));
switch (format) {
#ifdef _WIN32
case OUTPUT_BMP:
WriteBmp(name, i, buffer, stride, width, height);
break;
case OUTPUT_EMF:
WriteEmf(page, name, i);
break;
#endif
case OUTPUT_PPM:
WritePpm(name, i, buffer, stride, width, height);
break;
default:
break;
}
FPDFBitmap_Destroy(bitmap);
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
FORM_OnBeforeClosePage(page, form);
FPDFText_ClosePage(text_page);
FPDF_ClosePage(page);
}
FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
FPDFDOC_ExitFormFillEnviroument(form);
FPDF_CloseDocument(doc);
FPDFAvail_Destroy(pdf_avail);
printf("Loaded, parsed and rendered %d pages.\n", rendered_pages);
printf("Skipped %d bad pages.\n", bad_pages);
}
int main(int argc, const char* argv[]) {
v8::V8::InitializeICU();
OutputFormat format = OUTPUT_NONE;
std::list<const char*> files;
if (!ParseCommandLine(argc, argv, &format, &files)) {
printf("Usage: pdfium_test [OPTION] [FILE]...\n");
printf("--ppm write page images <pdf-name>.<page-number>.ppm\n");
#ifdef _WIN32
printf("--bmp write page images <pdf-name>.<page-number>.bmp\n");
printf("--emf write page meta files <pdf-name>.<page-number>.emf\n");
#endif
return 1;
}
FPDF_InitLibrary(NULL);
UNSUPPORT_INFO unsuppored_info;
memset(&unsuppored_info, '\0', sizeof(unsuppored_info));
unsuppored_info.version = 1;
unsuppored_info.FSDK_UnSupport_Handler = Unsupported_Handler;
FSDK_SetUnSpObjProcessHandler(&unsuppored_info);
while (!files.empty()) {
const char* filename = files.front();
files.pop_front();
FILE* file = fopen(filename, "rb");
if (!file) {
fprintf(stderr, "Failed to open: %s\n", filename);
continue;
}
(void) fseek(file, 0, SEEK_END);
size_t len = ftell(file);
(void) fseek(file, 0, SEEK_SET);
char* pBuf = (char*) malloc(len);
size_t ret = fread(pBuf, 1, len, file);
(void) fclose(file);
if (ret != len) {
fprintf(stderr, "Failed to read: %s\n", filename);
} else {
RenderPdf(filename, pBuf, len, format);
}
free(pBuf);
}
FPDF_DestroyLibrary();
return 0;
}
<commit_msg>Fix compile on mac: format string mismatch error.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <string>
#include <utility>
#include "../fpdfsdk/include/fpdf_dataavail.h"
#include "../fpdfsdk/include/fpdf_ext.h"
#include "../fpdfsdk/include/fpdfformfill.h"
#include "../fpdfsdk/include/fpdftext.h"
#include "../fpdfsdk/include/fpdfview.h"
#include "v8/include/v8.h"
#ifdef _WIN32
#define snprintf _snprintf
#endif
enum OutputFormat {
OUTPUT_NONE,
OUTPUT_PPM,
#ifdef _WIN32
OUTPUT_BMP,
OUTPUT_EMF,
#endif
};
static void WritePpm(const char* pdf_name, int num, const void* buffer_void,
int stride, int width, int height) {
const char* buffer = reinterpret_cast<const char*>(buffer_void);
if (stride < 0 || width < 0 || height < 0)
return;
if (height > 0 && width > INT_MAX / height)
return;
int out_len = width * height;
if (out_len > INT_MAX / 3)
return;
out_len *= 3;
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num);
FILE* fp = fopen(filename, "wb");
if (!fp)
return;
fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height);
// Source data is B, G, R, unused.
// Dest data is R, G, B.
char* result = new char[out_len];
if (result) {
for (int h = 0; h < height; ++h) {
const char* src_line = buffer + (stride * h);
char* dest_line = result + (width * h * 3);
for (int w = 0; w < width; ++w) {
// R
dest_line[w * 3] = src_line[(w * 4) + 2];
// G
dest_line[(w * 3) + 1] = src_line[(w * 4) + 1];
// B
dest_line[(w * 3) + 2] = src_line[w * 4];
}
}
fwrite(result, out_len, 1, fp);
delete [] result;
}
fclose(fp);
}
#ifdef _WIN32
static void WriteBmp(const char* pdf_name, int num, const void* buffer,
int stride, int width, int height) {
if (stride < 0 || width < 0 || height < 0)
return;
if (height > 0 && width > INT_MAX / height)
return;
int out_len = stride * height;
if (out_len > INT_MAX / 3)
return;
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.bmp", pdf_name, num);
FILE* fp = fopen(filename, "wb");
if (!fp)
return;
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi) - sizeof(RGBQUAD);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height; // top-down image
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
BITMAPFILEHEADER file_header = {0};
file_header.bfType = 0x4d42;
file_header.bfSize = sizeof(file_header) + bmi.bmiHeader.biSize + out_len;
file_header.bfOffBits = file_header.bfSize - out_len;
fwrite(&file_header, sizeof(file_header), 1, fp);
fwrite(&bmi, bmi.bmiHeader.biSize, 1, fp);
fwrite(buffer, out_len, 1, fp);
fclose(fp);
}
void WriteEmf(FPDF_PAGE page, const char* pdf_name, int num) {
int width = static_cast<int>(FPDF_GetPageWidth(page));
int height = static_cast<int>(FPDF_GetPageHeight(page));
char filename[256];
snprintf(filename, sizeof(filename), "%s.%d.emf", pdf_name, num);
HDC dc = CreateEnhMetaFileA(NULL, filename, NULL, NULL);
HRGN rgn = CreateRectRgn(0, 0, width, height);
SelectClipRgn(dc, rgn);
DeleteObject(rgn);
SelectObject(dc, GetStockObject(NULL_PEN));
SelectObject(dc, GetStockObject(WHITE_BRUSH));
// If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less.
Rectangle(dc, 0, 0, width + 1, height + 1);
FPDF_RenderPage(dc, page, 0, 0, width, height, 0,
FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
DeleteEnhMetaFile(CloseEnhMetaFile(dc));
}
#endif
int Form_Alert(IPDF_JSPLATFORM*, FPDF_WIDESTRING, FPDF_WIDESTRING, int, int) {
printf("Form_Alert called.\n");
return 0;
}
void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
std::string feature = "Unknown";
switch (type) {
case FPDF_UNSP_DOC_XFAFORM:
feature = "XFA";
break;
case FPDF_UNSP_DOC_PORTABLECOLLECTION:
feature = "Portfolios_Packages";
break;
case FPDF_UNSP_DOC_ATTACHMENT:
case FPDF_UNSP_ANNOT_ATTACHMENT:
feature = "Attachment";
break;
case FPDF_UNSP_DOC_SECURITY:
feature = "Rights_Management";
break;
case FPDF_UNSP_DOC_SHAREDREVIEW:
feature = "Shared_Review";
break;
case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
feature = "Shared_Form";
break;
case FPDF_UNSP_ANNOT_3DANNOT:
feature = "3D";
break;
case FPDF_UNSP_ANNOT_MOVIE:
feature = "Movie";
break;
case FPDF_UNSP_ANNOT_SOUND:
feature = "Sound";
break;
case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
feature = "Screen";
break;
case FPDF_UNSP_ANNOT_SIG:
feature = "Digital_Signature";
break;
}
printf("Unsupported feature: %s.\n", feature.c_str());
}
bool ParseCommandLine(int argc, const char* argv[], OutputFormat* output_format,
std::list<const char*>* files) {
*output_format = OUTPUT_NONE;
files->clear();
int cur_arg = 1;
for (; cur_arg < argc; ++cur_arg) {
if (strcmp(argv[cur_arg], "--ppm") == 0)
*output_format = OUTPUT_PPM;
#ifdef _WIN32
else if (strcmp(argv[cur_arg], "--emf") == 0)
*output_format = OUTPUT_EMF;
else if (strcmp(argv[cur_arg], "--bmp") == 0)
*output_format = OUTPUT_BMP;
#endif
else
break;
}
if (cur_arg > 2) // Multiple options.
return false;
if (cur_arg >= argc) // No input files.
return false;
for (int i = cur_arg; i < argc; i++)
files->push_back(argv[i]);
return true;
}
class TestLoader {
public:
TestLoader(const char* pBuf, size_t len);
const char* m_pBuf;
size_t m_Len;
};
TestLoader::TestLoader(const char* pBuf, size_t len)
: m_pBuf(pBuf), m_Len(len) {
}
int Get_Block(void* param, unsigned long pos, unsigned char* pBuf,
unsigned long size) {
TestLoader* pLoader = (TestLoader*) param;
if (pos + size < pos || pos + size > pLoader->m_Len) return 0;
memcpy(pBuf, pLoader->m_pBuf + pos, size);
return 1;
}
bool Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
return true;
}
void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {
}
void RenderPdf(const char* name, const char* pBuf, size_t len,
OutputFormat format) {
printf("Rendering PDF file %s.\n", name);
IPDF_JSPLATFORM platform_callbacks;
memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
platform_callbacks.version = 1;
platform_callbacks.app_alert = Form_Alert;
FPDF_FORMFILLINFO form_callbacks;
memset(&form_callbacks, '\0', sizeof(form_callbacks));
form_callbacks.version = 1;
form_callbacks.m_pJsPlatform = &platform_callbacks;
TestLoader loader(pBuf, len);
FPDF_FILEACCESS file_access;
memset(&file_access, '\0', sizeof(file_access));
file_access.m_FileLen = static_cast<unsigned long>(len);
file_access.m_GetBlock = Get_Block;
file_access.m_Param = &loader;
FX_FILEAVAIL file_avail;
memset(&file_avail, '\0', sizeof(file_avail));
file_avail.version = 1;
file_avail.IsDataAvail = Is_Data_Avail;
FX_DOWNLOADHINTS hints;
memset(&hints, '\0', sizeof(hints));
hints.version = 1;
hints.AddSegment = Add_Segment;
FPDF_DOCUMENT doc;
FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
(void) FPDFAvail_IsDocAvail(pdf_avail, &hints);
if (!FPDFAvail_IsLinearized(pdf_avail)) {
printf("Non-linearized path...\n");
doc = FPDF_LoadCustomDocument(&file_access, NULL);
} else {
printf("Linearized path...\n");
doc = FPDFAvail_GetDocument(pdf_avail, NULL);
}
(void) FPDF_GetDocPermissions(doc);
(void) FPDFAvail_IsFormAvail(pdf_avail, &hints);
FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnviroument(doc, &form_callbacks);
FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
FPDF_SetFormFieldHighlightAlpha(form, 100);
int first_page = FPDFAvail_GetFirstPageNum(doc);
(void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints);
int page_count = FPDF_GetPageCount(doc);
for (int i = 0; i < page_count; ++i) {
(void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
}
FORM_DoDocumentJSAction(form);
FORM_DoDocumentOpenAction(form);
size_t rendered_pages = 0;
size_t bad_pages = 0;
for (int i = 0; i < page_count; ++i) {
FPDF_PAGE page = FPDF_LoadPage(doc, i);
if (!page) {
bad_pages ++;
continue;
}
FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
FORM_OnAfterLoadPage(page, form);
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
int width = static_cast<int>(FPDF_GetPageWidth(page));
int height = static_cast<int>(FPDF_GetPageHeight(page));
FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
rendered_pages ++;
FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
int stride = FPDFBitmap_GetStride(bitmap);
const char* buffer =
reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bitmap));
switch (format) {
#ifdef _WIN32
case OUTPUT_BMP:
WriteBmp(name, i, buffer, stride, width, height);
break;
case OUTPUT_EMF:
WriteEmf(page, name, i);
break;
#endif
case OUTPUT_PPM:
WritePpm(name, i, buffer, stride, width, height);
break;
default:
break;
}
FPDFBitmap_Destroy(bitmap);
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
FORM_OnBeforeClosePage(page, form);
FPDFText_ClosePage(text_page);
FPDF_ClosePage(page);
}
FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
FPDFDOC_ExitFormFillEnviroument(form);
FPDF_CloseDocument(doc);
FPDFAvail_Destroy(pdf_avail);
printf("Loaded, parsed and rendered %zu pages.\n", rendered_pages);
printf("Skipped %zu bad pages.\n", bad_pages);
}
int main(int argc, const char* argv[]) {
v8::V8::InitializeICU();
OutputFormat format = OUTPUT_NONE;
std::list<const char*> files;
if (!ParseCommandLine(argc, argv, &format, &files)) {
printf("Usage: pdfium_test [OPTION] [FILE]...\n");
printf("--ppm write page images <pdf-name>.<page-number>.ppm\n");
#ifdef _WIN32
printf("--bmp write page images <pdf-name>.<page-number>.bmp\n");
printf("--emf write page meta files <pdf-name>.<page-number>.emf\n");
#endif
return 1;
}
FPDF_InitLibrary(NULL);
UNSUPPORT_INFO unsuppored_info;
memset(&unsuppored_info, '\0', sizeof(unsuppored_info));
unsuppored_info.version = 1;
unsuppored_info.FSDK_UnSupport_Handler = Unsupported_Handler;
FSDK_SetUnSpObjProcessHandler(&unsuppored_info);
while (!files.empty()) {
const char* filename = files.front();
files.pop_front();
FILE* file = fopen(filename, "rb");
if (!file) {
fprintf(stderr, "Failed to open: %s\n", filename);
continue;
}
(void) fseek(file, 0, SEEK_END);
size_t len = ftell(file);
(void) fseek(file, 0, SEEK_SET);
char* pBuf = (char*) malloc(len);
size_t ret = fread(pBuf, 1, len, file);
(void) fclose(file);
if (ret != len) {
fprintf(stderr, "Failed to read: %s\n", filename);
} else {
RenderPdf(filename, pBuf, len, format);
}
free(pBuf);
}
FPDF_DestroyLibrary();
return 0;
}
<|endoftext|> |
<commit_before>#include "ExportFolderPropertiesOperation.h"
#include "MAPIFolders.h"
struct ID
{
WORD replid;
BYTE globcnt[6];
};
ExportFolderPropertiesOperation::ExportFolderPropertiesOperation(tstring *pstrBasePath, tstring *pstrMailbox, UserArgs::ActionScope nScope, Log *log, tstring *pstrPropTags, Log *exportFile)
:OperationBase(pstrBasePath, pstrMailbox, nScope, log)
{
this->exportFile = exportFile;
this->pstrPropTags = pstrPropTags;
}
ExportFolderPropertiesOperation::~ExportFolderPropertiesOperation()
{
}
HRESULT ExportFolderPropertiesOperation::Initialize(void)
{
HRESULT hr = S_OK;
std::vector<tstring> splitPropStrings;
CORg(OperationBase::Initialize());
splitPropStrings = Split(this->pstrPropTags->c_str(), (_T(',')));
lpPropsToExport = NULL;
CORg(MAPIAllocateBuffer(CbNewSPropTagArray(splitPropStrings.size()),
(LPVOID*)&lpPropsToExport));
this->lpPropsToExport->cValues = splitPropStrings.size();
for (INT x = 0; x < this->lpPropsToExport->cValues; x++)
{
ULONG ptag = std::wcstoul(splitPropStrings.at(x).c_str(), NULL, 16);
if (ptag == 0xffffffff)
{
hr = E_FAIL;
*pLog << "Failed to parse property tag: " << splitPropStrings.at(x);
goto Error;
}
else
{
lpPropsToExport->aulPropTag[x] = ptag;
}
}
*exportFile << _T("Folder Path,");
for (INT x = 0; x < this->lpPropsToExport->cValues; x++)
{
*exportFile << std::hex << this->lpPropsToExport->aulPropTag[x];
if (x + 1 < this->lpPropsToExport->cValues)
{
*exportFile << _T(",");
}
}
*exportFile << "\n";
Error:
return hr;
}
void ExportFolderPropertiesOperation::ProcessFolder(LPMAPIFOLDER folder, tstring folderPath)
{
HRESULT hr = S_OK;
*pLog << "Exporting properties for folder: " << folderPath.c_str() << "\n";
ULONG cCount = 0;
SPropValue *rgprops = NULL;
CORg(folder->GetProps(lpPropsToExport, MAPI_UNICODE, &cCount, &rgprops));
*exportFile << folderPath.c_str() << _T(",");
for (ULONG y = 0; y < cCount; y++)
{
SPropValue thisProp = rgprops[y];
if (PROP_TYPE(thisProp.ulPropTag) == PT_STRING8)
{
*exportFile << thisProp.Value.lpszA;
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_UNICODE)
{
*exportFile << thisProp.Value.lpszW;
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_I8)
{
if (thisProp.ulPropTag == 0x67480014)
{
ID* pid = (ID*)&thisProp.Value.li.QuadPart;
ULONG ul = 0;
for (int i = 0; i < 6; ++i)
{
ul <<= 8;
ul += pid->globcnt[i];
}
*exportFile << std::hex << pid->replid << _T("-") << ul;
}
else
{
*exportFile << std::hex << thisProp.Value.li.QuadPart;
}
}
if (y + 1 < cCount)
{
*exportFile << _T(",");
}
}
*exportFile << "\n";
MAPIFreeBuffer(rgprops);
Cleanup:
return;
Error:
goto Cleanup;
}<commit_msg>- Updated ExportFolderProperties to support PT_LONG, PT_BOOLEAN, PT_BINARY - Changed it to output I8 in base 10 when it's not a FID<commit_after>#include "ExportFolderPropertiesOperation.h"
#include "MAPIFolders.h"
struct ID
{
WORD replid;
BYTE globcnt[6];
};
ExportFolderPropertiesOperation::ExportFolderPropertiesOperation(tstring *pstrBasePath, tstring *pstrMailbox, UserArgs::ActionScope nScope, Log *log, tstring *pstrPropTags, Log *exportFile)
:OperationBase(pstrBasePath, pstrMailbox, nScope, log)
{
this->exportFile = exportFile;
this->pstrPropTags = pstrPropTags;
}
ExportFolderPropertiesOperation::~ExportFolderPropertiesOperation()
{
}
HRESULT ExportFolderPropertiesOperation::Initialize(void)
{
HRESULT hr = S_OK;
std::vector<tstring> splitPropStrings;
CORg(OperationBase::Initialize());
splitPropStrings = Split(this->pstrPropTags->c_str(), (_T(',')));
lpPropsToExport = NULL;
CORg(MAPIAllocateBuffer(CbNewSPropTagArray(splitPropStrings.size()),
(LPVOID*)&lpPropsToExport));
this->lpPropsToExport->cValues = splitPropStrings.size();
for (INT x = 0; x < this->lpPropsToExport->cValues; x++)
{
ULONG ptag = std::wcstoul(splitPropStrings.at(x).c_str(), NULL, 16);
if (ptag == 0xffffffff)
{
hr = E_FAIL;
*pLog << "Failed to parse property tag: " << splitPropStrings.at(x);
goto Error;
}
else
{
lpPropsToExport->aulPropTag[x] = ptag;
}
}
*exportFile << _T("Folder Path,");
for (INT x = 0; x < this->lpPropsToExport->cValues; x++)
{
*exportFile << std::hex << this->lpPropsToExport->aulPropTag[x];
if (x + 1 < this->lpPropsToExport->cValues)
{
*exportFile << _T(",");
}
}
*exportFile << "\n";
Error:
return hr;
}
void ExportFolderPropertiesOperation::ProcessFolder(LPMAPIFOLDER folder, tstring folderPath)
{
HRESULT hr = S_OK;
*pLog << "Exporting properties for folder: " << folderPath.c_str() << "\n";
ULONG cCount = 0;
SPropValue *rgprops = NULL;
CORg(folder->GetProps(lpPropsToExport, MAPI_UNICODE, &cCount, &rgprops));
*exportFile << folderPath.c_str() << _T(",");
for (ULONG y = 0; y < cCount; y++)
{
SPropValue thisProp = rgprops[y];
if (PROP_TYPE(thisProp.ulPropTag) == PT_STRING8)
{
*exportFile << thisProp.Value.lpszA;
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_UNICODE)
{
*exportFile << thisProp.Value.lpszW;
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_I8)
{
if (thisProp.ulPropTag == 0x67480014)
{
ID* pid = (ID*)&thisProp.Value.li.QuadPart;
ULONG ul = 0;
for (int i = 0; i < 6; ++i)
{
ul <<= 8;
ul += pid->globcnt[i];
}
*exportFile << std::hex << pid->replid << _T("-") << ul;
}
else
{
*exportFile << thisProp.Value.li.QuadPart;
}
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_LONG)
{
*exportFile << thisProp.Value.l;
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_BOOLEAN)
{
if (thisProp.Value.b)
{
*exportFile << "True";
}
else
{
*exportFile << "False";
}
}
else if (PROP_TYPE(thisProp.ulPropTag) == PT_BINARY)
{
for (ULONG i = 0; i < thisProp.Value.bin.cb; i++)
{
BYTE oneByte = thisProp.Value.bin.lpb[i];
if (oneByte < 0x10)
{
*exportFile << _T("0");
}
*exportFile << std::hex << oneByte;
}
}
else
{
*exportFile << _T("MAPIFolders cannot export this property type");
}
if (y + 1 < cCount)
{
*exportFile << _T(",");
}
}
*exportFile << "\n";
MAPIFreeBuffer(rgprops);
Cleanup:
return;
Error:
goto Cleanup;
}<|endoftext|> |
<commit_before>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0
AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
delete this->m_AIComponents.at(i);
}
return SUCCESS;
}
int AIHandler::Initialize(int max)
{
this->m_nrOfAIComponents = 0;
if (max < 0)
{
// temp
m_maxOfAIComponents = 3;
//return FAIL;
}
this->m_maxOfAIComponents = max;
for (int i = 0; i < this->m_maxOfAIComponents; i++)
{
m_AIComponents.push_back(CreateAIComponent(i));
}
return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
{
// AIComponent logic/behavior, movement of e.g. platforms
DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->m_position;
int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
int pattern = this->m_AIComponents.at(i)->m_pattern;
int time = this->m_AIComponents.at(i)->m_time;
int direction = this->m_AIComponents.at(i)->m_direction;
if (pattern == 1)
{
if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
{
if (direction == 0)
this->m_AIComponents.at(i)->m_direction = 1;
else
this->m_AIComponents.at(i)->m_direction = 0;
}
}
else if (pattern == 3)
{
//TODO Round-trip pattern
}
else
{
//Identical to pattern 2 (Circular)
if (direction == 0)
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint++;
if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = 0;
}
}
else
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint--;
if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
}
}
}
//Update position
DirectX::XMVECTOR v;
v = DirectX::XMVectorSubtract(
this->m_AIComponents.at(i)->m_waypoints[this->m_AIComponents.at(i)->m_nextWaypoint],
pos);
DirectX::XMVECTOR m;
m = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), 10); //Speed?
m = DirectX::XMVectorScale(m, deltaTime);
this->m_AIComponents.at(i)->m_position = DirectX::XMVectorMultiply(m, this->m_AIComponents.at(i)->m_position);
}
}
return SUCCESS;
}
void AIHandler::SetComponentActive(int compID)
{
this->m_AIComponents.at(compID)->m_active = true;
}
void AIHandler::SetComponentFalse(int compID)
{
this->m_AIComponents.at(compID)->m_active = false;
}
void AIHandler::SetEntityID(int compID, int entityID)
{
this->m_AIComponents.at(compID)->m_entityID = entityID;
}
void AIHandler::SetTriggered(int compID, bool triggered)
{
this->m_AIComponents.at(compID)->m_triggered = triggered;
}
void AIHandler::SetTime(int compID, int time)
{
this->m_AIComponents.at(compID)->m_time = time;
}
void AIHandler::SetSpeed(int compID, int speed)
{
this->m_AIComponents.at(compID)->m_speed = speed;
}
void AIHandler::SetDirection(int compID, int direction)
{
this->m_AIComponents.at(compID)->m_direction = direction;
}
void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}
void AIHandler::SetPattern(int compID, int pattern)
{
this->m_AIComponents.at(compID)->m_pattern = pattern;
}
void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
for (int i = 0; i < 8; i++)
{
this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
}
}
int AIHandler::GetNrOfAIComponents() const
{
return this->m_nrOfAIComponents;
}
DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
return this->m_AIComponents.at(compID)->m_position;
}
AIComponent* AIHandler::CreateAIComponent(int entityID)
{
AIComponent* newComponent = nullptr;
newComponent = new AIComponent;
newComponent->m_active = 0;
newComponent->m_entityID = entityID;
newComponent->m_position = DirectX::XMVECTOR();
newComponent->m_triggered = false;
newComponent->m_time = 0;
newComponent->m_speed = 0;
newComponent->m_direction = 0;
newComponent->m_currentWaypoint = 0;
newComponent->m_nrOfWaypoint = 0;
for (int i = 0; i < 8; i++) {
newComponent->m_waypoints[i] = DirectX::XMVECTOR();
newComponent->m_nrOfWaypoint++;
}
return newComponent;
}
bool AIHandler::WaypointApprox(int compID)
{
using namespace DirectX;
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
,this->m_AIComponents.at(compID)->m_waypoints[current]);
float length = VectorLength(v);
if (length > 0.1)
{
return true;
}
return false;
}
int AIHandler::GetNextWaypoint(int compID, int pattern)
{
/*const int ARR_LEN = 10;
int arr[ARR_LEN] = { 0,1,2,3,4,5,6,7,8,9 };
for (int i = 0; i < ARR_LEN * 2; ++i)
cout << arr[i % ARR_LEN] << " ";*/
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
if (pattern == 1)
{
//TODO Linear pattern next waypoint logic
}
else
{
//if (this->m_AIComponents.at(compID)->m_nrOfWaypoint)
}
if (next == current)
{
}
this->m_AIComponents.at(compID)->m_currentWaypoint;
this->m_AIComponents.at(compID)->m_direction;
//this->m_AIComponents.at(compID)->m_waypoints[i];
return 0;
}
float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
return length;
}
<commit_msg>UPDATE Cleanup and initializing some new variables<commit_after>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0
AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
delete this->m_AIComponents.at(i);
}
return SUCCESS;
}
int AIHandler::Initialize(int max)
{
this->m_nrOfAIComponents = 0;
if (max < 0)
{
// temp
m_maxOfAIComponents = 3;
//return FAIL;
}
this->m_maxOfAIComponents = max;
for (int i = 0; i < this->m_maxOfAIComponents; i++)
{
m_AIComponents.push_back(CreateAIComponent(i));
}
return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
{
// AIComponent logic/behavior, movement of e.g. platforms
DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->m_position;
int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
int pattern = this->m_AIComponents.at(i)->m_pattern;
int time = this->m_AIComponents.at(i)->m_time;
int direction = this->m_AIComponents.at(i)->m_direction;
if (pattern == 1)
{
if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
{
if (direction == 0)
this->m_AIComponents.at(i)->m_direction = 1;
else
this->m_AIComponents.at(i)->m_direction = 0;
}
}
else if (pattern == 3)
{
//TODO Round-trip pattern
}
else
{
//Identical to pattern 2 (Circular)
if (direction == 0)
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint++;
if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = 0;
}
}
else
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint--;
if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
}
}
}
//Update position
DirectX::XMVECTOR v;
v = DirectX::XMVectorSubtract(
this->m_AIComponents.at(i)->m_waypoints[this->m_AIComponents.at(i)->m_nextWaypoint],
pos);
DirectX::XMVECTOR m;
m = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), 10); //Speed?
m = DirectX::XMVectorScale(m, deltaTime);
this->m_AIComponents.at(i)->m_position = DirectX::XMVectorMultiply(m, this->m_AIComponents.at(i)->m_position);
}
}
return SUCCESS;
}
void AIHandler::SetComponentActive(int compID)
{
this->m_AIComponents.at(compID)->m_active = true;
}
void AIHandler::SetComponentFalse(int compID)
{
this->m_AIComponents.at(compID)->m_active = false;
}
void AIHandler::SetEntityID(int compID, int entityID)
{
this->m_AIComponents.at(compID)->m_entityID = entityID;
}
void AIHandler::SetTriggered(int compID, bool triggered)
{
this->m_AIComponents.at(compID)->m_triggered = triggered;
}
void AIHandler::SetTime(int compID, int time)
{
this->m_AIComponents.at(compID)->m_time = time;
}
void AIHandler::SetSpeed(int compID, int speed)
{
this->m_AIComponents.at(compID)->m_speed = speed;
}
void AIHandler::SetDirection(int compID, int direction)
{
this->m_AIComponents.at(compID)->m_direction = direction;
}
void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}
void AIHandler::SetPattern(int compID, int pattern)
{
this->m_AIComponents.at(compID)->m_pattern = pattern;
}
void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
for (int i = 0; i < 8; i++)
{
this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
}
}
int AIHandler::GetNrOfAIComponents() const
{
return this->m_nrOfAIComponents;
}
DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
return this->m_AIComponents.at(compID)->m_position;
}
AIComponent* AIHandler::CreateAIComponent(int entityID)
{
AIComponent* newComponent = nullptr;
newComponent = new AIComponent;
newComponent->m_active = 0;
newComponent->m_entityID = entityID;
newComponent->m_position = DirectX::XMVECTOR();
newComponent->m_triggered = false;
newComponent->m_pattern = 0;
newComponent->m_time = 0;
newComponent->m_speed = 0;
newComponent->m_direction = 0;
newComponent->m_nextWaypoint = 0;
newComponent->m_currentWaypoint = 0;
newComponent->m_nrOfWaypoint = 0;
for (int i = 0; i < 8; i++) {
newComponent->m_waypoints[i] = DirectX::XMVECTOR();
newComponent->m_nrOfWaypoint++;
}
return newComponent;
}
bool AIHandler::WaypointApprox(int compID)
{
using namespace DirectX;
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
,this->m_AIComponents.at(compID)->m_waypoints[current]);
float length = VectorLength(v);
if (length > 0.1)
{
return true;
}
return false;
}
int AIHandler::GetNextWaypoint(int compID, int pattern)
{
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
if (pattern == 1)
{
//TODO Linear pattern next waypoint logic
}
else
{
}
if (next == current)
{
}
this->m_AIComponents.at(compID)->m_currentWaypoint;
this->m_AIComponents.at(compID)->m_direction;
return 0;
}
float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
return length;
}
<|endoftext|> |
<commit_before> #include <stdio.h>
#include "log.h"
int main(void)
{
Logger::GetLogger()->log_open("mycat");
int i = 10;
float j = 23.45;
Logger::GetLogger()->Info("info,%d,%f", i,j);
Logger::GetLogger()->Error("error");
Logger::GetLogger()->Warning("warn");
Logger::GetLogger()->log_close();
return 0;
}
<commit_msg>git_rm<commit_after><|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------
// Implementation of the derived class for track residuals
// based on linear chi2 minimization (in approximation of
// small alignment angles and translations)
//
//-----------------------------------------------------------------
#include <TMath.h>
#include <TGeoMatrix.h>
#include "AliLog.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "AliTrackResidualsFast.h"
#include <TMatrixDSym.h>
#include <TMatrixDSymEigen.h>
ClassImp(AliTrackResidualsFast)
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast():
AliTrackResiduals(),
fSumR(0)
{
// Default constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(Int_t ntracks):
AliTrackResiduals(ntracks),
fSumR(0)
{
// Constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(const AliTrackResidualsFast &res):
AliTrackResiduals(res),
fSumR(res.fSumR)
{
// Copy constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
}
//______________________________________________________________________________
AliTrackResidualsFast &AliTrackResidualsFast::operator= (const AliTrackResidualsFast& res)
{
// Assignment operator
((AliTrackResiduals *)this)->operator=(res);
for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
fSumR = res.fSumR;
return *this;
}
//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Minimize()
{
// Implementation of fast linear Chi2
// based minimization of track residuals sum
// if(fBFixed[0]||fBFixed[1]||fBFixed[2]||fBFixed[3]||fBFixed[4]||fBFixed[5])
// AliError("Cannot yet fix parameters in this minimizer");
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
fSumR = 0;
AliTrackPoint p1,p2;
for (Int_t itrack = 0; itrack < fLast; itrack++) {
if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
fVolArray[itrack]->GetPoint(p1,ipoint);
fTrackArray[itrack]->GetPoint(p2,ipoint);
AddPoints(p1,p2);
}
}
return Update();
// debug info
// Float_t chi2 = 0;
// for (Int_t itrack = 0; itrack < fLast; itrack++) {
// if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
// for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
// fVolArray[itrack]->GetPoint(p1,ipoint);
// fAlignObj->Transform(p1);
// fTrackArray[itrack]->GetPoint(p2,ipoint);
// Float_t residual = p2.GetResidual(p1,kFALSE);
// chi2 += residual;
// }
// }
// printf("Final chi2 = %f\n",chi2);
}
//______________________________________________________________________________
void AliTrackResidualsFast::AddPoints(AliTrackPoint &p, AliTrackPoint &pprime)
{
// Update the sums used for
// the linear chi2 minimization
Float_t xyz[3],xyzp[3];
Float_t cov[6],covp[6];
p.GetXYZ(xyz,cov); pprime.GetXYZ(xyzp,covp);
TMatrixDSym mcov(3);
mcov(0,0) = cov[0]; mcov(0,1) = cov[1]; mcov(0,2) = cov[2];
mcov(1,0) = cov[1]; mcov(1,1) = cov[3]; mcov(1,2) = cov[4];
mcov(2,0) = cov[2]; mcov(2,1) = cov[4]; mcov(2,2) = cov[5];
TMatrixDSym mcovp(3);
mcovp(0,0) = covp[0]; mcovp(0,1) = covp[1]; mcovp(0,2) = covp[2];
mcovp(1,0) = covp[1]; mcovp(1,1) = covp[3]; mcovp(1,2) = covp[4];
mcovp(2,0) = covp[2]; mcovp(2,1) = covp[4]; mcovp(2,2) = covp[5];
TMatrixDSym msum = mcov + mcovp;
msum.Invert();
if (!msum.IsValid()) return;
TMatrixD sums(3,1);
sums(0,0) = (xyzp[0]-xyz[0]);
sums(1,0) = (xyzp[1]-xyz[1]);
sums(2,0) = (xyzp[2]-xyz[2]);
TMatrixD sumst = sums.T(); sums.T();
TMatrixD mf(3,6);
mf(0,0) = 1; mf(1,0) = 0; mf(2,0) = 0;
mf(0,1) = 0; mf(1,1) = 1; mf(2,1) = 0;
mf(0,2) = 0; mf(1,2) = 0; mf(2,2) = 1;
mf(0,3) = 0; mf(1,3) = -xyz[2]; mf(2,3) = xyz[1];
mf(0,4) = xyz[2]; mf(1,4) = 0; mf(2,4) =-xyz[0];
mf(0,5) =-xyz[1]; mf(1,5) = xyz[0]; mf(2,5) = 0;
for(Int_t j=0;j<6;j++){
if(fBFixed[j]==kTRUE){
mf(0,j)=0.;mf(1,j)=0.;mf(2,j)=0.;
}
}
TMatrixD mft = mf.T(); mf.T();
TMatrixD sums2 = mft * msum * sums;
TMatrixD smatrix = mft * msum * mf;
fSum[0] += smatrix(0,0);
fSum[1] += smatrix(0,1);
fSum[2] += smatrix(0,2);
fSum[3] += smatrix(0,3);
fSum[4] += smatrix(0,4);
fSum[5] += smatrix(0,5);
fSum[6] += smatrix(1,1);
fSum[7] += smatrix(1,2);
fSum[8] += smatrix(1,3);
fSum[9] += smatrix(1,4);
fSum[10]+= smatrix(1,5);
fSum[11]+= smatrix(2,2);
fSum[12]+= smatrix(2,3);
fSum[13]+= smatrix(2,4);
fSum[14]+= smatrix(2,5);
fSum[15]+= smatrix(3,3);
fSum[16]+= smatrix(3,4);
fSum[17]+= smatrix(3,5);
fSum[18]+= smatrix(4,4);
fSum[19]+= smatrix(4,5);
fSum[20]+= smatrix(5,5);
fSum[21] += sums2(0,0);
fSum[22] += sums2(1,0);
fSum[23] += sums2(2,0);
fSum[24] += sums2(3,0);
fSum[25] += sums2(4,0);
fSum[26] += sums2(5,0);
TMatrixD tmp = sumst * msum * sums;
fSumR += tmp(0,0);
fNdf += 3;
}
//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Update()
{
// Find the alignment parameters
// by using the already accumulated
// sums
TMatrixDSym smatrix(6);
TMatrixD sums(1,6);
smatrix(0,0) = fSum[0];
smatrix(0,1) = smatrix(1,0) = fSum[1];
smatrix(0,2) = smatrix(2,0) = fSum[2];
smatrix(0,3) = smatrix(3,0) = fSum[3];
smatrix(0,4) = smatrix(4,0) = fSum[4];
smatrix(0,5) = smatrix(5,0) = fSum[5];
smatrix(1,1) = fSum[6];
smatrix(1,2) = smatrix(2,1) = fSum[7];
smatrix(1,3) = smatrix(3,1) = fSum[8];
smatrix(1,4) = smatrix(4,1) = fSum[9];
smatrix(1,5) = smatrix(5,1) = fSum[10];
smatrix(2,2) = fSum[11];
smatrix(2,3) = smatrix(3,2) = fSum[12];
smatrix(2,4) = smatrix(4,2) = fSum[13];
smatrix(2,5) = smatrix(5,2) = fSum[14];
smatrix(3,3) = fSum[15];
smatrix(3,4) = smatrix(4,3) = fSum[16];
smatrix(3,5) = smatrix(5,3) = fSum[17];
smatrix(4,4) = fSum[18];
smatrix(4,5) = smatrix(5,4) = fSum[19];
smatrix(5,5) = fSum[20];
sums(0,0) = fSum[21]; sums(0,1) = fSum[22]; sums(0,2) = fSum[23];
sums(0,3) = fSum[24]; sums(0,4) = fSum[25]; sums(0,5) = fSum[26];
Int_t fixedparamat[6]={0,0,0,0,0,0};
const Int_t unfixedparam=GetNFreeParam();
Int_t position[6],last=0;//position is of size 6 but only unfiexedparam indeces will be used
if(fBFixed[0]==kTRUE){
fixedparamat[0]=1;
}
else {
position[0]=0;
last++;
}
for(Int_t j=1;j<6;j++){
if(fBFixed[j]==kTRUE){
fixedparamat[j]=fixedparamat[j-1]+1;
}
else {
fixedparamat[j]=fixedparamat[j-1];
position[last]=j;
last++;
}
}
TMatrixDSym smatrixRedu(unfixedparam);
for(Int_t i=0;i<unfixedparam;i++){
for(Int_t j=0;j<unfixedparam;j++){
smatrixRedu(i,j)=smatrix(position[i],position[j]);
}
}
// smatrixRedu.Print();
smatrixRedu.Invert();
if (!smatrixRedu.IsValid()) {
printf("Minimization Failed! \n");
return kFALSE;
}
TMatrixDSym smatrixUp(6);
for(Int_t i=0;i<6;i++){
for(Int_t j=0;j<6;j++){
if(fBFixed[i]==kTRUE||fBFixed[j]==kTRUE)smatrixUp(i,j)=0.;
else smatrixUp(i,j)=smatrixRedu(i-fixedparamat[i],j-fixedparamat[j]);
}
}
Double_t covmatrarray[21];
for(Int_t i=0;i<6;i++){
for(Int_t j=0;j<=i;j++){
if(fBFixed[i]==kFALSE&&fBFixed[j]==kFALSE){
if(TMath::Abs(smatrixUp(i,j)/TMath::Sqrt(TMath::Abs(smatrixUp(i,i)*smatrixUp(j,j))))>1.01)printf("Too large Correlation number!\n");
}
covmatrarray[i*(i+1)/2+j]=smatrixUp(i,j);
}
}
TMatrixD res = sums*smatrixUp;
fAlignObj->SetPars(res(0,0),res(0,1),res(0,2),
TMath::RadToDeg()*res(0,3),
TMath::RadToDeg()*res(0,4),
TMath::RadToDeg()*res(0,5));
fAlignObj->SetCorrMatrix(covmatrarray);
TMatrixD tmp = res*sums.T();
fChi2 = fSumR - tmp(0,0);
fNdf -= unfixedparam;
return kTRUE;
}
<commit_msg>Coverity fix.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------
// Implementation of the derived class for track residuals
// based on linear chi2 minimization (in approximation of
// small alignment angles and translations)
//
//-----------------------------------------------------------------
#include <TMath.h>
#include <TGeoMatrix.h>
#include "AliLog.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "AliTrackResidualsFast.h"
#include <TMatrixDSym.h>
#include <TMatrixDSymEigen.h>
ClassImp(AliTrackResidualsFast)
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast():
AliTrackResiduals(),
fSumR(0)
{
// Default constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(Int_t ntracks):
AliTrackResiduals(ntracks),
fSumR(0)
{
// Constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}
//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(const AliTrackResidualsFast &res):
AliTrackResiduals(res),
fSumR(res.fSumR)
{
// Copy constructor
for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
}
//______________________________________________________________________________
AliTrackResidualsFast &AliTrackResidualsFast::operator= (const AliTrackResidualsFast& res)
{
// Assignment operator
((AliTrackResiduals *)this)->operator=(res);
for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
fSumR = res.fSumR;
return *this;
}
//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Minimize()
{
// Implementation of fast linear Chi2
// based minimization of track residuals sum
// if(fBFixed[0]||fBFixed[1]||fBFixed[2]||fBFixed[3]||fBFixed[4]||fBFixed[5])
// AliError("Cannot yet fix parameters in this minimizer");
for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
fSumR = 0;
AliTrackPoint p1,p2;
for (Int_t itrack = 0; itrack < fLast; itrack++) {
if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
fVolArray[itrack]->GetPoint(p1,ipoint);
fTrackArray[itrack]->GetPoint(p2,ipoint);
AddPoints(p1,p2);
}
}
return Update();
// debug info
// Float_t chi2 = 0;
// for (Int_t itrack = 0; itrack < fLast; itrack++) {
// if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
// for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
// fVolArray[itrack]->GetPoint(p1,ipoint);
// fAlignObj->Transform(p1);
// fTrackArray[itrack]->GetPoint(p2,ipoint);
// Float_t residual = p2.GetResidual(p1,kFALSE);
// chi2 += residual;
// }
// }
// printf("Final chi2 = %f\n",chi2);
}
//______________________________________________________________________________
void AliTrackResidualsFast::AddPoints(AliTrackPoint &p, AliTrackPoint &pprime)
{
// Update the sums used for
// the linear chi2 minimization
Float_t xyz[3],xyzp[3];
Float_t cov[6],covp[6];
p.GetXYZ(xyz,cov); pprime.GetXYZ(xyzp,covp);
TMatrixDSym mcov(3);
mcov(0,0) = cov[0]; mcov(0,1) = cov[1]; mcov(0,2) = cov[2];
mcov(1,0) = cov[1]; mcov(1,1) = cov[3]; mcov(1,2) = cov[4];
mcov(2,0) = cov[2]; mcov(2,1) = cov[4]; mcov(2,2) = cov[5];
TMatrixDSym mcovp(3);
mcovp(0,0) = covp[0]; mcovp(0,1) = covp[1]; mcovp(0,2) = covp[2];
mcovp(1,0) = covp[1]; mcovp(1,1) = covp[3]; mcovp(1,2) = covp[4];
mcovp(2,0) = covp[2]; mcovp(2,1) = covp[4]; mcovp(2,2) = covp[5];
TMatrixDSym msum = mcov + mcovp;
msum.Invert();
if (!msum.IsValid()) return;
TMatrixD sums(3,1);
sums(0,0) = (xyzp[0]-xyz[0]);
sums(1,0) = (xyzp[1]-xyz[1]);
sums(2,0) = (xyzp[2]-xyz[2]);
TMatrixD sumst = sums.T(); sums.T();
TMatrixD mf(3,6);
mf(0,0) = 1; mf(1,0) = 0; mf(2,0) = 0;
mf(0,1) = 0; mf(1,1) = 1; mf(2,1) = 0;
mf(0,2) = 0; mf(1,2) = 0; mf(2,2) = 1;
mf(0,3) = 0; mf(1,3) = -xyz[2]; mf(2,3) = xyz[1];
mf(0,4) = xyz[2]; mf(1,4) = 0; mf(2,4) =-xyz[0];
mf(0,5) =-xyz[1]; mf(1,5) = xyz[0]; mf(2,5) = 0;
for(Int_t j=0;j<6;j++){
if(fBFixed[j]==kTRUE){
mf(0,j)=0.;mf(1,j)=0.;mf(2,j)=0.;
}
}
TMatrixD mft = mf.T(); mf.T();
TMatrixD sums2 = mft * msum * sums;
TMatrixD smatrix = mft * msum * mf;
fSum[0] += smatrix(0,0);
fSum[1] += smatrix(0,1);
fSum[2] += smatrix(0,2);
fSum[3] += smatrix(0,3);
fSum[4] += smatrix(0,4);
fSum[5] += smatrix(0,5);
fSum[6] += smatrix(1,1);
fSum[7] += smatrix(1,2);
fSum[8] += smatrix(1,3);
fSum[9] += smatrix(1,4);
fSum[10]+= smatrix(1,5);
fSum[11]+= smatrix(2,2);
fSum[12]+= smatrix(2,3);
fSum[13]+= smatrix(2,4);
fSum[14]+= smatrix(2,5);
fSum[15]+= smatrix(3,3);
fSum[16]+= smatrix(3,4);
fSum[17]+= smatrix(3,5);
fSum[18]+= smatrix(4,4);
fSum[19]+= smatrix(4,5);
fSum[20]+= smatrix(5,5);
fSum[21] += sums2(0,0);
fSum[22] += sums2(1,0);
fSum[23] += sums2(2,0);
fSum[24] += sums2(3,0);
fSum[25] += sums2(4,0);
fSum[26] += sums2(5,0);
TMatrixD tmp = sumst * msum * sums;
fSumR += tmp(0,0);
fNdf += 3;
}
//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Update()
{
// Find the alignment parameters
// by using the already accumulated
// sums
TMatrixDSym smatrix(6);
TMatrixD sums(1,6);
smatrix(0,0) = fSum[0];
smatrix(0,1) = smatrix(1,0) = fSum[1];
smatrix(0,2) = smatrix(2,0) = fSum[2];
smatrix(0,3) = smatrix(3,0) = fSum[3];
smatrix(0,4) = smatrix(4,0) = fSum[4];
smatrix(0,5) = smatrix(5,0) = fSum[5];
smatrix(1,1) = fSum[6];
smatrix(1,2) = smatrix(2,1) = fSum[7];
smatrix(1,3) = smatrix(3,1) = fSum[8];
smatrix(1,4) = smatrix(4,1) = fSum[9];
smatrix(1,5) = smatrix(5,1) = fSum[10];
smatrix(2,2) = fSum[11];
smatrix(2,3) = smatrix(3,2) = fSum[12];
smatrix(2,4) = smatrix(4,2) = fSum[13];
smatrix(2,5) = smatrix(5,2) = fSum[14];
smatrix(3,3) = fSum[15];
smatrix(3,4) = smatrix(4,3) = fSum[16];
smatrix(3,5) = smatrix(5,3) = fSum[17];
smatrix(4,4) = fSum[18];
smatrix(4,5) = smatrix(5,4) = fSum[19];
smatrix(5,5) = fSum[20];
sums(0,0) = fSum[21]; sums(0,1) = fSum[22]; sums(0,2) = fSum[23];
sums(0,3) = fSum[24]; sums(0,4) = fSum[25]; sums(0,5) = fSum[26];
Int_t fixedparamat[6]={0,0,0,0,0,0};
const Int_t unfixedparam=GetNFreeParam();
Int_t position[6]={0,0,0,0,0,0};
Int_t last=0;//position is of size 6 but only unfiexedparam indeces will be used
if(fBFixed[0]==kTRUE){
fixedparamat[0]=1;
}
else {
position[0]=0;
last++;
}
for(Int_t j=1;j<6;j++){
if(fBFixed[j]==kTRUE){
fixedparamat[j]=fixedparamat[j-1]+1;
}
else {
fixedparamat[j]=fixedparamat[j-1];
position[last]=j;
last++;
}
}
TMatrixDSym smatrixRedu(unfixedparam);
for(Int_t i=0;i<unfixedparam;i++){
for(Int_t j=0;j<unfixedparam;j++){
smatrixRedu(i,j)=smatrix(position[i],position[j]);
}
}
// smatrixRedu.Print();
smatrixRedu.Invert();
if (!smatrixRedu.IsValid()) {
printf("Minimization Failed! \n");
return kFALSE;
}
TMatrixDSym smatrixUp(6);
for(Int_t i=0;i<6;i++){
for(Int_t j=0;j<6;j++){
if(fBFixed[i]==kTRUE||fBFixed[j]==kTRUE)smatrixUp(i,j)=0.;
else smatrixUp(i,j)=smatrixRedu(i-fixedparamat[i],j-fixedparamat[j]);
}
}
Double_t covmatrarray[21];
for(Int_t i=0;i<6;i++){
for(Int_t j=0;j<=i;j++){
if(fBFixed[i]==kFALSE&&fBFixed[j]==kFALSE){
if(TMath::Abs(smatrixUp(i,j)/TMath::Sqrt(TMath::Abs(smatrixUp(i,i)*smatrixUp(j,j))))>1.01)printf("Too large Correlation number!\n");
}
covmatrarray[i*(i+1)/2+j]=smatrixUp(i,j);
}
}
TMatrixD res = sums*smatrixUp;
fAlignObj->SetPars(res(0,0),res(0,1),res(0,2),
TMath::RadToDeg()*res(0,3),
TMath::RadToDeg()*res(0,4),
TMath::RadToDeg()*res(0,5));
fAlignObj->SetCorrMatrix(covmatrarray);
TMatrixD tmp = res*sums.T();
fChi2 = fSumR - tmp(0,0);
fNdf -= unfixedparam;
return kTRUE;
}
<|endoftext|> |
<commit_before>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <oaidl.h>
#include <objbase.h>
#include <AtlBase.h>
#include <AtlConv.h>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdlib.h>
#include "FSAPI.h"
#include "dictationbridge-core/master/master.h"
#include "combool.h"
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")
#define ERR(x, msg) do { \
if(x != S_OK) {\
MessageBox(NULL, msg L"\n", NULL, NULL);\
exit(1);\
}\
} while(0)
std::string wideToString(wchar_t const * text, unsigned int length) {
auto tmp = new char[length*2+1];
auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text,
length, tmp, length*2,
NULL, NULL);
tmp[resultingLen] = '\0';
std::string ret(tmp);
delete[] tmp;
return ret;
}
std::string BSTRToString(BSTR text) {
unsigned int len = SysStringLen(text);
return wideToString(text, len);
}
CComPtr<IJawsApi> pJfw =nullptr;
void initSpeak() {
CLSID JFWClass;
auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
ERR(res, L"Couldn't get Jaws interface ID");
res =pJfw.CoCreateInstance(JFWClass);
ERR(res, L"Couldn't create Jaws interface");
}
void speak(std::wstring text) {
CComBSTR bS =CComBSTR(text.size(), text.data());
CComBool silence =false;
CComBool bResult;
pJfw->SayString(bS, silence, &bResult);
}
void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
//We need to replace \r with nothing.
std::wstring text =textUnprocessed;
text.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {
return checkingCharacter == '\r';
}), end(text));
if(text.compare(L"\n\n") ==0
|| text.compare(L"") ==0 //new paragraph in word.
) {
speak(L"New paragraph.");
}
else if(text.compare(L"\n") ==0) {
speak(L"New line.");
}
else {
speak(text.c_str());
}
}
void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
std::wstringstream deletedText;
deletedText << "Deleted ";
deletedText << text;
speak(deletedText.str().c_str());
}
//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
std::wstring MICROPHONE_OFF = L"Dragon's microphone is off;";
std::wstring MICROPHONE_ON = L"Normal mode: You can dictate and use voice";
std::wstring MICROPHONE_SLEEPING = L"The microphone is asleep;";
std::wstring microphoneState;
void announceMicrophoneState(const std::wstring state) {
if(state == MICROPHONE_ON) speak(L"Microphone on.");
else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
else speak(L"Microphone in unknown state.");
}
wchar_t processNameBuffer[1024] = {0};
void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
//First, is it coming from natspeak.exe?
DWORD procId;
GetWindowThreadProcessId(hwnd, &procId);
auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
//We can't recover from this failing, so abort.
if(procHandle == NULL) return;
DWORD len = 1024;
auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
CloseHandle(procHandle);
if(res == 0) return;
std::wstring processName =processNameBuffer;
if(processName.find(L"dragonbar.exe") == std::string::npos
&& processName.find(L"natspeak.exe") == std::string::npos) return;
//Attempt to get the new text.
CComPtr<IAccessible> pAcc;
CComVariant vChild;
HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);
if(hres != S_OK) return;
CComBSTR bName;
hres = pAcc->get_accName(vChild, &bName);
if(hres != S_OK) return;
std::wstring name =bName;
const std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
std::wstring newState = microphoneState;
for(int i = 0; i < 3; i++) {
if(name.find(possibles[i]) != std::string::npos) {
newState = possibles[i];
break;
}
}
if(newState != microphoneState) {
announceMicrophoneState(newState);
microphoneState = newState;
}
}
int keepRunning = 1; // Goes to 0 on WM_CLOSE.
LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper";
LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {
if(msg == WM_CLOSE) keepRunning = 0;
return DefWindowProc(hwnd, msg, wparam, lparam);
}
int CALLBACK WinMain(_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow) {
// First, is a core running?
if(FindWindow(msgWindowClassName, NULL)) {
MessageBox(NULL, L"Core already running.", NULL, NULL);
return 0;
}
WNDCLASS windowClass = {0};
windowClass.lpfnWndProc = exitProc;
windowClass.hInstance = hInstance;
windowClass.lpszClassName = msgWindowClassName;
auto msgWindowClass = RegisterClass(&windowClass);
if(msgWindowClass == 0) {
MessageBox(NULL, L"Failed to register window class.", NULL, NULL);
return 0;
}
auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
if(msgWindowHandle == 0) {
MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL);
return 0;
}
HRESULT res;
res = OleInitialize(NULL);
ERR(res, L"Couldn't initialize OLE");
initSpeak();
auto started = DBMaster_Start();
if(!started) {
printf("Couldn't start DictationBridge-core\n");
return 1;
}
DBMaster_SetTextInsertedCallback(textCallback);
DBMaster_SetTextDeletedCallback(textDeletedCallback);
if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
printf("Couldn't register to receive events\n");
return 1;
}
MSG msg;
while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if(keepRunning == 0) break;
}
DBMaster_Stop();
OleUninitialize();
DestroyWindow(msgWindowHandle);
return 0;
}
<commit_msg>Remove code and includes that we no longer use.<commit_after>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <AtlBase.h>
#include <algorithm>
#include <sstream>
#include <string>
#include "FSAPI.h"
#include "dictationbridge-core/master/master.h"
#include "combool.h"
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")
#define ERR(x, msg) do { \
if(x != S_OK) {\
MessageBox(NULL, msg L"\n", NULL, NULL);\
exit(1);\
}\
} while(0)
CComPtr<IJawsApi> pJfw =nullptr;
void initSpeak() {
CLSID JFWClass;
auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
ERR(res, L"Couldn't get Jaws interface ID");
res =pJfw.CoCreateInstance(JFWClass);
ERR(res, L"Couldn't create Jaws interface");
}
void speak(std::wstring text) {
CComBSTR bS =CComBSTR(text.size(), text.data());
CComBool silence =false;
CComBool bResult;
pJfw->SayString(bS, silence, &bResult);
}
void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
//We need to replace \r with nothing.
std::wstring text =textUnprocessed;
text.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {
return checkingCharacter == '\r';
}), end(text));
if(text.compare(L"\n\n") ==0
|| text.compare(L"") ==0 //new paragraph in word.
) {
speak(L"New paragraph.");
}
else if(text.compare(L"\n") ==0) {
speak(L"New line.");
}
else {
speak(text.c_str());
}
}
void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
std::wstringstream deletedText;
deletedText << "Deleted ";
deletedText << text;
speak(deletedText.str().c_str());
}
//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
std::wstring MICROPHONE_OFF = L"Dragon's microphone is off;";
std::wstring MICROPHONE_ON = L"Normal mode: You can dictate and use voice";
std::wstring MICROPHONE_SLEEPING = L"The microphone is asleep;";
std::wstring microphoneState;
void announceMicrophoneState(const std::wstring state) {
if(state == MICROPHONE_ON) speak(L"Microphone on.");
else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
else speak(L"Microphone in unknown state.");
}
wchar_t processNameBuffer[1024] = {0};
void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
//First, is it coming from natspeak.exe?
DWORD procId;
GetWindowThreadProcessId(hwnd, &procId);
auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
//We can't recover from this failing, so abort.
if(procHandle == NULL) return;
DWORD len = 1024;
auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
CloseHandle(procHandle);
if(res == 0) return;
std::wstring processName =processNameBuffer;
if(processName.find(L"dragonbar.exe") == std::string::npos
&& processName.find(L"natspeak.exe") == std::string::npos) return;
//Attempt to get the new text.
CComPtr<IAccessible> pAcc;
CComVariant vChild;
HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);
if(hres != S_OK) return;
CComBSTR bName;
hres = pAcc->get_accName(vChild, &bName);
if(hres != S_OK) return;
std::wstring name =bName;
const std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
std::wstring newState = microphoneState;
for(int i = 0; i < 3; i++) {
if(name.find(possibles[i]) != std::string::npos) {
newState = possibles[i];
break;
}
}
if(newState != microphoneState) {
announceMicrophoneState(newState);
microphoneState = newState;
}
}
int keepRunning = 1; // Goes to 0 on WM_CLOSE.
LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper";
LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {
if(msg == WM_CLOSE) keepRunning = 0;
return DefWindowProc(hwnd, msg, wparam, lparam);
}
int CALLBACK WinMain(_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow) {
// First, is a core running?
if(FindWindow(msgWindowClassName, NULL)) {
MessageBox(NULL, L"Core already running.", NULL, NULL);
return 0;
}
WNDCLASS windowClass = {0};
windowClass.lpfnWndProc = exitProc;
windowClass.hInstance = hInstance;
windowClass.lpszClassName = msgWindowClassName;
auto msgWindowClass = RegisterClass(&windowClass);
if(msgWindowClass == 0) {
MessageBox(NULL, L"Failed to register window class.", NULL, NULL);
return 0;
}
auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
if(msgWindowHandle == 0) {
MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL);
return 0;
}
HRESULT res;
res = OleInitialize(NULL);
ERR(res, L"Couldn't initialize OLE");
initSpeak();
auto started = DBMaster_Start();
if(!started) {
printf("Couldn't start DictationBridge-core\n");
return 1;
}
DBMaster_SetTextInsertedCallback(textCallback);
DBMaster_SetTextDeletedCallback(textDeletedCallback);
if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
printf("Couldn't register to receive events\n");
return 1;
}
MSG msg;
while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if(keepRunning == 0) break;
}
DBMaster_Stop();
OleUninitialize();
DestroyWindow(msgWindowHandle);
return 0;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <SurgSim/Graphics/OsgBoxRepresentation.h>
#include <SurgSim/Graphics/OsgRigidTransformConversions.h>
#include <SurgSim/Graphics/OsgUnitBox.h>
#include <osg/Geode>
#include <osg/Shape>
#include <osg/ShapeDrawable>
using SurgSim::Graphics::OsgBoxRepresentation;
using SurgSim::Graphics::OsgUnitBox;
OsgBoxRepresentation::OsgBoxRepresentation(const std::string& name) : Representation(name), BoxRepresentation(name),
OsgRepresentation(name, new osg::Switch()),
m_sharedUnitBox(getSharedUnitBox()),
m_scale(1.0, 1.0, 1.0)
{
m_switch = static_cast<osg::Switch*>(getOsgNode().get());
m_switch->setName(name + " Switch");
m_transform = new osg::PositionAttitudeTransform();
m_switch->setName(name + " Transform");
m_transform->addChild(m_sharedUnitBox->getNode());
m_switch->addChild(m_transform);
std::pair<osg::Quat, osg::Vec3d> pose = std::make_pair(m_transform->getAttitude(), m_transform->getPosition());
m_pose = fromOsg(pose);
}
void OsgBoxRepresentation::setVisible(bool visible)
{
m_switch->setChildValue(m_transform, visible);
}
bool OsgBoxRepresentation::isVisible() const
{
return m_switch->getChildValue(m_transform);
}
/// Sets the size along X-axis of the box
/// \param sizeX Size along X-axis of the box
void OsgBoxRepresentation::setSizeX(double sizeX)
{
m_scale.x() = sizeX;
m_transform->setScale(m_scale);
}
/// Returns the size along X-axis of the box
/// \return Size along X-axis of the box
double OsgBoxRepresentation::getSizeX() const
{
return m_scale.x();
}
/// Sets the size along Y-axis of the box
/// \param sizeY Size along Y-axis of the box
void OsgBoxRepresentation::setSizeY(double sizeY)
{
m_scale.y() = sizeY;
m_transform->setScale(m_scale);
}
/// Returns the size along Y-axis of the box
/// \return Size along Y-axis of the box
double OsgBoxRepresentation::getSizeY() const
{
return m_scale.y();
}
/// Sets the size along Z-axis of the box
/// \param sizeZ Size along Z-axis of the box
void OsgBoxRepresentation::setSizeZ(double sizeZ)
{
m_scale.z() = sizeZ;
m_transform->setScale(m_scale);
}
/// Returns the size along Z-axis of the box
/// \return Size along Z-axis of the box
double OsgBoxRepresentation::getSizeZ() const
{
return m_scale.z();
}
/// Sets the size of the box
/// \param sizeX Size along X-axis of the box
/// \param sizeY Size along Y-axis of the box
/// \param sizeZ Size along Z-axis of the box
void OsgBoxRepresentation::setSize(double sizeX, double sizeY, double sizeZ)
{
m_scale.x() = sizeX;
m_scale.y() = sizeY;
m_scale.z() = sizeZ;
m_transform->setScale(m_scale);
}
/// Gets the size of the box
/// \param sizeX Reference to store the size along X-axis of the box
/// \param sizeY Reference to store the size along Y-axis of the box
/// \param sizeZ Reference to store the size along Z-axis of the box
void OsgBoxRepresentation::getSize(double& sizeX, double& sizeY, double& sizeZ)
{
sizeX = m_scale.x();
sizeY = m_scale.y();
sizeZ = m_scale.z();
}
/// Sets the size of the box
/// \param size Size of the box
void OsgBoxRepresentation::setSize(SurgSim::Math::Vector3d size)
{
m_scale.set(size.x(), size.y(), size.z());
m_transform->setScale(m_scale);
}
/// Returns the radius of the sphere
/// \return Size of the box
SurgSim::Math::Vector3d OsgBoxRepresentation::getSize() const
{
return SurgSim::Math::Vector3d(m_scale._v);
}
void OsgBoxRepresentation::setPose(const SurgSim::Math::RigidTransform3d& transform)
{
m_pose = transform;
std::pair<osg::Quat, osg::Vec3d> pose = toOsg(m_pose);
m_transform->setAttitude(pose.first);
m_transform->setPosition(pose.second);
}
const SurgSim::Math::RigidTransform3d& OsgBoxRepresentation::getPose() const
{
return m_pose;
}
void OsgBoxRepresentation::update(double dt)
{
}
std::shared_ptr<OsgUnitBox> OsgBoxRepresentation::getSharedUnitBox()
{
static SurgSim::Framework::SharedInstance<OsgUnitBox> shared;
return shared.get();
}
<commit_msg>Member intialization order fixed and function comments removed from cpp file.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <SurgSim/Graphics/OsgBoxRepresentation.h>
#include <SurgSim/Graphics/OsgRigidTransformConversions.h>
#include <SurgSim/Graphics/OsgUnitBox.h>
#include <osg/Geode>
#include <osg/Shape>
#include <osg/ShapeDrawable>
using SurgSim::Graphics::OsgBoxRepresentation;
using SurgSim::Graphics::OsgUnitBox;
OsgBoxRepresentation::OsgBoxRepresentation(const std::string& name) : Representation(name), BoxRepresentation(name),
OsgRepresentation(name, new osg::Switch()),
m_scale(1.0, 1.0, 1.0),
m_sharedUnitBox(getSharedUnitBox())
{
m_switch = static_cast<osg::Switch*>(getOsgNode().get());
m_switch->setName(name + " Switch");
m_transform = new osg::PositionAttitudeTransform();
m_switch->setName(name + " Transform");
m_transform->addChild(m_sharedUnitBox->getNode());
m_switch->addChild(m_transform);
std::pair<osg::Quat, osg::Vec3d> pose = std::make_pair(m_transform->getAttitude(), m_transform->getPosition());
m_pose = fromOsg(pose);
}
void OsgBoxRepresentation::setVisible(bool visible)
{
m_switch->setChildValue(m_transform, visible);
}
bool OsgBoxRepresentation::isVisible() const
{
return m_switch->getChildValue(m_transform);
}
void OsgBoxRepresentation::setSizeX(double sizeX)
{
m_scale.x() = sizeX;
m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeX() const
{
return m_scale.x();
}
void OsgBoxRepresentation::setSizeY(double sizeY)
{
m_scale.y() = sizeY;
m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeY() const
{
return m_scale.y();
}
void OsgBoxRepresentation::setSizeZ(double sizeZ)
{
m_scale.z() = sizeZ;
m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeZ() const
{
return m_scale.z();
}
void OsgBoxRepresentation::setSize(double sizeX, double sizeY, double sizeZ)
{
m_scale.x() = sizeX;
m_scale.y() = sizeY;
m_scale.z() = sizeZ;
m_transform->setScale(m_scale);
}
void OsgBoxRepresentation::getSize(double& sizeX, double& sizeY, double& sizeZ)
{
sizeX = m_scale.x();
sizeY = m_scale.y();
sizeZ = m_scale.z();
}
void OsgBoxRepresentation::setSize(SurgSim::Math::Vector3d size)
{
m_scale.set(size.x(), size.y(), size.z());
m_transform->setScale(m_scale);
}
SurgSim::Math::Vector3d OsgBoxRepresentation::getSize() const
{
return SurgSim::Math::Vector3d(m_scale._v);
}
void OsgBoxRepresentation::setPose(const SurgSim::Math::RigidTransform3d& transform)
{
m_pose = transform;
std::pair<osg::Quat, osg::Vec3d> pose = toOsg(m_pose);
m_transform->setAttitude(pose.first);
m_transform->setPosition(pose.second);
}
const SurgSim::Math::RigidTransform3d& OsgBoxRepresentation::getPose() const
{
return m_pose;
}
void OsgBoxRepresentation::update(double dt)
{
}
std::shared_ptr<OsgUnitBox> OsgBoxRepresentation::getSharedUnitBox()
{
static SurgSim::Framework::SharedInstance<OsgUnitBox> shared;
return shared.get();
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 P.L. Lucas <[email protected]>
Copyright (C) 2013 <copyright holder> <email>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "monitorsettingsdialog.h"
#include "monitorwidget.h"
#include "timeoutdialog.h"
#include <KScreen/Output>
MonitorSettingsDialog::MonitorSettingsDialog() :
QDialog(nullptr, 0)
{
ui.setupUi(this);
KScreen::GetConfigOperation *operation = new KScreen::GetConfigOperation();
connect(operation, &KScreen::GetConfigOperation::finished, [&] (KScreen::ConfigOperation *op) {
KScreen::GetConfigOperation *configOp = qobject_cast<KScreen::GetConfigOperation *>(op);
if (configOp)
{
mOldConfig = configOp->config();
loadConfiguration(configOp->config());
}
});
connect(ui.buttonBox, &QDialogButtonBox::clicked, [&] (QAbstractButton *button) {
if (ui.buttonBox->standardButton(button) == QDialogButtonBox::Apply)
applyConfiguration();
});
}
MonitorSettingsDialog::~MonitorSettingsDialog()
{
}
void MonitorSettingsDialog::loadConfiguration(KScreen::ConfigPtr config)
{
if (mConfig == config)
return;
mConfig = config;
KScreen::OutputList outputs = mConfig->outputs();
for (const KScreen::OutputPtr &output : outputs)
{
if (output->isConnected())
{
MonitorWidget *monitor = new MonitorWidget(output, mConfig, this);
ui.monitorList->addItem(output->name());
ui.stackedWidget->addWidget(monitor);
}
}
ui.monitorList->setCurrentRow(0);
adjustSize();
}
/**
* Apply the settings
*/
void MonitorSettingsDialog::applyConfiguration()
{
if (mConfig && KScreen::Config::canBeApplied(mConfig))
{
KScreen::SetConfigOperation(mConfig).exec();
TimeoutDialog mTimeoutDialog;
if (mTimeoutDialog.exec() == QDialog::Rejected)
// TODO: why isn't this working? why??
QTimer::singleShot(5000, [&] {
KScreen::SetConfigOperation(mOldConfig).exec();
});
else
mOldConfig = mConfig;
}
}
void MonitorSettingsDialog::accept()
{
applyConfiguration();
QDialog::accept();
}
void MonitorSettingsDialog::reject()
{
QDialog::reject();
}
<commit_msg>lxqt-config-monitor: fix for reverting to previous configuration<commit_after>/*
Copyright (C) 2014 P.L. Lucas <[email protected]>
Copyright (C) 2013 <copyright holder> <email>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "monitorsettingsdialog.h"
#include "monitorwidget.h"
#include "timeoutdialog.h"
#include <KScreen/Output>
MonitorSettingsDialog::MonitorSettingsDialog() :
QDialog(nullptr, 0)
{
ui.setupUi(this);
KScreen::GetConfigOperation *operation = new KScreen::GetConfigOperation();
connect(operation, &KScreen::GetConfigOperation::finished, [this, operation] (KScreen::ConfigOperation *op) {
KScreen::GetConfigOperation *configOp = qobject_cast<KScreen::GetConfigOperation *>(op);
if (configOp)
{
mOldConfig = configOp->config()->clone();
loadConfiguration(configOp->config());
operation->deleteLater();
}
});
connect(ui.buttonBox, &QDialogButtonBox::clicked, [&] (QAbstractButton *button) {
if (ui.buttonBox->standardButton(button) == QDialogButtonBox::Apply)
applyConfiguration();
});
}
MonitorSettingsDialog::~MonitorSettingsDialog()
{
}
void MonitorSettingsDialog::loadConfiguration(KScreen::ConfigPtr config)
{
if (mConfig == config)
return;
mConfig = config;
KScreen::OutputList outputs = mConfig->outputs();
for (const KScreen::OutputPtr &output : outputs)
{
if (output->isConnected())
{
MonitorWidget *monitor = new MonitorWidget(output, mConfig, this);
ui.monitorList->addItem(output->name());
ui.stackedWidget->addWidget(monitor);
}
}
ui.monitorList->setCurrentRow(0);
adjustSize();
}
/**
* Apply the settings
*/
void MonitorSettingsDialog::applyConfiguration()
{
if (mConfig && KScreen::Config::canBeApplied(mConfig))
{
KScreen::SetConfigOperation(mConfig).exec();
TimeoutDialog mTimeoutDialog;
if (mTimeoutDialog.exec() == QDialog::Rejected)
KScreen::SetConfigOperation(mOldConfig).exec();
else
mOldConfig = mConfig->clone();
}
}
void MonitorSettingsDialog::accept()
{
applyConfiguration();
QDialog::accept();
}
void MonitorSettingsDialog::reject()
{
QDialog::reject();
}
<|endoftext|> |
<commit_before>/*
* This file is part of Maliit Plugins
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <[email protected]>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Neither the name of Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "utils.h"
#include "models/area.h"
#include "models/key.h"
#include "models/keyarea.h"
#include "models/layout.h"
#include "models/text.h"
#include "view/glass.h"
#include "view/setup.h"
#include "logic/wordengine.h"
#include "plugin/editor.h"
#include "inputmethodhostprobe.h"
#include <maliit/plugins/testsurfacefactory.h>
#include <QtCore>
#include <QtTest>
#include <QWidget>
#include <QList>
#include <QMouseEvent>
using namespace MaliitKeyboard;
Q_DECLARE_METATYPE(Layout::Orientation)
Q_DECLARE_METATYPE(QList<QMouseEvent*>)
namespace {
const int g_size = 48;
const int g_divider = 3;
QPoint keyOriginLookup(const QString &name)
{
static const int distance = g_size / g_divider;
if (name == "a") {
return QPoint(0, 0);
} else if (name == "b") {
return QPoint(distance, 0);
} else if (name == "c") {
return QPoint(0, distance);
} else if (name == "d") {
return QPoint(distance, distance);
} else if (name == "space") {
return QPoint(distance * 2, 0);
} else if (name == "return") {
return QPoint(distance * 2, distance);
}
return QPoint();
}
Key createKey(Key::Action action,
const QString &text)
{
static const QSize size(g_size / g_divider, g_size / g_divider);
Key result;
result.setAction(action);
result.setOrigin(keyOriginLookup(text));
result.rArea().setSize(size);
result.rLabel().setText(text);
return result;
}
// Populate KeyArea with six keys, a, b, c, d, space and return. Notice how the KeyArea
// covers the whole widget. Key width and height equals g_size / g_divider.
// .-----------.
// | a | b |<s>|
// |---|---|---|
// | c | d |<r>|
// `-----------'
KeyArea createAbcdArea()
{
KeyArea key_area;
Area area;
area.setSize(QSize(g_size, g_size));
key_area.setArea(area);
key_area.rKeys().append(createKey(Key::ActionInsert, "a"));
key_area.rKeys().append(createKey(Key::ActionInsert, "b"));
key_area.rKeys().append(createKey(Key::ActionInsert, "c"));
key_area.rKeys().append(createKey(Key::ActionInsert, "d"));
key_area.rKeys().append(createKey(Key::ActionSpace, "space"));
key_area.rKeys().append(createKey(Key::ActionReturn, "return"));
return key_area;
}
QList<QMouseEvent *> createPressReleaseEvent(const QPoint &origin,
Layout::Orientation orientation)
{
static const int offset(g_size / (g_divider * 2));
QList<QMouseEvent *> result;
QPoint pos = (orientation == Layout::Landscape) ? QPoint(origin.x() + offset, origin.y() + offset)
: QPoint(origin.y() + offset, g_size - (origin.x() + offset));
result.append(new QMouseEvent(QKeyEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
result.append(new QMouseEvent(QKeyEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
return result;
}
}
class TestPreeditString
: public QObject
{
Q_OBJECT
private:
typedef QList<Maliit::PreeditTextFormat> FormatList;
Q_SLOT void initTestCase()
{
qRegisterMetaType<QList<QMouseEvent*> >();
qRegisterMetaType<Layout::Orientation>();
qRegisterMetaType<FormatList>();
}
Q_SLOT void test_data()
{
QTest::addColumn<Layout::Orientation>("orientation");
QTest::addColumn<QList<QMouseEvent*> >("mouse_events");
QTest::addColumn<QString>("expected_last_preedit_string");
QTest::addColumn<QString>("expected_commit_string");
QTest::addColumn<FormatList>("expected_preedit_format");
for (int orientation = 0; orientation < 1; ++orientation) {
// FIXME: here should be 2 ^
// FIXME: tests fail for portrait layouts
const Layout::Orientation layout_orientation(orientation == 0 ? Layout::Landscape
: Layout::Portrait);
QTest::newRow("No mouse events: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>())
<< "" << "" << FormatList();
QTest::newRow("Only return pressed: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "" << "" << FormatList();
QTest::newRow("Release outside of widget: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(QPoint(g_size * 2, g_size * 2), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "" << "" << FormatList();
QTest::newRow("Release button over key 'a': expect commit string 'a'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "a" << "a" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));
QTest::newRow("Release button over key 'a', but no commit: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation))
<< "a" << "" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));
QTest::newRow("Release button over keys 'c, b, d, a': expect commit string 'cbda'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("space"), layout_orientation))
<< "cbda" << "cbda " << (FormatList() << Maliit::PreeditTextFormat(0, 4, Maliit::PreeditDefault));
QTest::newRow("Typing two words: expect commit string 'ab cd', with last preedit being 'cd'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("space"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "cd" << "ab cd" << (FormatList() << Maliit::PreeditTextFormat(0, 2, Maliit::PreeditDefault));
}
}
Q_SLOT void test()
{
// FIXME: mikhas: We should have tests for the preedit &
// preedit correctness stuff, and how it blends with word
// prediction. I guess you will need to add
// WordEngine::setSpellChecker() API so that you can inject a
// fake spellchecker, for the tests. Otherwise, the test would
// have to be skipped when there's no hunspell/presage, which
// I wouldn't like to have.
QFETCH(Layout::Orientation, orientation);
QFETCH(QList<QMouseEvent*>, mouse_events);
QFETCH(QString, expected_last_preedit_string);
QFETCH(QString, expected_commit_string);
QFETCH(QList<Maliit::PreeditTextFormat>, expected_preedit_format);
Glass glass;
Editor editor(EditorOptions(), new Model::Text, new Logic::WordEngine, 0);
InputMethodHostProbe host;
SharedLayout layout(new Layout);
QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> surface(Maliit::Plugins::createTestGraphicsViewSurface());
QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> extended_surface(Maliit::Plugins::createTestGraphicsViewSurface(surface));
// geometry stuff is usually done by maliit-server, so we need
// to do it manually here:
//surface->view()->viewport()->setGeometry(0, 0, g_size, g_size);
surface->view()->setSceneRect(0, 0, g_size, g_size);
surface->scene()->setSceneRect(0, 0, g_size, g_size);
glass.setSurface(surface);
glass.setExtendedSurface(extended_surface);
glass.addLayout(layout);
editor.setHost(&host);
layout->setOrientation(orientation);
editor.setPreeditEnabled(true);
Setup::connectGlassToTextEditor(&glass, &editor);
const KeyArea &key_area(createAbcdArea());
layout->setExtendedPanel(key_area);
layout->setActivePanel(Layout::ExtendedPanel);
Q_FOREACH (QMouseEvent *ev, mouse_events) {
QApplication::instance()->postEvent(surface->view()->viewport(), ev);
}
TestUtils::waitForSignal(&glass, SIGNAL(keyReleased(Key,SharedLayout)));
QCOMPARE(host.lastPreeditString(), expected_last_preedit_string);
QCOMPARE(host.commitStringHistory(), expected_commit_string);
QCOMPARE(host.lastPreeditTextFormatList(), expected_preedit_format);
}
};
QTEST_MAIN(TestPreeditString)
#include "main.moc"
<commit_msg>Add equality operator for Maliit::PreeditTextFormat.<commit_after>/*
* This file is part of Maliit Plugins
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <[email protected]>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Neither the name of Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "utils.h"
#include "models/area.h"
#include "models/key.h"
#include "models/keyarea.h"
#include "models/layout.h"
#include "models/text.h"
#include "view/glass.h"
#include "view/setup.h"
#include "logic/wordengine.h"
#include "plugin/editor.h"
#include "inputmethodhostprobe.h"
#include <maliit/plugins/testsurfacefactory.h>
#include <QtCore>
#include <QtTest>
#include <QWidget>
#include <QList>
#include <QMouseEvent>
using namespace MaliitKeyboard;
Q_DECLARE_METATYPE(Layout::Orientation)
Q_DECLARE_METATYPE(QList<QMouseEvent*>)
namespace {
const int g_size = 48;
const int g_divider = 3;
QPoint keyOriginLookup(const QString &name)
{
static const int distance = g_size / g_divider;
if (name == "a") {
return QPoint(0, 0);
} else if (name == "b") {
return QPoint(distance, 0);
} else if (name == "c") {
return QPoint(0, distance);
} else if (name == "d") {
return QPoint(distance, distance);
} else if (name == "space") {
return QPoint(distance * 2, 0);
} else if (name == "return") {
return QPoint(distance * 2, distance);
}
return QPoint();
}
Key createKey(Key::Action action,
const QString &text)
{
static const QSize size(g_size / g_divider, g_size / g_divider);
Key result;
result.setAction(action);
result.setOrigin(keyOriginLookup(text));
result.rArea().setSize(size);
result.rLabel().setText(text);
return result;
}
// Populate KeyArea with six keys, a, b, c, d, space and return. Notice how the KeyArea
// covers the whole widget. Key width and height equals g_size / g_divider.
// .-----------.
// | a | b |<s>|
// |---|---|---|
// | c | d |<r>|
// `-----------'
KeyArea createAbcdArea()
{
KeyArea key_area;
Area area;
area.setSize(QSize(g_size, g_size));
key_area.setArea(area);
key_area.rKeys().append(createKey(Key::ActionInsert, "a"));
key_area.rKeys().append(createKey(Key::ActionInsert, "b"));
key_area.rKeys().append(createKey(Key::ActionInsert, "c"));
key_area.rKeys().append(createKey(Key::ActionInsert, "d"));
key_area.rKeys().append(createKey(Key::ActionSpace, "space"));
key_area.rKeys().append(createKey(Key::ActionReturn, "return"));
return key_area;
}
QList<QMouseEvent *> createPressReleaseEvent(const QPoint &origin,
Layout::Orientation orientation)
{
static const int offset(g_size / (g_divider * 2));
QList<QMouseEvent *> result;
QPoint pos = (orientation == Layout::Landscape) ? QPoint(origin.x() + offset, origin.y() + offset)
: QPoint(origin.y() + offset, g_size - (origin.x() + offset));
result.append(new QMouseEvent(QKeyEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
result.append(new QMouseEvent(QKeyEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
return result;
}
bool operator==(const Maliit::PreeditTextFormat &a, const Maliit::PreeditTextFormat &b) {
return ((a.start == b.start) and (a.length == b.length) and (a.preeditFace == b.preeditFace));
}
} // unnamed namespace
class TestPreeditString
: public QObject
{
Q_OBJECT
private:
typedef QList<Maliit::PreeditTextFormat> FormatList;
Q_SLOT void initTestCase()
{
qRegisterMetaType<QList<QMouseEvent*> >();
qRegisterMetaType<Layout::Orientation>();
qRegisterMetaType<FormatList>();
}
Q_SLOT void test_data()
{
QTest::addColumn<Layout::Orientation>("orientation");
QTest::addColumn<QList<QMouseEvent*> >("mouse_events");
QTest::addColumn<QString>("expected_last_preedit_string");
QTest::addColumn<QString>("expected_commit_string");
QTest::addColumn<FormatList>("expected_preedit_format");
for (int orientation = 0; orientation < 1; ++orientation) {
// FIXME: here should be 2 ^
// FIXME: tests fail for portrait layouts
const Layout::Orientation layout_orientation(orientation == 0 ? Layout::Landscape
: Layout::Portrait);
QTest::newRow("No mouse events: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>())
<< "" << "" << FormatList();
QTest::newRow("Only return pressed: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "" << "" << FormatList();
QTest::newRow("Release outside of widget: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(QPoint(g_size * 2, g_size * 2), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "" << "" << FormatList();
QTest::newRow("Release button over key 'a': expect commit string 'a'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "a" << "a" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));
QTest::newRow("Release button over key 'a', but no commit: expect empty commit string.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation))
<< "a" << "" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));
QTest::newRow("Release button over keys 'c, b, d, a': expect commit string 'cbda'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("space"), layout_orientation))
<< "cbda" << "cbda " << (FormatList() << Maliit::PreeditTextFormat(0, 4, Maliit::PreeditDefault));
QTest::newRow("Typing two words: expect commit string 'ab cd', with last preedit being 'cd'.")
<< layout_orientation
<< (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("space"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
<< createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
<< "cd" << "ab cd" << (FormatList() << Maliit::PreeditTextFormat(0, 2, Maliit::PreeditDefault));
}
}
Q_SLOT void test()
{
// FIXME: mikhas: We should have tests for the preedit &
// preedit correctness stuff, and how it blends with word
// prediction. I guess you will need to add
// WordEngine::setSpellChecker() API so that you can inject a
// fake spellchecker, for the tests. Otherwise, the test would
// have to be skipped when there's no hunspell/presage, which
// I wouldn't like to have.
QFETCH(Layout::Orientation, orientation);
QFETCH(QList<QMouseEvent*>, mouse_events);
QFETCH(QString, expected_last_preedit_string);
QFETCH(QString, expected_commit_string);
QFETCH(QList<Maliit::PreeditTextFormat>, expected_preedit_format);
Glass glass;
Editor editor(EditorOptions(), new Model::Text, new Logic::WordEngine, 0);
InputMethodHostProbe host;
SharedLayout layout(new Layout);
QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> surface(Maliit::Plugins::createTestGraphicsViewSurface());
QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> extended_surface(Maliit::Plugins::createTestGraphicsViewSurface(surface));
// geometry stuff is usually done by maliit-server, so we need
// to do it manually here:
//surface->view()->viewport()->setGeometry(0, 0, g_size, g_size);
surface->view()->setSceneRect(0, 0, g_size, g_size);
surface->scene()->setSceneRect(0, 0, g_size, g_size);
glass.setSurface(surface);
glass.setExtendedSurface(extended_surface);
glass.addLayout(layout);
editor.setHost(&host);
layout->setOrientation(orientation);
editor.setPreeditEnabled(true);
Setup::connectGlassToTextEditor(&glass, &editor);
const KeyArea &key_area(createAbcdArea());
layout->setExtendedPanel(key_area);
layout->setActivePanel(Layout::ExtendedPanel);
Q_FOREACH (QMouseEvent *ev, mouse_events) {
QApplication::instance()->postEvent(surface->view()->viewport(), ev);
}
TestUtils::waitForSignal(&glass, SIGNAL(keyReleased(Key,SharedLayout)));
QCOMPARE(host.lastPreeditString(), expected_last_preedit_string);
QCOMPARE(host.commitStringHistory(), expected_commit_string);
QCOMPARE(host.lastPreeditTextFormatList(), expected_preedit_format);
}
};
QTEST_MAIN(TestPreeditString)
#include "main.moc"
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: Fresnel.cpp
Description: Fresnel reflections and refractions
-----------------------------------------------------------------------------
*/
#include "ExampleApplication.h"
#include "OgreHardwarePixelBuffer.h"
// Hacky globals
Camera* theCam;
Entity* pPlaneEnt;
std::vector<Entity*> aboveWaterEnts;
std::vector<Entity*> belowWaterEnts;
// Fish!
#define NUM_FISH 30
#define NUM_FISH_WAYPOINTS 10
#define FISH_PATH_LENGTH 200
#define FISH_SCALE 1.2
AnimationState* fishAnimations[NUM_FISH];
SimpleSpline fishSplines[NUM_FISH];
Vector3 fishLastPosition[NUM_FISH];
SceneNode* fishNodes[NUM_FISH];
Real animTime = 0.0f;
Plane reflectionPlane;
class RefractionTextureListener : public RenderTargetListener
{
public:
void preRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Hide plane and objects above the water
pPlaneEnt->setVisible(false);
std::vector<Entity*>::iterator i, iend;
iend = aboveWaterEnts.end();
for (i = aboveWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(false);
}
}
void postRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Show plane and objects above the water
pPlaneEnt->setVisible(true);
std::vector<Entity*>::iterator i, iend;
iend = aboveWaterEnts.end();
for (i = aboveWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(true);
}
}
};
class ReflectionTextureListener : public RenderTargetListener
{
public:
void preRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Hide plane and objects below the water
pPlaneEnt->setVisible(false);
std::vector<Entity*>::iterator i, iend;
iend = belowWaterEnts.end();
for (i = belowWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(false);
}
theCam->enableReflection(reflectionPlane);
}
void postRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Show plane and objects below the water
pPlaneEnt->setVisible(true);
std::vector<Entity*>::iterator i, iend;
iend = belowWaterEnts.end();
for (i = belowWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(true);
}
theCam->disableReflection();
}
};
class FresnelFrameListener : public ExampleFrameListener
{
public:
FresnelFrameListener(RenderWindow* win, Camera* cam)
: ExampleFrameListener(win, cam, false, false)
{}
bool frameRenderingQueued(const FrameEvent &evt)
{
animTime += evt.timeSinceLastFrame;
while (animTime > FISH_PATH_LENGTH)
animTime -= FISH_PATH_LENGTH;
for (size_t fish = 0; fish < NUM_FISH; ++fish)
{
// Animate the fish
fishAnimations[fish]->addTime(evt.timeSinceLastFrame*2);
// Move the fish
Vector3 newPos = fishSplines[fish].interpolate(animTime / FISH_PATH_LENGTH);
fishNodes[fish]->setPosition(newPos);
// Work out the direction
Vector3 direction = fishLastPosition[fish] - newPos;
direction.normalise();
// Test for opposite vectors
Real d = 1.0f + Vector3::UNIT_X.dotProduct(direction);
if (fabs(d) < 0.00001)
{
// Diametrically opposed vectors
Quaternion orientation;
orientation.FromAxes(Vector3::NEGATIVE_UNIT_X,
Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_Z);
fishNodes[fish]->setOrientation(orientation);
}
else
{
fishNodes[fish]->setOrientation(
Vector3::UNIT_X.getRotationTo(direction));
}
fishLastPosition[fish] = newPos;
}
return ExampleFrameListener::frameRenderingQueued(evt);
}
};
class FresnelApplication : public ExampleApplication
{
protected:
RefractionTextureListener mRefractionListener;
ReflectionTextureListener mReflectionListener;
public:
FresnelApplication() {
}
~FresnelApplication()
{
}
protected:
// Just override the mandatory create scene method
void createScene(void)
{
// Check prerequisites first
const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();
if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM)))
{
OGRE_EXCEPT(1, "Your card does not support vertex and fragment programs, so cannot "
"run this demo. Sorry!",
"Fresnel::createScene");
}
else
{
if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") &&
!GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") &&
!GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4")
)
{
OGRE_EXCEPT(1, "Your card does not support advanced fragment programs, "
"so cannot run this demo. Sorry!",
"Fresnel::createScene");
}
}
theCam = mCamera;
theCam->setPosition(-50,125,760);
theCam->setDirection (0,0,-1);
// Set ambient light
mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));
// Create a point light
Light* l = mSceneMgr->createLight("MainLight");
l->setType(Light::LT_DIRECTIONAL);
l->setDirection(-Vector3::UNIT_Y);
Entity* pEnt;
TexturePtr mTexture = TextureManager::getSingleton().createManual( "Refraction",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
512, 512, 0, PF_R8G8B8, TU_RENDERTARGET );
//RenderTexture* rttTex = mRoot->getRenderSystem()->createRenderTexture( "Refraction", 512, 512 );
RenderTarget *rttTex = mTexture->getBuffer()->getRenderTarget();
{
Viewport *v = rttTex->addViewport( mCamera );
MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction");
v->setOverlaysEnabled(false);
rttTex->addListener(&mRefractionListener);
}
mTexture = TextureManager::getSingleton().createManual( "Reflection",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
512, 512, 0, PF_R8G8B8, TU_RENDERTARGET );
//rttTex = mRoot->getRenderSystem()->createRenderTexture( "Reflection", 512, 512 );
rttTex = mTexture->getBuffer()->getRenderTarget();
{
Viewport *v = rttTex->addViewport( mCamera );
MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection");
v->setOverlaysEnabled(false);
rttTex->addListener(&mReflectionListener);
}
// Define a floor plane mesh
reflectionPlane.normal = Vector3::UNIT_Y;
reflectionPlane.d = 0;
MeshManager::getSingleton().createPlane("ReflectPlane",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
reflectionPlane,
700,1300,10,10,true,1,3,5,Vector3::UNIT_Z);
pPlaneEnt = mSceneMgr->createEntity( "plane", "ReflectPlane" );
pPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction");
mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);
mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox");
// My node to which all objects will be attached
SceneNode* myRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
// above water entities
pEnt = mSceneMgr->createEntity( "RomanBathUpper", "RomanBathUpper.mesh" );
myRootNode->attachObject(pEnt);
aboveWaterEnts.push_back(pEnt);
pEnt = mSceneMgr->createEntity( "Columns", "Columns.mesh" );
myRootNode->attachObject(pEnt);
aboveWaterEnts.push_back(pEnt);
Ogre::SceneNode *headNode = myRootNode->createChildSceneNode ();
pEnt = mSceneMgr->createEntity( "OgreHead", "ogrehead.mesh" );
pEnt->setMaterialName ("RomanBath/OgreStone");
headNode->attachObject(pEnt);
headNode->setPosition(-350,55,130);
headNode->rotate(Vector3::UNIT_Y, Degree (90));
aboveWaterEnts.push_back(pEnt);
// below water entities
pEnt = mSceneMgr->createEntity( "RomanBathLower", "RomanBathLower.mesh" );
myRootNode->attachObject(pEnt);
belowWaterEnts.push_back(pEnt);
for (size_t fishNo = 0; fishNo < NUM_FISH; ++fishNo)
{
pEnt = mSceneMgr->createEntity("fish" + StringConverter::toString(fishNo), "fish.mesh");
fishNodes[fishNo] = myRootNode->createChildSceneNode();
fishNodes[fishNo]->setScale(FISH_SCALE, FISH_SCALE, FISH_SCALE);
fishAnimations[fishNo] = pEnt->getAnimationState("swim");
fishAnimations[fishNo]->setEnabled(true);
fishNodes[fishNo]->attachObject(pEnt);
belowWaterEnts.push_back(pEnt);
// Generate a random selection of points for the fish to swim to
fishSplines[fishNo].setAutoCalculate(false);
Vector3 lastPos;
for (size_t waypoint = 0; waypoint < NUM_FISH_WAYPOINTS; ++waypoint)
{
Vector3 pos = Vector3(
Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700);
if (waypoint > 0)
{
// check this waypoint isn't too far, we don't want turbo-fish ;)
// since the waypoints are achieved every 5 seconds, half the length
// of the pond is ok
while ((lastPos - pos).length() > 750)
{
pos = Vector3(
Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700);
}
}
fishSplines[fishNo].addPoint(pos);
lastPos = pos;
}
// close the spline
fishSplines[fishNo].addPoint(fishSplines[fishNo].getPoint(0));
// recalc
fishSplines[fishNo].recalcTangents();
}
}
void createFrameListener(void)
{
mFrameListener= new FresnelFrameListener(mWindow, mCamera);
mFrameListener->showDebugOverlay(true);
mRoot->addFrameListener(mFrameListener);
}
};
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char **argv)
#endif
{
// Create application object
FresnelApplication app;
try {
app.go();
} catch( Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " << e.getFullDescription();
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
<commit_msg>Fix license statement on Fresnel demo code - all samples are supposed to be public domain / free use.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
You may use this sample code for anything you like, it is not covered by the
LGPL like the rest of the engine.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: Fresnel.cpp
Description: Fresnel reflections and refractions
-----------------------------------------------------------------------------
*/
#include "ExampleApplication.h"
#include "OgreHardwarePixelBuffer.h"
// Hacky globals
Camera* theCam;
Entity* pPlaneEnt;
std::vector<Entity*> aboveWaterEnts;
std::vector<Entity*> belowWaterEnts;
// Fish!
#define NUM_FISH 30
#define NUM_FISH_WAYPOINTS 10
#define FISH_PATH_LENGTH 200
#define FISH_SCALE 1.2
AnimationState* fishAnimations[NUM_FISH];
SimpleSpline fishSplines[NUM_FISH];
Vector3 fishLastPosition[NUM_FISH];
SceneNode* fishNodes[NUM_FISH];
Real animTime = 0.0f;
Plane reflectionPlane;
class RefractionTextureListener : public RenderTargetListener
{
public:
void preRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Hide plane and objects above the water
pPlaneEnt->setVisible(false);
std::vector<Entity*>::iterator i, iend;
iend = aboveWaterEnts.end();
for (i = aboveWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(false);
}
}
void postRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Show plane and objects above the water
pPlaneEnt->setVisible(true);
std::vector<Entity*>::iterator i, iend;
iend = aboveWaterEnts.end();
for (i = aboveWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(true);
}
}
};
class ReflectionTextureListener : public RenderTargetListener
{
public:
void preRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Hide plane and objects below the water
pPlaneEnt->setVisible(false);
std::vector<Entity*>::iterator i, iend;
iend = belowWaterEnts.end();
for (i = belowWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(false);
}
theCam->enableReflection(reflectionPlane);
}
void postRenderTargetUpdate(const RenderTargetEvent& evt)
{
// Show plane and objects below the water
pPlaneEnt->setVisible(true);
std::vector<Entity*>::iterator i, iend;
iend = belowWaterEnts.end();
for (i = belowWaterEnts.begin(); i != iend; ++i)
{
(*i)->setVisible(true);
}
theCam->disableReflection();
}
};
class FresnelFrameListener : public ExampleFrameListener
{
public:
FresnelFrameListener(RenderWindow* win, Camera* cam)
: ExampleFrameListener(win, cam, false, false)
{}
bool frameRenderingQueued(const FrameEvent &evt)
{
animTime += evt.timeSinceLastFrame;
while (animTime > FISH_PATH_LENGTH)
animTime -= FISH_PATH_LENGTH;
for (size_t fish = 0; fish < NUM_FISH; ++fish)
{
// Animate the fish
fishAnimations[fish]->addTime(evt.timeSinceLastFrame*2);
// Move the fish
Vector3 newPos = fishSplines[fish].interpolate(animTime / FISH_PATH_LENGTH);
fishNodes[fish]->setPosition(newPos);
// Work out the direction
Vector3 direction = fishLastPosition[fish] - newPos;
direction.normalise();
// Test for opposite vectors
Real d = 1.0f + Vector3::UNIT_X.dotProduct(direction);
if (fabs(d) < 0.00001)
{
// Diametrically opposed vectors
Quaternion orientation;
orientation.FromAxes(Vector3::NEGATIVE_UNIT_X,
Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_Z);
fishNodes[fish]->setOrientation(orientation);
}
else
{
fishNodes[fish]->setOrientation(
Vector3::UNIT_X.getRotationTo(direction));
}
fishLastPosition[fish] = newPos;
}
return ExampleFrameListener::frameRenderingQueued(evt);
}
};
class FresnelApplication : public ExampleApplication
{
protected:
RefractionTextureListener mRefractionListener;
ReflectionTextureListener mReflectionListener;
public:
FresnelApplication() {
}
~FresnelApplication()
{
}
protected:
// Just override the mandatory create scene method
void createScene(void)
{
// Check prerequisites first
const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();
if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM)))
{
OGRE_EXCEPT(1, "Your card does not support vertex and fragment programs, so cannot "
"run this demo. Sorry!",
"Fresnel::createScene");
}
else
{
if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") &&
!GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") &&
!GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4")
)
{
OGRE_EXCEPT(1, "Your card does not support advanced fragment programs, "
"so cannot run this demo. Sorry!",
"Fresnel::createScene");
}
}
theCam = mCamera;
theCam->setPosition(-50,125,760);
theCam->setDirection (0,0,-1);
// Set ambient light
mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));
// Create a point light
Light* l = mSceneMgr->createLight("MainLight");
l->setType(Light::LT_DIRECTIONAL);
l->setDirection(-Vector3::UNIT_Y);
Entity* pEnt;
TexturePtr mTexture = TextureManager::getSingleton().createManual( "Refraction",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
512, 512, 0, PF_R8G8B8, TU_RENDERTARGET );
//RenderTexture* rttTex = mRoot->getRenderSystem()->createRenderTexture( "Refraction", 512, 512 );
RenderTarget *rttTex = mTexture->getBuffer()->getRenderTarget();
{
Viewport *v = rttTex->addViewport( mCamera );
MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction");
v->setOverlaysEnabled(false);
rttTex->addListener(&mRefractionListener);
}
mTexture = TextureManager::getSingleton().createManual( "Reflection",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
512, 512, 0, PF_R8G8B8, TU_RENDERTARGET );
//rttTex = mRoot->getRenderSystem()->createRenderTexture( "Reflection", 512, 512 );
rttTex = mTexture->getBuffer()->getRenderTarget();
{
Viewport *v = rttTex->addViewport( mCamera );
MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection");
v->setOverlaysEnabled(false);
rttTex->addListener(&mReflectionListener);
}
// Define a floor plane mesh
reflectionPlane.normal = Vector3::UNIT_Y;
reflectionPlane.d = 0;
MeshManager::getSingleton().createPlane("ReflectPlane",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
reflectionPlane,
700,1300,10,10,true,1,3,5,Vector3::UNIT_Z);
pPlaneEnt = mSceneMgr->createEntity( "plane", "ReflectPlane" );
pPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction");
mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);
mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox");
// My node to which all objects will be attached
SceneNode* myRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
// above water entities
pEnt = mSceneMgr->createEntity( "RomanBathUpper", "RomanBathUpper.mesh" );
myRootNode->attachObject(pEnt);
aboveWaterEnts.push_back(pEnt);
pEnt = mSceneMgr->createEntity( "Columns", "Columns.mesh" );
myRootNode->attachObject(pEnt);
aboveWaterEnts.push_back(pEnt);
Ogre::SceneNode *headNode = myRootNode->createChildSceneNode ();
pEnt = mSceneMgr->createEntity( "OgreHead", "ogrehead.mesh" );
pEnt->setMaterialName ("RomanBath/OgreStone");
headNode->attachObject(pEnt);
headNode->setPosition(-350,55,130);
headNode->rotate(Vector3::UNIT_Y, Degree (90));
aboveWaterEnts.push_back(pEnt);
// below water entities
pEnt = mSceneMgr->createEntity( "RomanBathLower", "RomanBathLower.mesh" );
myRootNode->attachObject(pEnt);
belowWaterEnts.push_back(pEnt);
for (size_t fishNo = 0; fishNo < NUM_FISH; ++fishNo)
{
pEnt = mSceneMgr->createEntity("fish" + StringConverter::toString(fishNo), "fish.mesh");
fishNodes[fishNo] = myRootNode->createChildSceneNode();
fishNodes[fishNo]->setScale(FISH_SCALE, FISH_SCALE, FISH_SCALE);
fishAnimations[fishNo] = pEnt->getAnimationState("swim");
fishAnimations[fishNo]->setEnabled(true);
fishNodes[fishNo]->attachObject(pEnt);
belowWaterEnts.push_back(pEnt);
// Generate a random selection of points for the fish to swim to
fishSplines[fishNo].setAutoCalculate(false);
Vector3 lastPos;
for (size_t waypoint = 0; waypoint < NUM_FISH_WAYPOINTS; ++waypoint)
{
Vector3 pos = Vector3(
Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700);
if (waypoint > 0)
{
// check this waypoint isn't too far, we don't want turbo-fish ;)
// since the waypoints are achieved every 5 seconds, half the length
// of the pond is ok
while ((lastPos - pos).length() > 750)
{
pos = Vector3(
Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700);
}
}
fishSplines[fishNo].addPoint(pos);
lastPos = pos;
}
// close the spline
fishSplines[fishNo].addPoint(fishSplines[fishNo].getPoint(0));
// recalc
fishSplines[fishNo].recalcTangents();
}
}
void createFrameListener(void)
{
mFrameListener= new FresnelFrameListener(mWindow, mCamera);
mFrameListener->showDebugOverlay(true);
mRoot->addFrameListener(mFrameListener);
}
};
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char **argv)
#endif
{
// Create application object
FresnelApplication app;
try {
app.go();
} catch( Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " << e.getFullDescription();
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>#include <OpcodeBase.hpp>
#include <cmath>
#include <iostream>
#include <list>
#include <vector>
// Why not use the constants already defined?
static MYFLT pi = std::atan(1.0) * MYFLT(4.0);
class RCLowpassFilter
{
public:
void initialize(MYFLT sampleRate, MYFLT cutoffHz, MYFLT initialValue)
{
MYFLT tau = MYFLT(1.0) / (MYFLT(2.0) * pi * cutoffHz);
alpha = MYFLT(1.0) / (MYFLT(1.0) + (tau * sampleRate));
value = initialValue;
}
MYFLT update(MYFLT inputValue)
{
value += alpha * (inputValue - value);
return value;
}
protected:
MYFLT alpha;
MYFLT value;
};
class LinearInterpolator
{
public:
LinearInterpolator() :
priorValue(MYFLT(0.0)),
currentValue(MYFLT(0.0))
{
}
virtual void put(MYFLT inputValue)
{
priorValue = currentValue;
currentValue = inputValue;
}
virtual MYFLT get(MYFLT fraction)
{
return priorValue + (fraction * (currentValue - priorValue));
}
protected:
MYFLT priorValue;
MYFLT currentValue;
};
class DelayLine : public std::vector<MYFLT>
{
public:
MYFLT sampleRate;
int writingFrame;
int size_;
void initialize(size_t sampleRate_, MYFLT maximumDelay = 10.0)
{
sampleRate = (MYFLT) sampleRate_;
size_ = (int) std::ceil(maximumDelay * sampleRate);
std::cout << "DelayLine::initialize: size: " << size_ << std::endl;
std::cout << "DelayLine::initialize: sampleRate: " << sampleRate << std::endl;
resize(size_);
writingFrame = 0;
}
void write(MYFLT value)
{
while (writingFrame >= size_) {
writingFrame -= size_;
}
(*this)[(size_t) writingFrame] = value;
//std::cout << "DelayLine::write: writingFrame: " << writingFrame << std::endl;
writingFrame++;
}
MYFLT delaySeconds(MYFLT delaySeconds)
{
int delayFrames_ = (int) (delaySeconds * sampleRate);
return delayFrames(delayFrames_);
}
MYFLT delayFrames(int delayFrames_)
{
//std::cout << "DelayLine::delayFrames: delayFrames: " << delayFrames_ << std::endl;
int readingFrame = writingFrame - delayFrames_;
while (readingFrame < 0) {
readingFrame += size_;
}
while (readingFrame >= size_) {
readingFrame -= size_;
}
// std::cout << "DelayLine::delayFrames: readingFrame: " << readingFrame << std::endl;
return (*this)[(size_t) readingFrame];
}
};
std::list<RCLowpassFilter *> smoothingFilterInstances;
std::list<DelayLine *> delayLineInstances;
class Doppler : public OpcodeBase<Doppler>
{
public:
// Csound opcode outputs.
MYFLT *audioOutput;
// Csound opcode inputs.
MYFLT *audioInput;
MYFLT *kSourcePosition; // usually meters
MYFLT *kMicPosition; // usually meters
MYFLT *jSpeedOfSound; // usually meters/second
MYFLT *jUpdateFilterCutoff; // Hz
// Doppler internal state.
MYFLT speedOfSound; // usually meters/second
MYFLT smoothingFilterCutoff; // Hz
MYFLT sampleRate; // Hz
MYFLT samplesPerDistance; // usually samples/meter
MYFLT blockRate; // Hz
int blockSize; // samples
RCLowpassFilter *smoothingFilter;
LinearInterpolator *audioInterpolator;
std::list< std::vector<MYFLT> *> *audioBufferQueue;
std::list<MYFLT> *sourcePositionQueue;
int relativeIndex;
int currentIndex;
int init(CSOUND *csound)
{
sampleRate = csound->GetSr(csound);
blockSize = csound->GetKsmps(csound);
blockRate = sampleRate / blockSize;
// Take care of default values.
if (*jSpeedOfSound == MYFLT(-1.0)) {
*jSpeedOfSound = MYFLT(340.29);
}
speedOfSound = *jSpeedOfSound;
if (*jUpdateFilterCutoff == MYFLT(-1.0)) {
// MYFLT blockRateNyquist = blockRate / MYFLT(2.0);
// *jUpdateFilterCutoff = blockRateNyquist / MYFLT(2.0);
*jUpdateFilterCutoff = MYFLT(6.0); // very conservative
}
smoothingFilterCutoff = *jUpdateFilterCutoff;
samplesPerDistance = sampleRate / speedOfSound;
audioInterpolator = new LinearInterpolator;
smoothingFilter = NULL;
audioBufferQueue = new std::list< std::vector<MYFLT> *>;
sourcePositionQueue = new std::list<MYFLT>;
currentIndex = 0;
relativeIndex = 0;
return OK;
}
int kontrol(CSOUND *csound)
{
MYFLT sourcePosition = *kSourcePosition;
MYFLT micPosition = *kMicPosition;
std::vector<MYFLT> *sourceBuffer = new std::vector<MYFLT>;
sourceBuffer->resize(blockSize);
for (size_t inputFrame = 0; inputFrame < blockSize; inputFrame++) {
(*sourceBuffer)[inputFrame] = audioInput[inputFrame];
}
audioBufferQueue->push_back(sourceBuffer);
sourcePositionQueue->push_back(sourcePosition);
std::vector<MYFLT> *currentBuffer = audioBufferQueue->front();
MYFLT targetPosition = sourcePositionQueue->front() - micPosition;
// The smoothing filter cannot be initialized at i-time,
// because it must be initialized from a k-rate variable.
if (!smoothingFilter) {
smoothingFilter = new RCLowpassFilter();
smoothingFilter->initialize(sampleRate, smoothingFilterCutoff, targetPosition);
log(csound, "Doppler::kontrol: sizeof(MYFLT): %10d\n", sizeof(MYFLT));
log(csound, "Doppler::kontrol: PI: %10.3f\n", pi);
log(csound, "Doppler::kontrol: this: %10p\n", this);
log(csound, "Doppler::kontrol: sampleRate: %10.3f\n", sampleRate);
log(csound, "Doppler::kontrol: blockSize: %10.3f\n", blockSize);
log(csound, "Doppler::kontrol: blockRate: %10.3f\n", blockRate);
log(csound, "Doppler::kontrol: speedOfSound: %10.3f\n", speedOfSound);
log(csound, "Doppler::kontrol: samplesPerDistance: %10.3f\n", samplesPerDistance);
log(csound, "Doppler::kontrol: smoothingFilterCutoff: %10.3f\n", smoothingFilterCutoff);
log(csound, "Doppler::kontrol: kMicPosition: %10.3f\n", *kMicPosition);
log(csound, "Doppler::kontrol: kSourcePosition: %10.3f\n", *kSourcePosition);
}
for (size_t outputFrame = 0; outputFrame < blockSize; outputFrame++) {
MYFLT position = smoothingFilter->update(targetPosition);
MYFLT distance = std::fabs(position);
MYFLT sourceTime = relativeIndex - (distance * samplesPerDistance);
int targetIndex = int(sourceTime);
MYFLT fraction = sourceTime - targetIndex;
relativeIndex++;
for ( ; targetIndex >= currentIndex; currentIndex++) {
if (currentIndex >= blockSize) {
relativeIndex -= blockSize;
currentIndex -= blockSize;
targetIndex -= blockSize;
delete audioBufferQueue->front();
audioBufferQueue->pop_front();
sourcePositionQueue->pop_front();
currentBuffer = audioBufferQueue->front();
targetPosition = sourcePositionQueue->front() - micPosition;
}
audioInterpolator->put((*currentBuffer)[currentIndex]);
}
MYFLT currentSample = audioInterpolator->get(fraction);
audioOutput[outputFrame] = currentSample;
}
return OK;
}
};
#ifdef NEVER
struct Doppler2 : public OpcodeBase<Doppler2>
{
// Csound opcode outputs.
MYFLT *audioOutput;
// Csound opcode inputs.
MYFLT *audioInput;
MYFLT *kSourcePosition;
MYFLT *kMicPosition;
MYFLT *jSpeedOfSound;
MYFLT *jUpdateFilterCutoff;
// Doppler internal state.
MYFLT speedOfSound;
MYFLT smoothingFilterCutoff;
MYFLT sampleRate;
MYFLT samplesPerDistance;
MYFLT blockSize;
MYFLT blockRate;
RCLowpassFilter *smoothingFilter;
LinearInterpolator *audioInterpolator;
DelayLine *delayLine;
int init(CSOUND *csound)
{
sampleRate = csound->GetSr(csound);
blockSize = csound->GetKsmps(csound);
blockRate = sampleRate / blockSize;
// Take care of default values.
if (*jSpeedOfSound == MYFLT(-1.0)) {
*jSpeedOfSound = MYFLT(340.29);
}
speedOfSound = *jSpeedOfSound;
if (*jUpdateFilterCutoff == MYFLT(-1.0)) {
MYFLT blockRateNyquist = blockRate / MYFLT(2.0);
*jUpdateFilterCutoff = blockRateNyquist / MYFLT(2.0);
}
smoothingFilterCutoff = *jUpdateFilterCutoff;
samplesPerDistance = sampleRate / speedOfSound;
audioInterpolator = new LinearInterpolator;
// The smoothing filter cannot be initialized at i-time,
// because it must be initialized from a k-rate variable.
smoothingFilter = 0;
delayLine = new DelayLine;
return OK;
}
int kontrol(CSOUND *csound)
{
MYFLT sourcePosition = *kSourcePosition;
MYFLT micPosition = *kMicPosition;
MYFLT position = sourcePosition - micPosition;
// On the very first block only, initialize the smoothing filter.
if (!smoothingFilter) {
smoothingFilter = new RCLowpassFilter();
smoothingFilter->initialize(sampleRate, smoothingFilterCutoff, *kSourcePosition);
log(csound, "Doppler::kontrol: sizeof(MYFLT): %10d\n", sizeof(MYFLT));
log(csound, "Doppler::kontrol: PI: %10.3f\n", pi);
log(csound, "Doppler::kontrol: this: %10p\n", this);
log(csound, "Doppler::kontrol: sampleRate: %10.3f\n", sampleRate);
log(csound, "Doppler::kontrol: blockSize: %10.3f\n", blockSize);
log(csound, "Doppler::kontrol: blockRate: %10.3f\n", blockRate);
log(csound, "Doppler::kontrol: speedOfSound: %10.3f\n", speedOfSound);
log(csound, "Doppler::kontrol: samplesPerDistance: %10.3f\n", samplesPerDistance);
log(csound, "Doppler::kontrol: smoothingFilterCutoff: %10.3f\n", smoothingFilterCutoff);
log(csound, "Doppler::kontrol: kMicPosition: %10.3f\n", *kMicPosition);
log(csound, "Doppler::kontrol: kSourcePosition: %10.3f\n", *kSourcePosition);
delayLine->initialize(sampleRate, 10.0);
}
for (size_t frame = 0; frame < blockSize; frame++) {
delayLine->write(audioInput[frame]);
MYFLT distance = std::fabs(position);
MYFLT delayFrames = distance * samplesPerDistance;
MYFLT delayFramesFloor = int(delayFrames);
MYFLT fraction = delayFrames - delayFramesFloor;
MYFLT currentValue = delayLine->delayFrames((int) delayFrames);
audioInterpolator->put(currentValue);
currentValue = audioInterpolator->get(fraction);
position = smoothingFilter->update(position);
audioOutput[frame] = currentValue;
}
return OK;
}
};
#endif
extern "C"
{
OENTRY oentries[] =
{
{
(char*)"doppler",
sizeof(Doppler),
3,
(char*)"a",
(char*)"akkjj",
(SUBR) Doppler::init_,
(SUBR) Doppler::kontrol_,
0,
},
#ifdef NEVER
{
(char*)"doppler2",
sizeof(Doppler2),
3,
(char*)"a",
(char*)"akkjj",
(SUBR) Doppler2::init_,
(SUBR) Doppler2::kontrol_,
0,
},
#endif
{
0,
0,
0,
0,
0,
0,
0,
0,
}
};
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
int status = 0;
for(OENTRY *oentry = &oentries[0]; oentry->opname; oentry++)
{
status |= csound->AppendOpcode(csound, oentry->opname,
oentry->dsblksiz, oentry->thread,
oentry->outypes, oentry->intypes,
(int (*)(CSOUND*,void*)) oentry->iopadr,
(int (*)(CSOUND*,void*)) oentry->kopadr,
(int (*)(CSOUND*,void*)) oentry->aopadr);
}
return status;
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
//csound->Message(csound, "Deleting C++ objects from doppler...\n");
for (std::list<RCLowpassFilter *>::iterator it = smoothingFilterInstances.begin();
it != smoothingFilterInstances.end();
++it) {
delete *it;
}
smoothingFilterInstances.clear();
for (std::list<DelayLine *>::iterator it = delayLineInstances.begin();
it != delayLineInstances.end();
++it) {
delete *it;
}
delayLineInstances.clear();
return 0;
}
}
<commit_msg>stop overwriting arguem,nts<commit_after>#include <OpcodeBase.hpp>
#include <cmath>
#include <iostream>
#include <list>
#include <vector>
// Why not use the constants already defined?
static MYFLT pi = std::atan(1.0) * MYFLT(4.0);
class RCLowpassFilter
{
public:
void initialize(MYFLT sampleRate, MYFLT cutoffHz, MYFLT initialValue)
{
MYFLT tau = MYFLT(1.0) / (MYFLT(2.0) * pi * cutoffHz);
alpha = MYFLT(1.0) / (MYFLT(1.0) + (tau * sampleRate));
value = initialValue;
}
MYFLT update(MYFLT inputValue)
{
value += alpha * (inputValue - value);
return value;
}
protected:
MYFLT alpha;
MYFLT value;
};
class LinearInterpolator
{
public:
LinearInterpolator() :
priorValue(MYFLT(0.0)),
currentValue(MYFLT(0.0))
{
}
virtual void put(MYFLT inputValue)
{
priorValue = currentValue;
currentValue = inputValue;
}
virtual MYFLT get(MYFLT fraction)
{
return priorValue + (fraction * (currentValue - priorValue));
}
protected:
MYFLT priorValue;
MYFLT currentValue;
};
class DelayLine : public std::vector<MYFLT>
{
public:
MYFLT sampleRate;
int writingFrame;
int size_;
void initialize(size_t sampleRate_, MYFLT maximumDelay = 10.0)
{
sampleRate = (MYFLT) sampleRate_;
size_ = (int) std::ceil(maximumDelay * sampleRate);
std::cout << "DelayLine::initialize: size: " << size_ << std::endl;
std::cout << "DelayLine::initialize: sampleRate: " << sampleRate << std::endl;
resize(size_);
writingFrame = 0;
}
void write(MYFLT value)
{
while (writingFrame >= size_) {
writingFrame -= size_;
}
(*this)[(size_t) writingFrame] = value;
//std::cout << "DelayLine::write: writingFrame: " << writingFrame << std::endl;
writingFrame++;
}
MYFLT delaySeconds(MYFLT delaySeconds)
{
int delayFrames_ = (int) (delaySeconds * sampleRate);
return delayFrames(delayFrames_);
}
MYFLT delayFrames(int delayFrames_)
{
//std::cout << "DelayLine::delayFrames: delayFrames: " << delayFrames_ << std::endl;
int readingFrame = writingFrame - delayFrames_;
while (readingFrame < 0) {
readingFrame += size_;
}
while (readingFrame >= size_) {
readingFrame -= size_;
}
// std::cout << "DelayLine::delayFrames: readingFrame: " << readingFrame << std::endl;
return (*this)[(size_t) readingFrame];
}
};
std::list<RCLowpassFilter *> smoothingFilterInstances;
std::list<DelayLine *> delayLineInstances;
class Doppler : public OpcodeBase<Doppler>
{
public:
// Csound opcode outputs.
MYFLT *audioOutput;
// Csound opcode inputs.
MYFLT *audioInput;
MYFLT *kSourcePosition; // usually meters
MYFLT *kMicPosition; // usually meters
MYFLT *jSpeedOfSound; // usually meters/second
MYFLT *jUpdateFilterCutoff; // Hz
// Doppler internal state.
MYFLT speedOfSound; // usually meters/second
MYFLT smoothingFilterCutoff; // Hz
MYFLT sampleRate; // Hz
MYFLT samplesPerDistance; // usually samples/meter
MYFLT blockRate; // Hz
int blockSize; // samples
RCLowpassFilter *smoothingFilter;
LinearInterpolator *audioInterpolator;
std::list< std::vector<MYFLT> *> *audioBufferQueue;
std::list<MYFLT> *sourcePositionQueue;
int relativeIndex;
int currentIndex;
int init(CSOUND *csound)
{
sampleRate = csound->GetSr(csound);
blockSize = csound->GetKsmps(csound);
blockRate = sampleRate / blockSize;
// Take care of default values.
if (*jSpeedOfSound == MYFLT(-1.0)) {
speedOfSound = MYFLT(340.29);
}
else speedOfSound = *jSpeedOfSound;
if (*jUpdateFilterCutoff == MYFLT(-1.0)) {
// MYFLT blockRateNyquist = blockRate / MYFLT(2.0);
// *jUpdateFilterCutoff = blockRateNyquist / MYFLT(2.0);
smoothingFilterCutoff = MYFLT(6.0); // very conservative
}
else smoothingFilterCutoff = *jUpdateFilterCutoff;
samplesPerDistance = sampleRate / speedOfSound;
audioInterpolator = new LinearInterpolator;
smoothingFilter = NULL;
audioBufferQueue = new std::list< std::vector<MYFLT> *>;
sourcePositionQueue = new std::list<MYFLT>;
currentIndex = 0;
relativeIndex = 0;
return OK;
}
int kontrol(CSOUND *csound)
{
MYFLT sourcePosition = *kSourcePosition;
MYFLT micPosition = *kMicPosition;
std::vector<MYFLT> *sourceBuffer = new std::vector<MYFLT>;
sourceBuffer->resize(blockSize);
for (size_t inputFrame = 0; inputFrame < blockSize; inputFrame++) {
(*sourceBuffer)[inputFrame] = audioInput[inputFrame];
}
audioBufferQueue->push_back(sourceBuffer);
sourcePositionQueue->push_back(sourcePosition);
std::vector<MYFLT> *currentBuffer = audioBufferQueue->front();
MYFLT targetPosition = sourcePositionQueue->front() - micPosition;
// The smoothing filter cannot be initialized at i-time,
// because it must be initialized from a k-rate variable.
if (!smoothingFilter) {
smoothingFilter = new RCLowpassFilter();
smoothingFilter->initialize(sampleRate, smoothingFilterCutoff, targetPosition);
log(csound, "Doppler::kontrol: sizeof(MYFLT): %10d\n", sizeof(MYFLT));
log(csound, "Doppler::kontrol: PI: %10.3f\n", pi);
log(csound, "Doppler::kontrol: this: %10p\n", this);
log(csound, "Doppler::kontrol: sampleRate: %10.3f\n", sampleRate);
log(csound, "Doppler::kontrol: blockSize: %10.3f\n", blockSize);
log(csound, "Doppler::kontrol: blockRate: %10.3f\n", blockRate);
log(csound, "Doppler::kontrol: speedOfSound: %10.3f\n", speedOfSound);
log(csound, "Doppler::kontrol: samplesPerDistance: %10.3f\n", samplesPerDistance);
log(csound, "Doppler::kontrol: smoothingFilterCutoff: %10.3f\n", smoothingFilterCutoff);
log(csound, "Doppler::kontrol: kMicPosition: %10.3f\n", *kMicPosition);
log(csound, "Doppler::kontrol: kSourcePosition: %10.3f\n", *kSourcePosition);
}
for (size_t outputFrame = 0; outputFrame < blockSize; outputFrame++) {
MYFLT position = smoothingFilter->update(targetPosition);
MYFLT distance = std::fabs(position);
MYFLT sourceTime = relativeIndex - (distance * samplesPerDistance);
int targetIndex = int(sourceTime);
MYFLT fraction = sourceTime - targetIndex;
relativeIndex++;
for ( ; targetIndex >= currentIndex; currentIndex++) {
if (currentIndex >= blockSize) {
relativeIndex -= blockSize;
currentIndex -= blockSize;
targetIndex -= blockSize;
delete audioBufferQueue->front();
audioBufferQueue->pop_front();
sourcePositionQueue->pop_front();
currentBuffer = audioBufferQueue->front();
targetPosition = sourcePositionQueue->front() - micPosition;
}
audioInterpolator->put((*currentBuffer)[currentIndex]);
}
MYFLT currentSample = audioInterpolator->get(fraction);
audioOutput[outputFrame] = currentSample;
}
return OK;
}
};
#ifdef NEVER
struct Doppler2 : public OpcodeBase<Doppler2>
{
// Csound opcode outputs.
MYFLT *audioOutput;
// Csound opcode inputs.
MYFLT *audioInput;
MYFLT *kSourcePosition;
MYFLT *kMicPosition;
MYFLT *jSpeedOfSound;
MYFLT *jUpdateFilterCutoff;
// Doppler internal state.
MYFLT speedOfSound;
MYFLT smoothingFilterCutoff;
MYFLT sampleRate;
MYFLT samplesPerDistance;
MYFLT blockSize;
MYFLT blockRate;
RCLowpassFilter *smoothingFilter;
LinearInterpolator *audioInterpolator;
DelayLine *delayLine;
int init(CSOUND *csound)
{
sampleRate = csound->GetSr(csound);
blockSize = csound->GetKsmps(csound);
blockRate = sampleRate / blockSize;
// Take care of default values.
if (*jSpeedOfSound == MYFLT(-1.0)) {
SpeedOfSound = MYFLT(340.29);
}
else speedOfSound = *jSpeedOfSound;
if (*jUpdateFilterCutoff == MYFLT(-1.0)) {
MYFLT blockRateNyquist = blockRate / MYFLT(2.0);
smoothingFilterCutoff = blockRateNyquist / MYFLT(2.0);
}
else smoothingFilterCutoff = *jUpdateFilterCutoff;
samplesPerDistance = sampleRate / speedOfSound;
audioInterpolator = new LinearInterpolator;
// The smoothing filter cannot be initialized at i-time,
// because it must be initialized from a k-rate variable.
smoothingFilter = 0;
delayLine = new DelayLine;
return OK;
}
int kontrol(CSOUND *csound)
{
MYFLT sourcePosition = *kSourcePosition;
MYFLT micPosition = *kMicPosition;
MYFLT position = sourcePosition - micPosition;
// On the very first block only, initialize the smoothing filter.
if (!smoothingFilter) {
smoothingFilter = new RCLowpassFilter();
smoothingFilter->initialize(sampleRate, smoothingFilterCutoff, *kSourcePosition);
log(csound, "Doppler::kontrol: sizeof(MYFLT): %10d\n", sizeof(MYFLT));
log(csound, "Doppler::kontrol: PI: %10.3f\n", pi);
log(csound, "Doppler::kontrol: this: %10p\n", this);
log(csound, "Doppler::kontrol: sampleRate: %10.3f\n", sampleRate);
log(csound, "Doppler::kontrol: blockSize: %10.3f\n", blockSize);
log(csound, "Doppler::kontrol: blockRate: %10.3f\n", blockRate);
log(csound, "Doppler::kontrol: speedOfSound: %10.3f\n", speedOfSound);
log(csound, "Doppler::kontrol: samplesPerDistance: %10.3f\n", samplesPerDistance);
log(csound, "Doppler::kontrol: smoothingFilterCutoff: %10.3f\n", smoothingFilterCutoff);
log(csound, "Doppler::kontrol: kMicPosition: %10.3f\n", *kMicPosition);
log(csound, "Doppler::kontrol: kSourcePosition: %10.3f\n", *kSourcePosition);
delayLine->initialize(sampleRate, 10.0);
}
for (size_t frame = 0; frame < blockSize; frame++) {
delayLine->write(audioInput[frame]);
MYFLT distance = std::fabs(position);
MYFLT delayFrames = distance * samplesPerDistance;
MYFLT delayFramesFloor = int(delayFrames);
MYFLT fraction = delayFrames - delayFramesFloor;
MYFLT currentValue = delayLine->delayFrames((int) delayFrames);
audioInterpolator->put(currentValue);
currentValue = audioInterpolator->get(fraction);
position = smoothingFilter->update(position);
audioOutput[frame] = currentValue;
}
return OK;
}
};
#endif
extern "C"
{
OENTRY oentries[] =
{
{
(char*)"doppler",
sizeof(Doppler),
3,
(char*)"a",
(char*)"akkjj",
(SUBR) Doppler::init_,
(SUBR) Doppler::kontrol_,
0,
},
#ifdef NEVER
{
(char*)"doppler2",
sizeof(Doppler2),
3,
(char*)"a",
(char*)"akkjj",
(SUBR) Doppler2::init_,
(SUBR) Doppler2::kontrol_,
0,
},
#endif
{
0,
0,
0,
0,
0,
0,
0,
0,
}
};
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
int status = 0;
for(OENTRY *oentry = &oentries[0]; oentry->opname; oentry++)
{
status |= csound->AppendOpcode(csound, oentry->opname,
oentry->dsblksiz, oentry->thread,
oentry->outypes, oentry->intypes,
(int (*)(CSOUND*,void*)) oentry->iopadr,
(int (*)(CSOUND*,void*)) oentry->kopadr,
(int (*)(CSOUND*,void*)) oentry->aopadr);
}
return status;
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
//csound->Message(csound, "Deleting C++ objects from doppler...\n");
for (std::list<RCLowpassFilter *>::iterator it = smoothingFilterInstances.begin();
it != smoothingFilterInstances.end();
++it) {
delete *it;
}
smoothingFilterInstances.clear();
for (std::list<DelayLine *>::iterator it = delayLineInstances.begin();
it != delayLineInstances.end();
++it) {
delete *it;
}
delayLineInstances.clear();
return 0;
}
}
<|endoftext|> |
<commit_before>#include "General.h"
#include <shellapi.h>
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "../3RVX/SkinInfo.h"
#include "UIContext.h"
#define KEY_NAME L"3RVX"
#define STARTUP_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"
void General::Command(unsigned short nCode, unsigned short ctrlId) {
switch (nCode) {
case BN_CLICKED:
if (ctrlId == BTN_WEBSITE && _url != L"") {
ShellExecute(NULL, L"open", _url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
}
break;
case CBN_SELCHANGE:
switch (ctrlId) {
case CMB_SKIN:
LoadSkinInfo(_ctxt->GetComboSelection(CMB_SKIN));
break;
case CMB_LANG:
// Language selection
break;
}
}
}
void General::LoadSettings() {
Settings *settings = Settings::Instance();
_ctxt->SetCheck(CHK_STARTUP, RunOnStartup());
_ctxt->SetCheck(CHK_NOTIFY, settings->NotifyIconEnabled());
_ctxt->SetCheck(CHK_SOUNDS, settings->SoundEffectsEnabled());
/* Determine which skins are available */
std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str());
for (std::wstring skin : skins) {
_ctxt->AddComboItem(CMB_SKIN, skin);
}
/* Update the combo box with the current skin */
std::wstring current = settings->CurrentSkin();
int idx = _ctxt->SelectComboItem(CMB_SKIN, current);
if (idx == CB_ERR) {
_ctxt->SelectComboItem(CMB_SKIN, DEFAULT_SKIN);
}
LoadSkinInfo(current);
// /* Populate the language box */
// std::list<CString> languages = FindLanguages(
// settings->LanguagesDir().c_str());
// for (CString language : languages) {
// _lang.AddString(language);
// }
// std::wstring currentLang = settings->LanguageName();
// _lang.SelectString(0, currentLang.c_str());
}
void General::SaveSettings() {
RunOnStartup(true);
}
bool General::RunOnStartup() {
long res;
HKEY key;
bool run = false;
res = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_KEY, NULL, KEY_READ, &key);
if (res == ERROR_SUCCESS) {
res = RegQueryValueEx(key, KEY_NAME, NULL, NULL, NULL, NULL);
run = (res == ERROR_SUCCESS);
}
RegCloseKey(key);
return run;
}
bool General::RunOnStartup(bool enable) {
long res;
HKEY key;
bool ok = false;
std::wstring path = Settings::AppDir() + L"\\3RVX.exe";
res = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_KEY, NULL, KEY_ALL_ACCESS, &key);
if (res == ERROR_SUCCESS) {
if (enable) {
res = RegSetValueEx(key, KEY_NAME, NULL, REG_SZ,
(LPBYTE) path.c_str(), path.size() + 1);
ok = (res == ERROR_SUCCESS);
} else {
res = RegDeleteValue(key, KEY_NAME);
ok = (res == ERROR_SUCCESS);
}
}
RegCloseKey(key);
return ok;
}
std::list<std::wstring> General::FindSkins(std::wstring dir) {
std::list<std::wstring> skins;
WIN32_FIND_DATA ffd;
HANDLE hFind;
CLOG(L"Finding skins in: %s", dir.c_str());
dir += L"\\*";
hFind = FindFirstFile(dir.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
return skins;
}
do {
std::wstring fName(ffd.cFileName);
if (fName.at(0) == L'.') {
continue;
}
QCLOG(L"%s", fName.c_str());
skins.push_back(fName);
} while (FindNextFile(hFind, &ffd));
FindClose(hFind);
return skins;
}
void General::LoadSkinInfo(std::wstring skinName) {
std::wstring skinXML = Settings::Instance()->SkinXML(skinName);
SkinInfo s(skinXML);
std::wstring authorText(L"Author: ");
authorText.append(s.Author());
_ctxt->SetText(LBL_AUTHOR, authorText);
std::wstring url = s.URL();
if (url == L"") {
_ctxt->Disable(BTN_WEBSITE);
} else {
_url = s.URL();
_ctxt->Enable(BTN_WEBSITE);
}
}
std::list<std::wstring> General::FindLanguages(std::wstring dir) {
std::list<std::wstring> languages;
WIN32_FIND_DATA ffd;
HANDLE hFind;
CLOG(L"Finding language translations in: %s", dir.c_str());
dir += L"\\*.xml";
hFind = FindFirstFile(dir.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
CLOG(L"FindFirstFile() failed");
return languages;
}
do {
std::wstring fName(ffd.cFileName);
if (fName.at(0) == L'.') {
continue;
}
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
continue;
}
QCLOG(L"%s", fName.c_str());
languages.push_back(fName);
} while (FindNextFile(hFind, &ffd));
FindClose(hFind);
return languages;
}
<commit_msg>Populate the language box<commit_after>#include "General.h"
#include <shellapi.h>
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "../3RVX/SkinInfo.h"
#include "UIContext.h"
#define KEY_NAME L"3RVX"
#define STARTUP_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"
void General::Command(unsigned short nCode, unsigned short ctrlId) {
switch (nCode) {
case BN_CLICKED:
if (ctrlId == BTN_WEBSITE && _url != L"") {
ShellExecute(NULL, L"open", _url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
}
break;
case CBN_SELCHANGE:
switch (ctrlId) {
case CMB_SKIN:
LoadSkinInfo(_ctxt->GetComboSelection(CMB_SKIN));
break;
case CMB_LANG:
// Language selection
break;
}
}
}
void General::LoadSettings() {
Settings *settings = Settings::Instance();
_ctxt->SetCheck(CHK_STARTUP, RunOnStartup());
_ctxt->SetCheck(CHK_NOTIFY, settings->NotifyIconEnabled());
_ctxt->SetCheck(CHK_SOUNDS, settings->SoundEffectsEnabled());
/* Determine which skins are available */
std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str());
for (std::wstring skin : skins) {
_ctxt->AddComboItem(CMB_SKIN, skin);
}
/* Update the combo box with the current skin */
std::wstring current = settings->CurrentSkin();
int idx = _ctxt->SelectComboItem(CMB_SKIN, current);
if (idx == CB_ERR) {
_ctxt->SelectComboItem(CMB_SKIN, DEFAULT_SKIN);
}
LoadSkinInfo(current);
/* Populate the language box */
std::list<std::wstring> languages = FindLanguages(
settings->LanguagesDir().c_str());
for (std::wstring language : languages) {
_ctxt->AddComboItem(CMB_LANG, language);
}
std::wstring currentLang = settings->LanguageName();
_ctxt->SelectComboItem(CMB_LANG, currentLang);
}
void General::SaveSettings() {
RunOnStartup(true);
}
bool General::RunOnStartup() {
long res;
HKEY key;
bool run = false;
res = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_KEY, NULL, KEY_READ, &key);
if (res == ERROR_SUCCESS) {
res = RegQueryValueEx(key, KEY_NAME, NULL, NULL, NULL, NULL);
run = (res == ERROR_SUCCESS);
}
RegCloseKey(key);
return run;
}
bool General::RunOnStartup(bool enable) {
long res;
HKEY key;
bool ok = false;
std::wstring path = Settings::AppDir() + L"\\3RVX.exe";
res = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_KEY, NULL, KEY_ALL_ACCESS, &key);
if (res == ERROR_SUCCESS) {
if (enable) {
res = RegSetValueEx(key, KEY_NAME, NULL, REG_SZ,
(LPBYTE) path.c_str(), path.size() + 1);
ok = (res == ERROR_SUCCESS);
} else {
res = RegDeleteValue(key, KEY_NAME);
ok = (res == ERROR_SUCCESS);
}
}
RegCloseKey(key);
return ok;
}
std::list<std::wstring> General::FindSkins(std::wstring dir) {
std::list<std::wstring> skins;
WIN32_FIND_DATA ffd;
HANDLE hFind;
CLOG(L"Finding skins in: %s", dir.c_str());
dir += L"\\*";
hFind = FindFirstFile(dir.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
return skins;
}
do {
std::wstring fName(ffd.cFileName);
if (fName.at(0) == L'.') {
continue;
}
QCLOG(L"%s", fName.c_str());
skins.push_back(fName);
} while (FindNextFile(hFind, &ffd));
FindClose(hFind);
return skins;
}
void General::LoadSkinInfo(std::wstring skinName) {
std::wstring skinXML = Settings::Instance()->SkinXML(skinName);
SkinInfo s(skinXML);
std::wstring authorText(L"Author: ");
authorText.append(s.Author());
_ctxt->SetText(LBL_AUTHOR, authorText);
std::wstring url = s.URL();
if (url == L"") {
_ctxt->Disable(BTN_WEBSITE);
} else {
_url = s.URL();
_ctxt->Enable(BTN_WEBSITE);
}
}
std::list<std::wstring> General::FindLanguages(std::wstring dir) {
std::list<std::wstring> languages;
WIN32_FIND_DATA ffd;
HANDLE hFind;
CLOG(L"Finding language translations in: %s", dir.c_str());
dir += L"\\*.xml";
hFind = FindFirstFile(dir.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
CLOG(L"FindFirstFile() failed");
return languages;
}
do {
std::wstring fName(ffd.cFileName);
if (fName.at(0) == L'.') {
continue;
}
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
continue;
}
QCLOG(L"%s", fName.c_str());
languages.push_back(fName);
} while (FindNextFile(hFind, &ffd));
FindClose(hFind);
return languages;
}
<|endoftext|> |
<commit_before>#include "cbase.h"
//#include "asw_objective_escape.h"
#include "mod_objective_escape.h"
#include "asw_game_resource.h"
#include "asw_marine_resource.h"
#include "asw_marine.h"
#include "triggers.h"
#include "mod_player_performance.h"
#include "missionchooser/iasw_random_missions.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
LINK_ENTITY_TO_CLASS( mod_objective_escape, CMOD_Objective_Escape );
BEGIN_DATADESC( CMOD_Objective_Escape )
DEFINE_FIELD( m_hTrigger, FIELD_EHANDLE ),
DEFINE_INPUTFUNC( FIELD_VOID, "MarineInEscapeArea", InputMarineInEscapeArea ),
END_DATADESC()
CUtlVector<CMOD_Objective_Escape*> g_aEscapeObjectives;
//CASW_Objective_Escape * m_aswEscape;
CMOD_Objective_Escape::CMOD_Objective_Escape() : CASW_Objective()
{
m_hTrigger = NULL;
g_aEscapeObjectives.AddToTail( this );
//m_aswEscape = new CASW_Objective_Escape();
}
CMOD_Objective_Escape::~CMOD_Objective_Escape()
{
g_aEscapeObjectives.FindAndRemove( this );
}
void CMOD_Objective_Escape::Spawn(){
//m_aswEscape = new CASW_Objective_Escape();
}
void CMOD_Objective_Escape::InputMarineInEscapeArea( inputdata_t &inputdata ){
Msg("Maine in Escape Area");
CBaseTrigger* pTrig = dynamic_cast<CBaseTrigger*>(inputdata.pCaller);
if (!pTrig)
{
Msg("Error: Escape objective input called by something that wasn't a trigger\n");
return;
}
if (pTrig != GetTrigger() && GetTrigger()!= NULL)
{
Msg("Error: Escape objective input called by two different triggers. Only 1 escape area is allowed per map.\n");
return;
}
m_hTrigger = pTrig;
CheckEscapeStatus();
}
void CMOD_Objective_Escape::CheckEscapeStatus()
{
if (OtherObjectivesComplete() && AllLiveMarinesInExit())
{
//Dynamically build the map for the next mission.
BuildMapForNextMission();
//Fires ASW_Objective::OnObjectiveComplete
Msg("Setting Objective to Complete\n");
SetComplete(true);
}
}
bool CMOD_Objective_Escape::OtherObjectivesComplete(){
if ( !ASWGameResource() )
return false;
CASW_Game_Resource* pGameResource = ASWGameResource();
for (int i=0;i<12;i++)
{
CASW_Objective* pObjective = pGameResource->GetObjective(i);
// if another objective isn't optional and isn't complete, then we're not ready to escape
if (pObjective && pObjective!=this
&& !pObjective->IsObjectiveOptional() && !pObjective->IsObjectiveComplete())
{
Msg("Not all Objectives complete\n");
return false;
}
}
Msg("All Objectives complete\n");
return true;
}
bool CMOD_Objective_Escape::AllLiveMarinesInExit()
{
if ( !ASWGameResource() ||!GetTrigger() )
{
Msg("All Live Marines are NOT in Exit\n");
return false;
}
CASW_Game_Resource* pGameResource = ASWGameResource();
for (int i=0;i<pGameResource->GetMaxMarineResources();i++)
{
CASW_Marine_Resource* pMR = pGameResource->GetMarineResource(i);
if (pMR && pMR->GetHealthPercent() > 0
&& pMR->GetMarineEntity())
{
// we've got a live marine, check if he's in the exit area
if (!GetTrigger()->IsTouching(pMR->GetMarineEntity()))
{
Msg("All Live Marines are NOT in Exit\n");
return false; // a live marine isn't in the exit zone
}
}
}
Msg("All Live Marines are in Exit\n");
return true;
}
void MOD_Level_Builder::BuildMapForNextMission()
{
CASW_Campaign_Info *pCampaign = CAlienSwarm::GetCampaignInfo();
if (!pCampaign)
{
Msg("Failed to load Campaign with CAlienSwarm::GetCampaignInfo()\n");
return;
}
CASW_Campaign_Save *pSave = CAlienSwarm::GetCampaignInfoGetCampaignSave();
if (!pSave)
{
Msg("Failed to load Campaign Save with CAlienSwarm::GetCampaignInfoGetCampaignSave()\n");
return;
}
int iNextMission = pSave->m_iNumMissionsComplete;
CASW_Campaign_Mission_t* pNextMission = pCampaign->GetMission(iNextMission);
if (!pNextMission)
{
Msg("Failed to load next campaign mission with pCampaign->GetMission(iNextMission)\n");
return;
}
int iPlayerPerformance = CMOD_Player_Performance::PlayerPerformance()->CalculatePerformance();
missionchooser->modLevel_Builder()->BuildMapForMissionFromLayoutFile(
pNextMission->m_MapName.ToCStr(), iPlayerPerformance);
}
CBaseTrigger* CMOD_Objective_Escape::GetTrigger()
{
return dynamic_cast<CBaseTrigger*>(m_hTrigger.Get());
}<commit_msg><commit_after>#include "cbase.h"
//#include "asw_objective_escape.h"
#include "mod_objective_escape.h"
#include "asw_game_resource.h"
#include "asw_marine_resource.h"
#include "asw_marine.h"
#include "triggers.h"
#include "mod_player_performance.h"
#include "missionchooser/iasw_random_missions.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
LINK_ENTITY_TO_CLASS( mod_objective_escape, CMOD_Objective_Escape );
BEGIN_DATADESC( CMOD_Objective_Escape )
DEFINE_FIELD( m_hTrigger, FIELD_EHANDLE ),
DEFINE_INPUTFUNC( FIELD_VOID, "MarineInEscapeArea", InputMarineInEscapeArea ),
END_DATADESC()
CUtlVector<CMOD_Objective_Escape*> g_aEscapeObjectives;
//CASW_Objective_Escape * m_aswEscape;
CMOD_Objective_Escape::CMOD_Objective_Escape() : CASW_Objective()
{
m_hTrigger = NULL;
g_aEscapeObjectives.AddToTail( this );
//m_aswEscape = new CASW_Objective_Escape();
}
CMOD_Objective_Escape::~CMOD_Objective_Escape()
{
g_aEscapeObjectives.FindAndRemove( this );
}
void CMOD_Objective_Escape::Spawn(){
//m_aswEscape = new CASW_Objective_Escape();
}
void CMOD_Objective_Escape::InputMarineInEscapeArea( inputdata_t &inputdata ){
Msg("Maine in Escape Area");
CBaseTrigger* pTrig = dynamic_cast<CBaseTrigger*>(inputdata.pCaller);
if (!pTrig)
{
Msg("Error: Escape objective input called by something that wasn't a trigger\n");
return;
}
if (pTrig != GetTrigger() && GetTrigger()!= NULL)
{
Msg("Error: Escape objective input called by two different triggers. Only 1 escape area is allowed per map.\n");
return;
}
m_hTrigger = pTrig;
CheckEscapeStatus();
}
void CMOD_Objective_Escape::CheckEscapeStatus()
{
if (OtherObjectivesComplete() && AllLiveMarinesInExit())
{
//Dynamically build the map for the next mission.
BuildMapForNextMission();
//Fires ASW_Objective::OnObjectiveComplete
Msg("Setting Objective to Complete\n");
SetComplete(true);
}
}
bool CMOD_Objective_Escape::OtherObjectivesComplete(){
if ( !ASWGameResource() )
return false;
CASW_Game_Resource* pGameResource = ASWGameResource();
for (int i=0;i<12;i++)
{
CASW_Objective* pObjective = pGameResource->GetObjective(i);
// if another objective isn't optional and isn't complete, then we're not ready to escape
if (pObjective && pObjective!=this
&& !pObjective->IsObjectiveOptional() && !pObjective->IsObjectiveComplete())
{
Msg("Not all Objectives complete\n");
return false;
}
}
Msg("All Objectives complete\n");
return true;
}
bool CMOD_Objective_Escape::AllLiveMarinesInExit()
{
if ( !ASWGameResource() ||!GetTrigger() )
{
Msg("All Live Marines are NOT in Exit\n");
return false;
}
CASW_Game_Resource* pGameResource = ASWGameResource();
for (int i=0;i<pGameResource->GetMaxMarineResources();i++)
{
CASW_Marine_Resource* pMR = pGameResource->GetMarineResource(i);
if (pMR && pMR->GetHealthPercent() > 0
&& pMR->GetMarineEntity())
{
// we've got a live marine, check if he's in the exit area
if (!GetTrigger()->IsTouching(pMR->GetMarineEntity()))
{
Msg("All Live Marines are NOT in Exit\n");
return false; // a live marine isn't in the exit zone
}
}
}
Msg("All Live Marines are in Exit\n");
return true;
}
void CMOD_Objective_Escape::BuildMapForNextMission()
{
CASW_Campaign_Info *pCampaign = CAlienSwarm::GetCampaignInfo();
if (!pCampaign)
{
Msg("Failed to load Campaign with CAlienSwarm::GetCampaignInfo()\n");
return;
}
CASW_Campaign_Save *pSave = CAlienSwarm::GetCampaignInfoGetCampaignSave();
if (!pSave)
{
Msg("Failed to load Campaign Save with CAlienSwarm::GetCampaignInfoGetCampaignSave()\n");
return;
}
int iNextMission = pSave->m_iNumMissionsComplete;
CASW_Campaign_Mission_t* pNextMission = pCampaign->GetMission(iNextMission);
if (!pNextMission)
{
Msg("Failed to load next campaign mission with pCampaign->GetMission(iNextMission)\n");
return;
}
int iPlayerPerformance = CMOD_Player_Performance::PlayerPerformance()->CalculatePerformance();
missionchooser->modLevel_Builder()->BuildMapForMissionFromLayoutFile(
pNextMission->m_MapName.ToCStr(), iPlayerPerformance);
}
CBaseTrigger* CMOD_Objective_Escape::GetTrigger()
{
return dynamic_cast<CBaseTrigger*>(m_hTrigger.Get());
}<|endoftext|> |
<commit_before>#include "../../../wrdSyntaxTest.hpp"
using namespace wrd;
using namespace std;
namespace {
struct defAssignExprTest : public wrdSyntaxTest {};
}
TEST_F(defAssignExprTest, simpleGlobalDefAssign) {
// control group.
make().parse(R"SRC(
age int // age is age
main() int // main is also a main
age := 5
return 0
)SRC").shouldVerified(true);
scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer());
scope& shares = (scope&) (((scopes&) getSlot().subs()).getNext().getContainer());
ASSERT_FALSE(nul(shares));
ASSERT_FALSE(nul(owns));
ASSERT_EQ(owns.len(), 1);
ASSERT_EQ(shares.len(), 2);
run();
ASSERT_EQ(getSubPack().sub<wInt>("age").cast<int>(), 0);
}
TEST_F(defAssignExprTest, simpleLocalDefAssign) {
// control group.
make().parse(R"SRC(
age int // age is age
main() int // main is also a main
age = 3
age := 5
age = 2
return 0
)SRC").shouldVerified(true);
run();
ASSERT_EQ(getSubPack().sub("age").cast<int>(), 3);
}
TEST_F(defAssignExprTest, testCircularDependencies) {
make("holymoly").parse(R"SRC(
pack holymoly
a := c
b := a
c := b // type can't be defined.
main() int
return 0
)SRC").shouldParsed(true);
shouldVerified(false);
// however when runs it, it throws an error.
}
TEST_F(defAssignExprTest, testNearCircularDependencies) {
make("holymoly").parse(R"SRC(
pack holymoly
c := 1 // type can be defined.
a := c
b := a
main() int
sys.con.print(a as str)
sys.con.print(b as str)
return 0
)SRC").shouldParsed(true);
shouldVerified(true);
// however when runs it, it throws an error.
// because assigning 1 to c will be done after evaluating of assignment of the 'a'.
}
TEST_F(defAssignExprTest, testDefAssign1) {
make().parse(R"SRC(
foo() int
return a = 2
a := foo() + 5
main() int
sys.con.print("a=" + a)
return 0
)SRC").shouldVerified(true);
run();
}
<commit_msg>wrd: test: add TC for defAssignExpr<commit_after>#include "../../../wrdSyntaxTest.hpp"
using namespace wrd;
using namespace std;
namespace {
struct defAssignExprTest : public wrdSyntaxTest {};
}
TEST_F(defAssignExprTest, simpleGlobalDefAssign) {
// control group.
make().parse(R"SRC(
age int // age is age
main() int // main is also a main
age := 5
return 0
)SRC").shouldVerified(true);
scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer());
scope& shares = (scope&) (((scopes&) getSlot().subs()).getNext().getContainer());
ASSERT_FALSE(nul(shares));
ASSERT_FALSE(nul(owns));
ASSERT_EQ(owns.len(), 1);
ASSERT_EQ(shares.len(), 2);
run();
ASSERT_EQ(getSubPack().sub<wInt>("age").cast<int>(), 0);
}
TEST_F(defAssignExprTest, simpleLocalDefAssign) {
// control group.
make().parse(R"SRC(
age int // age is age
main() int // main is also a main
age = 3
age := 5
age = 2
return 0
)SRC").shouldVerified(true);
run();
ASSERT_EQ(getSubPack().sub("age").cast<int>(), 3);
}
TEST_F(defAssignExprTest, testCircularDependencies) {
make("holymoly").parse(R"SRC(
pack holymoly
a := c
b := a
c := b // type can't be defined.
main() int
return 0
)SRC").shouldParsed(true);
shouldVerified(false);
// however when runs it, it throws an error.
}
TEST_F(defAssignExprTest, testNearCircularDependencies) {
make("holymoly").parse(R"SRC(
pack holymoly
c := 1 // type can be defined.
a := c
b := a
main() int
sys.con.print(a as str)
sys.con.print(b as str)
return 0
)SRC").shouldParsed(true);
shouldVerified(true);
// however when runs it, it throws an error.
// because assigning 1 to c will be done after evaluating of assignment of the 'a'.
}
TEST_F(defAssignExprTest, testDefAssign1) {
make().parse(R"SRC(
foo() int
return a = 2
a := foo() + 5
main() int
sys.con.print("a=" + a)
return 0
)SRC").shouldVerified(true);
run();
}
TEST_F(defAssignExprTest, defAssignInObjectRefersInvalidFuncNegative) {
make().parse(R"SRC(
aka sys.con c
nickname := foo()
foo() str
c.print("I'm foo!\n")
return 1 // this is invalid function.
main() void
c.print("your nickname is " + nickname)
)SRC").shouldParsed(true);
shouldVerified(false);
}
TEST_F(defAssignExprTest, defAssignInObjectRefersInvalidFuncNegative2) {
make().parse(R"SRC(
aka sys.con c
nickname := boo() // refers the func that doesn't exist.
foo() str
c.print("I'm foo!\n")
return 1 // this is invalid function.
main() void
c.print("your nickname is " + nickname)
)SRC").shouldParsed(true);
shouldVerified(false);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: oj $ $Date: 2002-08-23 05:55:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** compare two strings
*/
extern int
#if defined( WNT )
__cdecl
#endif
#if defined( ICC ) && defined( OS2 )
_Optlink
#endif
NameCompare( const void* pFirst, const void* pSecond)
{
return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
}
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters[i].replace('%', '*')));
}
else
{
if (nShiftPos != i)
pTableFilters[nShiftPos] = pTableFilters[i];
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_bConstructed(sal_False)
,m_xConnection(_xCon)
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
{
try
{
m_xMetaData = _xCon->getMetaData();
}
catch(SQLException&)
{
}
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False);
bFilterMatch = bNoTableFilters
|| ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct : catched an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_xConnection = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && _rWCSearch.size())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -------------------------------------------------------------------------
Reference< XNamed > OFilteredContainer::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -----------------------------------------------------------------------------
// ..............................................................................
} // namespace
// ..............................................................................
<commit_msg>#96435# pointer access corrected<commit_after>/*************************************************************************
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2002-08-26 07:59:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** compare two strings
*/
extern int
#if defined( WNT )
__cdecl
#endif
#if defined( ICC ) && defined( OS2 )
_Optlink
#endif
NameCompare( const void* pFirst, const void* pSecond)
{
return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
}
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_bConstructed(sal_False)
,m_xConnection(_xCon)
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
{
try
{
m_xMetaData = _xCon->getMetaData();
}
catch(SQLException&)
{
}
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False);
bFilterMatch = bNoTableFilters
|| ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct : catched an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_xConnection = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && _rWCSearch.size())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -------------------------------------------------------------------------
Reference< XNamed > OFilteredContainer::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -----------------------------------------------------------------------------
// ..............................................................................
} // namespace
// ..............................................................................
<|endoftext|> |
<commit_before>#include "rapid_perception/box3d_roi_server.h"
#include <math.h>
#include <string>
#include "boost/bind.hpp"
#include "interactive_markers/interactive_marker_server.h"
#include "rapid_msgs/Roi3D.h"
#include "visualization_msgs/InteractiveMarker.h"
#include "visualization_msgs/InteractiveMarkerControl.h"
#include "visualization_msgs/InteractiveMarkerFeedback.h"
#include "visualization_msgs/Marker.h"
using interactive_markers::InteractiveMarkerServer;
using rapid_msgs::Roi3D;
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerControl;
using visualization_msgs::InteractiveMarkerFeedbackConstPtr;
using visualization_msgs::Marker;
namespace rapid {
namespace perception {
Box3DRoiServer::Box3DRoiServer(const std::string& topic)
: server_(new InteractiveMarkerServer(topic)),
base_frame_("base_footprint") {}
Box3DRoiServer::~Box3DRoiServer() {
if (server_ != NULL) {
delete server_;
}
}
InteractiveMarker Box3DRoiServer::Box(double x, double y, double z,
double scale_x, double scale_y,
double scale_z) {
Marker box;
box.type = Marker::CUBE;
box.scale.x = scale_x;
box.scale.y = scale_y;
box.scale.z = scale_z;
box.color.r = 0.25;
box.color.g = 0.25;
box.color.b = 0.5;
box.color.a = 0.5;
InteractiveMarkerControl control;
control.markers.push_back(box);
control.always_visible = true;
control.interaction_mode = InteractiveMarkerControl::NONE;
InteractiveMarker marker;
marker.name = "box";
marker.controls.push_back(control);
marker.header.frame_id = base_frame_;
marker.pose.position.x = x;
marker.pose.position.y = y;
marker.pose.position.z = z;
marker.scale = box.scale.x;
return marker;
}
void Box3DRoiServer::Start() { Start(0.5, 0, 1, 0.3, 0.3, 0.3); }
void Box3DRoiServer::Start(double x, double y, double z, double scale_x,
double scale_y, double scale_z) {
InteractiveMarker box_marker = Box(x, y, z, scale_x, scale_y, scale_z);
server_->insert(box_marker);
roi_.transform.translation.x = x;
roi_.transform.translation.y = y;
roi_.transform.translation.z = z;
roi_.transform.rotation.w = 1;
roi_.dimensions.x = scale_x;
roi_.dimensions.y = scale_y;
roi_.dimensions.z = scale_z;
InteractiveMarker x_marker =
Arrow("x", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(x_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker y_marker =
Arrow("y", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(y_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker z_marker =
Arrow("z", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(z_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_x_marker =
Arrow("x", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_x_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_y_marker =
Arrow("y", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_y_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_z_marker =
Arrow("z", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_z_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
server_->applyChanges();
}
void Box3DRoiServer::Stop() {
server_->erase("box");
server_->erase("pos_x");
server_->erase("pos_y");
server_->erase("pos_z");
server_->erase("neg_x");
server_->erase("neg_y");
server_->erase("neg_z");
server_->applyChanges();
}
InteractiveMarker Box3DRoiServer::Arrow(const std::string& dim,
const std::string& polarity,
double box_x, double box_y,
double box_z, double box_scale_x,
double box_scale_y,
double box_scale_z) {
Marker arrow;
arrow.type = Marker::ARROW;
arrow.scale.x = 0.05;
arrow.scale.y = 0.025;
arrow.scale.z = 0.025;
if (dim == "x") {
arrow.color.r = 1;
} else if (dim == "y") {
arrow.color.g = 1;
} else if (dim == "z") {
arrow.color.b = 1;
}
arrow.color.a = 1;
double sign = 1;
if (polarity == "neg") {
sign = -1;
}
InteractiveMarkerControl control;
control.orientation.w = 1;
arrow.pose.orientation.w = 1;
if (dim == "x") {
if (sign == -1) {
control.orientation.w = 0;
control.orientation.z = 1;
}
} else if (dim == "y") {
control.orientation.z = sign;
} else if (dim == "z") {
control.orientation.y = -sign;
}
arrow.pose.orientation = control.orientation;
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
control.markers.push_back(arrow);
InteractiveMarker marker;
marker.name = polarity + "_" + dim;
marker.controls.push_back(control);
marker.header.frame_id = base_frame_;
marker.pose.position.x = box_x;
marker.pose.position.y = box_y;
marker.pose.position.z = box_z;
marker.pose.orientation.w = 1;
if (dim == "x") {
marker.pose.position.x = box_x + sign * box_scale_x / 2 + sign * 0.05;
} else if (dim == "y") {
marker.pose.position.y = box_y + sign * box_scale_y / 2 + sign * 0.05;
} else if (dim == "z") {
marker.pose.position.z = box_z + sign * box_scale_z / 2 + sign * 0.05;
}
marker.scale = 0.05;
return marker;
}
void Box3DRoiServer::Update(const std::string& dim, const std::string& polarity,
const geometry_msgs::Point& point) {
InteractiveMarker old_box;
server_->get("box", old_box);
const geometry_msgs::Point& old_pos = old_box.pose.position;
const geometry_msgs::Vector3& old_scale =
old_box.controls[0].markers[0].scale;
double sign = 1;
if (polarity == "neg") {
sign = -1;
}
double opposite_pos = 0; // Position of opposite face.
double input_pos = 0; // Position requested by user.
if (dim == "x") {
input_pos = point.x - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.x - old_scale.x / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.x + old_scale.x / 2, input_pos + 0.01);
}
} else if (dim == "y") {
input_pos = point.y - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.y - old_scale.y / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.y + old_scale.y / 2, input_pos + 0.01);
}
} else if (dim == "z") {
input_pos = point.z - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.z - old_scale.z / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.z + old_scale.z / 2, input_pos + 0.01);
}
}
double new_scale = sign * (input_pos - opposite_pos);
double new_pos = (opposite_pos + input_pos) / 2;
// Update box
InteractiveMarker box;
double new_x = old_pos.x;
double new_y = old_pos.y;
double new_z = old_pos.z;
double new_scale_x = old_scale.x;
double new_scale_y = old_scale.y;
double new_scale_z = old_scale.z;
if (dim == "x") {
new_x = new_pos;
new_scale_x = new_scale;
} else if (dim == "y") {
new_y = new_pos;
new_scale_y = new_scale;
} else if (dim == "z") {
new_z = new_pos;
new_scale_z = new_scale;
}
box = Box(new_x, new_y, new_z, new_scale_x, new_scale_y, new_scale_z);
server_->insert(box);
// Update ROI
roi_.transform.translation.x = new_x;
roi_.transform.translation.y = new_y;
roi_.transform.translation.z = new_z;
roi_.dimensions.x = new_scale_x;
roi_.dimensions.y = new_scale_y;
roi_.dimensions.z = new_scale_z;
// Update arrows
InteractiveMarker pos_x = Arrow("x", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_x", pos_x.pose, pos_x.header);
InteractiveMarker neg_x = Arrow("x", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_x", neg_x.pose, neg_x.header);
InteractiveMarker pos_y = Arrow("y", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_y", pos_y.pose, pos_y.header);
InteractiveMarker neg_y = Arrow("y", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_y", neg_y.pose, neg_y.header);
InteractiveMarker pos_z = Arrow("z", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_z", pos_z.pose, pos_z.header);
InteractiveMarker neg_z = Arrow("z", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_z", neg_z.pose, neg_z.header);
server_->applyChanges();
}
void Box3DRoiServer::Feedback(
const InteractiveMarkerFeedbackConstPtr& feedback) {
const geometry_msgs::Point& point = feedback->pose.position;
if (feedback->marker_name == "pos_x") {
Update("x", "pos", point);
} else if (feedback->marker_name == "pos_y") {
Update("y", "pos", point);
} else if (feedback->marker_name == "pos_z") {
Update("z", "pos", point);
} else if (feedback->marker_name == "neg_x") {
Update("x", "neg", point);
} else if (feedback->marker_name == "neg_y") {
Update("y", "neg", point);
} else if (feedback->marker_name == "neg_z") {
Update("z", "neg", point);
}
}
rapid_msgs::Roi3D Box3DRoiServer::roi() { return roi_; }
void Box3DRoiServer::set_base_frame(const std::string& base_frame) {
base_frame_ = base_frame;
}
} // namespace perception
} // namespace rapid
<commit_msg>Add outline box to ROI marker.<commit_after>#include "rapid_perception/box3d_roi_server.h"
#include <math.h>
#include <string>
#include "boost/bind.hpp"
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/Vector3.h"
#include "interactive_markers/interactive_marker_server.h"
#include "rapid_msgs/Roi3D.h"
#include "visualization_msgs/InteractiveMarker.h"
#include "visualization_msgs/InteractiveMarkerControl.h"
#include "visualization_msgs/InteractiveMarkerFeedback.h"
#include "visualization_msgs/Marker.h"
#include "rapid_viz/markers.h"
using interactive_markers::InteractiveMarkerServer;
using rapid_msgs::Roi3D;
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerControl;
using visualization_msgs::InteractiveMarkerFeedbackConstPtr;
using visualization_msgs::Marker;
namespace rapid {
namespace perception {
Box3DRoiServer::Box3DRoiServer(const std::string& topic)
: server_(new InteractiveMarkerServer(topic)),
base_frame_("base_footprint") {}
Box3DRoiServer::~Box3DRoiServer() {
if (server_ != NULL) {
delete server_;
}
}
InteractiveMarker Box3DRoiServer::Box(double x, double y, double z,
double scale_x, double scale_y,
double scale_z) {
Marker box;
box.type = Marker::CUBE;
box.scale.x = scale_x;
box.scale.y = scale_y;
box.scale.z = scale_z;
box.color.r = 0.25;
box.color.g = 0.25;
box.color.b = 0.5;
box.color.a = 0.5;
geometry_msgs::PoseStamped ps;
// ps.header.frame_id = base_frame_;
ps.pose.orientation.w = 1;
geometry_msgs::Vector3 scale;
scale.x = scale_x;
scale.y = scale_y;
scale.z = scale_z;
Marker outline_box = rapid::viz::OutlineBox(ps, scale);
InteractiveMarkerControl control;
control.markers.push_back(box);
control.markers.push_back(outline_box);
control.always_visible = true;
control.interaction_mode = InteractiveMarkerControl::NONE;
InteractiveMarker marker;
marker.name = "box";
marker.controls.push_back(control);
marker.header.frame_id = base_frame_;
marker.pose.position.x = x;
marker.pose.position.y = y;
marker.pose.position.z = z;
marker.scale = box.scale.x;
return marker;
}
void Box3DRoiServer::Start() { Start(0.5, 0, 1, 0.3, 0.3, 0.3); }
void Box3DRoiServer::Start(double x, double y, double z, double scale_x,
double scale_y, double scale_z) {
InteractiveMarker box_marker = Box(x, y, z, scale_x, scale_y, scale_z);
server_->insert(box_marker);
roi_.transform.translation.x = x;
roi_.transform.translation.y = y;
roi_.transform.translation.z = z;
roi_.transform.rotation.w = 1;
roi_.dimensions.x = scale_x;
roi_.dimensions.y = scale_y;
roi_.dimensions.z = scale_z;
InteractiveMarker x_marker =
Arrow("x", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(x_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker y_marker =
Arrow("y", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(y_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker z_marker =
Arrow("z", "pos", x, y, z, scale_x, scale_y, scale_z);
server_->insert(z_marker, boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_x_marker =
Arrow("x", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_x_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_y_marker =
Arrow("y", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_y_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
InteractiveMarker neg_z_marker =
Arrow("z", "neg", x, y, z, scale_x, scale_y, scale_z);
server_->insert(neg_z_marker,
boost::bind(&Box3DRoiServer::Feedback, this, _1));
server_->applyChanges();
}
void Box3DRoiServer::Stop() {
server_->erase("box");
server_->erase("pos_x");
server_->erase("pos_y");
server_->erase("pos_z");
server_->erase("neg_x");
server_->erase("neg_y");
server_->erase("neg_z");
server_->applyChanges();
}
InteractiveMarker Box3DRoiServer::Arrow(const std::string& dim,
const std::string& polarity,
double box_x, double box_y,
double box_z, double box_scale_x,
double box_scale_y,
double box_scale_z) {
Marker arrow;
arrow.type = Marker::ARROW;
arrow.scale.x = 0.05;
arrow.scale.y = 0.05;
arrow.scale.z = 0.05;
if (dim == "x") {
arrow.color.r = 1;
} else if (dim == "y") {
arrow.color.g = 1;
} else if (dim == "z") {
arrow.color.b = 1;
}
arrow.color.a = 0.9;
double sign = 1;
if (polarity == "neg") {
sign = -1;
}
InteractiveMarkerControl control;
control.orientation.w = 1;
arrow.pose.orientation.w = 1;
if (dim == "x") {
if (sign == -1) {
control.orientation.w = 0;
control.orientation.z = 1;
}
} else if (dim == "y") {
control.orientation.z = sign;
} else if (dim == "z") {
control.orientation.y = -sign;
}
arrow.pose.orientation = control.orientation;
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
control.markers.push_back(arrow);
InteractiveMarker marker;
marker.name = polarity + "_" + dim;
marker.controls.push_back(control);
marker.header.frame_id = base_frame_;
marker.pose.position.x = box_x;
marker.pose.position.y = box_y;
marker.pose.position.z = box_z;
marker.pose.orientation.w = 1;
if (dim == "x") {
marker.pose.position.x = box_x + sign * box_scale_x / 2 + sign * 0.05;
} else if (dim == "y") {
marker.pose.position.y = box_y + sign * box_scale_y / 2 + sign * 0.05;
} else if (dim == "z") {
marker.pose.position.z = box_z + sign * box_scale_z / 2 + sign * 0.05;
}
marker.scale = 0.05;
return marker;
}
void Box3DRoiServer::Update(const std::string& dim, const std::string& polarity,
const geometry_msgs::Point& point) {
InteractiveMarker old_box;
server_->get("box", old_box);
const geometry_msgs::Point& old_pos = old_box.pose.position;
const geometry_msgs::Vector3& old_scale =
old_box.controls[0].markers[0].scale;
double sign = 1;
if (polarity == "neg") {
sign = -1;
}
double opposite_pos = 0; // Position of opposite face.
double input_pos = 0; // Position requested by user.
if (dim == "x") {
input_pos = point.x - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.x - old_scale.x / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.x + old_scale.x / 2, input_pos + 0.01);
}
} else if (dim == "y") {
input_pos = point.y - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.y - old_scale.y / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.y + old_scale.y / 2, input_pos + 0.01);
}
} else if (dim == "z") {
input_pos = point.z - sign * 0.05;
if (sign == 1) {
opposite_pos = std::min(old_pos.z - old_scale.z / 2, input_pos - 0.01);
} else {
opposite_pos = std::max(old_pos.z + old_scale.z / 2, input_pos + 0.01);
}
}
double new_scale = sign * (input_pos - opposite_pos);
double new_pos = (opposite_pos + input_pos) / 2;
// Update box
InteractiveMarker box;
double new_x = old_pos.x;
double new_y = old_pos.y;
double new_z = old_pos.z;
double new_scale_x = old_scale.x;
double new_scale_y = old_scale.y;
double new_scale_z = old_scale.z;
if (dim == "x") {
new_x = new_pos;
new_scale_x = new_scale;
} else if (dim == "y") {
new_y = new_pos;
new_scale_y = new_scale;
} else if (dim == "z") {
new_z = new_pos;
new_scale_z = new_scale;
}
box = Box(new_x, new_y, new_z, new_scale_x, new_scale_y, new_scale_z);
server_->insert(box);
// Update ROI
roi_.transform.translation.x = new_x;
roi_.transform.translation.y = new_y;
roi_.transform.translation.z = new_z;
roi_.dimensions.x = new_scale_x;
roi_.dimensions.y = new_scale_y;
roi_.dimensions.z = new_scale_z;
// Update arrows
InteractiveMarker pos_x = Arrow("x", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_x", pos_x.pose, pos_x.header);
InteractiveMarker neg_x = Arrow("x", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_x", neg_x.pose, neg_x.header);
InteractiveMarker pos_y = Arrow("y", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_y", pos_y.pose, pos_y.header);
InteractiveMarker neg_y = Arrow("y", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_y", neg_y.pose, neg_y.header);
InteractiveMarker pos_z = Arrow("z", "pos", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("pos_z", pos_z.pose, pos_z.header);
InteractiveMarker neg_z = Arrow("z", "neg", new_x, new_y, new_z, new_scale_x,
new_scale_y, new_scale_z);
server_->setPose("neg_z", neg_z.pose, neg_z.header);
server_->applyChanges();
}
void Box3DRoiServer::Feedback(
const InteractiveMarkerFeedbackConstPtr& feedback) {
const geometry_msgs::Point& point = feedback->pose.position;
if (feedback->marker_name == "pos_x") {
Update("x", "pos", point);
} else if (feedback->marker_name == "pos_y") {
Update("y", "pos", point);
} else if (feedback->marker_name == "pos_z") {
Update("z", "pos", point);
} else if (feedback->marker_name == "neg_x") {
Update("x", "neg", point);
} else if (feedback->marker_name == "neg_y") {
Update("y", "neg", point);
} else if (feedback->marker_name == "neg_z") {
Update("z", "neg", point);
}
}
rapid_msgs::Roi3D Box3DRoiServer::roi() { return roi_; }
void Box3DRoiServer::set_base_frame(const std::string& base_frame) {
base_frame_ = base_frame;
}
} // namespace perception
} // namespace rapid
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AdvancedSettingsDlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 07:31:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _DBAUI_ADVANCEDSETTINGSDLG_HXX
#include "AdvancedSettingsDlg.hxx"
#endif
#ifndef DBAUI_ADVANCEDPAGEDLG_HXX
#include "AdvancedPageDlg.hxx"
#endif
using namespace dbaui;
extern "C" void SAL_CALL createRegistryInfo_OAdvancedSettingsDialog()
{
static OMultiInstanceAutoRegistration< OAdvancedSettingsDialog > aAutoRegistration;
}
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
//=========================================================================
//-------------------------------------------------------------------------
OAdvancedSettingsDialog::OAdvancedSettingsDialog(const Reference< XMultiServiceFactory >& _rxORB)
:ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OAdvancedSettingsDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL OAdvancedSettingsDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return *(new OAdvancedSettingsDialog(_rxFactory));
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OAdvancedSettingsDialog::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
//-------------------------------------------------------------------------
::rtl::OUString OAdvancedSettingsDialog::getImplementationName_Static() throw(RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.OAdvancedSettingsDialog"));
}
//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL OAdvancedSettingsDialog::getSupportedServiceNames() throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
//-------------------------------------------------------------------------
::comphelper::StringSequence OAdvancedSettingsDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
::comphelper::StringSequence aSupported(1);
aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.AdvancedDatabaseSettingsDialog"));
return aSupported;
}
//-------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OAdvancedSettingsDialog::getPropertySetInfo() throw(RuntimeException)
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OAdvancedSettingsDialog::getInfoHelper()
{
return *const_cast<OAdvancedSettingsDialog*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OAdvancedSettingsDialog::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* OAdvancedSettingsDialog::createDialog(Window* _pParent)
{
OAdvancedTabPageDlg* pDlg = new OAdvancedTabPageDlg(_pParent, m_pDatasourceItems, m_xORB,m_aInitialSelection);
return pDlg;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS dba24b (1.4.130); FILE MERGED 2007/08/27 10:42:05 fs 1.4.130.1: some re-factoring in preparation of #i80930#: moved declaration from .hxx to .cxx<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AdvancedSettingsDlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-11-01 15:38:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#include "unoadmin.hxx"
#include "dbu_reghelper.hxx"
#include "advancedsettingsdlg.hxx"
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
//=========================================================================
//= OAdvancedSettingsDialog
//=========================================================================
class OAdvancedSettingsDialog
:public ODatabaseAdministrationDialog
,public ::comphelper::OPropertyArrayUsageHelper< OAdvancedSettingsDialog >
{
protected:
OAdvancedSettingsDialog(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
public:
// XTypeProvider
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo - static methods
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
protected:
// OGenericUnoDialog overridables
virtual Dialog* createDialog(Window* _pParent);
};
//=========================================================================
//-------------------------------------------------------------------------
OAdvancedSettingsDialog::OAdvancedSettingsDialog(const Reference< XMultiServiceFactory >& _rxORB)
:ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OAdvancedSettingsDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL OAdvancedSettingsDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return *(new OAdvancedSettingsDialog(_rxFactory));
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OAdvancedSettingsDialog::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
//-------------------------------------------------------------------------
::rtl::OUString OAdvancedSettingsDialog::getImplementationName_Static() throw(RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.OAdvancedSettingsDialog"));
}
//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL OAdvancedSettingsDialog::getSupportedServiceNames() throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
//-------------------------------------------------------------------------
::comphelper::StringSequence OAdvancedSettingsDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
::comphelper::StringSequence aSupported(1);
aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.AdvancedDatabaseSettingsDialog"));
return aSupported;
}
//-------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OAdvancedSettingsDialog::getPropertySetInfo() throw(RuntimeException)
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OAdvancedSettingsDialog::getInfoHelper()
{
return *const_cast<OAdvancedSettingsDialog*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OAdvancedSettingsDialog::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* OAdvancedSettingsDialog::createDialog(Window* _pParent)
{
AdvancedSettingsDialog* pDlg = new AdvancedSettingsDialog(_pParent, m_pDatasourceItems, m_xORB,m_aInitialSelection);
return pDlg;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
extern "C" void SAL_CALL createRegistryInfo_OAdvancedSettingsDialog()
{
static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::OAdvancedSettingsDialog > aAutoRegistration;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hierarchyservices.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:29:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
#ifndef _HIERARCHYDATASOURCE_HXX
#include "hierarchydatasource.hxx"
#endif
using namespace com::sun::star;
using namespace hierarchy_ucp;
//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
const rtl::OUString & rImplementationName,
uno::Sequence< rtl::OUString > const & rServiceNames )
{
rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
aKeyName += rImplementationName;
aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );
uno::Reference< registry::XRegistryKey > xKey;
try
{
xKey = static_cast< registry::XRegistryKey * >(
pRegistryKey )->createKey( aKeyName );
}
catch ( registry::InvalidRegistryException const & )
{
}
if ( !xKey.is() )
return sal_False;
sal_Bool bSuccess = sal_True;
for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
{
try
{
xKey->createKey( rServiceNames[ n ] );
}
catch ( registry::InvalidRegistryException const & )
{
bSuccess = sal_False;
break;
}
}
return bSuccess;
}
//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
void * /*pServiceManager*/, void * pRegistryKey )
{
return pRegistryKey &&
//////////////////////////////////////////////////////////////////////
// Hierarchy Content Provider.
//////////////////////////////////////////////////////////////////////
writeInfo( pRegistryKey,
HierarchyContentProvider::getImplementationName_Static(),
HierarchyContentProvider::getSupportedServiceNames_Static() ) &&
//////////////////////////////////////////////////////////////////////
// Hierarchy Data Source.
//////////////////////////////////////////////////////////////////////
writeInfo( pRegistryKey,
HierarchyDataSource::getImplementationName_Static(),
HierarchyDataSource::getSupportedServiceNames_Static() );
}
//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = 0;
uno::Reference< lang::XMultiServiceFactory > xSMgr(
reinterpret_cast< lang::XMultiServiceFactory * >(
pServiceManager ) );
uno::Reference< lang::XSingleServiceFactory > xFactory;
//////////////////////////////////////////////////////////////////////
// Hierarchy Content Provider.
//////////////////////////////////////////////////////////////////////
if ( HierarchyContentProvider::getImplementationName_Static().
compareToAscii( pImplName ) == 0 )
{
xFactory = HierarchyContentProvider::createServiceFactory( xSMgr );
}
//////////////////////////////////////////////////////////////////////
// Hierarchy Data Source.
//////////////////////////////////////////////////////////////////////
else if ( HierarchyDataSource::getImplementationName_Static().
compareToAscii( pImplName ) == 0 )
{
xFactory = HierarchyDataSource::createServiceFactory( xSMgr );
}
//////////////////////////////////////////////////////////////////////
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.20); FILE MERGED 2006/09/01 17:55:47 kaib 1.6.20.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hierarchyservices.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:56:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
#ifndef _HIERARCHYDATASOURCE_HXX
#include "hierarchydatasource.hxx"
#endif
using namespace com::sun::star;
using namespace hierarchy_ucp;
//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
const rtl::OUString & rImplementationName,
uno::Sequence< rtl::OUString > const & rServiceNames )
{
rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
aKeyName += rImplementationName;
aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );
uno::Reference< registry::XRegistryKey > xKey;
try
{
xKey = static_cast< registry::XRegistryKey * >(
pRegistryKey )->createKey( aKeyName );
}
catch ( registry::InvalidRegistryException const & )
{
}
if ( !xKey.is() )
return sal_False;
sal_Bool bSuccess = sal_True;
for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
{
try
{
xKey->createKey( rServiceNames[ n ] );
}
catch ( registry::InvalidRegistryException const & )
{
bSuccess = sal_False;
break;
}
}
return bSuccess;
}
//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
void * /*pServiceManager*/, void * pRegistryKey )
{
return pRegistryKey &&
//////////////////////////////////////////////////////////////////////
// Hierarchy Content Provider.
//////////////////////////////////////////////////////////////////////
writeInfo( pRegistryKey,
HierarchyContentProvider::getImplementationName_Static(),
HierarchyContentProvider::getSupportedServiceNames_Static() ) &&
//////////////////////////////////////////////////////////////////////
// Hierarchy Data Source.
//////////////////////////////////////////////////////////////////////
writeInfo( pRegistryKey,
HierarchyDataSource::getImplementationName_Static(),
HierarchyDataSource::getSupportedServiceNames_Static() );
}
//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = 0;
uno::Reference< lang::XMultiServiceFactory > xSMgr(
reinterpret_cast< lang::XMultiServiceFactory * >(
pServiceManager ) );
uno::Reference< lang::XSingleServiceFactory > xFactory;
//////////////////////////////////////////////////////////////////////
// Hierarchy Content Provider.
//////////////////////////////////////////////////////////////////////
if ( HierarchyContentProvider::getImplementationName_Static().
compareToAscii( pImplName ) == 0 )
{
xFactory = HierarchyContentProvider::createServiceFactory( xSMgr );
}
//////////////////////////////////////////////////////////////////////
// Hierarchy Data Source.
//////////////////////////////////////////////////////////////////////
else if ( HierarchyDataSource::getImplementationName_Static().
compareToAscii( pImplName ) == 0 )
{
xFactory = HierarchyDataSource::createServiceFactory( xSMgr );
}
//////////////////////////////////////////////////////////////////////
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: VisualizeModel.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2014 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that loads an OpenSim model
* and visualize it in the API visualizer.
*/
// Author: Ayman Habib
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//______________________________________________________________________________
/**
* First exercise: create a model that does nothing.
*/
int main(int argc, char **argv)
{
try {
// Create an OpenSim model and set its name
if (argc < 2) {
string progName = IO::GetFileNameFromURI(argv[0]);
cout << "Filename needs to be specified or passed in.\n\n";
return 1;
}
std::string modelFile = std::string(argv[1]);
Model osimModel(modelFile);
//osimModel.print("updated_" + modelFile);
osimModel.setUseVisualizer(true);
osimModel.updDisplayHints().set_show_frames(true);
SimTK::State& si = osimModel.initSystem();
osimModel.equilibrateMuscles(si);
osimModel.getMultibodySystem().realize(si, Stage::Velocity);
osimModel.getVisualizer().show(si);
getchar(); // Keep Visualizer from dying until we inspect the visualization window..
}
catch (OpenSim::Exception ex)
{
std::cout << ex.getMessage() << std::endl;
return 1;
}
catch (std::exception ex)
{
std::cout << ex.what() << std::endl;
return 1;
}
catch (...)
{
std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
return 1;
}
return 0;
}
<commit_msg>Don't show Frames by default, they'll be individually controlled.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: VisualizeModel.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2014 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that loads an OpenSim model
* and visualize it in the API visualizer.
*/
// Author: Ayman Habib
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//______________________________________________________________________________
/**
* First exercise: create a model that does nothing.
*/
int main(int argc, char **argv)
{
try {
// Create an OpenSim model and set its name
if (argc < 2) {
string progName = IO::GetFileNameFromURI(argv[0]);
cout << "Filename needs to be specified or passed in.\n\n";
return 1;
}
std::string modelFile = std::string(argv[1]);
Model osimModel(modelFile);
//osimModel.print("updated_" + modelFile);
osimModel.setUseVisualizer(true);
osimModel.updDisplayHints().set_show_frames(false);
SimTK::State& si = osimModel.initSystem();
osimModel.equilibrateMuscles(si);
osimModel.getMultibodySystem().realize(si, Stage::Velocity);
osimModel.getVisualizer().show(si);
getchar(); // Keep Visualizer from dying until we inspect the visualization window..
}
catch (OpenSim::Exception ex)
{
std::cout << ex.getMessage() << std::endl;
return 1;
}
catch (std::exception ex)
{
std::cout << ex.what() << std::endl;
return 1;
}
catch (...)
{
std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "fileproperties.hpp"
namespace Davix {
FileProperties::FileProperties() :
filename(),
req_status(0),
nlink(0),
uid(0),
gid(0),
size(0),
mode(0),
atime(0),
mtime(0),
ctime(0){
}
} // namespace Davix
<commit_msg>Simplify file properties structure<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleOutlineView.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2007-04-25 14:40:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#define SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#ifndef SD_ACCESSIBILITY_ACCESSIBLE_DOCUMENT_VIEW_BASE_HXX
#include "AccessibleDocumentViewBase.hxx"
#endif
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
namespace sd {
class OutlineViewShell;
class Window;
}
namespace accessibility {
/** This class makes the Impress outline view accessible.
Please see the documentation of the base class for further
explanations of the individual methods. This class is a mere
wrapper around the AccessibleTextHelper class; as basically the
Outline View is a big Outliner.
*/
class AccessibleOutlineView
: public AccessibleDocumentViewBase
{
public:
AccessibleOutlineView (
::sd::Window* pSdWindow,
::sd::OutlineViewShell* pViewShell,
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XController>& rxController,
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent);
virtual ~AccessibleOutlineView (void);
/** Complete the initialization begun in the constructor.
*/
virtual void Init (void);
//===== IAccessibleViewForwarderListener ================================
virtual void ViewForwarderChanged (ChangeType aChangeType,
const IAccessibleViewForwarder* pViewForwarder);
//===== XAccessibleContext ==============================================
virtual sal_Int32 SAL_CALL
getAccessibleChildCount (void)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild (sal_Int32 nIndex)
throw (::com::sun::star::uno::RuntimeException);
//===== XAccessibleEventBroadcaster ========================================
virtual void SAL_CALL
addEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
using cppu::WeakComponentImplHelperBase::addEventListener;
using cppu::WeakComponentImplHelperBase::removeEventListener;
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
//===== lang::XEventListener ============================================
virtual void SAL_CALL
disposing (const ::com::sun::star::lang::EventObject& rEventObject)
throw (::com::sun::star::uno::RuntimeException);
//===== XPropertyChangeListener =========================================
virtual void SAL_CALL
propertyChange (const ::com::sun::star::beans::PropertyChangeEvent& rEventObject)
throw (::com::sun::star::uno::RuntimeException);
protected:
// overridden, as we hold the listeners ourselves
virtual void FireEvent (const ::com::sun::star::accessibility::AccessibleEventObject& aEvent);
// overridden to detect focus changes
virtual void Activated (void);
// overridden to detect focus changes
virtual void Deactivated (void);
// declared, but not defined
AccessibleOutlineView( const AccessibleOutlineView& );
AccessibleOutlineView& operator= ( const AccessibleOutlineView& );
// This method is called from the component helper base class while disposing.
virtual void SAL_CALL disposing (void);
/// Create an accessible name that contains the current view mode.
virtual ::rtl::OUString
CreateAccessibleName ()
throw (::com::sun::star::uno::RuntimeException);
/// Create an accessible description that contains the current
/// view mode.
virtual ::rtl::OUString
CreateAccessibleDescription ()
throw (::com::sun::star::uno::RuntimeException);
private:
/// Invalidate text helper, updates visible children
void UpdateChildren();
AccessibleTextHelper maTextHelper;
};
} // end of namespace accessibility
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.9.222); FILE MERGED 2008/04/01 15:35:00 thb 1.9.222.3: #i85898# Stripping all external header guards 2008/04/01 12:38:58 thb 1.9.222.2: #i85898# Stripping all external header guards 2008/03/31 13:58:08 rt 1.9.222.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleOutlineView.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#define SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#include "AccessibleDocumentViewBase.hxx"
#include <svx/AccessibleTextHelper.hxx>
namespace sd {
class OutlineViewShell;
class Window;
}
namespace accessibility {
/** This class makes the Impress outline view accessible.
Please see the documentation of the base class for further
explanations of the individual methods. This class is a mere
wrapper around the AccessibleTextHelper class; as basically the
Outline View is a big Outliner.
*/
class AccessibleOutlineView
: public AccessibleDocumentViewBase
{
public:
AccessibleOutlineView (
::sd::Window* pSdWindow,
::sd::OutlineViewShell* pViewShell,
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XController>& rxController,
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent);
virtual ~AccessibleOutlineView (void);
/** Complete the initialization begun in the constructor.
*/
virtual void Init (void);
//===== IAccessibleViewForwarderListener ================================
virtual void ViewForwarderChanged (ChangeType aChangeType,
const IAccessibleViewForwarder* pViewForwarder);
//===== XAccessibleContext ==============================================
virtual sal_Int32 SAL_CALL
getAccessibleChildCount (void)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild (sal_Int32 nIndex)
throw (::com::sun::star::uno::RuntimeException);
//===== XAccessibleEventBroadcaster ========================================
virtual void SAL_CALL
addEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
using cppu::WeakComponentImplHelperBase::addEventListener;
using cppu::WeakComponentImplHelperBase::removeEventListener;
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
//===== lang::XEventListener ============================================
virtual void SAL_CALL
disposing (const ::com::sun::star::lang::EventObject& rEventObject)
throw (::com::sun::star::uno::RuntimeException);
//===== XPropertyChangeListener =========================================
virtual void SAL_CALL
propertyChange (const ::com::sun::star::beans::PropertyChangeEvent& rEventObject)
throw (::com::sun::star::uno::RuntimeException);
protected:
// overridden, as we hold the listeners ourselves
virtual void FireEvent (const ::com::sun::star::accessibility::AccessibleEventObject& aEvent);
// overridden to detect focus changes
virtual void Activated (void);
// overridden to detect focus changes
virtual void Deactivated (void);
// declared, but not defined
AccessibleOutlineView( const AccessibleOutlineView& );
AccessibleOutlineView& operator= ( const AccessibleOutlineView& );
// This method is called from the component helper base class while disposing.
virtual void SAL_CALL disposing (void);
/// Create an accessible name that contains the current view mode.
virtual ::rtl::OUString
CreateAccessibleName ()
throw (::com::sun::star::uno::RuntimeException);
/// Create an accessible description that contains the current
/// view mode.
virtual ::rtl::OUString
CreateAccessibleDescription ()
throw (::com::sun::star::uno::RuntimeException);
private:
/// Invalidate text helper, updates visible children
void UpdateChildren();
AccessibleTextHelper maTextHelper;
};
} // end of namespace accessibility
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemanager.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-10-15 12:24:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "unodevtools/typemanager.hxx"
#include "rtl/alloc.h"
#include "registry/reader.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "com/sun/star/container/XSet.hpp"
#include "com/sun/star/reflection/XTypeDescription.hpp"
#include "com/sun/star/registry/XSimpleRegistry.hpp"
#include "com/sun/star/uno/XComponentContext.hpp"
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::reflection;
namespace unodevtools {
static RTTypeClass mapTypeClass(TypeClass typeclass) {
switch(typeclass) {
case TypeClass_ENUM:
return RT_TYPE_ENUM;
case TypeClass_TYPEDEF:
return RT_TYPE_TYPEDEF;
case TypeClass_STRUCT:
return RT_TYPE_STRUCT;
case TypeClass_UNION:
return RT_TYPE_UNION;
case TypeClass_EXCEPTION:
return RT_TYPE_EXCEPTION;
case TypeClass_INTERFACE:
return RT_TYPE_INTERFACE;
case TypeClass_SERVICE:
return RT_TYPE_SERVICE;
case TypeClass_MODULE:
return RT_TYPE_MODULE;
case TypeClass_CONSTANTS:
return RT_TYPE_CONSTANTS;
case TypeClass_SINGLETON:
return RT_TYPE_SINGLETON;
default:
break;
}
return RT_TYPE_INVALID;
}
UnoTypeManager::UnoTypeManager()
{
m_pImpl = new UnoTypeManagerImpl();
acquire();
}
UnoTypeManager::~UnoTypeManager()
{
release();
}
void UnoTypeManager::release()
{
if (0 == TypeManager::release())
delete m_pImpl;
}
sal_Bool UnoTypeManager::init(
const ::std::vector< ::rtl::OUString > registries)
{
Reference< XComponentContext > xContext=
defaultBootstrap_InitialComponentContext();
if ( !xContext.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't create initial UNO component context"));
throw RuntimeException( msg, Reference< XInterface >());
}
Any a = xContext->getValueByName(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"/singletons/com.sun.star.reflection.theTypeDescriptionManager")));
a >>= m_pImpl->m_tdmgr;
if ( !m_pImpl->m_tdmgr.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't get TypeDescriptionManager"));
throw RuntimeException( msg, Reference< XInterface >());
}
if ( !registries.empty() ) {
Reference< XMultiComponentFactory > xServiceManager(
xContext->getServiceManager() );
if ( !xServiceManager.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't get ServiceManager"));
throw RuntimeException( msg, Reference< XInterface >());
}
Sequence<Any> seqArgs(registries.size());
std::vector< OUString >::const_iterator iter = registries.begin();
int i = 0;
while ( iter != registries.end() )
{
Reference< XSimpleRegistry > xReg(
xServiceManager->createInstanceWithContext(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.registry.SimpleRegistry")),
xContext), UNO_QUERY);
xReg->open(convertToFileUrl(
OUStringToOString(*iter, RTL_TEXTENCODING_UTF8)),
sal_True, sal_False);
seqArgs[i++] = makeAny(xReg);
iter++;
}
Reference< XHierarchicalNameAccess > xTDProvider(
xServiceManager->createInstanceWithArgumentsAndContext(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.reflection.TypeDescriptionProvider")),
seqArgs, xContext),
UNO_QUERY);
if ( !xTDProvider.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't create local"
" type description provider"));
throw RuntimeException( msg, Reference< XInterface >());
}
a = makeAny(xTDProvider);
Reference< XSet > xSet(m_pImpl->m_tdmgr, UNO_QUERY);
xSet->insert(a);
}
return sal_True;
}
sal_Bool UnoTypeManager::isValidType(const ::rtl::OString& name) const
{
return m_pImpl->m_tdmgr->hasByHierarchicalName(
OStringToOUString(name, RTL_TEXTENCODING_UTF8));
}
OString UnoTypeManager::getTypeName(RegistryKey& rTypeKey) const
{
OString typeName = OUStringToOString(rTypeKey.getName(), RTL_TEXTENCODING_UTF8);
static OString sBase("/UCR");
if (typeName.indexOf(sBase) == 0) {
typeName = typeName.copy(typeName.indexOf('/', 1) + 1);
} else {
typeName = typeName.copy(1);
}
return typeName;
}
// extern
void* getTypeBlob(Reference< XHierarchicalNameAccess > xTDmgr,
const OString& typeName, sal_uInt32* pBlob);
typereg::Reader UnoTypeManager::getTypeReader(
const OString& name, sal_Bool * /*pIsExtraType*/ ) const
{
typereg::Reader reader;
void* pBlob = NULL;
sal_uInt32 blobsize = 0;
if ( (pBlob = getTypeBlob(m_pImpl->m_tdmgr, name, &blobsize)) != NULL )
reader = typereg::Reader(pBlob, blobsize, sal_True, TYPEREG_VERSION_1);
if ( pBlob )
rtl_freeMemory(pBlob);
return reader;
}
typereg::Reader UnoTypeManager::getTypeReader(RegistryKey& rTypeKey) const
{
typereg::Reader reader;
if (rTypeKey.isValid()) {
RegValueType valueType;
sal_uInt32 valueSize;
if (!rTypeKey.getValueInfo(OUString(), &valueType, &valueSize)) {
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if ( !rTypeKey.getValue(OUString(), pBuffer) ) {
reader = typereg::Reader(
pBuffer, valueSize, true, TYPEREG_VERSION_1);
}
rtl_freeMemory(pBuffer);
}
}
return reader;
}
RTTypeClass UnoTypeManager::getTypeClass(const OString& name) const
{
if ( m_pImpl->m_t2TypeClass.count(name) > 0 ) {
return m_pImpl->m_t2TypeClass[name];
} else {
Reference< XTypeDescription > xTD;
Any a = m_pImpl->m_tdmgr->getByHierarchicalName(
OStringToOUString(name, RTL_TEXTENCODING_UTF8));
a >>= xTD;
if ( xTD.is() ) {
RTTypeClass tc = mapTypeClass(xTD->getTypeClass());
if (tc != RT_TYPE_INVALID)
m_pImpl->m_t2TypeClass[name] = tc;
return tc;
}
}
return RT_TYPE_INVALID;
}
RTTypeClass UnoTypeManager::getTypeClass(RegistryKey& rTypeKey) const
{
OString name = getTypeName(rTypeKey);
if ( m_pImpl->m_t2TypeClass.count(name) > 0 ) {
return m_pImpl->m_t2TypeClass[name];
} else {
if ( rTypeKey.isValid() ) {
RegValueType valueType;
sal_uInt32 valueSize;
if ( !rTypeKey.getValueInfo(OUString(), &valueType, &valueSize) ) {
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if ( !rTypeKey.getValue(OUString(), pBuffer) ) {
typereg::Reader reader(
pBuffer, valueSize, false, TYPEREG_VERSION_1);
RTTypeClass ret = reader.getTypeClass();
rtl_freeMemory(pBuffer);
m_pImpl->m_t2TypeClass[name] = ret;
return ret;
}
rtl_freeMemory(pBuffer);
}
}
}
return RT_TYPE_INVALID;
}
} // end of namespace unodevtools
<commit_msg>INTEGRATION: CWS changefileheader (1.7.10); FILE MERGED 2008/03/28 15:51:24 rt 1.7.10.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemanager.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "unodevtools/typemanager.hxx"
#include "rtl/alloc.h"
#include "registry/reader.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "com/sun/star/container/XSet.hpp"
#include "com/sun/star/reflection/XTypeDescription.hpp"
#include "com/sun/star/registry/XSimpleRegistry.hpp"
#include "com/sun/star/uno/XComponentContext.hpp"
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::reflection;
namespace unodevtools {
static RTTypeClass mapTypeClass(TypeClass typeclass) {
switch(typeclass) {
case TypeClass_ENUM:
return RT_TYPE_ENUM;
case TypeClass_TYPEDEF:
return RT_TYPE_TYPEDEF;
case TypeClass_STRUCT:
return RT_TYPE_STRUCT;
case TypeClass_UNION:
return RT_TYPE_UNION;
case TypeClass_EXCEPTION:
return RT_TYPE_EXCEPTION;
case TypeClass_INTERFACE:
return RT_TYPE_INTERFACE;
case TypeClass_SERVICE:
return RT_TYPE_SERVICE;
case TypeClass_MODULE:
return RT_TYPE_MODULE;
case TypeClass_CONSTANTS:
return RT_TYPE_CONSTANTS;
case TypeClass_SINGLETON:
return RT_TYPE_SINGLETON;
default:
break;
}
return RT_TYPE_INVALID;
}
UnoTypeManager::UnoTypeManager()
{
m_pImpl = new UnoTypeManagerImpl();
acquire();
}
UnoTypeManager::~UnoTypeManager()
{
release();
}
void UnoTypeManager::release()
{
if (0 == TypeManager::release())
delete m_pImpl;
}
sal_Bool UnoTypeManager::init(
const ::std::vector< ::rtl::OUString > registries)
{
Reference< XComponentContext > xContext=
defaultBootstrap_InitialComponentContext();
if ( !xContext.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't create initial UNO component context"));
throw RuntimeException( msg, Reference< XInterface >());
}
Any a = xContext->getValueByName(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"/singletons/com.sun.star.reflection.theTypeDescriptionManager")));
a >>= m_pImpl->m_tdmgr;
if ( !m_pImpl->m_tdmgr.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't get TypeDescriptionManager"));
throw RuntimeException( msg, Reference< XInterface >());
}
if ( !registries.empty() ) {
Reference< XMultiComponentFactory > xServiceManager(
xContext->getServiceManager() );
if ( !xServiceManager.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't get ServiceManager"));
throw RuntimeException( msg, Reference< XInterface >());
}
Sequence<Any> seqArgs(registries.size());
std::vector< OUString >::const_iterator iter = registries.begin();
int i = 0;
while ( iter != registries.end() )
{
Reference< XSimpleRegistry > xReg(
xServiceManager->createInstanceWithContext(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.registry.SimpleRegistry")),
xContext), UNO_QUERY);
xReg->open(convertToFileUrl(
OUStringToOString(*iter, RTL_TEXTENCODING_UTF8)),
sal_True, sal_False);
seqArgs[i++] = makeAny(xReg);
iter++;
}
Reference< XHierarchicalNameAccess > xTDProvider(
xServiceManager->createInstanceWithArgumentsAndContext(
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.reflection.TypeDescriptionProvider")),
seqArgs, xContext),
UNO_QUERY);
if ( !xTDProvider.is() ) {
OUString msg(RTL_CONSTASCII_USTRINGPARAM(
"internal UNO problem, can't create local"
" type description provider"));
throw RuntimeException( msg, Reference< XInterface >());
}
a = makeAny(xTDProvider);
Reference< XSet > xSet(m_pImpl->m_tdmgr, UNO_QUERY);
xSet->insert(a);
}
return sal_True;
}
sal_Bool UnoTypeManager::isValidType(const ::rtl::OString& name) const
{
return m_pImpl->m_tdmgr->hasByHierarchicalName(
OStringToOUString(name, RTL_TEXTENCODING_UTF8));
}
OString UnoTypeManager::getTypeName(RegistryKey& rTypeKey) const
{
OString typeName = OUStringToOString(rTypeKey.getName(), RTL_TEXTENCODING_UTF8);
static OString sBase("/UCR");
if (typeName.indexOf(sBase) == 0) {
typeName = typeName.copy(typeName.indexOf('/', 1) + 1);
} else {
typeName = typeName.copy(1);
}
return typeName;
}
// extern
void* getTypeBlob(Reference< XHierarchicalNameAccess > xTDmgr,
const OString& typeName, sal_uInt32* pBlob);
typereg::Reader UnoTypeManager::getTypeReader(
const OString& name, sal_Bool * /*pIsExtraType*/ ) const
{
typereg::Reader reader;
void* pBlob = NULL;
sal_uInt32 blobsize = 0;
if ( (pBlob = getTypeBlob(m_pImpl->m_tdmgr, name, &blobsize)) != NULL )
reader = typereg::Reader(pBlob, blobsize, sal_True, TYPEREG_VERSION_1);
if ( pBlob )
rtl_freeMemory(pBlob);
return reader;
}
typereg::Reader UnoTypeManager::getTypeReader(RegistryKey& rTypeKey) const
{
typereg::Reader reader;
if (rTypeKey.isValid()) {
RegValueType valueType;
sal_uInt32 valueSize;
if (!rTypeKey.getValueInfo(OUString(), &valueType, &valueSize)) {
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if ( !rTypeKey.getValue(OUString(), pBuffer) ) {
reader = typereg::Reader(
pBuffer, valueSize, true, TYPEREG_VERSION_1);
}
rtl_freeMemory(pBuffer);
}
}
return reader;
}
RTTypeClass UnoTypeManager::getTypeClass(const OString& name) const
{
if ( m_pImpl->m_t2TypeClass.count(name) > 0 ) {
return m_pImpl->m_t2TypeClass[name];
} else {
Reference< XTypeDescription > xTD;
Any a = m_pImpl->m_tdmgr->getByHierarchicalName(
OStringToOUString(name, RTL_TEXTENCODING_UTF8));
a >>= xTD;
if ( xTD.is() ) {
RTTypeClass tc = mapTypeClass(xTD->getTypeClass());
if (tc != RT_TYPE_INVALID)
m_pImpl->m_t2TypeClass[name] = tc;
return tc;
}
}
return RT_TYPE_INVALID;
}
RTTypeClass UnoTypeManager::getTypeClass(RegistryKey& rTypeKey) const
{
OString name = getTypeName(rTypeKey);
if ( m_pImpl->m_t2TypeClass.count(name) > 0 ) {
return m_pImpl->m_t2TypeClass[name];
} else {
if ( rTypeKey.isValid() ) {
RegValueType valueType;
sal_uInt32 valueSize;
if ( !rTypeKey.getValueInfo(OUString(), &valueType, &valueSize) ) {
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if ( !rTypeKey.getValue(OUString(), pBuffer) ) {
typereg::Reader reader(
pBuffer, valueSize, false, TYPEREG_VERSION_1);
RTTypeClass ret = reader.getTypeClass();
rtl_freeMemory(pBuffer);
m_pImpl->m_t2TypeClass[name] = ret;
return ret;
}
rtl_freeMemory(pBuffer);
}
}
}
return RT_TYPE_INVALID;
}
} // end of namespace unodevtools
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_resource.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 09:42:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "cppuhelper/implbase1.hxx"
#include "unotools/configmgr.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace dp_misc {
namespace {
struct OfficeLocale :
public rtl::StaticWithInit<const lang::Locale, OfficeLocale> {
const lang::Locale operator () () {
OUString slang;
if (! (::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::LOCALE ) >>= slang))
throw RuntimeException( OUSTR("Cannot determine language!"), 0 );
return toLocale(slang);
}
};
void dummy() {}
struct DeploymentResMgr : public rtl::StaticWithInit<
ResMgr *, DeploymentResMgr> {
ResMgr * operator () () {
return ResMgr::CreateResMgr( "deployment" LIBRARY_SOLARUPD(),
OfficeLocale::get() );
}
};
osl::Mutex s_mutex;
} // anon namespace
//==============================================================================
ResId getResId( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
return ResId( id, DeploymentResMgr::get() );
}
//==============================================================================
String getResourceString( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
String ret( ResId( id, DeploymentResMgr::get() ) );
if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
static String s_brandName;
if (s_brandName.Len() == 0) {
OUString brandName(
::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::PRODUCTNAME ).get<OUString>() );
s_brandName = brandName;
}
ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
}
return ret;
}
//throws an Exception on failure
//primary subtag 2 or three letters(A-Z, a-z), i or x
void checkPrimarySubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 3)
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 1
&& (arLang[0] != 'i' && arLang[0] != 'x'))
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 2 || len == 3)
{
for (sal_Int32 i = 0; i < len; i++)
{
if ( !((arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
//throws an Exception on failure
//second subtag 2 letter country code or 3-8 letter other code(A-Z, a-z, 0-9)
void checkSecondSubtag(::rtl::OUString const & tag, bool & bIsCountry)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 2 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
//country code
bIsCountry = false;
if (len == 2)
{
for (sal_Int32 i = 0; i < 2; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
bIsCountry = true;
}
if (len > 2)
{
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
void checkThirdSubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
//=============================================================================
//We parse the string acording to RFC 3066
//We only use the primary sub-tag and two subtags. That is lang-country-variant
//We do some simple tests if the string is correct. Actually this should do a
//validating parser
//We may have the case that there is no country tag, for example en-welsh
::com::sun::star::lang::Locale toLocale( ::rtl::OUString const & slang )
{
OUString _sLang = slang.trim();
::com::sun::star::lang::Locale locale;
sal_Int32 nIndex = 0;
OUString lang = _sLang.getToken( 0, '-', nIndex );
checkPrimarySubtag(lang);
locale.Language = lang;
OUString country = _sLang.getToken( 0, '-', nIndex );
if (country.getLength() > 0)
{
bool bIsCountry = false;
checkSecondSubtag(country, bIsCountry);
if (bIsCountry)
{
locale.Country = country;
}
else
{
locale.Variant = country;
}
}
if (locale.Variant.getLength() == 0)
{
OUString variant = _sLang.getToken( 0, '-', nIndex );
if (variant.getLength() > 0)
{
checkThirdSubtag(variant);
locale.Variant = variant;
}
}
return locale;
}
//==============================================================================
lang::Locale const & getOfficeLocale()
{
return OfficeLocale::get();
}
}
<commit_msg>INTEGRATION: CWS jl47_SRC680 (1.12.84.1.6); FILE MERGED 2006/09/20 11:48:32 jl 1.12.84.1.6.1: #i69642# added default language in case there is no user installation<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_resource.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: vg $ $Date: 2006-09-26 14:21:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustring.h"
#include "cppuhelper/implbase1.hxx"
#include "unotools/configmgr.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace dp_misc {
namespace {
struct OfficeLocale :
public rtl::StaticWithInit<const lang::Locale, OfficeLocale> {
const lang::Locale operator () () {
OUString slang;
if (! (::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::LOCALE ) >>= slang))
throw RuntimeException( OUSTR("Cannot determine language!"), 0 );
//fallback, the locale is currently only set when the user starts the
//office for the first time.
if (slang.getLength() == 0)
slang = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en-US"));
return toLocale(slang);
}
};
void dummy() {}
struct DeploymentResMgr : public rtl::StaticWithInit<
ResMgr *, DeploymentResMgr> {
ResMgr * operator () () {
return ResMgr::CreateResMgr( "deployment" LIBRARY_SOLARUPD(),
OfficeLocale::get() );
}
};
osl::Mutex s_mutex;
} // anon namespace
//==============================================================================
ResId getResId( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
return ResId( id, DeploymentResMgr::get() );
}
//==============================================================================
String getResourceString( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
String ret( ResId( id, DeploymentResMgr::get() ) );
if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
static String s_brandName;
if (s_brandName.Len() == 0) {
OUString brandName(
::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::PRODUCTNAME ).get<OUString>() );
s_brandName = brandName;
}
ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
}
return ret;
}
//throws an Exception on failure
//primary subtag 2 or three letters(A-Z, a-z), i or x
void checkPrimarySubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 3)
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 1
&& (arLang[0] != 'i' && arLang[0] != 'x'))
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 2 || len == 3)
{
for (sal_Int32 i = 0; i < len; i++)
{
if ( !((arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
//throws an Exception on failure
//second subtag 2 letter country code or 3-8 letter other code(A-Z, a-z, 0-9)
void checkSecondSubtag(::rtl::OUString const & tag, bool & bIsCountry)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 2 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
//country code
bIsCountry = false;
if (len == 2)
{
for (sal_Int32 i = 0; i < 2; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
bIsCountry = true;
}
if (len > 2)
{
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
void checkThirdSubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
//=============================================================================
//We parse the string acording to RFC 3066
//We only use the primary sub-tag and two subtags. That is lang-country-variant
//We do some simple tests if the string is correct. Actually this should do a
//validating parser
//We may have the case that there is no country tag, for example en-welsh
::com::sun::star::lang::Locale toLocale( ::rtl::OUString const & slang )
{
OUString _sLang = slang.trim();
::com::sun::star::lang::Locale locale;
sal_Int32 nIndex = 0;
OUString lang = _sLang.getToken( 0, '-', nIndex );
checkPrimarySubtag(lang);
locale.Language = lang;
OUString country = _sLang.getToken( 0, '-', nIndex );
if (country.getLength() > 0)
{
bool bIsCountry = false;
checkSecondSubtag(country, bIsCountry);
if (bIsCountry)
{
locale.Country = country;
}
else
{
locale.Variant = country;
}
}
if (locale.Variant.getLength() == 0)
{
OUString variant = _sLang.getToken( 0, '-', nIndex );
if (variant.getLength() > 0)
{
checkThirdSubtag(variant);
locale.Variant = variant;
}
}
return locale;
}
//==============================================================================
lang::Locale const & getOfficeLocale()
{
return OfficeLocale::get();
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2007 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::Envelope;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
std::string table_from_sql(std::string const& sql)
{
std::string table_name = boost::algorithm::to_lower_copy(sql);
boost::algorithm::replace_all(table_name,"\n"," ");
std::string::size_type idx = table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
if (idx != std::string::npos)
{
table_name=table_name.substr(idx);
}
idx=table_name.find_first_of(" ),");
if (idx != std::string::npos)
{
table_name = table_name.substr(0,idx);
}
}
return table_name;
}
sqlite_datasource::sqlite_datasource(parameters const& params)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params.get<std::string>("table","")),
metadata_(*params.get<std::string>("metadata","")),
geometry_field_(*params.get<std::string>("geometry_field","the_geom")),
key_field_(*params.get<std::string>("key_field","OGC_FID")),
row_offset_(*params_.get<int>("row_offset",0)),
row_limit_(*params_.get<int>("row_limit",0)),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")),
format_(mapnik::wkbGeneric)
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> paramater");
boost::optional<std::string> wkb = params.get<std::string>("wkb_format");
if (wkb)
{
if (*wkb == "spatialite")
format_ = mapnik::wkbSpatiaLite;
}
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
dataset_ = new sqlite_connection (*file);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext)
{
boost::char_separator<char> sep(",");
boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);
unsigned i = 0;
bool success = false;
double d[4];
for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();++beg)
{
try
{
d[i] = boost::lexical_cast<double>(*beg);
}
catch (boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
break;
}
if (i==3)
{
success = true;
break;
}
++i;
}
if (success)
{
extent_.init(d[0],d[1],d[2],d[3]);
extent_initialized_ = true;
}
}
std::string table_name = table_from_sql(table_);
if (metadata_ != "" && ! extent_initialized_)
{
std::ostringstream s;
s << "select xmin, ymin, xmax, ymax from " << metadata_;
s << " where lower(f_table_name) = lower('" << table_name << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "select count (*) from sqlite_master";
s << " where lower(name) = lower('idx_" << table_name << "_" << geometry_field_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
use_spatial_index_ = rs->column_integer (0) == 1;
}
#ifdef MAPNIK_DEBUG
if (! use_spatial_index_)
clog << "cannot use the spatial index " << endl;
#endif
}
{
/*
XXX - This is problematic, if we don't have at least a row,
we cannot determine the right columns types and names
as all column_type are SQLITE_NULL
*/
std::ostringstream s;
s << "select * from " << table_ << " limit 0";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
sqlite_datasource::~sqlite_datasource()
{
delete dataset_;
}
std::string const sqlite_datasource::name_="sqlite";
std::string sqlite_datasource::name()
{
return name_;
}
int sqlite_datasource::type() const
{
return type_;
}
Envelope<double> sqlite_datasource::envelope() const
{
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (dataset_)
{
mapnik::Envelope<double> const& e = q.get_bbox();
std::ostringstream s;
s << "select " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << "," << *pos << "";
++pos;
}
s << " from ";
std::string query (table_);
if (use_spatial_index_)
{
std::string table_name = table_from_sql(query);
std::ostringstream spatial_sql;
spatial_sql << std::setprecision(16);
spatial_sql << " where rowid in (select pkid from idx_" << table_name << "_" << geometry_field_;
spatial_sql << " where xmax>=" << e.minx() << " and xmin<=" << e.maxx() ;
spatial_sql << " and ymax>=" << e.miny() << " and ymin<=" << e.maxy() << ")";
if (boost::algorithm::ifind_first(query,"where"))
{
boost::algorithm::ireplace_first(query, "where", spatial_sql.str() + " and");
}
else if (boost::algorithm::find_first(query,table_name))
{
boost::algorithm::ireplace_first(query, table_name , table_name + " " + spatial_sql.str());
}
}
s << query ;
if (row_limit_ > 0) {
s << " limit " << row_limit_;
}
if (row_offset_ > 0) {
s << " offset " << row_offset_;
}
#ifdef MAPNIK_DEBUG
std::cerr << s.str() << "\n";
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
#if 0
if (dataset_ && layer_)
{
OGRPoint point;
point.setX (pt.x);
point.setY (pt.y);
layer_->SetSpatialFilter (&point);
return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_));
}
#endif
return featureset_ptr();
}
<commit_msg>+ revert to "limit 1" logic + discard everything after table name when building table descriptor to avoid seq scan<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2007 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::Envelope;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
std::string table_from_sql(std::string const& sql)
{
std::string table_name = boost::algorithm::to_lower_copy(sql);
boost::algorithm::replace_all(table_name,"\n"," ");
std::string::size_type idx = table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
if (idx != std::string::npos)
{
table_name=table_name.substr(idx);
}
idx=table_name.find_first_of(" ),");
if (idx != std::string::npos)
{
table_name = table_name.substr(0,idx);
}
}
return table_name;
}
sqlite_datasource::sqlite_datasource(parameters const& params)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params.get<std::string>("table","")),
metadata_(*params.get<std::string>("metadata","")),
geometry_field_(*params.get<std::string>("geometry_field","the_geom")),
key_field_(*params.get<std::string>("key_field","OGC_FID")),
row_offset_(*params_.get<int>("row_offset",0)),
row_limit_(*params_.get<int>("row_limit",0)),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")),
format_(mapnik::wkbGeneric)
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> paramater");
boost::optional<std::string> wkb = params.get<std::string>("wkb_format");
if (wkb)
{
if (*wkb == "spatialite")
format_ = mapnik::wkbSpatiaLite;
}
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
dataset_ = new sqlite_connection (*file);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext)
{
boost::char_separator<char> sep(",");
boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);
unsigned i = 0;
bool success = false;
double d[4];
for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();++beg)
{
try
{
d[i] = boost::lexical_cast<double>(*beg);
}
catch (boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
break;
}
if (i==3)
{
success = true;
break;
}
++i;
}
if (success)
{
extent_.init(d[0],d[1],d[2],d[3]);
extent_initialized_ = true;
}
}
std::string table_name = table_from_sql(table_);
if (metadata_ != "" && ! extent_initialized_)
{
std::ostringstream s;
s << "select xmin, ymin, xmax, ymax from " << metadata_;
s << " where lower(f_table_name) = lower('" << table_name << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "select count (*) from sqlite_master";
s << " where lower(name) = lower('idx_" << table_name << "_" << geometry_field_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
use_spatial_index_ = rs->column_integer (0) == 1;
}
#ifdef MAPNIK_DEBUG
if (! use_spatial_index_)
clog << "cannot use the spatial index " << endl;
#endif
}
{
/*
XXX - This is problematic, if we don't have at least a row,
we cannot determine the right columns types and names
as all column_type are SQLITE_NULL
*/
std::string::size_type idx = table_.find(table_name);
std::ostringstream s;
s << "select * from (" << table_.substr(0,idx + table_name.length()) << ") limit 1";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
sqlite_datasource::~sqlite_datasource()
{
delete dataset_;
}
std::string const sqlite_datasource::name_="sqlite";
std::string sqlite_datasource::name()
{
return name_;
}
int sqlite_datasource::type() const
{
return type_;
}
Envelope<double> sqlite_datasource::envelope() const
{
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (dataset_)
{
mapnik::Envelope<double> const& e = q.get_bbox();
std::ostringstream s;
s << "select " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << "," << *pos << "";
++pos;
}
s << " from ";
std::string query (table_);
if (use_spatial_index_)
{
std::string table_name = table_from_sql(query);
std::ostringstream spatial_sql;
spatial_sql << std::setprecision(16);
spatial_sql << " where rowid in (select pkid from idx_" << table_name << "_" << geometry_field_;
spatial_sql << " where xmax>=" << e.minx() << " and xmin<=" << e.maxx() ;
spatial_sql << " and ymax>=" << e.miny() << " and ymin<=" << e.maxy() << ")";
if (boost::algorithm::ifind_first(query,"where"))
{
boost::algorithm::ireplace_first(query, "where", spatial_sql.str() + " and");
}
else if (boost::algorithm::find_first(query,table_name))
{
boost::algorithm::ireplace_first(query, table_name , table_name + " " + spatial_sql.str());
}
}
s << query ;
if (row_limit_ > 0) {
s << " limit " << row_limit_;
}
if (row_offset_ > 0) {
s << " offset " << row_offset_;
}
#ifdef MAPNIK_DEBUG
std::cerr << s.str() << "\n";
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
#if 0
if (dataset_ && layer_)
{
OGRPoint point;
point.setX (pt.x);
point.setY (pt.y);
layer_->SetSpatialFilter (&point);
return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_));
}
#endif
return featureset_ptr();
}
<|endoftext|> |
<commit_before><commit_msg>Fix MC 2<commit_after><|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "forkcallcontext.hh"
#include "common.hh"
#include <algorithm>
#include <sofia-sip/sip_status.h>
using namespace ::std;
ForkCallContext::ForkCallContext(Agent *agent, const std::shared_ptr<RequestSipEvent> &event, shared_ptr<ForkContextConfig> cfg, ForkContextListener* listener) :
ForkContext(agent, event,cfg, listener), mFinal(0),mCancelled(false) {
LOGD("New ForkCallContext %p", this);
}
ForkCallContext::~ForkCallContext() {
LOGD("Destroy ForkCallContext %p", this);
}
void ForkCallContext::cancel() {
mCancelled=true;
cancelOthers();
}
void ForkCallContext::forward(const shared_ptr<SipEvent> &ev, bool force) {
sip_t *sip = ev->getMsgSip()->getSip();
bool fakeSipEvent = (mFinal > 0 && !force) || mIncoming == NULL;
if (mCfg->mForkOneResponse) { // TODO: respect RFC 3261 16.7.5
if (sip->sip_status->st_status == 183 || sip->sip_status->st_status == 180) {
auto it = find(mForwardResponses.begin(), mForwardResponses.end(), sip->sip_status->st_status);
if (it != mForwardResponses.end()) {
fakeSipEvent = true;
} else {
mForwardResponses.push_back(sip->sip_status->st_status);
}
}
}
if (fakeSipEvent) {
ev->setIncomingAgent(shared_ptr<IncomingAgent>());
}
if (sip->sip_status->st_status >= 200 && sip->sip_status->st_status < 700) {
++mFinal;
}
}
void ForkCallContext::decline(const shared_ptr<OutgoingTransaction> &transaction, shared_ptr<ResponseSipEvent> &ev) {
if (!mCfg->mForkNoGlobalDecline) {
cancelOthers(transaction);
forward(ev);
} else {
if (mOutgoings.size() != 1) {
ev->setIncomingAgent(shared_ptr<IncomingAgent>());
} else {
forward(ev);
}
}
}
void ForkCallContext::cancelOthers(const shared_ptr<OutgoingTransaction> &transaction) {
if (mFinal == 0) {
for (list<shared_ptr<OutgoingTransaction>>::iterator it = mOutgoings.begin(); it != mOutgoings.end();) {
if (*it != transaction) {
shared_ptr<OutgoingTransaction> tr = (*it);
it = mOutgoings.erase(it);
tr->cancel();
} else {
++it;
}
}
}
}
void ForkCallContext::onRequest(const shared_ptr<IncomingTransaction> &transaction, shared_ptr<RequestSipEvent> &event) {
event->setOutgoingAgent(shared_ptr<OutgoingAgent>());
const shared_ptr<MsgSip> &ms = event->getMsgSip();
sip_t *sip = ms->getSip();
if (sip != NULL && sip->sip_request != NULL) {
if (sip->sip_request->rq_method == sip_method_cancel) {
LOGD("Fork: incomingCallback cancel");
cancel();
}
}
}
void ForkCallContext::store(shared_ptr<ResponseSipEvent> &event) {
bool best = true;
if (mBestResponse != NULL) {
if (mBestResponse->getMsgSip()->getSip()->sip_status->st_status < event->getMsgSip()->getSip()->sip_status->st_status) {
best = false;
}
}
// Save
if (best) {
mBestResponse = make_shared<ResponseSipEvent>(event); // Copy event
mBestResponse->suspendProcessing();
}
// Don't forward
event->setIncomingAgent(shared_ptr<IncomingAgent>());
}
void ForkCallContext::onResponse(const shared_ptr<OutgoingTransaction> &transaction, shared_ptr<ResponseSipEvent> &event) {
event->setIncomingAgent(mIncoming);
const shared_ptr<MsgSip> &ms = event->getMsgSip();
sip_via_remove(ms->getMsg(), ms->getSip()); // remove via
sip_t *sip = ms->getSip();
if (sip != NULL && sip->sip_status != NULL) {
LOGD("Fork: outgoingCallback %d", sip->sip_status->st_status);
if (sip->sip_status->st_status > 100 && sip->sip_status->st_status < 200) {
forward(event);
return;
} else if (sip->sip_status->st_status >= 200 && sip->sip_status->st_status < 300) {
if (mCfg->mForkOneResponse) // TODO: respect RFC 3261 16.7.5
cancelOthers(transaction);
forward(event, true);
return;
} else if (sip->sip_status->st_status >= 600 && sip->sip_status->st_status < 700) {
decline(transaction, event);
return;
} else {
if (!mCancelled)
store(event);
else forward(event,true);
return;
}
}
LOGW("Outgoing transaction: ignore message");
}
void ForkCallContext::onNew(const shared_ptr<IncomingTransaction> &transaction) {
ForkContext::onNew(transaction);
}
void ForkCallContext::onDestroy(const shared_ptr<IncomingTransaction> &transaction) {
return ForkContext::onDestroy(transaction);
}
void ForkCallContext::onNew(const shared_ptr<OutgoingTransaction> &transaction) {
ForkContext::onNew(transaction);
}
void ForkCallContext::checkFinished(){
if (mOutgoings.size() == 0 && (mLateTimerExpired || mLateTimer==NULL)) {
if (mIncoming != NULL && mFinal == 0) {
if (mBestResponse == NULL) {
// Create response
shared_ptr<MsgSip> msgsip(mIncoming->createResponse(SIP_408_REQUEST_TIMEOUT));
shared_ptr<ResponseSipEvent> ev(new ResponseSipEvent(dynamic_pointer_cast<OutgoingAgent>(mAgent->shared_from_this()), msgsip));
ev->setIncomingAgent(mIncoming);
mAgent->sendResponseEvent(ev);
} else {
mAgent->injectResponseEvent(mBestResponse); // Reply
}
++mFinal;
}
mBestResponse.reset();
mIncoming.reset();
mListener->onForkContextFinished(shared_from_this());
}
}
void ForkCallContext::onDestroy(const shared_ptr<OutgoingTransaction> &transaction) {
ForkContext::onDestroy(transaction);
}
bool ForkCallContext::hasFinalResponse(){
return mFinal>0 || mCancelled;
}
<commit_msg>After cancel, don't send 408 in Fork call context finished.<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "forkcallcontext.hh"
#include "common.hh"
#include <algorithm>
#include <sofia-sip/sip_status.h>
using namespace ::std;
ForkCallContext::ForkCallContext(Agent *agent, const std::shared_ptr<RequestSipEvent> &event, shared_ptr<ForkContextConfig> cfg, ForkContextListener* listener) :
ForkContext(agent, event,cfg, listener), mFinal(0),mCancelled(false) {
LOGD("New ForkCallContext %p", this);
}
ForkCallContext::~ForkCallContext() {
LOGD("Destroy ForkCallContext %p", this);
}
void ForkCallContext::cancel() {
mCancelled=true;
cancelOthers();
}
void ForkCallContext::forward(const shared_ptr<SipEvent> &ev, bool force) {
sip_t *sip = ev->getMsgSip()->getSip();
bool fakeSipEvent = (mFinal > 0 && !force) || mIncoming == NULL;
if (mCfg->mForkOneResponse) { // TODO: respect RFC 3261 16.7.5
if (sip->sip_status->st_status == 183 || sip->sip_status->st_status == 180) {
auto it = find(mForwardResponses.begin(), mForwardResponses.end(), sip->sip_status->st_status);
if (it != mForwardResponses.end()) {
fakeSipEvent = true;
} else {
mForwardResponses.push_back(sip->sip_status->st_status);
}
}
}
if (fakeSipEvent) {
ev->setIncomingAgent(shared_ptr<IncomingAgent>());
}
if (sip->sip_status->st_status >= 200 && sip->sip_status->st_status < 700) {
++mFinal;
}
}
void ForkCallContext::decline(const shared_ptr<OutgoingTransaction> &transaction, shared_ptr<ResponseSipEvent> &ev) {
if (!mCfg->mForkNoGlobalDecline) {
cancelOthers(transaction);
forward(ev);
} else {
if (mOutgoings.size() != 1) {
ev->setIncomingAgent(shared_ptr<IncomingAgent>());
} else {
forward(ev);
}
}
}
void ForkCallContext::cancelOthers(const shared_ptr<OutgoingTransaction> &transaction) {
if (mFinal == 0) {
for (list<shared_ptr<OutgoingTransaction>>::iterator it = mOutgoings.begin(); it != mOutgoings.end();) {
if (*it != transaction) {
shared_ptr<OutgoingTransaction> tr = (*it);
it = mOutgoings.erase(it);
tr->cancel();
} else {
++it;
}
}
}
}
void ForkCallContext::onRequest(const shared_ptr<IncomingTransaction> &transaction, shared_ptr<RequestSipEvent> &event) {
event->setOutgoingAgent(shared_ptr<OutgoingAgent>());
const shared_ptr<MsgSip> &ms = event->getMsgSip();
sip_t *sip = ms->getSip();
if (sip != NULL && sip->sip_request != NULL) {
if (sip->sip_request->rq_method == sip_method_cancel) {
LOGD("Fork: incomingCallback cancel");
cancel();
}
}
}
void ForkCallContext::store(shared_ptr<ResponseSipEvent> &event) {
bool best = true;
if (mBestResponse != NULL) {
if (mBestResponse->getMsgSip()->getSip()->sip_status->st_status < event->getMsgSip()->getSip()->sip_status->st_status) {
best = false;
}
}
// Save
if (best) {
mBestResponse = make_shared<ResponseSipEvent>(event); // Copy event
mBestResponse->suspendProcessing();
}
// Don't forward
event->setIncomingAgent(shared_ptr<IncomingAgent>());
}
void ForkCallContext::onResponse(const shared_ptr<OutgoingTransaction> &transaction, shared_ptr<ResponseSipEvent> &event) {
event->setIncomingAgent(mIncoming);
const shared_ptr<MsgSip> &ms = event->getMsgSip();
sip_via_remove(ms->getMsg(), ms->getSip()); // remove via
sip_t *sip = ms->getSip();
if (sip != NULL && sip->sip_status != NULL) {
LOGD("Fork: outgoingCallback %d", sip->sip_status->st_status);
if (sip->sip_status->st_status > 100 && sip->sip_status->st_status < 200) {
forward(event);
return;
} else if (sip->sip_status->st_status >= 200 && sip->sip_status->st_status < 300) {
if (mCfg->mForkOneResponse) // TODO: respect RFC 3261 16.7.5
cancelOthers(transaction);
forward(event, true);
return;
} else if (sip->sip_status->st_status >= 600 && sip->sip_status->st_status < 700) {
decline(transaction, event);
return;
} else {
if (!mCancelled)
store(event);
else forward(event,true);
return;
}
}
LOGW("Outgoing transaction: ignore message");
}
void ForkCallContext::onNew(const shared_ptr<IncomingTransaction> &transaction) {
ForkContext::onNew(transaction);
}
void ForkCallContext::onDestroy(const shared_ptr<IncomingTransaction> &transaction) {
return ForkContext::onDestroy(transaction);
}
void ForkCallContext::onNew(const shared_ptr<OutgoingTransaction> &transaction) {
ForkContext::onNew(transaction);
}
void ForkCallContext::checkFinished(){
if (mOutgoings.size() == 0 && (mLateTimerExpired || mLateTimer==NULL)) {
if (mIncoming != NULL && !hasFinalResponse()) {
if (mBestResponse == NULL) {
// Create response
shared_ptr<MsgSip> msgsip(mIncoming->createResponse(SIP_408_REQUEST_TIMEOUT));
shared_ptr<ResponseSipEvent> ev(new ResponseSipEvent(dynamic_pointer_cast<OutgoingAgent>(mAgent->shared_from_this()), msgsip));
ev->setIncomingAgent(mIncoming);
mAgent->sendResponseEvent(ev);
} else {
mAgent->injectResponseEvent(mBestResponse); // Reply
}
++mFinal;
}
mBestResponse.reset();
mIncoming.reset();
mListener->onForkContextFinished(shared_from_this());
}
}
void ForkCallContext::onDestroy(const shared_ptr<OutgoingTransaction> &transaction) {
ForkContext::onDestroy(transaction);
}
bool ForkCallContext::hasFinalResponse(){
return mFinal>0 || mCancelled;
}
<|endoftext|> |
<commit_before>// Time: O(n^2)
// Space: O(n)
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* class Master {
* public:
* int guess(string word);
* };
*/
class Solution {
public:
void findSecretWord(vector<string>& wordlist, Master& master) {
vector<vector<int>> H(wordlist.size(), vector<int>(wordlist.size()));
for (int i = 0; i < wordlist.size(); ++i) {
for (int j = 0; j < wordlist.size(); ++j) {
H[i][j] = match(wordlist[i], wordlist[j]);
}
}
vector<int> possible(wordlist.size());
iota(possible.begin(), possible.end(), 0);
int n = 0;
while (!possible.empty() && n < 6) {
auto guess = solve(H, possible);
n = master.guess(wordlist[guess]);
vector<int> new_possible;
for (const auto& j : possible) {
if (H[guess][j] == n) {
new_possible.emplace_back(j);
}
}
possible = new_possible;
}
}
private:
int solve(const vector<vector<int>>& H,
const vector<int>& possible) {
vector<int> min_max_group = possible;
int best_guess = -1;
for (const auto& guess : possible) {
vector<vector<int>> groups(7);
for (const auto& j : possible) {
if (j != guess) {
groups[H[guess][j]].emplace_back(j);
}
}
int max_group_i = 0;
for (int i = 0; i < groups.size(); ++i) {
if (groups[i].size() > groups[max_group_i].size()) {
max_group_i = i;
}
}
if (groups[max_group_i].size() < min_max_group.size()) {
min_max_group = groups[max_group_i];
best_guess = guess;
}
}
return best_guess;
}
int match(const string& a, const string& b) {
int matches = 0;
for (int i = 0; i < a.length(); ++i) {
if (a[i] == b[i]) {
++matches;
}
}
return matches;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
void findSecretWord(vector<string>& wordlist, Master& master) {
for (int i = 0, n = 0; i < 10 && n < 6; ++i) {
unordered_map<string, int> count;
for (const auto& w1 : wordlist) {
for (const auto& w2 : wordlist) {
if (match(w1, w2) == 0) {
++count[w1];
}
}
}
string guess;
for (const auto& w : wordlist) {
if (guess.empty() ||
count[w] < count[guess]) {
guess = w;
}
}
n = master.guess(guess);
vector<string> new_wordlist;
for (const auto& w : wordlist) {
if (match(w, guess) == n) {
new_wordlist.emplace_back(w);
}
}
wordlist = new_wordlist;
}
}
private:
int match(const string& a, const string& b) {
int matches = 0;
for (int i = 0; i < a.length(); ++i) {
if (a[i] == b[i]) {
++matches;
}
}
return matches;
}
};
<commit_msg>Update guess-the-word.cpp<commit_after>// Time: O(n^2)
// Space: O(n)
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* class Master {
* public:
* int guess(string word);
* };
*/
class Solution {
public:
void findSecretWord(vector<string>& wordlist, Master& master) {
vector<vector<int>> H(wordlist.size(), vector<int>(wordlist.size()));
for (int i = 0; i < wordlist.size(); ++i) {
for (int j = 0; j < wordlist.size(); ++j) {
H[i][j] = match(wordlist[i], wordlist[j]);
}
}
vector<int> possible(wordlist.size());
iota(possible.begin(), possible.end(), 0);
int n = 0;
while (n < 6) {
auto guess = solve(H, possible);
n = master.guess(wordlist[guess]);
vector<int> new_possible;
for (const auto& j : possible) {
if (H[guess][j] == n) {
new_possible.emplace_back(j);
}
}
possible = new_possible;
}
}
private:
int solve(const vector<vector<int>>& H,
const vector<int>& possible) {
vector<int> min_max_group = possible;
int best_guess = -1;
for (const auto& guess : possible) {
vector<vector<int>> groups(7);
for (const auto& j : possible) {
if (j != guess) {
groups[H[guess][j]].emplace_back(j);
}
}
int max_group_i = 0;
for (int i = 0; i < groups.size(); ++i) {
if (groups[i].size() > groups[max_group_i].size()) {
max_group_i = i;
}
}
if (groups[max_group_i].size() < min_max_group.size()) {
min_max_group = groups[max_group_i];
best_guess = guess;
}
}
return best_guess;
}
int match(const string& a, const string& b) {
int matches = 0;
for (int i = 0; i < a.length(); ++i) {
if (a[i] == b[i]) {
++matches;
}
}
return matches;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
void findSecretWord(vector<string>& wordlist, Master& master) {
vector<vector<int>> H(wordlist.size(), vector<int>(wordlist.size()));
for (int i = 0; i < wordlist.size(); ++i) {
for (int j = 0; j < wordlist.size(); ++j) {
H[i][j] = match(wordlist[i], wordlist[j]);
}
}
vector<int> possible(wordlist.size());
iota(possible.begin(), possible.end(), 0);
int n = 0;
while (n < 6) {
auto guess = solve(H, possible);
n = master.guess(wordlist[guess]);
vector<int> new_possible;
for (const auto& j : possible) {
if (H[guess][j] == n) {
new_possible.emplace_back(j);
}
}
possible = new_possible;
}
}
private:
int solve(const vector<vector<int>>& H,
const vector<int>& possible) {
vector<int> min_max_group = possible;
int best_guess = -1;
for (const auto& guess : possible) {
vector<vector<int>> groups(7);
for (const auto& j : possible) {
if (j != guess) {
groups[H[guess][j]].emplace_back(j);
}
}
int max_group_i = 0;
if (groups[max_group_i].size() < min_max_group.size()) {
min_max_group = groups[max_group_i];
best_guess = guess;
}
}
return best_guess;
}
int match(const string& a, const string& b) {
int matches = 0;
for (int i = 0; i < a.length(); ++i) {
if (a[i] == b[i]) {
++matches;
}
}
return matches;
}
};
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkLocalAffineTransform_hxx
#define __itkLocalAffineTransform_hxx
#include "itkNumericTraits.h"
#include "vnl/algo/vnl_matrix_inverse.h"
#include "vnl_sd_matrix_tools.h"
#include "itkLocalAffineTransform.h"
namespace itk
{
/** Constructor with default arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform():Superclass(ParametersDimension)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Constructor with default arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform(unsigned int parametersDimension):
Superclass(parametersDimension)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Constructor with explicit arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform(const MatrixType & matrix,
const OutputVectorType & offset):
Superclass(matrix, offset)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Destructor */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::
~LocalAffineTransform()
{
return;
}
/** Compute the principal logarithm of an affine transform */
template< class TScalarType, unsigned int NDimensions >
vnl_matrix<TScalarType>
LocalAffineTransform< TScalarType, NDimensions >::ComputeLogarithmMatrix(
AffineTransformPointer affineTransform)
{
vnl_matrix<TScalarType> homoMat(NDimensions+1, NDimensions+1);
this->GetHomogeneousMatrix(homoMat, affineTransform);
vnl_matrix<TScalarType> logMat = sdtools::GetLogarithm(homoMat);
return logMat;
}
/** Compute the exponential of an affine transform */
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >::ComputeExponentialTransform(
vnl_matrix<TScalarType> velocity)
{
AffineTransformPointer expAffine = AffineTransformType::New();
vnl_matrix<TScalarType> expMat = sdtools::GetExponential(velocity);
this->SetHomogeneousTransform(expAffine, expMat);
return expAffine;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::SetHomogeneousTransform(
AffineTransformPointer &affineTransform,
const vnl_matrix<TScalarType> &homoMatrix)
{
MatrixType vmat;
OutputVectorType voffset;
TScalarType scale = homoMatrix[NDimensions][NDimensions];
for (unsigned int i=0; i<NDimensions; i++)
{
for (unsigned int j=0; j<NDimensions; j++)
{
vmat[i][j] = homoMatrix[i][j] / scale;
}
voffset[i] = homoMatrix[i][NDimensions] / scale;
}
affineTransform->SetCenter(this->GetCenter());
affineTransform->SetMatrix(vmat);
affineTransform->SetOffset(voffset);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::GetHomogeneousMatrix(
vnl_matrix<TScalarType> &homoMatrix,
const AffineTransformPointer &affineTransform)
{
MatrixType mat = affineTransform->GetMatrix();
OutputVectorType offset = affineTransform->GetOffset();
homoMatrix.fill(0.0);
for (unsigned int i=0; i<NDimensions; i++)
{
for (unsigned int j=0; j<NDimensions; j++)
{
homoMatrix[i][j] = mat[i][j];
}
homoMatrix[i][NDimensions] = offset[i];
}
homoMatrix[NDimensions][NDimensions] = 1;
}
template< class TScalarType, unsigned int NDimensions >
vnl_matrix<TScalarType>
LocalAffineTransform< TScalarType, NDimensions >
::GetVelocityMatrix()
{
if (this->m_VelocityMatrix.empty())
{
this->m_VelocityMatrix = this->ComputeLogarithmMatrix(this);
}
return this->m_VelocityMatrix;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::UpdatePartialVelocityMatrix()
{
double timePeriod = (double)(m_StopTime - m_StartTime) / m_TimeStampMax;
this->m_PartialVelocityMatrix = this->GetVelocityMatrix();
this->m_PartialVelocityMatrix *= timePeriod;
}
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::OutputVectorType
LocalAffineTransform< TScalarType, NDimensions >
::GetPartialVelocityAtPoint(const PointType &point)
{
OutputVectorType velocity;
for (unsigned int r=0; r<NDimensions; r++)
{
velocity[r] = this->m_PartialVelocityMatrix[r][NDimensions];
for (unsigned int c=0; c<NDimensions; c++)
{
velocity[r] += this->m_PartialVelocityMatrix[r][c] * point[c];
}
}
return velocity;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::AddFixedPoint(InputPointType point)
{
if (this->m_FixedPointSet.IsNull())
{
this->m_FixedPointSet = PointSetType::New();
}
typename PointSetType::PointIndentifier id = this->m_FixedPointSet->GetNumberOfPoints();
this->m_FixedPointSet.SetPoint(id, point);
}
template< class TScalarType, unsigned int NDimensions >
template< class TSpatialObject >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeFixedMaskImageFromSpatialObject(TSpatialObject *spatialObject, SizeType size)
{
typedef itk::SpatialObjectToImageFilter<TSpatialObject,MaskImageType> SpatialObjectToImageFilterType;
typename SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(spatialObject);
imageFilter->SetInsideValue(1);
imageFilter->SetOutsideValue(0);
imageFilter->SetSize(size);
imageFilter->Update();
this->m_FixedMaskImage = imageFilter->GetOutput();
}
template< class TScalarType, unsigned int NDimensions >
template< class TSpatialObject >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeFixedMaskImageFromSpatialObject(TSpatialObject *spatialObject,
PointType origin,
DirectionType direction,
SpacingType spacing,
SizeType size)
{
typedef itk::SpatialObjectToImageFilter<TSpatialObject,MaskImageType> SpatialObjectToImageFilterType;
typename SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(spatialObject);
imageFilter->SetInsideValue(1);
imageFilter->SetOutsideValue(0);
imageFilter->SetOrigin(origin);
imageFilter->SetSpacing(spacing);
imageFilter->SetDirection(direction);
imageFilter->SetSize(size);
imageFilter->Update();
this->m_FixedMaskImage = imageFilter->GetOutput();
}
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >
::GetPartialTransform(int startTime, int stopTime)
{
AffineTransformPointer partialTransform = AffineTransform::New();
int duration = stopTime - startTime;
if (duration == 0)
{
partialTransform->SetCenter(this->GetCenter());
partialTransform->SetIdentity();
}
else if (duration == this->m_TimeStampMax)
{
partialTransform->SetCenter(this->GetCenter());
partialTransform->SetMatrix(this->GetMatrix());
partialTransform->SetOffset(this->GetOffset());
}
else if (duration == -this->m_TimeStampMax)
{
partialTransform->SetCenter(this->GetCenter());
bool invertible = this->GetInverse(partialTransform);
if (!invertible)
{
itkWarningMacro("This LocalAffineTransform is not invertible.");
}
}
else
{
double factor = (double)duration / this->m_TimeStampMax;
vnl_matrix<TScalarType> partialVelocity = this->GetVelocityMatrix();
partialVelocity *= factor;
partialTransform = this->ComputeExponentialTransform(partialVelocity);
}
return partialTransform;
}
/**
* The existing method AffineTransform::Scale(factor) scales around the center.
* Instead, we scale around (0,0) in ScaleMatrixOffset().
*/
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >
::ScaleMatrixOffset(AffineTransformPointer transform, double factor)
{
AffineTransformPointer result = AffineTransformType::New();
result->SetCenter(transform->GetCenter());
AffineTransformType::MatrixType newMatrix = transform->GetMatrix();
newMatrix *= factor;
result->SetMatrix(newMatrix);
AffineTransformType::OutputVectorType newOffset = transform->GetOffset();
newOffset *= factor;
result->SetOffset(newOffset);
return result;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpMaskIntoPointSet(PointSetPointer &pointSet, const MaskImagePointer &mask,
const AffineTransformPointer &transform)
{
typedef ImageRegionIteratorWithIndex< MaskImageType > IteratorType;
IteratorType it( mask, mask->GetLargestPossibleRegion() );
//fill the moving mask with values
typename PointSetType::PointIdentifier pointId = pointSet->GetNumberOfPoints();
PointType point, point2;
for( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
if (it.Get() != 0) //foreground
{
mask->TransformIndexToPhysicalPoint(it.GetIndex(), point);
point2 = transform->TransformPoint(point);
pointSet->SetPoint(pointId++, point2);
}
}
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpFixedMaskIntoPointSet(int timeStamp)
{
AffineTransformPointer forwardTransform = this->GetPartialTransform(0, timeStamp);
this->WarpMaskIntoPointSet(this->m_SamplePointSet,
this->m_FixedMaskImage, forwardTransform);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpMovingMaskIntoPointSet(int timeStamp)
{
AffineTransformPointer backwardTransform = this->GetPartialTransform(this->m_TimeStampMax, timeStamp);
this->WarpMaskIntoPointSet(this->m_SamplePointSet,
this->m_MovingMaskImage, backwardTransform);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeSamplePointSet(int timeStamp)
{
//fill m_SamplePointSet with points
this->m_SamplePointSet = PointSetType::New();
this->WarpFixedMaskIntoPointSet(timeStamp);
this->WarpMovingMaskIntoPointSet(timeStamp);
}
/**
* Warp the fixed mask to the moving mask. The moving mask
* uses the meta information from the fixed mask except its
* region. Instead, the region will be expanded to contain
* the warped mask.
*/
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeMovingMaskImage()
{
ContinuousIndexType mappedCorner, minIndex, maxIndex;
//compute minIndex and maxIndex of the warped mask
RegionType fixedRegion = this->m_FixedMaskImage->GetLargestPossibleRegion();
minIndex = fixedRegion.GetIndex();
maxIndex = fixedRegion.GetUpperIndex();
typedef typename itk::VectorContainer<int, IndexType> IndexContainerType;
typename IndexContainerType::Pointer corners =
PicslImageHelper::GetCorners<RegionType>(fixedRegion);
typename IndexContainerType::ConstIterator corner;
for ( corner = corners->Begin(); corner != corners->End(); corner++)
{
IndexType cornerIndex = corner.Value();
PointType cornerPoint, mappedPoint;
//map the corner index into the physical point
this->m_FixedMaskImage->TransformIndexToPhysicalPoint(cornerIndex, cornerPoint);
//transform the point by this local affine transform
mappedPoint = this->TransformPoint(cornerPoint);
//map the transformed point to index
this->m_FixedMaskImage->TransformPhysicalPointToContinuousIndex(mappedPoint, mappedCorner);
PicslImageHelper::CopyWithMin<ContinuousIndexType>(minIndex, mappedCorner);
PicslImageHelper::CopyWithMax<ContinuousIndexType>(maxIndex, mappedCorner);
}
//allocate the moving mask with the possible region
IndexType index1, index2;
index1.CopyWithRound(minIndex);
index2.CopyWithRound(maxIndex);
RegionType movingRegion;
movingRegion.SetIndex(index1);
movingRegion.SetUpperIndex(index2);
MaskImagePointer movingMask = MaskImageType::New();
movingMask->CopyInformation(this->m_FixedMaskImage);
movingMask->SetRegions(movingRegion);
movingMask->Allocate();
//compute the inverse transform
typename Superclass::Pointer inverse = Superclass::New();
bool insideImage, invertible = this->GetInverse(inverse);
if (!invertible)
{
itkWarningMacro("This LocalAffineTransform is not invertible.");
return;
}
PointType point1, point2;
typename MaskImageType::PixelType pixel;
IndexType minMovingMaskIndex, maxMovingMaskIndex;
minMovingMaskIndex = fixedRegion.GetIndex();
maxMovingMaskIndex = fixedRegion.GetUpperIndex();
//fill the moving mask with values
typedef ImageRegionIteratorWithIndex< MaskImageType > IteratorType;
IteratorType it( movingMask, movingMask->GetLargestPossibleRegion() );
for( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
index1 = it.GetIndex();
movingMask->TransformIndexToPhysicalPoint(index1, point1);
point2 = inverse->TransformPoint(point1);
insideImage = this->m_FixedMaskImage->TransformPhysicalPointToIndex(point2, index2);
pixel = 0;
if (insideImage)
{
pixel = this->m_FixedMaskImage->GetPixel(index2);
if (pixel != 0) //foreground
{
//update min and max indices
PicslImageHelper::CopyWithMin<IndexType>(minMovingMaskIndex, index1);
PicslImageHelper::CopyWithMax<IndexType>(maxMovingMaskIndex, index1);
}
}
it.Set(pixel);
} //for iterator of movingMask
RegionType extractRegion;
extractRegion.SetIndex(minMovingMaskIndex);
extractRegion.SetUpperIndex(maxMovingMaskIndex);
typedef itk::ExtractImageFilter< MaskImageType, MaskImageType > FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetExtractionRegion(extractRegion);
filter->SetInput(movingMask);
#if ITK_VERSION_MAJOR >= 4
filter->SetDirectionCollapseToIdentity(); // This is required.
#endif
filter->Update();
this->m_MovingMaskImage = filter->GetOutput();
}
/** Print self */
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
} // namespace
#endif
<commit_msg>ENH: fixed a compiler error on linux<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkLocalAffineTransform_hxx
#define __itkLocalAffineTransform_hxx
#include "itkNumericTraits.h"
#include "vnl/algo/vnl_matrix_inverse.h"
#include "vnl_sd_matrix_tools.h"
#include "itkLocalAffineTransform.h"
namespace itk
{
/** Constructor with default arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform():Superclass(ParametersDimension)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Constructor with default arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform(unsigned int parametersDimension):
Superclass(parametersDimension)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Constructor with explicit arguments */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::LocalAffineTransform(const MatrixType & matrix,
const OutputVectorType & offset):
Superclass(matrix, offset)
{
this->m_StartTime = 0.0;
this->m_StopTime = 0.0;
}
/** Destructor */
template< class TScalarType, unsigned int NDimensions >
LocalAffineTransform< TScalarType, NDimensions >::
~LocalAffineTransform()
{
return;
}
/** Compute the principal logarithm of an affine transform */
template< class TScalarType, unsigned int NDimensions >
vnl_matrix<TScalarType>
LocalAffineTransform< TScalarType, NDimensions >::ComputeLogarithmMatrix(
AffineTransformPointer affineTransform)
{
vnl_matrix<TScalarType> homoMat(NDimensions+1, NDimensions+1);
this->GetHomogeneousMatrix(homoMat, affineTransform);
vnl_matrix<TScalarType> logMat = sdtools::GetLogarithm(homoMat);
return logMat;
}
/** Compute the exponential of an affine transform */
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >::ComputeExponentialTransform(
vnl_matrix<TScalarType> velocity)
{
AffineTransformPointer expAffine = AffineTransformType::New();
vnl_matrix<TScalarType> expMat = sdtools::GetExponential(velocity);
this->SetHomogeneousTransform(expAffine, expMat);
return expAffine;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::SetHomogeneousTransform(
AffineTransformPointer &affineTransform,
const vnl_matrix<TScalarType> &homoMatrix)
{
MatrixType vmat;
OutputVectorType voffset;
TScalarType scale = homoMatrix[NDimensions][NDimensions];
for (unsigned int i=0; i<NDimensions; i++)
{
for (unsigned int j=0; j<NDimensions; j++)
{
vmat[i][j] = homoMatrix[i][j] / scale;
}
voffset[i] = homoMatrix[i][NDimensions] / scale;
}
affineTransform->SetCenter(this->GetCenter());
affineTransform->SetMatrix(vmat);
affineTransform->SetOffset(voffset);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::GetHomogeneousMatrix(
vnl_matrix<TScalarType> &homoMatrix,
const AffineTransformPointer &affineTransform)
{
MatrixType mat = affineTransform->GetMatrix();
OutputVectorType offset = affineTransform->GetOffset();
homoMatrix.fill(0.0);
for (unsigned int i=0; i<NDimensions; i++)
{
for (unsigned int j=0; j<NDimensions; j++)
{
homoMatrix[i][j] = mat[i][j];
}
homoMatrix[i][NDimensions] = offset[i];
}
homoMatrix[NDimensions][NDimensions] = 1;
}
template< class TScalarType, unsigned int NDimensions >
vnl_matrix<TScalarType>
LocalAffineTransform< TScalarType, NDimensions >
::GetVelocityMatrix()
{
if (this->m_VelocityMatrix.empty())
{
this->m_VelocityMatrix = this->ComputeLogarithmMatrix(this);
}
return this->m_VelocityMatrix;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::UpdatePartialVelocityMatrix()
{
double timePeriod = (double)(m_StopTime - m_StartTime) / m_TimeStampMax;
this->m_PartialVelocityMatrix = this->GetVelocityMatrix();
this->m_PartialVelocityMatrix *= timePeriod;
}
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::OutputVectorType
LocalAffineTransform< TScalarType, NDimensions >
::GetPartialVelocityAtPoint(const PointType &point)
{
OutputVectorType velocity;
for (unsigned int r=0; r<NDimensions; r++)
{
velocity[r] = this->m_PartialVelocityMatrix[r][NDimensions];
for (unsigned int c=0; c<NDimensions; c++)
{
velocity[r] += this->m_PartialVelocityMatrix[r][c] * point[c];
}
}
return velocity;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::AddFixedPoint(InputPointType point)
{
if (this->m_FixedPointSet.IsNull())
{
this->m_FixedPointSet = PointSetType::New();
}
typename PointSetType::PointIndentifier id = this->m_FixedPointSet->GetNumberOfPoints();
this->m_FixedPointSet.SetPoint(id, point);
}
template< class TScalarType, unsigned int NDimensions >
template< class TSpatialObject >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeFixedMaskImageFromSpatialObject(TSpatialObject *spatialObject, SizeType size)
{
typedef itk::SpatialObjectToImageFilter<TSpatialObject,MaskImageType> SpatialObjectToImageFilterType;
typename SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(spatialObject);
imageFilter->SetInsideValue(1);
imageFilter->SetOutsideValue(0);
imageFilter->SetSize(size);
imageFilter->Update();
this->m_FixedMaskImage = imageFilter->GetOutput();
}
template< class TScalarType, unsigned int NDimensions >
template< class TSpatialObject >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeFixedMaskImageFromSpatialObject(TSpatialObject *spatialObject,
PointType origin,
DirectionType direction,
SpacingType spacing,
SizeType size)
{
typedef itk::SpatialObjectToImageFilter<TSpatialObject,MaskImageType> SpatialObjectToImageFilterType;
typename SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(spatialObject);
imageFilter->SetInsideValue(1);
imageFilter->SetOutsideValue(0);
imageFilter->SetOrigin(origin);
imageFilter->SetSpacing(spacing);
imageFilter->SetDirection(direction);
imageFilter->SetSize(size);
imageFilter->Update();
this->m_FixedMaskImage = imageFilter->GetOutput();
}
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >
::GetPartialTransform(int startTime, int stopTime)
{
AffineTransformPointer partialTransform = AffineTransformType::New();
int duration = stopTime - startTime;
if (duration == 0)
{
partialTransform->SetCenter(this->GetCenter());
partialTransform->SetIdentity();
}
else if (duration == this->m_TimeStampMax)
{
partialTransform->SetCenter(this->GetCenter());
partialTransform->SetMatrix(this->GetMatrix());
partialTransform->SetOffset(this->GetOffset());
}
else if (duration == -this->m_TimeStampMax)
{
partialTransform->SetCenter(this->GetCenter());
bool invertible = this->GetInverse(partialTransform);
if (!invertible)
{
itkWarningMacro("This LocalAffineTransform is not invertible.");
}
}
else
{
double factor = (double)duration / this->m_TimeStampMax;
vnl_matrix<TScalarType> partialVelocity = this->GetVelocityMatrix();
partialVelocity *= factor;
partialTransform = this->ComputeExponentialTransform(partialVelocity);
}
return partialTransform;
}
/**
* The existing method AffineTransform::Scale(factor) scales around the center.
* Instead, we scale around (0,0) in ScaleMatrixOffset().
*/
template< class TScalarType, unsigned int NDimensions >
typename LocalAffineTransform< TScalarType, NDimensions >::AffineTransformPointer
LocalAffineTransform< TScalarType, NDimensions >
::ScaleMatrixOffset(AffineTransformPointer transform, double factor)
{
AffineTransformPointer result = AffineTransformType::New();
result->SetCenter(transform->GetCenter());
AffineTransformType::MatrixType newMatrix = transform->GetMatrix();
newMatrix *= factor;
result->SetMatrix(newMatrix);
AffineTransformType::OutputVectorType newOffset = transform->GetOffset();
newOffset *= factor;
result->SetOffset(newOffset);
return result;
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpMaskIntoPointSet(PointSetPointer &pointSet, const MaskImagePointer &mask,
const AffineTransformPointer &transform)
{
typedef ImageRegionIteratorWithIndex< MaskImageType > IteratorType;
IteratorType it( mask, mask->GetLargestPossibleRegion() );
//fill the moving mask with values
typename PointSetType::PointIdentifier pointId = pointSet->GetNumberOfPoints();
PointType point, point2;
for( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
if (it.Get() != 0) //foreground
{
mask->TransformIndexToPhysicalPoint(it.GetIndex(), point);
point2 = transform->TransformPoint(point);
pointSet->SetPoint(pointId++, point2);
}
}
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpFixedMaskIntoPointSet(int timeStamp)
{
AffineTransformPointer forwardTransform = this->GetPartialTransform(0, timeStamp);
this->WarpMaskIntoPointSet(this->m_SamplePointSet,
this->m_FixedMaskImage, forwardTransform);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::WarpMovingMaskIntoPointSet(int timeStamp)
{
AffineTransformPointer backwardTransform = this->GetPartialTransform(this->m_TimeStampMax, timeStamp);
this->WarpMaskIntoPointSet(this->m_SamplePointSet,
this->m_MovingMaskImage, backwardTransform);
}
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeSamplePointSet(int timeStamp)
{
//fill m_SamplePointSet with points
this->m_SamplePointSet = PointSetType::New();
this->WarpFixedMaskIntoPointSet(timeStamp);
this->WarpMovingMaskIntoPointSet(timeStamp);
}
/**
* Warp the fixed mask to the moving mask. The moving mask
* uses the meta information from the fixed mask except its
* region. Instead, the region will be expanded to contain
* the warped mask.
*/
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >
::ComputeMovingMaskImage()
{
ContinuousIndexType mappedCorner, minIndex, maxIndex;
//compute minIndex and maxIndex of the warped mask
RegionType fixedRegion = this->m_FixedMaskImage->GetLargestPossibleRegion();
minIndex = fixedRegion.GetIndex();
maxIndex = fixedRegion.GetUpperIndex();
typedef typename itk::VectorContainer<int, IndexType> IndexContainerType;
typename IndexContainerType::Pointer corners =
PicslImageHelper::GetCorners<RegionType>(fixedRegion);
typename IndexContainerType::ConstIterator corner;
for ( corner = corners->Begin(); corner != corners->End(); corner++)
{
IndexType cornerIndex = corner.Value();
PointType cornerPoint, mappedPoint;
//map the corner index into the physical point
this->m_FixedMaskImage->TransformIndexToPhysicalPoint(cornerIndex, cornerPoint);
//transform the point by this local affine transform
mappedPoint = this->TransformPoint(cornerPoint);
//map the transformed point to index
this->m_FixedMaskImage->TransformPhysicalPointToContinuousIndex(mappedPoint, mappedCorner);
PicslImageHelper::CopyWithMin<ContinuousIndexType>(minIndex, mappedCorner);
PicslImageHelper::CopyWithMax<ContinuousIndexType>(maxIndex, mappedCorner);
}
//allocate the moving mask with the possible region
IndexType index1, index2;
index1.CopyWithRound(minIndex);
index2.CopyWithRound(maxIndex);
RegionType movingRegion;
movingRegion.SetIndex(index1);
movingRegion.SetUpperIndex(index2);
MaskImagePointer movingMask = MaskImageType::New();
movingMask->CopyInformation(this->m_FixedMaskImage);
movingMask->SetRegions(movingRegion);
movingMask->Allocate();
//compute the inverse transform
typename Superclass::Pointer inverse = Superclass::New();
bool insideImage, invertible = this->GetInverse(inverse);
if (!invertible)
{
itkWarningMacro("This LocalAffineTransform is not invertible.");
return;
}
PointType point1, point2;
typename MaskImageType::PixelType pixel;
IndexType minMovingMaskIndex, maxMovingMaskIndex;
minMovingMaskIndex = fixedRegion.GetIndex();
maxMovingMaskIndex = fixedRegion.GetUpperIndex();
//fill the moving mask with values
typedef ImageRegionIteratorWithIndex< MaskImageType > IteratorType;
IteratorType it( movingMask, movingMask->GetLargestPossibleRegion() );
for( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
index1 = it.GetIndex();
movingMask->TransformIndexToPhysicalPoint(index1, point1);
point2 = inverse->TransformPoint(point1);
insideImage = this->m_FixedMaskImage->TransformPhysicalPointToIndex(point2, index2);
pixel = 0;
if (insideImage)
{
pixel = this->m_FixedMaskImage->GetPixel(index2);
if (pixel != 0) //foreground
{
//update min and max indices
PicslImageHelper::CopyWithMin<IndexType>(minMovingMaskIndex, index1);
PicslImageHelper::CopyWithMax<IndexType>(maxMovingMaskIndex, index1);
}
}
it.Set(pixel);
} //for iterator of movingMask
RegionType extractRegion;
extractRegion.SetIndex(minMovingMaskIndex);
extractRegion.SetUpperIndex(maxMovingMaskIndex);
typedef itk::ExtractImageFilter< MaskImageType, MaskImageType > FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetExtractionRegion(extractRegion);
filter->SetInput(movingMask);
#if ITK_VERSION_MAJOR >= 4
filter->SetDirectionCollapseToIdentity(); // This is required.
#endif
filter->Update();
this->m_MovingMaskImage = filter->GetOutput();
}
/** Print self */
template< class TScalarType, unsigned int NDimensions >
void
LocalAffineTransform< TScalarType, NDimensions >::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
} // namespace
#endif
<|endoftext|> |
<commit_before>#include <iostream>
class MyClass
{
public:
void DoThing() const & { std::cout << "Thing was done as const &" << std::endl; }
void DoThing() const && { std::cout << "Thing was done as const &&" << std::endl; }
void DoThing() & { std::cout << "Thing was done as &" << std::endl; }
void DoThing() && { std::cout << "Thing was done as &&" << std::endl; }
};
int main(int argc, char* argv[])
{
MyClass m;
m.DoThing();
MyClass().DoThing();
const MyClass& crm = m;
crm.DoThing();
auto returnMyClass = []()->const MyClass{return MyClass();};
returnMyClass().DoThing();
}
<commit_msg>Added stack overflow reference<commit_after>// http://stackoverflow.com/questions/17521238/what-are-rvalue-references-for-this-for
#include <iostream>
class MyClass
{
public:
void DoThing() const & { std::cout << "Thing was done as const &" << std::endl; }
void DoThing() const && { std::cout << "Thing was done as const &&" << std::endl; }
void DoThing() & { std::cout << "Thing was done as &" << std::endl; }
void DoThing() && { std::cout << "Thing was done as &&" << std::endl; }
};
int main(int argc, char* argv[])
{
MyClass m;
m.DoThing();
MyClass().DoThing();
const MyClass& crm = m;
crm.DoThing();
auto returnMyClass = []()->const MyClass{return MyClass();};
returnMyClass().DoThing();
}
<|endoftext|> |
<commit_before>#include "calc.h"
#include "sevensegment.h"
#include "pocketcalculator.h"
#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"
#include <string>
#include <sstream>
#include <limits>
#include <algorithm>
namespace calc_tests {
constexpr int max { std::numeric_limits<int>::max() },
min { std::numeric_limits<int>::min() };
void multiplies_positive_numbers() {
ASSERT_EQUAL(20, calc(4, 5, '*'));
}
void multiplies_negative_with_positive_number() {
ASSERT_EQUAL(-30, calc(-6, 5, '*'));
}
void multiplies_negative_numbers() {
ASSERT_EQUAL(20, calc(-4, -5, '*'));
}
void recognizes_overflows_when_multiplying() {
ASSERT_THROWS(calc(4, max/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(4, min/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(-4, max/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(-4, min/3, '*'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_multiplying() {
calc(1, max, '*');
calc(1, min, '*');
calc(-1, max, '*');
calc(-1, min+1, '*');
calc(2, max/2, '*');
calc(2, min/2, '*');
calc(-2, max/2, '*');
calc(-2, min/2+1, '*');
}
void divides() {
ASSERT_EQUAL(5, calc(60, 12, '/'));
ASSERT_EQUAL(-3, calc(9, -3, '/'));
}
void throws_when_dividing_by_zero() {
ASSERT_THROWS(calc(1, 0, '/'), std::domain_error);
}
void adds() {
ASSERT_EQUAL(5, calc(2, 3, '+'));
ASSERT_EQUAL(-10, calc(-6, -4, '+'));
}
void recognizes_overflows_when_adding() {
ASSERT_THROWS(calc(max, 1, '+'), std::overflow_error);
ASSERT_THROWS(calc(min, -1, '+'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_adding() {
calc(max, 0, '+');
calc(min, 0, '+');
}
void subtracts() {
ASSERT_EQUAL(17, calc(20, 3, '-'));
ASSERT_EQUAL(-5, calc(-2, 3, '-'));
}
void recognizes_overflows_when_subtracting() {
ASSERT_THROWS(calc(max, -1, '-'), std::overflow_error);
ASSERT_THROWS(calc(min, 1, '-'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_subtracting() {
calc(max, 0, '-');
calc(min, 0, '-');
}
void knows_modulo() {
ASSERT_EQUAL(5, calc(15, 10, '%'));
ASSERT_EQUAL(-5, calc(-15, 10, '%'));
}
void throws_when_modulo_zero() {
ASSERT_THROWS(calc(10, 0, '%'), std::domain_error);
}
void throws_when_given_invalid_operator() {
ASSERT_THROWS(calc(1, 1, '^'), std::runtime_error);
}
void takes_term_from_istream() {
std::istringstream term_stream { "1+1" };
int result = calc(term_stream);
ASSERT_EQUAL(2, result);
}
const std::vector<std::string> invalid_terms {
"foobar",
"3+2-",
"1",
"8--",
"*",
"4%%6",
"3//7",
};
void throws_when_given_invalid_term() {
for(auto const term : invalid_terms) {
std::istringstream term_stream { term };
ASSERT_THROWS(calc(term_stream), std::exception);
}
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(multiplies_positive_numbers));
s.push_back(CUTE(multiplies_negative_with_positive_number));
s.push_back(CUTE(multiplies_negative_numbers));
s.push_back(CUTE(recognizes_overflows_when_multiplying));
s.push_back(CUTE(doesnt_overflow_near_limits_when_multiplying));
s.push_back(CUTE(divides));
s.push_back(CUTE(throws_when_dividing_by_zero));
s.push_back(CUTE(adds));
s.push_back(CUTE(recognizes_overflows_when_adding));
s.push_back(CUTE(doesnt_overflow_near_limits_when_adding));
s.push_back(CUTE(subtracts));
s.push_back(CUTE(recognizes_overflows_when_subtracting));
s.push_back(CUTE(doesnt_overflow_near_limits_when_subtracting));
s.push_back(CUTE(throws_when_given_invalid_operator));
s.push_back(CUTE(knows_modulo));
s.push_back(CUTE(throws_when_modulo_zero));
s.push_back(CUTE(takes_term_from_istream));
s.push_back(CUTE(throws_when_given_invalid_term));
}
}
namespace sevensegment_tests {
const std::string large_8 {
" - \n"
"| |\n"
" - \n"
"| |\n"
" - \n"
};
const std::string large_1 {
" \n"
" |\n"
" \n"
" |\n"
" \n"
};
const std::string large_3_scale2 {
" -- \n"
" |\n"
" |\n"
" -- \n"
" |\n"
" |\n"
" -- \n"
};
void prints_digit() {
std::ostringstream output {};
sevensegment::printLargeDigit(8, output, 1);
ASSERT_EQUAL(large_8, output.str());
output.str("");
sevensegment::printLargeDigit(1, output, 1);
ASSERT_EQUAL(large_1, output.str());
}
void prints_scaled_digit() {
std::ostringstream output {};
sevensegment::printLargeDigit(3, output, 2);
ASSERT_EQUAL(large_3_scale2, output.str());
}
void throws_when_digit_out_of_range() {
std::ostringstream output {};
ASSERT_THROWS(sevensegment::printLargeDigit(10,output, 1),
std::out_of_range);
}
void throws_when_scale_out_of_range() {
std::ostringstream output {};
ASSERT_THROWS(sevensegment::printLargeDigit(5,output, 0),
std::range_error);
}
const std::string large_number {
" - - - \n"
"| | | | | |\n"
" - - - - \n"
" | | || |\n"
" - - - \n"
};
const std::string large_negative_number {
" - - \n"
" | |\n"
" - - - \n"
" | |\n"
" - - \n"
};
void prints_number() {
std::ostringstream output {};
sevensegment::printLargeNumber(54321, output, 1);
ASSERT_EQUAL(large_number, output.str());
}
void prints_negative_number() {
std::ostringstream output {};
sevensegment::printLargeNumber(-33, output, 1);
ASSERT_EQUAL(large_negative_number, output.str());
}
const std::string large_error {
" - \n"
"| \n"
" - - - - - \n"
"| | | | || \n"
" - - \n"
};
void prints_error() {
std::ostringstream output {};
sevensegment::printLargeError(output, 1);
ASSERT_EQUAL(large_error, output.str());
}
void throws_when_too_many_digits_for_display() {
std::ostringstream output {};
ASSERT_THROWS(sevensegment::printLargeNumber(100000000, output, 1),
std::overflow_error);
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(prints_digit));
s.push_back(CUTE(prints_scaled_digit));
s.push_back(CUTE(throws_when_digit_out_of_range));
s.push_back(CUTE(throws_when_scale_out_of_range));
s.push_back(CUTE(prints_number));
s.push_back(CUTE(prints_negative_number));
s.push_back(CUTE(prints_error));
s.push_back(CUTE(throws_when_too_many_digits_for_display));
}
}
namespace pocketcalculator_tests {
const std::string large_22 {
" - - \n"
" | |\n"
" - - \n"
"| | \n"
" - - \n"
};
void gets_term_and_prints_result() {
std::ostringstream output {};
std::istringstream input { "2+20" };
pocketcalculator::start(input, output, 1);
ASSERT_EQUAL(large_22, output.str());
}
void prints_error_on_invalid_input() {
for(auto const term : calc_tests::invalid_terms) {
std::ostringstream output {};
std::istringstream input { term };
pocketcalculator::start(input, output, 1);
ASSERT_EQUAL(sevensegment_tests::large_error, output.str());
}
}
const std::string large_2_scale4 {
" ---- \n"
" |\n"
" |\n"
" |\n"
" |\n"
" ---- \n"
"| \n"
"| \n"
"| \n"
"| \n"
" ---- \n"
};
void scales() {
std::ostringstream output { };
std::istringstream input { "1+1" };
pocketcalculator::start(input, output, 4);
ASSERT_EQUAL(large_2_scale4, output.str());
}
const std::string large_2 {
" - \n"
" |\n"
" - \n"
"| \n"
" - \n"
};
void uses_default_scale_when_scale_omitted() {
std::ostringstream output {};
std::istringstream input {"1+1"};
pocketcalculator::start(input, output);
ASSERT_EQUAL(large_2, output.str());
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(gets_term_and_prints_result));
s.push_back(CUTE(prints_error_on_invalid_input));
s.push_back(CUTE(scales));
s.push_back(CUTE(uses_default_scale_when_scale_omitted));
}
// TODO: add env scale test
// TODO: test with and without env var set
}
void runAllTests(int argc, char const *argv[]){
cute::suite s {};
calc_tests::add_tests_to_suite(s);
sevensegment_tests::add_tests_to_suite(s);
pocketcalculator_tests::add_tests_to_suite(s);
cute::xml_file_opener xmlfile(argc,argv);
cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out);
cute::makeRunner(lis,argc,argv)(s, "AllTests");
}
int main(int argc, char const *argv[]){
runAllTests(argc,argv);
return 0;
}
<commit_msg>style<commit_after>#include "calc.h"
#include "sevensegment.h"
#include "pocketcalculator.h"
#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"
#include <string>
#include <sstream>
#include <limits>
#include <algorithm>
namespace calc_tests {
constexpr int max { std::numeric_limits<int>::max() },
min { std::numeric_limits<int>::min() };
void multiplies_positive_numbers() {
ASSERT_EQUAL(20, calc(4, 5, '*'));
}
void multiplies_negative_with_positive_number() {
ASSERT_EQUAL(-30, calc(-6, 5, '*'));
}
void multiplies_negative_numbers() {
ASSERT_EQUAL(20, calc(-4, -5, '*'));
}
void recognizes_overflows_when_multiplying() {
ASSERT_THROWS(calc(4, max/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(4, min/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(-4, max/3, '*'), std::overflow_error);
ASSERT_THROWS(calc(-4, min/3, '*'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_multiplying() {
calc(1, max, '*');
calc(1, min, '*');
calc(-1, max, '*');
calc(-1, min+1, '*');
calc(2, max/2, '*');
calc(2, min/2, '*');
calc(-2, max/2, '*');
calc(-2, min/2+1, '*');
}
void divides() {
ASSERT_EQUAL(5, calc(60, 12, '/'));
ASSERT_EQUAL(-3, calc(9, -3, '/'));
}
void throws_when_dividing_by_zero() {
ASSERT_THROWS(calc(1, 0, '/'), std::domain_error);
}
void adds() {
ASSERT_EQUAL(5, calc(2, 3, '+'));
ASSERT_EQUAL(-10, calc(-6, -4, '+'));
}
void recognizes_overflows_when_adding() {
ASSERT_THROWS(calc(max, 1, '+'), std::overflow_error);
ASSERT_THROWS(calc(min, -1, '+'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_adding() {
calc(max, 0, '+');
calc(min, 0, '+');
}
void subtracts() {
ASSERT_EQUAL(17, calc(20, 3, '-'));
ASSERT_EQUAL(-5, calc(-2, 3, '-'));
}
void recognizes_overflows_when_subtracting() {
ASSERT_THROWS(calc(max, -1, '-'), std::overflow_error);
ASSERT_THROWS(calc(min, 1, '-'), std::overflow_error);
}
void doesnt_overflow_near_limits_when_subtracting() {
calc(max, 0, '-');
calc(min, 0, '-');
}
void knows_modulo() {
ASSERT_EQUAL(5, calc(15, 10, '%'));
ASSERT_EQUAL(-5, calc(-15, 10, '%'));
}
void throws_when_modulo_zero() {
ASSERT_THROWS(calc(10, 0, '%'), std::domain_error);
}
void throws_when_given_invalid_operator() {
ASSERT_THROWS(calc(1, 1, '^'), std::runtime_error);
}
void takes_term_from_istream() {
std::istringstream term_stream { "1+1" };
int result = calc(term_stream);
ASSERT_EQUAL(2, result);
}
const std::vector<std::string> invalid_terms {
"foobar",
"3+2-",
"1",
"8--",
"*",
"4%%6",
"3//7",
};
void throws_when_given_invalid_term() {
for(auto const term : invalid_terms) {
std::istringstream term_stream { term };
ASSERT_THROWS(calc(term_stream), std::exception);
}
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(multiplies_positive_numbers));
s.push_back(CUTE(multiplies_negative_with_positive_number));
s.push_back(CUTE(multiplies_negative_numbers));
s.push_back(CUTE(recognizes_overflows_when_multiplying));
s.push_back(CUTE(doesnt_overflow_near_limits_when_multiplying));
s.push_back(CUTE(divides));
s.push_back(CUTE(throws_when_dividing_by_zero));
s.push_back(CUTE(adds));
s.push_back(CUTE(recognizes_overflows_when_adding));
s.push_back(CUTE(doesnt_overflow_near_limits_when_adding));
s.push_back(CUTE(subtracts));
s.push_back(CUTE(recognizes_overflows_when_subtracting));
s.push_back(CUTE(doesnt_overflow_near_limits_when_subtracting));
s.push_back(CUTE(throws_when_given_invalid_operator));
s.push_back(CUTE(knows_modulo));
s.push_back(CUTE(throws_when_modulo_zero));
s.push_back(CUTE(takes_term_from_istream));
s.push_back(CUTE(throws_when_given_invalid_term));
}
}
namespace sevensegment_tests {
const std::string large_8 {
" - \n"
"| |\n"
" - \n"
"| |\n"
" - \n"
};
const std::string large_1 {
" \n"
" |\n"
" \n"
" |\n"
" \n"
};
const std::string large_3_scale2 {
" -- \n"
" |\n"
" |\n"
" -- \n"
" |\n"
" |\n"
" -- \n"
};
void prints_digit() {
std::ostringstream output { };
sevensegment::printLargeDigit(8, output, 1);
ASSERT_EQUAL(large_8, output.str());
output.str("");
sevensegment::printLargeDigit(1, output, 1);
ASSERT_EQUAL(large_1, output.str());
}
void prints_scaled_digit() {
std::ostringstream output { };
sevensegment::printLargeDigit(3, output, 2);
ASSERT_EQUAL(large_3_scale2, output.str());
}
void throws_when_digit_out_of_range() {
std::ostringstream output { };
ASSERT_THROWS(sevensegment::printLargeDigit(10,output, 1),
std::out_of_range);
}
void throws_when_scale_out_of_range() {
std::ostringstream output { };
ASSERT_THROWS(sevensegment::printLargeDigit(5,output, 0),
std::range_error);
}
const std::string large_number {
" - - - \n"
"| | | | | |\n"
" - - - - \n"
" | | || |\n"
" - - - \n"
};
const std::string large_negative_number {
" - - \n"
" | |\n"
" - - - \n"
" | |\n"
" - - \n"
};
void prints_number() {
std::ostringstream output { };
sevensegment::printLargeNumber(54321, output, 1);
ASSERT_EQUAL(large_number, output.str());
}
void prints_negative_number() {
std::ostringstream output { };
sevensegment::printLargeNumber(-33, output, 1);
ASSERT_EQUAL(large_negative_number, output.str());
}
const std::string large_error {
" - \n"
"| \n"
" - - - - - \n"
"| | | | || \n"
" - - \n"
};
void prints_error() {
std::ostringstream output {};
sevensegment::printLargeError(output, 1);
ASSERT_EQUAL(large_error, output.str());
}
void throws_when_too_many_digits_for_display() {
std::ostringstream output {};
ASSERT_THROWS(sevensegment::printLargeNumber(100000000, output, 1),
std::overflow_error);
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(prints_digit));
s.push_back(CUTE(prints_scaled_digit));
s.push_back(CUTE(throws_when_digit_out_of_range));
s.push_back(CUTE(throws_when_scale_out_of_range));
s.push_back(CUTE(prints_number));
s.push_back(CUTE(prints_negative_number));
s.push_back(CUTE(prints_error));
s.push_back(CUTE(throws_when_too_many_digits_for_display));
}
}
namespace pocketcalculator_tests {
const std::string large_22 {
" - - \n"
" | |\n"
" - - \n"
"| | \n"
" - - \n"
};
void gets_term_and_prints_result() {
std::ostringstream output { };
std::istringstream input { "2+20" };
pocketcalculator::start(input, output, 1);
ASSERT_EQUAL(large_22, output.str());
}
void prints_error_on_invalid_input() {
for(auto const term : calc_tests::invalid_terms) {
std::ostringstream output { };
std::istringstream input { term };
pocketcalculator::start(input, output, 1);
ASSERT_EQUAL(sevensegment_tests::large_error, output.str());
}
}
const std::string large_2_scale4 {
" ---- \n"
" |\n"
" |\n"
" |\n"
" |\n"
" ---- \n"
"| \n"
"| \n"
"| \n"
"| \n"
" ---- \n"
};
void scales() {
std::ostringstream output { };
std::istringstream input { "1+1" };
pocketcalculator::start(input, output, 4);
ASSERT_EQUAL(large_2_scale4, output.str());
}
const std::string large_2 {
" - \n"
" |\n"
" - \n"
"| \n"
" - \n"
};
void uses_default_scale_when_scale_omitted() {
std::ostringstream output { };
std::istringstream input { "1+1" };
pocketcalculator::start(input, output);
ASSERT_EQUAL(large_2, output.str());
}
void add_tests_to_suite(cute::suite& s) {
s.push_back(CUTE(gets_term_and_prints_result));
s.push_back(CUTE(prints_error_on_invalid_input));
s.push_back(CUTE(scales));
s.push_back(CUTE(uses_default_scale_when_scale_omitted));
}
// TODO: add env scale test
// TODO: test with and without env var set
}
void runAllTests(int argc, char const *argv[]){
cute::suite s {};
calc_tests::add_tests_to_suite(s);
sevensegment_tests::add_tests_to_suite(s);
pocketcalculator_tests::add_tests_to_suite(s);
cute::xml_file_opener xmlfile(argc,argv);
cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out);
cute::makeRunner(lis,argc,argv)(s, "AllTests");
}
int main(int argc, char const *argv[]){
runAllTests(argc,argv);
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file ReuseQueueTest.cpp
* @brief ReuseQueue class tester.
* @author zer0
* @date 2016-08-03
*/
#include <gtest/gtest.h>
#include <libtbag/container/ReuseQueue.hpp>
using namespace libtbag;
using namespace libtbag::container;
TEST(ReuseQueueTest, Constructor)
{
ReuseQueue<int> q1;
ReuseQueue<int> q2;
q1.push(1);
ASSERT_EQ(1U, q1.size());
q2 = q1;
ASSERT_EQ(1U, q1.size());
ASSERT_EQ(1U, q2.size());
}
TEST(ReuseQueueTest, MoveConstructor)
{
ReuseQueue<int> q1;
ReuseQueue<int> q2;
ASSERT_EQ(0U, q1.size());
ASSERT_EQ(0U, q2.size());
q1.push(1);
q2 = std::move(q1);
ASSERT_EQ(1U, q2.size());
}
TEST(ReuseQueueTest, Default)
{
ReuseQueue<int> queue;
ASSERT_EQ(0U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
ASSERT_TRUE(queue.empty());
ASSERT_TRUE(queue.emptyOfReady());
queue.push(100);
queue.push(200);
ASSERT_EQ(2U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
int result;
ASSERT_EQ(100, queue.front());
queue.pop();
ASSERT_EQ(200, queue.front());
ASSERT_EQ(1U, queue.size());
ASSERT_EQ(1U, queue.sizeOfReady());
queue.push(300);
ASSERT_EQ(2U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
queue.push(400);
ASSERT_EQ(3U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
queue.clear();
ASSERT_TRUE(queue.empty());
ASSERT_TRUE(queue.emptyOfReady());
}
TEST(ReuseQueueTest, PushLambda)
{
int const TEST_VALUE1 = 100;
int const TEST_VALUE2 = 200;
ReuseQueue<int> q1;
ASSERT_EQ(0, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(0, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_TRUE(q1.emptyOfTotal());
q1.push([&](int & v){ v = TEST_VALUE1; });
ASSERT_EQ(TEST_VALUE1, q1.front());
ASSERT_EQ(TEST_VALUE1, q1.back());
q1.push([&](int & v){ v = TEST_VALUE2; });
ASSERT_EQ(TEST_VALUE1, q1.front());
ASSERT_EQ(TEST_VALUE2, q1.back());
ASSERT_EQ(2, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_FALSE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
q1.pop();
ASSERT_EQ(TEST_VALUE2, q1.front());
ASSERT_EQ(TEST_VALUE2, q1.back());
ASSERT_EQ(1, q1.size());
ASSERT_EQ(1, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_FALSE(q1.empty());
ASSERT_FALSE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
int result;
ASSERT_TRUE(q1.frontAndPop(&result));
ASSERT_EQ(TEST_VALUE2, result);
ASSERT_EQ(0, q1.size());
ASSERT_EQ(2, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_FALSE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
q1.clear();
ASSERT_EQ(0, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(0, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_TRUE(q1.emptyOfTotal());
q1.push([&](int & v){ v = TEST_VALUE1; });
q1.push([&](int & v){ v = TEST_VALUE2; });
ASSERT_EQ(2, q1.size());
q1.popAll();
ASSERT_EQ(0, q1.size());
}
<commit_msg>Fixed bug in ReuseQueueTest.Default tester.<commit_after>/**
* @file ReuseQueueTest.cpp
* @brief ReuseQueue class tester.
* @author zer0
* @date 2016-08-03
*/
#include <gtest/gtest.h>
#include <libtbag/container/ReuseQueue.hpp>
using namespace libtbag;
using namespace libtbag::container;
TEST(ReuseQueueTest, Constructor)
{
ReuseQueue<int> q1;
ReuseQueue<int> q2;
q1.push(1);
ASSERT_EQ(1U, q1.size());
q2 = q1;
ASSERT_EQ(1U, q1.size());
ASSERT_EQ(1U, q2.size());
}
TEST(ReuseQueueTest, MoveConstructor)
{
ReuseQueue<int> q1;
ReuseQueue<int> q2;
ASSERT_EQ(0U, q1.size());
ASSERT_EQ(0U, q2.size());
q1.push(1);
q2 = std::move(q1);
ASSERT_EQ(1U, q2.size());
}
TEST(ReuseQueueTest, Default)
{
ReuseQueue<int> queue;
ASSERT_EQ(0U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
ASSERT_TRUE(queue.empty());
ASSERT_TRUE(queue.emptyOfReady());
queue.push(100);
queue.push(200);
ASSERT_EQ(2U, queue.size());
ASSERT_EQ(0U, queue.sizeOfReady());
int result;
ASSERT_EQ(100, queue.front());
queue.pop();
ASSERT_EQ(200, queue.front());
ASSERT_EQ(1U, queue.size());
ASSERT_EQ(1U, queue.sizeOfReady());
queue.push(300);
ASSERT_EQ(2U, queue.size());
ASSERT_EQ(1U, queue.sizeOfReady());
queue.push(400);
ASSERT_EQ(3U, queue.size());
ASSERT_EQ(1U, queue.sizeOfReady());
queue.clear();
ASSERT_TRUE(queue.empty());
ASSERT_TRUE(queue.emptyOfReady());
}
TEST(ReuseQueueTest, PushLambda)
{
int const TEST_VALUE1 = 100;
int const TEST_VALUE2 = 200;
ReuseQueue<int> q1;
ASSERT_EQ(0, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(0, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_TRUE(q1.emptyOfTotal());
q1.push([&](int & v){ v = TEST_VALUE1; });
ASSERT_EQ(TEST_VALUE1, q1.front());
ASSERT_EQ(TEST_VALUE1, q1.back());
q1.push([&](int & v){ v = TEST_VALUE2; });
ASSERT_EQ(TEST_VALUE1, q1.front());
ASSERT_EQ(TEST_VALUE2, q1.back());
ASSERT_EQ(2, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_FALSE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
q1.pop();
ASSERT_EQ(TEST_VALUE2, q1.front());
ASSERT_EQ(TEST_VALUE2, q1.back());
ASSERT_EQ(1, q1.size());
ASSERT_EQ(1, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_FALSE(q1.empty());
ASSERT_FALSE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
int result;
ASSERT_TRUE(q1.frontAndPop(&result));
ASSERT_EQ(TEST_VALUE2, result);
ASSERT_EQ(0, q1.size());
ASSERT_EQ(2, q1.sizeOfReady());
ASSERT_EQ(2, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_FALSE(q1.emptyOfReady());
ASSERT_FALSE(q1.emptyOfTotal());
q1.clear();
ASSERT_EQ(0, q1.size());
ASSERT_EQ(0, q1.sizeOfReady());
ASSERT_EQ(0, q1.sizeOfTotal());
ASSERT_TRUE(q1.empty());
ASSERT_TRUE(q1.emptyOfReady());
ASSERT_TRUE(q1.emptyOfTotal());
q1.push([&](int & v){ v = TEST_VALUE1; });
q1.push([&](int & v){ v = TEST_VALUE2; });
ASSERT_EQ(2, q1.size());
q1.popAll();
ASSERT_EQ(0, q1.size());
}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2008 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// Test interaction with p4est with 2d mesh with some 20 cells
#include "../tests.h"
#include "coarse_grid_common.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/tensor.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_in.h>
template<int dim>
void test(std::ostream & /*out*/)
{
parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD);
GridIn<dim> gi;
gi.attach_triangulation (tr);
gi.read (SOURCE_DIR "../grid/grids/circle-grid.inp");
write_vtk(tr, "1");
}
int main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
deallog.push("2d");
test<2>(logfile);
deallog.pop();
}
<commit_msg>fix tests<commit_after>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2008 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// Test interaction with p4est with 2d mesh with some 20 cells
#include "../tests.h"
#include "coarse_grid_common.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/tensor.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_in.h>
template<int dim>
void test(std::ostream & /*out*/)
{
parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD);
GridIn<dim> gi;
gi.attach_triangulation (tr);
gi.read (SOURCE_DIR "/../grid/grids/circle-grid.inp");
write_vtk(tr, "1");
}
int main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
deallog.push("2d");
test<2>(logfile);
deallog.pop();
}
<|endoftext|> |
<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
#ifndef _HANDLETABLE_INL
#define _HANDLETABLE_INL
inline void HndAssignHandle(OBJECTHANDLE handle, OBJECTREF objref)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// sanity
_ASSERTE(handle);
#ifdef _DEBUG_IMPL
// handle should not be in unloaded domain
ValidateAppDomainForHandle(handle);
// Make sure the objref is valid before it is assigned to a handle
ValidateAssignObjrefForHandle(objref, HndGetHandleTableADIndex(HndGetHandleTable(handle)));
#endif
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
HndLogSetEvent(handle, value);
// if we are doing a non-NULL pointer store then invoke the write-barrier
if (value)
HndWriteBarrier(handle, objref);
// store the pointer
*(_UNCHECKED_OBJECTREF *)handle = value;
}
inline void* HndInterlockedCompareExchangeHandle(OBJECTHANDLE handle, OBJECTREF objref, OBJECTREF oldObjref)
{
WRAPPER_NO_CONTRACT;
// sanity
_ASSERTE(handle);
#ifdef _DEBUG_IMPL
// handle should not be in unloaded domain
ValidateAppDomainForHandle(handle);
// Make sure the objref is valid before it is assigned to a handle
ValidateAssignObjrefForHandle(objref, HndGetHandleTableADIndex(HndGetHandleTable(handle)));
#endif
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
_UNCHECKED_OBJECTREF oldValue = OBJECTREF_TO_UNCHECKED_OBJECTREF(oldObjref);
// if we are doing a non-NULL pointer store then invoke the write-barrier
if (value)
HndWriteBarrier(handle, objref);
// store the pointer
void* ret = Interlocked::CompareExchangePointer(reinterpret_cast<_UNCHECKED_OBJECTREF volatile*>(handle), value, oldValue);
if (ret == oldValue)
HndLogSetEvent(handle, value);
return ret;
}
inline BOOL HndFirstAssignHandle(OBJECTHANDLE handle, OBJECTREF objref)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// sanity
_ASSERTE(handle);
#ifdef _DEBUG_IMPL
// handle should not be in unloaded domain
ValidateAppDomainForHandle(handle);
// Make sure the objref is valid before it is assigned to a handle
ValidateAssignObjrefForHandle(objref, HndGetHandleTableADIndex(HndGetHandleTable(handle)));
#endif
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
_UNCHECKED_OBJECTREF null = NULL;
// store the pointer if we are the first ones here
BOOL success = (NULL == Interlocked::CompareExchangePointer(reinterpret_cast<_UNCHECKED_OBJECTREF volatile*>(handle),
value,
null));
// if we successfully did a non-NULL pointer store then invoke the write-barrier
if (success)
{
if (value)
HndWriteBarrier(handle, objref);
HndLogSetEvent(handle, value);
}
// return our result
return success;
}
#endif // _HANDLETABLE_INL
<commit_msg>Remove handle assignment validation from GC side.<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
#ifndef _HANDLETABLE_INL
#define _HANDLETABLE_INL
inline void HndAssignHandle(OBJECTHANDLE handle, OBJECTREF objref)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// sanity
_ASSERTE(handle);
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
HndLogSetEvent(handle, value);
// if we are doing a non-NULL pointer store then invoke the write-barrier
if (value)
HndWriteBarrier(handle, objref);
// store the pointer
*(_UNCHECKED_OBJECTREF *)handle = value;
}
inline void* HndInterlockedCompareExchangeHandle(OBJECTHANDLE handle, OBJECTREF objref, OBJECTREF oldObjref)
{
WRAPPER_NO_CONTRACT;
// sanity
_ASSERTE(handle);
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
_UNCHECKED_OBJECTREF oldValue = OBJECTREF_TO_UNCHECKED_OBJECTREF(oldObjref);
// if we are doing a non-NULL pointer store then invoke the write-barrier
if (value)
HndWriteBarrier(handle, objref);
// store the pointer
void* ret = Interlocked::CompareExchangePointer(reinterpret_cast<_UNCHECKED_OBJECTREF volatile*>(handle), value, oldValue);
if (ret == oldValue)
HndLogSetEvent(handle, value);
return ret;
}
inline BOOL HndFirstAssignHandle(OBJECTHANDLE handle, OBJECTREF objref)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// sanity
_ASSERTE(handle);
// unwrap the objectref we were given
_UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);
_UNCHECKED_OBJECTREF null = NULL;
// store the pointer if we are the first ones here
BOOL success = (NULL == Interlocked::CompareExchangePointer(reinterpret_cast<_UNCHECKED_OBJECTREF volatile*>(handle),
value,
null));
// if we successfully did a non-NULL pointer store then invoke the write-barrier
if (success)
{
if (value)
HndWriteBarrier(handle, objref);
HndLogSetEvent(handle, value);
}
// return our result
return success;
}
#endif // _HANDLETABLE_INL
<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OTRadValve TempControl tests.
*/
#include <gtest/gtest.h>
#include <stdio.h>
#include "OTSIM900Link.h"
// Test for general sanity of OTSIM900Link.
// Make sure that an instance can be created and does not die horribly.
// Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card.
TEST(OTSIM900Link,basicsDeadCard)
{
const bool verbose = false;
class NULLSerialStream final : public Stream
{
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); }
virtual int available() override { return(-1); }
virtual int read() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0;
EXPECT_TRUE(l0.begin());
EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 100; ++i) { l0.poll(); }
EXPECT_GE(OTSIM900Link::START_UP, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP";
// ...
l0.end();
}
// Test for general sanity of OTSIM900Link.
// Make sure that an instance can be created and does not die horribly.
// Underlying simulated serial/SIM900 accepts output, does not respond.
namespace B1
{
const bool verbose = true;
// Does a trivial simulation of SIM900, responding to start of 'A' of AT command.
class TrivialSimulator final : public Stream
{
public:
// Events exposed.
static bool haveSeenCommandStart;
private:
// Command being collected from OTSIM900Link.
bool waitingForCommand = true;
bool collectingCommand = false;
// Entire request starting "AT"; no trailing CR or LF stored.
std::string command;
// Reply (postfix) being returned to OTSIM900Link: empty if none.
std::string reply;
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t uc) override
{
const char c = (char)uc;
if(waitingForCommand)
{
// Look for leading 'A' of 'AT' to start a command.
if('A' == c)
{
waitingForCommand = false;
collectingCommand = true;
command = 'A';
haveSeenCommandStart = true; // Note at least one command start.
}
}
else
{
// Look for CR (or LF) to terminate a command.
if(('\r' == c) || ('\n' == c))
{
waitingForCommand = true;
collectingCommand = false;
if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); }
// Respond to particular commands...
if("AT" == command) { reply = "AT\r"; }
// DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL.
else if("AT+CPIN?" == command) { reply = "No PIN"; }
}
else if(collectingCommand) { command += c; }
}
if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } }
return(1);
}
virtual int read() override
{
if(0 == reply.size()) { return(-1); }
const char c = reply[0];
if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } }
reply.erase(0, 1);
return(c);
}
virtual int available() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
// Events exposed.
bool TrivialSimulator::haveSeenCommandStart;
}
TEST(OTSIM900Link,basics)
{
// const bool verbose = true;
ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart);
OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0;
EXPECT_TRUE(l0.begin());
EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 100; ++i) { l0.poll(); }
EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900";
EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION";
// ...
l0.end();
}
<commit_msg>TODO-1034: varying responses in simulator<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OTRadValve TempControl tests.
*/
#include <gtest/gtest.h>
#include <stdio.h>
#include <stdlib.h>
#include "OTSIM900Link.h"
// Test for general sanity of OTSIM900Link.
// Make sure that an instance can be created and does not die horribly.
// Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card.
TEST(OTSIM900Link,basicsDeadCard)
{
const bool verbose = false;
class NULLSerialStream final : public Stream
{
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); }
virtual int available() override { return(-1); }
virtual int read() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0;
EXPECT_TRUE(l0.begin());
EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 100; ++i) { l0.poll(); }
EXPECT_GE(OTSIM900Link::START_UP, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP";
// ...
l0.end();
}
// Test for general sanity of OTSIM900Link.
// Make sure that an instance can be created and does not die horribly.
// Underlying simulated serial/SIM900 accepts output, does not respond.
namespace B1
{
const bool verbose = true;
// Does a trivial simulation of SIM900, responding to start of 'A' of AT command.
class TrivialSimulator final : public Stream
{
public:
// Events exposed.
static bool haveSeenCommandStart;
private:
// Command being collected from OTSIM900Link.
bool waitingForCommand = true;
bool collectingCommand = false;
// Entire request starting "AT"; no trailing CR or LF stored.
std::string command;
// Reply (postfix) being returned to OTSIM900Link: empty if none.
std::string reply;
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t uc) override
{
const char c = (char)uc;
if(waitingForCommand)
{
// Look for leading 'A' of 'AT' to start a command.
if('A' == c)
{
waitingForCommand = false;
collectingCommand = true;
command = 'A';
haveSeenCommandStart = true; // Note at least one command start.
}
}
else
{
// Look for CR (or LF) to terminate a command.
if(('\r' == c) || ('\n' == c))
{
waitingForCommand = true;
collectingCommand = false;
if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); }
// Respond to particular commands...
if("AT" == command) { reply = "AT\r"; }
// DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL.
// Should futz/vary the response to check sensitivity.
// TODO: have at least one response be expected SIM900 answer for no-PIN SIM.
else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN" : "OK READY"; }
}
else if(collectingCommand) { command += c; }
}
if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } }
return(1);
}
virtual int read() override
{
if(0 == reply.size()) { return(-1); }
const char c = reply[0];
if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } }
reply.erase(0, 1);
return(c);
}
virtual int available() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
// Events exposed.
bool TrivialSimulator::haveSeenCommandStart;
}
TEST(OTSIM900Link,basicsSimpleSimulator)
{
// const bool verbose = true;
srandomdev(); // Seed random() for use in simulator.
ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart);
OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0;
EXPECT_TRUE(l0.begin());
EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 100; ++i) { l0.poll(); }
EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900";
EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION";
// ...
l0.end();
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> v(10); // Create vector of size 10
v = {34, 23, 30, 19};
// Display the size of the vector
cout << "Vector size: " << v.size() << endl;
cout << "Vector capacity: " << v.capacity() << endl;
// Print vector with a for loop using array syntax (UNSAFE)
for (unsigned int ii=0; ii<v.size(); ii++) {
cout << v[ii] << " ";
}
cout << endl << endl;
cout << "front: " << v.front() << endl;
cout << " back: " << v.back() << endl;
cout << endl;
v.push_back(42);
v.push_back(37);
v.push_back(51);
v.push_back(63);
v.push_back(17);
v.push_back(6);
v.push_back(92);
v.push_back(77);
cout << "After push_back:" << endl;
cout << "Vector size: " << v.size() << endl;
cout << "Vector capacity: " << v.capacity() << endl;
// Print vector using at()
for (unsigned int ii=0; ii<v.size(); ii++) {
cout << v.at(ii) << " ";
}
cout << endl << endl;;
v[5] = 99;
v.pop_back();
cout << "After v[5]=99 & pop_back:" << endl;
// Print vector using for-each
for (auto& ii : v) {
cout << ii << " ";
}
cout << endl;
return 0;
}
<commit_msg>Changed loop variable names<commit_after>#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> v(10); // Create vector of size 10
v = {34, 23, 30, 19};
// Display the size of the vector
cout << "Vector size: " << v.size() << endl;
cout << "Vector capacity: " << v.capacity() << endl;
// Print vector with a for loop using array syntax (UNSAFE)
for (unsigned int ii=0; ii<v.size(); ii++) {
cout << v[ii] << " ";
}
cout << endl << endl;
cout << "front: " << v.front() << endl;
cout << " back: " << v.back() << endl;
cout << endl;
v.push_back(42);
v.push_back(37);
v.push_back(51);
v.push_back(63);
v.push_back(17);
v.push_back(6);
v.push_back(92);
v.push_back(77);
cout << "After push_back:" << endl;
cout << "Vector size: " << v.size() << endl;
cout << "Vector capacity: " << v.capacity() << endl;
// Print vector using at()
for (unsigned int jj=0; jj<v.size(); jj++) {
cout << v.at(jj) << " ";
}
cout << endl << endl;;
v[5] = 99;
v.pop_back();
cout << "After v[5]=99 & pop_back:" << endl;
// Print vector using for-each
for (auto& kk : v) {
cout << kk << " ";
}
cout << endl;
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.