text stringlengths 54 60.6k |
|---|
<commit_before>/// \file
/// \ingroup tutorial_fit
/// \notebook
/// Fitting of a TGraph2D with a 3D straight line
///
/// run this macro by doing:
///
/// ~~~{.cpp}
/// root>.x line3Dfit.C+
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Lorenzo Moneta
#include <TMath.h>
#include <TGraph2D.h>
#include <TRandom2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
#include <TH1.h>
#include <Math/Functor.h>
#include <TPolyLine3D.h>
#include <Math/Vector3D.h>
#include <Fit/Fitter.h>
using namespace ROOT::Math;
// define the parametric line equation
void line(double t, const double *p, double &x, double &y, double &z) {
// a parametric line is define from 6 parameters but 4 are independent
// x0,y0,z0,z1,y1,z1 which are the coordinates of two points on the line
// can choose z0 = 0 if line not parallel to x-y plane and z1 = 1;
x = p[0] + p[1]*t;
y = p[2] + p[3]*t;
z = t;
}
bool first = true;
// function Object to be minimized
struct SumDistance2 {
// the TGraph is a data member of the object
TGraph2D * fGraph;
SumDistance2(TGraph2D * g) : fGraph(g) {}
// calculate distance line-point
double distance2(double x,double y,double z, const double *p) {
// distance line point is D= | (xp-x0) cross ux |
// where ux is direction of line and x0 is a point in the line (like t = 0)
XYZVector xp(x,y,z);
XYZVector x0(p[0], p[2], 0. );
XYZVector x1(p[0] + p[1], p[2] + p[3], 1. );
XYZVector u = (x1-x0).Unit();
double d2 = ((xp-x0).Cross(u)) .Mag2();
return d2;
}
// implementation of the function to be minimized
double operator() (const double * par) {
assert(fGraph != 0);
double * x = fGraph->GetX();
double * y = fGraph->GetY();
double * z = fGraph->GetZ();
int npoints = fGraph->GetN();
double sum = 0;
for (int i = 0; i < npoints; ++i) {
double d = distance2(x[i],y[i],z[i],par);
sum += d;
}
if (first)
std::cout << "Total Initial distance square = " << sum << std::endl;
first = false;
return sum;
}
};
Int_t line3Dfit()
{
gStyle->SetOptStat(0);
gStyle->SetOptFit();
//double e = 0.1;
Int_t nd = 10000;
// double xmin = 0; double ymin = 0;
// double xmax = 10; double ymax = 10;
TGraph2D * gr = new TGraph2D();
// Fill the 2D graph
double p0[4] = {10,20,1,2};
// generate graph with the 3d points
for (Int_t N=0; N<nd; N++) {
double x,y,z = 0;
// Generate a random number
double t = gRandom->Uniform(0,10);
line(t,p0,x,y,z);
double err = 1;
// do a gaussian smearing around the points in all coordinates
x += gRandom->Gaus(0,err);
y += gRandom->Gaus(0,err);
z += gRandom->Gaus(0,err);
gr->SetPoint(N,x,y,z);
//dt->SetPointError(N,0,0,err);
}
// fit the graph now
ROOT::Fit::Fitter fitter;
// make the functor objet
SumDistance2 sdist(gr);
ROOT::Math::Functor fcn(sdist,4);
// set the function and the initial parameter values
double pStart[4] = {1,1,1,1};
fitter.SetFCN(fcn,pStart);
// set step sizes different than default ones (0.3 times parameter values)
for (int i = 0; i < 4; ++i) fitter.Config().ParSettings(i).SetStepSize(0.01);
bool ok = fitter.FitFCN();
if (!ok) {
Error("line3Dfit","Line3D Fit failed");
return 1;
}
const ROOT::Fit::FitResult & result = fitter.Result();
std::cout << "Total final distance square " << result.MinFcnValue() << std::endl;
result.Print(std::cout);
gr->Draw("p0");
// get fit parameters
const double * parFit = result.GetParams();
// draw the fitted line
int n = 1000;
double t0 = 0;
double dt = 10;
TPolyLine3D *l = new TPolyLine3D(n);
for (int i = 0; i <n;++i) {
double t = t0+ dt*i/n;
double x,y,z;
line(t,parFit,x,y,z);
l->SetPoint(i,x,y,z);
}
l->SetLineColor(kRed);
l->Draw("same");
// draw original line
TPolyLine3D *l0 = new TPolyLine3D(n);
for (int i = 0; i <n;++i) {
double t = t0+ dt*i/n;
double x,y,z;
line(t,p0,x,y,z);
l0->SetPoint(i,x,y,z);
}
l0->SetLineColor(kBlue);
l0->Draw("same");
return 0;
}
int main() {
return line3Dfit();
}
<commit_msg>Adjust code to coding conventions.<commit_after>/// \file
/// \ingroup tutorial_fit
/// \notebook
/// Fitting of a TGraph2D with a 3D straight line
///
/// run this macro by doing:
///
/// ~~~{.cpp}
/// root>.x line3Dfit.C+
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Lorenzo Moneta
#include <TMath.h>
#include <TGraph2D.h>
#include <TRandom2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
#include <TH1.h>
#include <Math/Functor.h>
#include <TPolyLine3D.h>
#include <Math/Vector3D.h>
#include <Fit/Fitter.h>
using namespace ROOT::Math;
// define the parametric line equation
void line(double t, const double *p, double &x, double &y, double &z) {
// a parametric line is define from 6 parameters but 4 are independent
// x0,y0,z0,z1,y1,z1 which are the coordinates of two points on the line
// can choose z0 = 0 if line not parallel to x-y plane and z1 = 1;
x = p[0] + p[1]*t;
y = p[2] + p[3]*t;
z = t;
}
bool first = true;
// function Object to be minimized
struct SumDistance2 {
// the TGraph is a data member of the object
TGraph2D *fGraph;
SumDistance2(TGraph2D *g) : fGraph(g) {}
// calculate distance line-point
double distance2(double x,double y,double z, const double *p) {
// distance line point is D= | (xp-x0) cross ux |
// where ux is direction of line and x0 is a point in the line (like t = 0)
XYZVector xp(x,y,z);
XYZVector x0(p[0], p[2], 0. );
XYZVector x1(p[0] + p[1], p[2] + p[3], 1. );
XYZVector u = (x1-x0).Unit();
double d2 = ((xp-x0).Cross(u)).Mag2();
return d2;
}
// implementation of the function to be minimized
double operator() (const double *par) {
assert(fGraph != 0);
double * x = fGraph->GetX();
double * y = fGraph->GetY();
double * z = fGraph->GetZ();
int npoints = fGraph->GetN();
double sum = 0;
for (int i = 0; i < npoints; ++i) {
double d = distance2(x[i],y[i],z[i],par);
sum += d;
}
if (first) {
std::cout << "Total Initial distance square = " << sum << std::endl;
}
first = false;
return sum;
}
};
Int_t line3Dfit()
{
gStyle->SetOptStat(0);
gStyle->SetOptFit();
//double e = 0.1;
Int_t nd = 10000;
// double xmin = 0; double ymin = 0;
// double xmax = 10; double ymax = 10;
TGraph2D * gr = new TGraph2D();
// Fill the 2D graph
double p0[4] = {10,20,1,2};
// generate graph with the 3d points
for (Int_t N=0; N<nd; N++) {
double x,y,z = 0;
// Generate a random number
double t = gRandom->Uniform(0,10);
line(t,p0,x,y,z);
double err = 1;
// do a gaussian smearing around the points in all coordinates
x += gRandom->Gaus(0,err);
y += gRandom->Gaus(0,err);
z += gRandom->Gaus(0,err);
gr->SetPoint(N,x,y,z);
//dt->SetPointError(N,0,0,err);
}
// fit the graph now
ROOT::Fit::Fitter fitter;
// make the functor objet
SumDistance2 sdist(gr);
ROOT::Math::Functor fcn(sdist,4);
// set the function and the initial parameter values
double pStart[4] = {1,1,1,1};
fitter.SetFCN(fcn,pStart);
// set step sizes different than default ones (0.3 times parameter values)
for (int i = 0; i < 4; ++i) fitter.Config().ParSettings(i).SetStepSize(0.01);
bool ok = fitter.FitFCN();
if (!ok) {
Error("line3Dfit","Line3D Fit failed");
return 1;
}
const ROOT::Fit::FitResult & result = fitter.Result();
std::cout << "Total final distance square " << result.MinFcnValue() << std::endl;
result.Print(std::cout);
gr->Draw("p0");
// get fit parameters
const double * parFit = result.GetParams();
// draw the fitted line
int n = 1000;
double t0 = 0;
double dt = 10;
TPolyLine3D *l = new TPolyLine3D(n);
for (int i = 0; i <n;++i) {
double t = t0+ dt*i/n;
double x,y,z;
line(t,parFit,x,y,z);
l->SetPoint(i,x,y,z);
}
l->SetLineColor(kRed);
l->Draw("same");
// draw original line
TPolyLine3D *l0 = new TPolyLine3D(n);
for (int i = 0; i <n;++i) {
double t = t0+ dt*i/n;
double x,y,z;
line(t,p0,x,y,z);
l0->SetPoint(i,x,y,z);
}
l0->SetLineColor(kBlue);
l0->Draw("same");
return 0;
}
int main() {
return line3Dfit();
}
<|endoftext|> |
<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* Halide code.
Func blurxy(Func input, Func blur_y) {
Func blur_x;
Var x, y, xi, yi;
// The algorithm - no storage or order
blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))/3;
blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))/3;
// The schedule - defines order, locality; implies storage
blur_y.tile(x, y, xi, yi, 256, 32)
.vectorize(xi, 8).parallel(y);
blur_x.compute_at(blur_y, x).vectorize(x, 8);
}
*/
#define SIZE0 1280
#define SIZE1 768
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
global::set_loop_iterator_type(p_int32);
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
/*
* Declare a function blurxy.
* Declare two arguments (tiramisu buffers) for the function: b_input and b_blury
* Declare an invariant for the function.
*/
function blurxy("blurxy");
constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &blurxy);
constant p1("M", expr((int32_t) SIZE1), p_int32, true, NULL, 0, &blurxy);
// Declare a wrapper around the input.
computation c_input("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &blurxy);
var i("i"), j("j"), i0("i0"), i1("i1"), j0("j0"), j1("j1");
// Declare the computations c_blurx and c_blury.
expr e1 = (c_input(i - 1, j) +
c_input(i , j) +
c_input(i + 1, j)) / ((uint8_t) 3);
computation c_blurx("[N,M]->{c_blurx[i,j]: 0<i<N and 0<j<M}", e1, true, p_uint8, &blurxy);
expr e2 = (c_blurx(i, j - 1) +
c_blurx(i, j) +
c_blurx(i, j + 1)) / ((uint8_t) 3);
computation c_blury("[N,M]->{c_blury[i,j]: 1<i<N-1 and 1<j<M-1}", e2, true, p_uint8, &blurxy);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Set the schedule of each computation.
// The identity schedule means that the program order is not modified
// (i.e. no optimization is applied).
c_blurx.tile(i, j, 2, 2, i0, j0, i1, j1);
c_blurx.tag_parallel_level(i0, j0);
c_blury.after(c_blurx, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_input("b_input", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_input, &blurxy);
buffer b_blury("b_blury", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_output, &blurxy);
buffer b_blurx("b_blurx", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_temporary, &blurxy);
// Map the computations to a buffer.
c_input.set_access("{c_input[i,j]->b_input[i,j]}");
c_blurx.set_access("{c_blurx[i,j]->b_blurx[i,j]}");
c_blury.set_access("{c_blury[i,j]->b_blury[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Set the arguments to blurxy
blurxy.set_arguments({&b_input, &b_blury});
// Generate code
blurxy.gen_time_space_domain();
blurxy.gen_isl_ast();
blurxy.gen_halide_stmt();
blurxy.gen_halide_obj("build/generated_fct_tutorial_02.o");
// Some debugging
blurxy.dump_iteration_domain();
blurxy.dump_halide_stmt();
// Dump all the fields of the blurxy class.
blurxy.dump(true);
return 0;
}
<commit_msg>Update tutorial_02.cpp<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* Halide code.
Func blurxy(Func input, Func blur_y) {
Func blur_x;
Var x, y, xi, yi;
// The algorithm - no storage or order
blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))/3;
blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))/3;
// The schedule - defines order, locality; implies storage
blur_y.tile(x, y, xi, yi, 256, 32)
.vectorize(xi, 8).parallel(y);
blur_x.compute_at(blur_y, x).vectorize(x, 8);
}
*/
#define SIZE0 1280
#define SIZE1 768
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
global::set_loop_iterator_type(p_int32);
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
/*
* Declare a function blurxy.
* Declare two arguments (tiramisu buffers) for the function: b_input and b_blury
* Declare an invariant for the function.
*/
function blurxy("blurxy");
constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &blurxy);
constant p1("M", expr((int32_t) SIZE1), p_int32, true, NULL, 0, &blurxy);
// Declare a wrapper around the input.
computation c_input("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &blurxy);
var i("i"), j("j"), i0("i0"), i1("i1"), j0("j0"), j1("j1");
// Declare the computations c_blurx and c_blury.
expr e1 = (c_input(i - 1, j) +
c_input(i , j) +
c_input(i + 1, j)) / ((uint8_t) 3);
computation c_blurx("[N,M]->{c_blurx[i,j]: 0<i<N and 0<j<M}", e1, true, p_uint8, &blurxy);
expr e2 = (c_blurx(i, j - 1) +
c_blurx(i, j) +
c_blurx(i, j + 1)) / ((uint8_t) 3);
computation c_blury("[N,M]->{c_blury[i,j]: 1<i<N-1 and 1<j<M-1}", e2, true, p_uint8, &blurxy);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Set the schedule of each computation.
c_blurx.tile(i, j, 2, 2, i0, j0, i1, j1);
c_blurx.tag_parallel_level(i0, j0);
c_blury.after(c_blurx, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_input("b_input", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_input, &blurxy);
buffer b_blury("b_blury", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_output, &blurxy);
buffer b_blurx("b_blurx", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE1)}, p_uint8, a_temporary, &blurxy);
// Map the computations to a buffer.
c_input.set_access("{c_input[i,j]->b_input[i,j]}");
c_blurx.set_access("{c_blurx[i,j]->b_blurx[i,j]}");
c_blury.set_access("{c_blury[i,j]->b_blury[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Set the arguments to blurxy
blurxy.set_arguments({&b_input, &b_blury});
// Generate code
blurxy.gen_time_space_domain();
blurxy.gen_isl_ast();
blurxy.gen_halide_stmt();
blurxy.gen_halide_obj("build/generated_fct_tutorial_02.o");
// Some debugging
blurxy.dump_iteration_domain();
blurxy.dump_halide_stmt();
// Dump all the fields of the blurxy class.
blurxy.dump(true);
return 0;
}
<|endoftext|> |
<commit_before>#include "GameEngine.h"
#include "Direction.h"
#include "EndGameEvent.h"
#include "Stage.h"
static const PhysicalObject::SpeedVector kZeroSpeedVector { Speed(0), Speed(0) };
static const PhysicalObject::AccelerationVector kZeroAccelerationVector { Acceleration(0), Acceleration(0) };
GameEngine::GameEngine()
{
}
void GameEngine::RegistrateObject(PhysicalObject* actor)
{
ground_actors_.push_back(actor);
}
void GameEngine::CheckGraySquareActorLocation(PhysicalObject* actor,
const PhysicalObject::Point& old_location,
const PhysicalObject::Point& new_location)
{
Direction horisontal_direction = Direction::kNotChanged;
Direction vertical_direction = Direction::kNotChanged;
// Check end game (fall)
if ((new_location.y + actor->GetSize().y) >= oxygine::getStage()->getSize().y * kPixel)
{
EndGameEvent ev;
oxygine::Stage::instance->dispatchEvent(&ev);
}
if (old_location.x < new_location.x) {
horisontal_direction = Direction::kRight;
}
else if (old_location.x > new_location.x) {
horisontal_direction = Direction::kLeft;
}
if (old_location.y < new_location.y) {
vertical_direction = Direction::kDown;
}
else if (old_location.y > new_location.y) {
vertical_direction = Direction::kUp;
}
Distance new_x(actor->GetLocation().x.Value());
Distance new_y(actor->GetLocation().y.Value());
bool is_touched_horizontally = false;
bool is_touched_vertically = false;
Distance actor_old_upper_bound = old_location.y;
Distance actor_new_upper_bound = new_location.y;
Distance actor_old_lower_bound = old_location.y + actor->GetSize().y;
Distance actor_new_lower_bound = new_location.y + actor->GetSize().y;
Distance actor_left_bound = new_location.x;
Distance actor_right_bound = new_location.x + actor->GetSize().x;
Distance actor_old_left_bound = old_location.x;
Distance actor_old_right_bound = old_location.x + actor->GetSize().x;
for (PhysicalObject* barrier: ground_actors_)
{
Distance barrier_right_bound = barrier->GetLocation().x + barrier->GetSize().x;
Distance barrier_left_bound = barrier->GetLocation().x;
Distance barrier_upper_bound = barrier->GetLocation().y;
Distance barrier_lower_bound = barrier->GetLocation().y + barrier->GetSize().y;
// Set Y value
switch (vertical_direction)
{
case Direction::kUp:
if (barrier_lower_bound > actor_new_upper_bound &&
barrier_lower_bound <= actor_old_upper_bound &&
((actor_left_bound >= barrier_left_bound &&
actor_left_bound < barrier_right_bound) ||
(actor_right_bound <= barrier_right_bound &&
actor_right_bound > barrier_left_bound) ||
(actor_left_bound < barrier_left_bound &&
actor_right_bound > barrier_right_bound)))
{
is_touched_vertically = true;
if (new_y < barrier_lower_bound)
{
new_y = barrier_lower_bound;
}
}
break;
case Direction::kDown:
if (barrier_upper_bound < actor_new_lower_bound &&
barrier_upper_bound >= actor_old_lower_bound &&
((actor_left_bound >= barrier_left_bound &&
actor_left_bound < barrier_right_bound) ||
(actor_right_bound <= barrier_right_bound &&
actor_right_bound > barrier_left_bound) ||
(actor_left_bound < barrier_left_bound &&
actor_right_bound > barrier_right_bound)))
{
is_touched_vertically = true;
if (new_y > barrier_upper_bound - actor->GetSize().y)
{
new_y = barrier_upper_bound - actor->GetSize().y;
}
}
break;
}
// Set X value
switch (horisontal_direction)
{
case Direction::kRight:
if (barrier_left_bound < actor_right_bound &&
barrier_left_bound >= actor_old_right_bound &&
((actor_new_upper_bound >= barrier_upper_bound &&
actor_new_upper_bound < barrier_lower_bound) ||
(actor_new_lower_bound > barrier_upper_bound &&
actor_new_lower_bound <= barrier_lower_bound) ||
(actor_new_upper_bound < barrier_upper_bound &&
actor_new_lower_bound > barrier_lower_bound)))
{
is_touched_horizontally = true;
if (new_x > (barrier_left_bound - actor->GetSize().x))
{
new_x = barrier_left_bound - actor->GetSize().x;
}
}
break;
case Direction::kLeft:
if (barrier_right_bound > actor_left_bound &&
barrier_right_bound <= actor_old_left_bound &&
((actor_new_upper_bound >= barrier_upper_bound &&
actor_new_upper_bound < barrier_lower_bound) ||
(actor_new_lower_bound > barrier_upper_bound &&
actor_new_lower_bound <= barrier_lower_bound) ||
(actor_new_upper_bound < barrier_upper_bound &&
actor_new_lower_bound > barrier_lower_bound)))
{
is_touched_horizontally = true;
if (new_x < barrier_right_bound)
{
new_x = barrier_right_bound;
}
}
break;
}
}
if (is_touched_horizontally || is_touched_vertically)
{
PhysicalObject::Point new_location(new_x, new_y);
actor->SetLocation(new_location);
}
if (is_touched_horizontally)
{
actor->SetSpeed({ Speed(0), actor->GetSpeed().y });
actor->SetAcceleration({ Acceleration(0), actor->GetAcceleration().y });
}
if (is_touched_vertically)
{
actor->SetSpeed({ actor->GetSpeed().x, Speed(0) });
actor->SetAcceleration({ actor->GetAcceleration().x, Acceleration(0) });
}
return;
}
void GameEngine::Reset()
{
ground_actors_.clear();
}
GameEngine& GameEngine::GetInstance()
{
static GameEngine instance;
return instance;
}<commit_msg>Formatted code with default VS formatting<commit_after>#include "GameEngine.h"
#include "Direction.h"
#include "EndGameEvent.h"
#include "Stage.h"
static const PhysicalObject::SpeedVector kZeroSpeedVector{ Speed(0), Speed(0) };
static const PhysicalObject::AccelerationVector kZeroAccelerationVector{ Acceleration(0), Acceleration(0) };
GameEngine::GameEngine()
{
}
void GameEngine::RegistrateObject(PhysicalObject* actor)
{
ground_actors_.push_back(actor);
}
void GameEngine::CheckGraySquareActorLocation(PhysicalObject* actor,
const PhysicalObject::Point& old_location,
const PhysicalObject::Point& new_location)
{
Direction horisontal_direction = Direction::kNotChanged;
Direction vertical_direction = Direction::kNotChanged;
// Check end game (fall)
if ((new_location.y + actor->GetSize().y) >= oxygine::getStage()->getSize().y * kPixel)
{
EndGameEvent ev;
oxygine::Stage::instance->dispatchEvent(&ev);
}
if (old_location.x < new_location.x) {
horisontal_direction = Direction::kRight;
}
else if (old_location.x > new_location.x) {
horisontal_direction = Direction::kLeft;
}
if (old_location.y < new_location.y) {
vertical_direction = Direction::kDown;
}
else if (old_location.y > new_location.y) {
vertical_direction = Direction::kUp;
}
Distance new_x(actor->GetLocation().x.Value());
Distance new_y(actor->GetLocation().y.Value());
bool is_touched_horizontally = false;
bool is_touched_vertically = false;
Distance actor_old_upper_bound = old_location.y;
Distance actor_new_upper_bound = new_location.y;
Distance actor_old_lower_bound = old_location.y + actor->GetSize().y;
Distance actor_new_lower_bound = new_location.y + actor->GetSize().y;
Distance actor_left_bound = new_location.x;
Distance actor_right_bound = new_location.x + actor->GetSize().x;
Distance actor_old_left_bound = old_location.x;
Distance actor_old_right_bound = old_location.x + actor->GetSize().x;
for (PhysicalObject* barrier : ground_actors_)
{
Distance barrier_right_bound = barrier->GetLocation().x + barrier->GetSize().x;
Distance barrier_left_bound = barrier->GetLocation().x;
Distance barrier_upper_bound = barrier->GetLocation().y;
Distance barrier_lower_bound = barrier->GetLocation().y + barrier->GetSize().y;
// Set Y value
switch (vertical_direction)
{
case Direction::kUp:
if (barrier_lower_bound > actor_new_upper_bound &&
barrier_lower_bound <= actor_old_upper_bound &&
((actor_left_bound >= barrier_left_bound &&
actor_left_bound < barrier_right_bound) ||
(actor_right_bound <= barrier_right_bound &&
actor_right_bound > barrier_left_bound) ||
(actor_left_bound < barrier_left_bound &&
actor_right_bound > barrier_right_bound)))
{
is_touched_vertically = true;
if (new_y < barrier_lower_bound)
{
new_y = barrier_lower_bound;
}
}
break;
case Direction::kDown:
if (barrier_upper_bound < actor_new_lower_bound &&
barrier_upper_bound >= actor_old_lower_bound &&
((actor_left_bound >= barrier_left_bound &&
actor_left_bound < barrier_right_bound) ||
(actor_right_bound <= barrier_right_bound &&
actor_right_bound > barrier_left_bound) ||
(actor_left_bound < barrier_left_bound &&
actor_right_bound > barrier_right_bound)))
{
is_touched_vertically = true;
if (new_y > barrier_upper_bound - actor->GetSize().y)
{
new_y = barrier_upper_bound - actor->GetSize().y;
}
}
break;
}
// Set X value
switch (horisontal_direction)
{
case Direction::kRight:
if (barrier_left_bound < actor_right_bound &&
barrier_left_bound >= actor_old_right_bound &&
((actor_new_upper_bound >= barrier_upper_bound &&
actor_new_upper_bound < barrier_lower_bound) ||
(actor_new_lower_bound > barrier_upper_bound &&
actor_new_lower_bound <= barrier_lower_bound) ||
(actor_new_upper_bound < barrier_upper_bound &&
actor_new_lower_bound > barrier_lower_bound)))
{
is_touched_horizontally = true;
if (new_x > (barrier_left_bound - actor->GetSize().x))
{
new_x = barrier_left_bound - actor->GetSize().x;
}
}
break;
case Direction::kLeft:
if (barrier_right_bound > actor_left_bound &&
barrier_right_bound <= actor_old_left_bound &&
((actor_new_upper_bound >= barrier_upper_bound &&
actor_new_upper_bound < barrier_lower_bound) ||
(actor_new_lower_bound > barrier_upper_bound &&
actor_new_lower_bound <= barrier_lower_bound) ||
(actor_new_upper_bound < barrier_upper_bound &&
actor_new_lower_bound > barrier_lower_bound)))
{
is_touched_horizontally = true;
if (new_x < barrier_right_bound)
{
new_x = barrier_right_bound;
}
}
break;
}
}
if (is_touched_horizontally || is_touched_vertically)
{
PhysicalObject::Point new_location(new_x, new_y);
actor->SetLocation(new_location);
}
if (is_touched_horizontally)
{
actor->SetSpeed({ Speed(0), actor->GetSpeed().y });
actor->SetAcceleration({ Acceleration(0), actor->GetAcceleration().y });
}
if (is_touched_vertically)
{
actor->SetSpeed({ actor->GetSpeed().x, Speed(0) });
actor->SetAcceleration({ actor->GetAcceleration().x, Acceleration(0) });
}
return;
}
void GameEngine::Reset()
{
ground_actors_.clear();
}
GameEngine& GameEngine::GetInstance()
{
static GameEngine instance;
return instance;
}<|endoftext|> |
<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* CSR SpMV.
for (i = 0; i < M; i++)
for (j = row_start[i]; j<row_start[i+1]; j++)
{
y[i] += values[j] * x[col_idx[j]];
}
*/
/* CSR SpMV Simplified.
for (i = 0; i < M; i++)
int b0 = row_start[i];
int b1 = row_start[i+1];
for (j = b0; j < b1; j++)
{
int t = col_idx[j];
y[i] += values[j] * x[t];
}
*/
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
global::set_loop_iterator_type(p_int32);
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
function spmv("spmv");
expr e_M = expr((int32_t) SIZE0);
constant M("M", e_M, p_int32, true, NULL, 0, &spmv);
computation c_row_start("[M]->{c_row_start[i]: 0<=i<M}", expr(), false, p_uint8, &spmv);
computation c_col_idx("[b0,b1]->{c_col_idx[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_values("[b0,b1]->{c_values[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_x("[M,b0,b1]->{c_x[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_y("[M,b0,b1]->{c_y[i,j]: 0<=i<M and b0<=j<b1}", expr(), true, p_uint8, &spmv);
spmv.set_context_set("[M,b0,b1]->{: M>0 and b0>0 and b1>0 and b1>b0 and b1%4=0}");
expr e_t = c_col_idx(var("j"));
constant t("t", e_t, p_int32, false, &c_y, 1, &spmv);
expr e_b1 = c_row_start(var("i") + 1);
constant b1("b1", e_b1, p_int32, false, &t, 0, &spmv);
expr e_b0 = c_row_start(var("i"));
constant b0("b0", e_b0, p_int32, false, &b1, 0, &spmv);
expr e_y = c_y(var("i")) + c_values(var("j")) * c_x(var("t"));
c_y.set_expression(e_y);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
b0.set_low_level_schedule("[M]->{b0[i]->b0[0,0,i,0,0,0]: 0<=i<M}");
b1.set_low_level_schedule("[M]->{b1[i]->b1[0,0,i,1,0,0]: 0<=i<M}");
t.set_low_level_schedule("[M,b0,b1]->{t[i,j]->t[0,0,i,2,j1,1,j2,0]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and b0<=j<(b1/4) and b1%4=0 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1; t[i,j]->t[0,0,i,2,j1,0,j2,0]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and (b1/4)<=j<b1 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1;}");
c_y.set_low_level_schedule("[M,b0,b1]->{c_y[i,j]->c_y[0,0,i,2,j1,1,j2,1]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and b0<=j<(b1/4) and b1%4=0 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1; c_y[i,j]->c_y[0,0,i,2,j1,0,j2,1]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and (b1/4)<=j<b1 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1;}");
c_y.tag_parallel_level(var("i"));
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_row_start("b_row_start", {tiramisu::expr(SIZE0)}, p_uint8, a_input, &spmv);
buffer b_col_idx("b_col_idx", {tiramisu::expr(SIZE0)}, p_uint8, a_input, &spmv);
buffer b_values("b_values", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_input, &spmv);
buffer b_x("b_x", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_input, &spmv);
buffer b_y("b_y", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_output, &spmv);
c_row_start.set_access("{c_row_start[i]->b_row_start[i]}");
c_col_idx.set_access("{c_col_idx[j]->b_col_idx[j]}");
c_values.set_access("{c_values[j]->b_values[j]}");
c_x.set_access("{c_x[j]->b_x[j]}");
c_y.set_access("{c_y[i,j]->b_y[i]}");
// -------------------------------------------------------
// Code Generator
// -------------------------------------------------------
spmv.set_arguments({&b_row_start, &b_col_idx, &b_values, &b_x, &b_y});
spmv.gen_time_space_domain();
spmv.gen_isl_ast();
spmv.gen_halide_stmt();
spmv.gen_halide_obj("build/generated_fct_tutorial_04.o");
// Some debugging
spmv.dump_halide_stmt();
return 0;
}
<commit_msg>Update tutorial_04.cpp<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* CSR SpMV.
for (i = 0; i < M; i++)
for (j = row_start[i]; j<row_start[i+1]; j++)
{
y[i] += values[j] * x[col_idx[j]];
}
*/
/* CSR SpMV Simplified.
for (i = 0; i < M; i++)
int b0 = row_start[i];
int b1 = row_start[i+1];
for (j = b0; j < b1; j++)
{
int t = col_idx[j];
y[i] += values[j] * x[t];
}
*/
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
function spmv("spmv");
expr e_M = expr((int32_t) SIZE0);
constant M("M", e_M, p_int32, true, NULL, 0, &spmv);
computation c_row_start("[M]->{c_row_start[i]: 0<=i<M}", expr(), false, p_uint8, &spmv);
computation c_col_idx("[b0,b1]->{c_col_idx[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_values("[b0,b1]->{c_values[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_x("[M,b0,b1]->{c_x[j]: b0<=j<b1}", expr(), false, p_uint8, &spmv);
computation c_y("[M,b0,b1]->{c_y[i,j]: 0<=i<M and b0<=j<b1}", expr(), true, p_uint8, &spmv);
spmv.set_context_set("[M,b0,b1]->{: M>0 and b0>0 and b1>0 and b1>b0 and b1%4=0}");
expr e_t = c_col_idx(var("j"));
constant t("t", e_t, p_int32, false, &c_y, 1, &spmv);
expr e_b1 = c_row_start(var("i") + 1);
constant b1("b1", e_b1, p_int32, false, &t, 0, &spmv);
expr e_b0 = c_row_start(var("i"));
constant b0("b0", e_b0, p_int32, false, &b1, 0, &spmv);
expr e_y = c_y(var("i")) + c_values(var("j")) * c_x(var("t"));
c_y.set_expression(e_y);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
b0.set_low_level_schedule("[M]->{b0[i]->b0[0,0,i,0,0,0]: 0<=i<M}");
b1.set_low_level_schedule("[M]->{b1[i]->b1[0,0,i,1,0,0]: 0<=i<M}");
t.set_low_level_schedule("[M,b0,b1]->{t[i,j]->t[0,0,i,2,j1,1,j2,0]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and b0<=j<(b1/4) and b1%4=0 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1; t[i,j]->t[0,0,i,2,j1,0,j2,0]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and (b1/4)<=j<b1 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1;}");
c_y.set_low_level_schedule("[M,b0,b1]->{c_y[i,j]->c_y[0,0,i,2,j1,1,j2,1]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and b0<=j<(b1/4) and b1%4=0 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1; c_y[i,j]->c_y[0,0,i,2,j1,0,j2,1]: j1= floor(j/4) and j2 = (j%4) and 0<=i<M and (b1/4)<=j<b1 and b1>b0 and b1>1 and b0>=1 and b1>=b0+1;}");
c_y.tag_parallel_level(var("i"));
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_row_start("b_row_start", {tiramisu::expr(SIZE0)}, p_uint8, a_input, &spmv);
buffer b_col_idx("b_col_idx", {tiramisu::expr(SIZE0)}, p_uint8, a_input, &spmv);
buffer b_values("b_values", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_input, &spmv);
buffer b_x("b_x", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_input, &spmv);
buffer b_y("b_y", {tiramisu::expr(SIZE0 * SIZE0)}, p_uint8, a_output, &spmv);
c_row_start.set_access("{c_row_start[i]->b_row_start[i]}");
c_col_idx.set_access("{c_col_idx[j]->b_col_idx[j]}");
c_values.set_access("{c_values[j]->b_values[j]}");
c_x.set_access("{c_x[j]->b_x[j]}");
c_y.set_access("{c_y[i,j]->b_y[i]}");
// -------------------------------------------------------
// Code Generator
// -------------------------------------------------------
spmv.set_arguments({&b_row_start, &b_col_idx, &b_values, &b_x, &b_y});
spmv.gen_time_space_domain();
spmv.gen_isl_ast();
spmv.gen_halide_stmt();
spmv.gen_halide_obj("build/generated_fct_tutorial_04.o");
// Some debugging
spmv.dump_halide_stmt();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright Joshua Boyce 2010-2012.
// 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)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
#pragma once
#include <memory>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/config.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/module.hpp"
namespace hadesmem
{
class Process;
namespace detail
{
struct ModuleIteratorImpl;
}
// Boost.Iterator causes the following warning under GCC:
// error: base class 'class boost::iterator_facade<hadesmem::ModuleIterator,
// hadesmem::Module, boost::single_pass_traversal_tag>' has a non-virtual
// destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
class ModuleIterator :
public boost::iterator_facade<
ModuleIterator,
Module,
boost::single_pass_traversal_tag
>
{
public:
ModuleIterator() BOOST_NOEXCEPT;
ModuleIterator(Process const& process);
private:
friend class boost::iterator_core_access;
typedef boost::iterator_facade<
ModuleIterator,
Module,
boost::single_pass_traversal_tag
> ModuleIteratorFacade;
ModuleIteratorFacade::reference dereference() const;
void increment();
bool equal(ModuleIterator const& other) const BOOST_NOEXCEPT;
std::shared_ptr<detail::ModuleIteratorImpl> impl_;
};
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic pop
#endif // #if defined(HADESMEM_GCC)
}
<commit_msg>* [module_iterator] Notes about InputIterator concept compliance.<commit_after>// Copyright Joshua Boyce 2010-2012.
// 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)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
#pragma once
#include <memory>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/config.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/module.hpp"
namespace hadesmem
{
class Process;
namespace detail
{
struct ModuleIteratorImpl;
}
// Boost.Iterator causes the following warning under GCC:
// error: base class 'class boost::iterator_facade<hadesmem::ModuleIterator,
// hadesmem::Module, boost::single_pass_traversal_tag>' has a non-virtual
// destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// ModuleIterator satisfies the requirements of an input iterator
// (C++ Standard, 24.2.1, Input Iterators [input.iterators]).
class ModuleIterator :
public boost::iterator_facade<
ModuleIterator,
Module,
boost::single_pass_traversal_tag
>
{
public:
ModuleIterator() BOOST_NOEXCEPT;
ModuleIterator(Process const& process);
private:
friend class boost::iterator_core_access;
typedef boost::iterator_facade<
ModuleIterator,
Module,
boost::single_pass_traversal_tag
> ModuleIteratorFacade;
ModuleIteratorFacade::reference dereference() const;
void increment();
bool equal(ModuleIterator const& other) const BOOST_NOEXCEPT;
std::shared_ptr<detail::ModuleIteratorImpl> impl_;
};
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic pop
#endif // #if defined(HADESMEM_GCC)
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory_resource>
#include "nova_renderer/memory/bytes.hpp"
#include "nova_renderer/memory/host_memory_resource.hpp"
#include "block_allocation_strategy.hpp"
namespace nova::mem {
template <typename AllocatedType = std::byte>
class AllocatorHandle : public std::pmr::polymorphic_allocator<AllocatedType> {
public:
AllocatorHandle() = default;
explicit AllocatorHandle(std::pmr::memory_resource* memory);
AllocatorHandle(const AllocatorHandle& other) = delete;
AllocatorHandle& operator=(const AllocatorHandle& other) = delete;
AllocatorHandle(AllocatorHandle&& old) noexcept = default;
AllocatorHandle& operator=(AllocatorHandle&& old) noexcept = default;
virtual ~AllocatorHandle() = default;
/*!
* \brief Allocates and constructs an object of the specified type
*
* Would be nice if C++ came with this method, but nope not yet
*/
template <typename... Args>
AllocatedType* new_object(Args&&... args);
/*!
* \brief Allocates an object of a different type than what this allocator normally created
*
* Intended use case is that you have a byte allocator that you allocate a few different object types from
*/
template <typename ObjectType, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
ObjectType* allocate_object();
/*!
* \brief Allocates a shared pointer that uses this allocator to allocate its internal memory
*
* \param deleter A functor that you want to use to delete the object
* \param args Any arguments to forward to the new object's constructor
*
* \return A shared pointer to the new object
*/
template <typename ObjectType,
typename DeleterType,
typename... Args,
typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
std::shared_ptr<ObjectType> allocate_shared(DeleterType deleter, Args&&... args);
/*!
* \brief Allocates and constructs an object of a different type
*
* Intended use case is that you have a byte allocator that you use to create objects of different types
*/
template <typename ObjectType, typename... Args, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
ObjectType* new_other_object(Args&&... args);
/*!
* \brief Creates a new allocator which will allocate a subsection of the total memory
*
* \param size The size of the memory which the suballocator will own
*/
template <typename ObjectType, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
AllocatorHandle<ObjectType>* create_suballocator(Bytes size);
};
template <typename AllocatedType>
AllocatorHandle<AllocatedType>::AllocatorHandle(std::pmr::memory_resource* memory)
: std::pmr::polymorphic_allocator<AllocatedType>(memory) {}
template <typename AllocatedType>
template <typename... Args>
AllocatedType* AllocatorHandle<AllocatedType>::new_object(Args&&... args) {
auto* mem = this->allocate(1);
this->construct(mem, args...);
return mem;
}
template <typename AllocatedType>
template <typename ObjectType, typename>
ObjectType* AllocatorHandle<AllocatedType>::allocate_object() {
auto* mem = this->allocate(sizeof(ObjectType));
return static_cast<ObjectType*>(mem);
}
template <typename AllocatedType>
template <typename ObjectType, typename DeleterType, typename... Args, typename>
std::shared_ptr<ObjectType> AllocatorHandle<AllocatedType>::allocate_shared(DeleterType deleter, Args&&... args) {
const auto ptr = allocate_object<ObjectType>(std::forward(args)...);
return std::shared_ptr<ObjectType>(ptr, deleter, std::pmr::polymorphic_allocator<std::byte>(this->resource()));
}
template <typename AllocatedType>
template <typename ObjectType, typename... Args, typename>
ObjectType* AllocatorHandle<AllocatedType>::new_other_object(Args&&... args) {
auto* mem = this->allocate(sizeof(ObjectType));
return new(mem) ObjectType(std::forward<Args>(args)...);
}
template <typename AllocatedType>
template <typename ObjectType, typename>
AllocatorHandle<ObjectType>* AllocatorHandle<AllocatedType>::create_suballocator(const Bytes size) {
auto* mem = this->allocate(size.b_count());
auto* mem_res = this->template new_other_object<HostMemoryResource<BlockAllocationStrategy>>(mem, size, nullptr);
return new_other_object<AllocatorHandle<ObjectType>>(mem_res);
}
} // namespace nova::mem
<commit_msg>[allocators] more better suballocator creation<commit_after>#pragma once
#include <memory_resource>
#include "nova_renderer/memory/bytes.hpp"
#include "nova_renderer/memory/host_memory_resource.hpp"
#include "block_allocation_strategy.hpp"
namespace nova::mem {
template <typename AllocatedType = std::byte>
class AllocatorHandle : public std::pmr::polymorphic_allocator<AllocatedType> {
public:
AllocatorHandle() = default;
explicit AllocatorHandle(std::pmr::memory_resource* memory);
AllocatorHandle(const AllocatorHandle& other) = delete;
AllocatorHandle& operator=(const AllocatorHandle& other) = delete;
AllocatorHandle(AllocatorHandle&& old) noexcept = default;
AllocatorHandle& operator=(AllocatorHandle&& old) noexcept = default;
virtual ~AllocatorHandle() = default;
/*!
* \brief Allocates and constructs an object of the specified type
*
* Would be nice if C++ came with this method, but nope not yet
*/
template <typename... Args>
AllocatedType* new_object(Args&&... args);
/*!
* \brief Allocates an object of a different type than what this allocator normally created
*
* Intended use case is that you have a byte allocator that you allocate a few different object types from
*/
template <typename ObjectType, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
ObjectType* allocate_object();
/*!
* \brief Allocates a shared pointer that uses this allocator to allocate its internal memory
*
* \param deleter A functor that you want to use to delete the object
* \param args Any arguments to forward to the new object's constructor
*
* \return A shared pointer to the new object
*/
template <typename ObjectType,
typename DeleterType,
typename... Args,
typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
std::shared_ptr<ObjectType> allocate_shared(DeleterType deleter, Args&&... args);
/*!
* \brief Allocates and constructs an object of a different type
*
* Intended use case is that you have a byte allocator that you use to create objects of different types
*/
template <typename ObjectType, typename... Args, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
ObjectType* new_other_object(Args&&... args);
/*!
* \brief Creates a new allocator which will allocate a subsection of the total memory
*
* \param size The size of the memory which the suballocator will own
*/
template <typename ObjectType, typename = std::enable_if_t<std::is_same_v<AllocatedType, std::byte>>>
AllocatorHandle<ObjectType>* create_suballocator(Bytes size);
};
template<typename AllocatedType = std::byte>
AllocatorHandle<AllocatedType> get_malloc_allocator() {
return AllocatorHandle<AllocatedType>(std::pmr::new_delete_resource());
}
template <typename AllocatedType>
AllocatorHandle<AllocatedType>::AllocatorHandle(std::pmr::memory_resource* memory)
: std::pmr::polymorphic_allocator<AllocatedType>(memory) {}
template <typename AllocatedType>
template <typename... Args>
AllocatedType* AllocatorHandle<AllocatedType>::new_object(Args&&... args) {
auto* mem = this->allocate(1);
this->construct(mem, args...);
return mem;
}
template <typename AllocatedType>
template <typename ObjectType, typename>
ObjectType* AllocatorHandle<AllocatedType>::allocate_object() {
auto* mem = this->allocate(sizeof(ObjectType));
return static_cast<ObjectType*>(mem);
}
template <typename AllocatedType>
template <typename ObjectType, typename DeleterType, typename... Args, typename>
std::shared_ptr<ObjectType> AllocatorHandle<AllocatedType>::allocate_shared(DeleterType deleter, Args&&... args) {
const auto ptr = allocate_object<ObjectType>(std::forward(args)...);
return std::shared_ptr<ObjectType>(ptr, deleter, std::pmr::polymorphic_allocator<std::byte>(this->resource()));
}
template <typename AllocatedType>
template <typename ObjectType, typename... Args, typename>
ObjectType* AllocatorHandle<AllocatedType>::new_other_object(Args&&... args) {
auto* mem = this->allocate(sizeof(ObjectType));
return new(mem) ObjectType(std::forward<Args>(args)...);
}
template <typename AllocatedType>
template <typename ObjectType, typename>
AllocatorHandle<ObjectType>* AllocatorHandle<AllocatedType>::create_suballocator(const Bytes size) {
auto* allocation_strategy = new_other_object<BlockAllocationStrategy>(get_malloc_allocator(), size);
auto* mem = this->allocate(size.b_count());
auto* mem_res = this->template new_other_object<HostMemoryResource<BlockAllocationStrategy>>(mem, size, allocation_strategy);
return new_other_object<AllocatorHandle<ObjectType>>(mem_res);
}
} // namespace nova::mem
<|endoftext|> |
<commit_before>#include "gtest.h"
#include "proposer.h"
class ProposerTest : public testing::Test {
protected:
int id;
int instances;
struct proposer* p;
virtual void SetUp() {
id = 2;
instances = 100;
p = proposer_new(id, instances);
}
virtual void TearDown() { }
};
TEST_F(ProposerTest, Prepare) {
int count = 10;
prepare_req pr;
for (int i = 0; i < count; ++i) {
pr = proposer_prepare(p);
ASSERT_EQ(pr.iid, i+1);
ASSERT_EQ(pr.ballot, id + MAX_N_OF_PROPOSERS);
}
ASSERT_EQ(count, proposer_prepared_count(p));
}
TEST_F(ProposerTest, PrepareAndAccept) {
prepare_req pr;
prepare_ack pa;
accept_req* ar;
accept_ack aa;
pr = proposer_prepare(p);
// aid, iid, bal, val_bal, val_size
pa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
pa = (prepare_ack) {2, pr.iid, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
// we have no value to propose!
ASSERT_EQ(proposer_accept(p), (void*)NULL);
proposer_propose(p, (char*)"value", 6);
ar = proposer_accept(p);
ASSERT_NE(ar, (accept_req*)NULL);
ASSERT_EQ(ar->iid, pr.iid);
ASSERT_EQ(ar->ballot, pr.ballot);
ASSERT_EQ(ar->value_size, 6);
ASSERT_STREQ(ar->value, "value");
// aid, iid, bal, val_bal, final, size
prepare_req* req;
aa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, 0};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
aa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, 0};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
}
TEST_F(ProposerTest, PreparePreempted) {
prepare_req pr;
prepare_ack pa;
prepare_req* pr_preempt;
accept_req* ar;
char value[] = "some value";
int value_size = strlen(value) + 1;
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
// preempt! proposer receives a different ballot...
pa = (prepare_ack) {1, pr.iid, pr.ballot+1, 0, 0};
pr_preempt = proposer_receive_prepare_ack(p, &pa);
ASSERT_NE((void*)NULL, pr_preempt);
ASSERT_EQ(pr_preempt->iid, pr.iid);
ASSERT_GT(pr_preempt->ballot, pr.ballot);
pa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
ASSERT_EQ(ar->iid, pr_preempt->iid);
ASSERT_EQ(ar->ballot, pr_preempt->ballot);
ASSERT_EQ(ar->value_size, value_size);
ASSERT_STREQ(ar->value, value);
free(ar);
free(pr_preempt);
}
TEST_F(ProposerTest, AcceptPreempted) {
prepare_req pr;
prepare_ack pa;
prepare_req* pr_preempt;
accept_req* ar;
accept_ack aa;
char value[] = "some value";
int value_size = strlen(value) + 1;
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
pa = (prepare_ack) {0, pr.iid, pr.ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
// preempt! proposer receives accept nack
aa = (accept_ack) {0, ar->iid, ar->ballot+1, 0, 0, 0};
pr_preempt = proposer_receive_accept_ack(p, &aa);
ASSERT_NE((void*)NULL, pr_preempt);
ASSERT_EQ(pr_preempt->iid, pr.iid);
ASSERT_GT(pr_preempt->ballot, ar->ballot);
free(ar);
// finally acquire the instance
pa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
// accept again
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
ASSERT_EQ(pr_preempt->iid, ar->iid);
ASSERT_EQ(pr_preempt->ballot, ar->ballot);
ASSERT_EQ(value_size, ar->value_size);
ASSERT_STREQ(value, ar->value);
aa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, value_size};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
aa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, value_size};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
free(ar);
free(pr_preempt);
}
TEST_F(ProposerTest, ProposedCount) {
int count = 10;
prepare_req pr;
prepare_ack pa;
accept_req* ar;
char value[] = "a value";
int value_size = strlen(value) + 1;
for (size_t i = 0; i < count; ++i) {
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
ASSERT_EQ(i + 1, proposer_prepared_count(p));
}
for (size_t i = 0; i < count; ++i)
proposer_accept(p);
ASSERT_EQ(count, proposer_prepared_count(p));
for (size_t i = 0; i < count; ++i) {
pa = (prepare_ack) {0, i+1, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
pa = (prepare_ack) {1, i+1, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
ar = proposer_accept(p);
free(ar);
ASSERT_EQ(count-(i+1), proposer_prepared_count(p));
}
}
<commit_msg>Changes the name of test ProposedCount to PreparedCount.<commit_after>#include "gtest.h"
#include "proposer.h"
class ProposerTest : public testing::Test {
protected:
int id;
int instances;
struct proposer* p;
virtual void SetUp() {
id = 2;
instances = 100;
p = proposer_new(id, instances);
}
virtual void TearDown() { }
};
TEST_F(ProposerTest, Prepare) {
int count = 10;
prepare_req pr;
for (int i = 0; i < count; ++i) {
pr = proposer_prepare(p);
ASSERT_EQ(pr.iid, i+1);
ASSERT_EQ(pr.ballot, id + MAX_N_OF_PROPOSERS);
}
ASSERT_EQ(count, proposer_prepared_count(p));
}
TEST_F(ProposerTest, PrepareAndAccept) {
prepare_req pr;
prepare_ack pa;
accept_req* ar;
accept_ack aa;
pr = proposer_prepare(p);
// aid, iid, bal, val_bal, val_size
pa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
pa = (prepare_ack) {2, pr.iid, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
// we have no value to propose!
ASSERT_EQ(proposer_accept(p), (void*)NULL);
proposer_propose(p, (char*)"value", 6);
ar = proposer_accept(p);
ASSERT_NE(ar, (accept_req*)NULL);
ASSERT_EQ(ar->iid, pr.iid);
ASSERT_EQ(ar->ballot, pr.ballot);
ASSERT_EQ(ar->value_size, 6);
ASSERT_STREQ(ar->value, "value");
// aid, iid, bal, val_bal, final, size
prepare_req* req;
aa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, 0};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
aa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, 0};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
}
TEST_F(ProposerTest, PreparePreempted) {
prepare_req pr;
prepare_ack pa;
prepare_req* pr_preempt;
accept_req* ar;
char value[] = "some value";
int value_size = strlen(value) + 1;
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
// preempt! proposer receives a different ballot...
pa = (prepare_ack) {1, pr.iid, pr.ballot+1, 0, 0};
pr_preempt = proposer_receive_prepare_ack(p, &pa);
ASSERT_NE((void*)NULL, pr_preempt);
ASSERT_EQ(pr_preempt->iid, pr.iid);
ASSERT_GT(pr_preempt->ballot, pr.ballot);
pa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
ASSERT_EQ(ar->iid, pr_preempt->iid);
ASSERT_EQ(ar->ballot, pr_preempt->ballot);
ASSERT_EQ(ar->value_size, value_size);
ASSERT_STREQ(ar->value, value);
free(ar);
free(pr_preempt);
}
TEST_F(ProposerTest, AcceptPreempted) {
prepare_req pr;
prepare_ack pa;
prepare_req* pr_preempt;
accept_req* ar;
accept_ack aa;
char value[] = "some value";
int value_size = strlen(value) + 1;
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
pa = (prepare_ack) {0, pr.iid, pr.ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
// preempt! proposer receives accept nack
aa = (accept_ack) {0, ar->iid, ar->ballot+1, 0, 0, 0};
pr_preempt = proposer_receive_accept_ack(p, &aa);
ASSERT_NE((void*)NULL, pr_preempt);
ASSERT_EQ(pr_preempt->iid, pr.iid);
ASSERT_GT(pr_preempt->ballot, ar->ballot);
free(ar);
// finally acquire the instance
pa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
pa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};
ASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);
// accept again
ar = proposer_accept(p);
ASSERT_NE(ar, (void*)NULL);
ASSERT_EQ(pr_preempt->iid, ar->iid);
ASSERT_EQ(pr_preempt->ballot, ar->ballot);
ASSERT_EQ(value_size, ar->value_size);
ASSERT_STREQ(value, ar->value);
aa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, value_size};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
aa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, value_size};
ASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);
free(ar);
free(pr_preempt);
}
TEST_F(ProposerTest, PreparedCount) {
int count = 10;
prepare_req pr;
prepare_ack pa;
accept_req* ar;
char value[] = "a value";
int value_size = strlen(value) + 1;
for (size_t i = 0; i < count; ++i) {
pr = proposer_prepare(p);
proposer_propose(p, value, value_size);
ASSERT_EQ(i + 1, proposer_prepared_count(p));
}
for (size_t i = 0; i < count; ++i)
proposer_accept(p);
ASSERT_EQ(count, proposer_prepared_count(p));
for (size_t i = 0; i < count; ++i) {
pa = (prepare_ack) {0, i+1, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
pa = (prepare_ack) {1, i+1, pr.ballot, 0, 0};
proposer_receive_prepare_ack(p, &pa);
ar = proposer_accept(p);
free(ar);
ASSERT_EQ(count-(i+1), proposer_prepared_count(p));
}
}
<|endoftext|> |
<commit_before>#include "OStreamServerLog.h"
#include <iostream>
using namespace HTTP::ServerLog;
const char *GetMethodName(HTTP::METHOD Method)
{
switch (Method)
{
case HTTP::METHOD_GET: return "GET ";
case HTTP::METHOD_POST: return "POST";
case HTTP::METHOD_HEAD: return "HEAD";
default: return "-";
}
}
void OStream::OnConnection(void *Connection, unsigned int SourceAddr, bool IsAllowed)
{
if (IsAllowed)
{
ConnDataHolder &CurrHolder=ConnMap[Connection];
char AddrBuff[20];
sprintf(AddrBuff,"%u.%u.%u.%u",
(SourceAddr >> 24),
(SourceAddr >> 16) & 0xFF,
(SourceAddr >> 8) & 0xFF,
(SourceAddr >> 0) & 0xFF);
CurrHolder.SourceAddr=AddrBuff;
CurrHolder.SourceAddr.append((4*3+3)-CurrHolder.SourceAddr.length(),' ');
}
}
void OStream::OnConnectionFinished(void *Connection)
{
boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);
if (FindI!=ConnMap.end())
{
if (FindI->second.IsWebSocket)
{
TargetS <<
FindI->second.SourceAddr << " WebSocketClose" <<
std::endl;
}
ConnMap.erase(FindI);
}
}
void OStream::OnRequest(void *Connection, HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA,
unsigned long long ContentLength, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
unsigned int ResponseCode, unsigned long long ResponseLength, void *UpgradeConn)
{
ConnDataHolder &CurrHolder=ConnMap[Connection];
TargetS <<
CurrHolder.SourceAddr << " " <<
GetMethodName(Method) << " " <<
Resource << " (" << ContentLength << "): "
<< ResponseCode << " (" << ResponseLength << ")" <<
std::endl;
if ((UpgradeConn) && (CurrHolder.IsWebSocket))
ConnMap[UpgradeConn]=CurrHolder;
}
void OStream::OnWebSocket(void *Connection, const std::string &Resource, bool IsSuccess, const char *Origin, const char *SubProtocol)
{
if (IsSuccess)
{
ConnDataHolder &CurrHolder=ConnMap[Connection];
TargetS <<
CurrHolder.SourceAddr << " WebSocket " <<
(Origin ? Origin : "") << ": " <<
(SubProtocol ? SubProtocol : "-") <<
std::endl;
CurrHolder.IsWebSocket=true;
}
}
<commit_msg>OStream::OnRequest: websocket logging fix<commit_after>#include "OStreamServerLog.h"
#include <iostream>
using namespace HTTP::ServerLog;
const char *GetMethodName(HTTP::METHOD Method)
{
switch (Method)
{
case HTTP::METHOD_GET: return "GET ";
case HTTP::METHOD_POST: return "POST";
case HTTP::METHOD_HEAD: return "HEAD";
default: return "-";
}
}
void OStream::OnConnection(void *Connection, unsigned int SourceAddr, bool IsAllowed)
{
if (IsAllowed)
{
ConnDataHolder &CurrHolder=ConnMap[Connection];
char AddrBuff[20];
sprintf(AddrBuff,"%u.%u.%u.%u",
(SourceAddr >> 24),
(SourceAddr >> 16) & 0xFF,
(SourceAddr >> 8) & 0xFF,
(SourceAddr >> 0) & 0xFF);
CurrHolder.SourceAddr=AddrBuff;
CurrHolder.SourceAddr.append((4*3+3)-CurrHolder.SourceAddr.length(),' ');
}
}
void OStream::OnConnectionFinished(void *Connection)
{
boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);
if (FindI!=ConnMap.end())
{
if (FindI->second.IsWebSocket)
{
TargetS <<
FindI->second.SourceAddr << " WebSocketClose" <<
std::endl;
}
ConnMap.erase(FindI);
}
}
void OStream::OnRequest(void *Connection, HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA,
unsigned long long ContentLength, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
unsigned int ResponseCode, unsigned long long ResponseLength, void *UpgradeConn)
{
boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);
if (FindI!=ConnMap.end())
{
TargetS <<
FindI->second.SourceAddr << " " <<
GetMethodName(Method) << " " <<
Resource << " (" << ContentLength << "): "
<< ResponseCode << " (" << ResponseLength << ")" <<
std::endl;
if ((UpgradeConn) && (FindI->second.IsWebSocket))
{
ConnMap[UpgradeConn]=FindI->second;
ConnMap.erase(FindI);
}
}
}
void OStream::OnWebSocket(void *Connection, const std::string &Resource, bool IsSuccess, const char *Origin, const char *SubProtocol)
{
if (IsSuccess)
{
ConnDataHolder &CurrHolder=ConnMap[Connection];
TargetS <<
CurrHolder.SourceAddr << " WebSocket " <<
(Origin ? Origin : "") << ": " <<
(SubProtocol ? SubProtocol : "-") <<
std::endl;
CurrHolder.IsWebSocket=true;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperBoolParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperTypes.h"
#include "otbWrapperApplication.h"
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl;
return EXIT_FAILURE;
}
using namespace otb::Wrapper;
const std::string module(argv[1]);
/* TestApplication is removed in CMakeLists.txt */
#if 0
if (module == "TestApplication")
return EXIT_SUCCESS;
#endif
ApplicationRegistry::AddApplicationPath(argv[2]);
Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str());
assert(!appli.IsNull());
std::map<ParameterType, std::string> parameterTypeToString;
parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean";
parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean";
parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice";
parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString";
parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer";
parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile";
parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer";
parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination";
parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination";
parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination";
parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile";
// TODO
parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString";
// ListView parameters are treated as plain string (QLineEdit) in qgis processing ui.
// This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB
// We tried to push something simple with checkboxes but its too risky for this version
// and clock is ticking...
parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString";
// For next update of plugin code ListView should use a custom widget wrapper and behave
// exactly like OTB Mapla. And this #if 0 block is our TODO remainder.
#if 0
parameterTypeToString[ParameterType_ListView] = "OTBParameterListView";
#endif
const std::vector<std::string> appKeyList = appli->GetParametersKeys(true);
const unsigned int nbOfParam = appKeyList.size();
std::string output_file = module + ".txt";
std::string algs_txt = "algs.txt";
if (argc > 3)
{
output_file = std::string(argv[3]) + module + ".txt";
algs_txt = std::string(argv[3]) + "algs.txt";
}
std::ofstream dFile;
dFile.open (output_file, std::ios::out);
std::cerr << "Writing " << output_file << std::endl;
std::string output_parameter_name;
bool hasRasterOutput = false;
{
for (unsigned int i = 0; i < nbOfParam; i++)
{
Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]);
if (param->GetMandatory())
{
ParameterType type = appli->GetParameterType(appKeyList[i]);
if (type == ParameterType_OutputImage )
{
output_parameter_name = appKeyList[i];
hasRasterOutput = true;
}
}
}
}
if(output_parameter_name.empty())
dFile << module << std::endl;
else
dFile << module << "|" << output_parameter_name << std::endl;
dFile << appli->GetDescription() << std::endl;
const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED";
dFile << group << std::endl;
for (unsigned int i = 0; i < nbOfParam; i++)
{
const std::string name = appKeyList[i];
Parameter::Pointer param = appli->GetParameterByKey(name);
ParameterType type = appli->GetParameterType(name);
const std::string description = param->GetName();
std::string qgis_type = parameterTypeToString[type];
#if 0
if (type == ParameterType_ListView)
{
ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer());
std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl;
if (lv_param->GetSingleSelection())
{
qgis_type = "QgsProcessingParameterEnum";
std::vector<std::string> key_list = appli->GetChoiceKeys(name);
std::string values = "";
for( auto k : key_list)
values += k + ";";
values.pop_back();
dFile << "|" << values ;
}
}
#endif
if ( type == ParameterType_Group ||
type == ParameterType_OutputProcessXML ||
type == ParameterType_InputProcessXML ||
type == ParameterType_RAM ||
param->GetRole() == Role_Output
)
{
// group parameter cannot have any value.
// outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy
// ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps
// parameter role cannot be of type Role_Output
continue;
}
assert(!qgis_type.empty());
if(qgis_type.empty())
{
std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl;
return EXIT_FAILURE;
}
bool isDestination = false;
bool isEpsgCode = false;
// use QgsProcessingParameterCrs if required.
// TODO: do a regex on name to match ==epsg || *\.epsg.\*
if ( name == "epsg"
|| name == "map.epsg.code"
|| name == "mapproj.epsg.code"
|| name == "mode.epsg.code")
{
qgis_type = "QgsProcessingParameterCrs";
isEpsgCode = true;
}
dFile << qgis_type << "|" << name << "|" << description;
std::string default_value = "None";
if (type == ParameterType_Int)
{
if (isEpsgCode)
{
if (param->HasValue() && appli->GetParameterInt(name) < 1)
default_value = "EPSG: " + appli->GetParameterAsString(name);
else
default_value = "ProjectCrs";
}
else
{
dFile << "|QgsProcessingParameterNumber.Integer";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
}
else if (type == ParameterType_Float)
{
dFile << "|QgsProcessingParameterNumber.Double";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
else if (type == ParameterType_Radius)
{
dFile << "|QgsProcessingParameterNumber.Integer";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
else if(type == ParameterType_InputFilename)
{
dFile << "|QgsProcessingParameterFile.File|txt";
}
else if(type == ParameterType_Directory)
{
dFile << "|QgsProcessingParameterFile.Folder|False";
}
else if (type == ParameterType_InputImageList)
{
dFile << "|3";
}
else if (type == ParameterType_InputVectorDataList)
{
dFile << "|-1";
}
else if (type == ParameterType_InputVectorData)
{
dFile << "|-1";
}
else if(type == ParameterType_InputFilenameList)
{
dFile << "|4";
}
else if (type == ParameterType_InputImage)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_String)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_StringList)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_ListView)
{
// default is None and nothing to add to dFile
}
else if(type == ParameterType_Bool)
{
default_value = appli->GetParameterAsString(name);
}
else if(type == ParameterType_Choice)
{
std::vector<std::string> key_list = appli->GetChoiceKeys(name);
std::string values = "";
for( auto k : key_list)
values += k + ";";
values.pop_back();
dFile << "|" << values ;
ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer());
default_value = std::to_string(cparam->GetValue());
}
else if(type == ParameterType_OutputVectorData ||
type == ParameterType_OutputImage ||
type == ParameterType_OutputFilename)
{
// No need for default_value, optional and extra fields in dFile.
// If parameter is a destination type. qgis_type|name|description is enough.
// So we simply set isDestination to true and skip to end to append a new line.
isDestination = true;
}
else
{
std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl;
return EXIT_FAILURE;
}
if (!isDestination)
{
std::string optional;
if (param->GetMandatory())
{
// type == ParameterType_StringList check is needed because:
//
// If parameter is mandatory it can have no value
// It is accepted in OTB that, string list could be generated dynamically
// qgis has no such option to handle dynamic values yet..
// So mandatory parameters whose type is StringList is considered optional
optional = param->HasValue() || type == ParameterType_StringList ? "True" : "False";
}
else
{
optional = "True";
}
dFile << "|" << default_value << "|" << optional;
}
dFile << std::endl;
}
if(hasRasterOutput)
{
dFile << "*QgsProcessingParameterEnum|outputpixeltype|Output pixel type|unit8;int;float;double|False|2|True" << std::endl;
}
dFile.close();
std::ofstream indexFile;
indexFile.open (algs_txt, std::ios::out | std::ios::app );
indexFile << group << "|" << module << std::endl;
indexFile.close();
std::cerr << "Updated " << algs_txt << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>TEST: comment debug info<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperBoolParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperTypes.h"
#include "otbWrapperApplication.h"
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl;
return EXIT_FAILURE;
}
using namespace otb::Wrapper;
const std::string module(argv[1]);
/* TestApplication is removed in CMakeLists.txt */
#if 0
if (module == "TestApplication")
return EXIT_SUCCESS;
#endif
ApplicationRegistry::AddApplicationPath(argv[2]);
Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str());
assert(!appli.IsNull());
std::map<ParameterType, std::string> parameterTypeToString;
parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean";
parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean";
parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber";
parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice";
parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString";
parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer";
parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile";
parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer";
parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers";
parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination";
parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination";
parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination";
parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile";
// TODO
parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString";
// ListView parameters are treated as plain string (QLineEdit) in qgis processing ui.
// This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB
// We tried to push something simple with checkboxes but its too risky for this version
// and clock is ticking...
parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString";
// For next update of plugin code ListView should use a custom widget wrapper and behave
// exactly like OTB Mapla. And this #if 0 block is our TODO remainder.
#if 0
parameterTypeToString[ParameterType_ListView] = "OTBParameterListView";
#endif
const std::vector<std::string> appKeyList = appli->GetParametersKeys(true);
const unsigned int nbOfParam = appKeyList.size();
std::string output_file = module + ".txt";
std::string algs_txt = "algs.txt";
if (argc > 3)
{
output_file = std::string(argv[3]) + module + ".txt";
algs_txt = std::string(argv[3]) + "algs.txt";
}
std::ofstream dFile;
dFile.open (output_file, std::ios::out);
std::cerr << "Writing " << output_file << std::endl;
std::string output_parameter_name;
bool hasRasterOutput = false;
{
for (unsigned int i = 0; i < nbOfParam; i++)
{
Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]);
if (param->GetMandatory())
{
ParameterType type = appli->GetParameterType(appKeyList[i]);
if (type == ParameterType_OutputImage )
{
output_parameter_name = appKeyList[i];
hasRasterOutput = true;
}
}
}
}
if(output_parameter_name.empty())
dFile << module << std::endl;
else
dFile << module << "|" << output_parameter_name << std::endl;
dFile << appli->GetDescription() << std::endl;
const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED";
dFile << group << std::endl;
for (unsigned int i = 0; i < nbOfParam; i++)
{
const std::string name = appKeyList[i];
Parameter::Pointer param = appli->GetParameterByKey(name);
ParameterType type = appli->GetParameterType(name);
const std::string description = param->GetName();
std::string qgis_type = parameterTypeToString[type];
#if 0
if (type == ParameterType_ListView)
{
ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer());
std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl;
if (lv_param->GetSingleSelection())
{
qgis_type = "QgsProcessingParameterEnum";
std::vector<std::string> key_list = appli->GetChoiceKeys(name);
std::string values = "";
for( auto k : key_list)
values += k + ";";
values.pop_back();
dFile << "|" << values ;
}
}
#endif
if ( type == ParameterType_Group ||
type == ParameterType_OutputProcessXML ||
type == ParameterType_InputProcessXML ||
type == ParameterType_RAM ||
param->GetRole() == Role_Output
)
{
// group parameter cannot have any value.
// outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy
// ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps
// parameter role cannot be of type Role_Output
continue;
}
assert(!qgis_type.empty());
if(qgis_type.empty())
{
std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl;
return EXIT_FAILURE;
}
bool isDestination = false;
bool isEpsgCode = false;
// use QgsProcessingParameterCrs if required.
// TODO: do a regex on name to match ==epsg || *\.epsg.\*
if ( name == "epsg"
|| name == "map.epsg.code"
|| name == "mapproj.epsg.code"
|| name == "mode.epsg.code")
{
qgis_type = "QgsProcessingParameterCrs";
isEpsgCode = true;
}
dFile << qgis_type << "|" << name << "|" << description;
std::string default_value = "None";
if (type == ParameterType_Int)
{
if (isEpsgCode)
{
if (param->HasValue() && appli->GetParameterInt(name) < 1)
default_value = "EPSG: " + appli->GetParameterAsString(name);
else
default_value = "ProjectCrs";
}
else
{
dFile << "|QgsProcessingParameterNumber.Integer";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
}
else if (type == ParameterType_Float)
{
dFile << "|QgsProcessingParameterNumber.Double";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
else if (type == ParameterType_Radius)
{
dFile << "|QgsProcessingParameterNumber.Integer";
default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
}
else if(type == ParameterType_InputFilename)
{
dFile << "|QgsProcessingParameterFile.File|txt";
}
else if(type == ParameterType_Directory)
{
dFile << "|QgsProcessingParameterFile.Folder|False";
}
else if (type == ParameterType_InputImageList)
{
dFile << "|3";
}
else if (type == ParameterType_InputVectorDataList)
{
dFile << "|-1";
}
else if (type == ParameterType_InputVectorData)
{
dFile << "|-1";
}
else if(type == ParameterType_InputFilenameList)
{
dFile << "|4";
}
else if (type == ParameterType_InputImage)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_String)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_StringList)
{
// default is None and nothing to add to dFile
}
else if(type ==ParameterType_ListView)
{
// default is None and nothing to add to dFile
}
else if(type == ParameterType_Bool)
{
default_value = appli->GetParameterAsString(name);
}
else if(type == ParameterType_Choice)
{
std::vector<std::string> key_list = appli->GetChoiceKeys(name);
std::string values = "";
for( auto k : key_list)
values += k + ";";
values.pop_back();
dFile << "|" << values ;
ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer());
default_value = std::to_string(cparam->GetValue());
}
else if(type == ParameterType_OutputVectorData ||
type == ParameterType_OutputImage ||
type == ParameterType_OutputFilename)
{
// No need for default_value, optional and extra fields in dFile.
// If parameter is a destination type. qgis_type|name|description is enough.
// So we simply set isDestination to true and skip to end to append a new line.
isDestination = true;
}
else
{
std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl;
return EXIT_FAILURE;
}
if (!isDestination)
{
std::string optional;
if (param->GetMandatory())
{
// type == ParameterType_StringList check is needed because:
//
// If parameter is mandatory it can have no value
// It is accepted in OTB that, string list could be generated dynamically
// qgis has no such option to handle dynamic values yet..
// So mandatory parameters whose type is StringList is considered optional
optional = param->HasValue() || type == ParameterType_StringList ? "True" : "False";
}
else
{
optional = "True";
}
#if 0
std::cerr << name;
std::cerr << " mandatory=" << param->GetMandatory();
std::cerr << " HasValue=" << param->HasValue();
std::cerr << " qgis_type=" << qgis_type;
std::cerr << "optional" << optional << std::endl;
#endif
dFile << "|" << default_value << "|" << optional;
}
dFile << std::endl;
}
if(hasRasterOutput)
{
dFile << "*QgsProcessingParameterEnum|outputpixeltype|Output pixel type|unit8;int;float;double|False|2|True" << std::endl;
}
dFile.close();
std::ofstream indexFile;
indexFile.open (algs_txt, std::ios::out | std::ios::app );
indexFile << group << "|" << module << std::endl;
indexFile.close();
std::cerr << "Updated " << algs_txt << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright 2022 The StableHLO Authors.
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 "stablehlo/reference/Element.h"
#include <complex>
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Support/DebugStringHelper.h"
namespace mlir {
namespace stablehlo {
namespace {
template <typename... Ts>
inline llvm::Error invalidArgument(char const *Fmt, const Ts &...Vals) {
return createStringError(llvm::errc::invalid_argument, Fmt, Vals...);
}
bool isSupportedUnsignedIntegerType(Type type) {
return type.isUnsignedInteger(4) || type.isUnsignedInteger(8) ||
type.isUnsignedInteger(16) || type.isUnsignedInteger(32) ||
type.isUnsignedInteger(64);
}
bool isSupportedSignedIntegerType(Type type) {
// TODO(#22): StableHLO, as bootstrapped from MHLO, inherits signless
// integers which was added in MHLO for legacy reasons. Going forward,
// StableHLO will adopt signfull integer semantics with signed and unsigned
// integer variants.
return type.isSignlessInteger(4) || type.isSignlessInteger(8) ||
type.isSignlessInteger(16) || type.isSignlessInteger(32) ||
type.isSignlessInteger(64);
}
bool isSupportedIntegerType(Type type) {
return isSupportedUnsignedIntegerType(type) ||
isSupportedSignedIntegerType(type);
}
bool isSupportedFloatType(Type type) {
return type.isF16() || type.isBF16() || type.isF32() || type.isF64();
}
bool isSupportedComplexType(Type type) {
auto complexTy = type.dyn_cast<mlir::ComplexType>();
if (!complexTy) return false;
auto complexElemTy = complexTy.getElementType();
return complexElemTy.isF32() || complexElemTy.isF64();
}
APFloat getFloatValue(Element element) {
return element.getValue().cast<FloatAttr>().getValue();
}
APInt getIntegerValue(Element element) {
return element.getValue().cast<IntegerAttr>().getValue();
}
std::complex<APFloat> getComplexValue(Element element) {
auto arryOfAttr = element.getValue().cast<ArrayAttr>().getValue();
return std::complex<APFloat>(arryOfAttr[0].cast<FloatAttr>().getValue(),
arryOfAttr[1].cast<FloatAttr>().getValue());
}
} // namespace
Element Element::operator+(const Element &other) const {
auto type = getType();
assert(type == other.getType());
if (isSupportedFloatType(type)) {
auto left = getFloatValue(*this);
auto right = getFloatValue(other);
return Element(type, FloatAttr::get(type, left + right));
}
if (isSupportedIntegerType(type)) {
auto left = getIntegerValue(*this);
auto right = getIntegerValue(other);
return Element(type, IntegerAttr::get(type, left + right));
}
if (isSupportedComplexType(type)) {
auto complexElemTy = type.cast<ComplexType>().getElementType();
auto leftComplexValue = getComplexValue(*this);
auto rightComplexValue = getComplexValue(other);
return Element(
type,
ArrayAttr::get(
type.getContext(),
{FloatAttr::get(complexElemTy,
leftComplexValue.real() + rightComplexValue.real()),
FloatAttr::get(complexElemTy, leftComplexValue.imag() +
rightComplexValue.imag())}));
}
// Report error.
auto err = invalidArgument("Unsupported element type: %s",
debugString(type).c_str());
report_fatal_error(std::move(err));
}
Element sine(const Element &e) {
Type type = e.getType();
if (isSupportedFloatType(type)) {
APFloat val = getFloatValue(e);
const llvm::fltSemantics &oldSemantics = val.getSemantics();
APFloat sinVal(std::sin(val.convertToDouble()));
bool roundingErr;
sinVal.convert(oldSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
return Element(type, FloatAttr::get(type, sinVal));
} else if (isSupportedComplexType(type)) {
auto complex = getComplexValue(e);
Type elementType = type.cast<ComplexType>().getElementType();
const llvm::fltSemantics &oldSemantics = complex.real().getSemantics();
std::complex<double> complexVal(complex.real().convertToDouble(),
complex.imag().convertToDouble());
std::complex<double> sinVal = std::sin(complexVal);
bool roundingErr;
APFloat realAPF(sinVal.real());
realAPF.convert(oldSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
APFloat imagAPF(sinVal.imag());
imagAPF.convert(oldSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
return Element(type,
ArrayAttr::get(type.getContext(),
{FloatAttr::get(elementType, realAPF),
FloatAttr::get(elementType, imagAPF)}));
}
// Report error.
auto err = invalidArgument("Unsupported element type: %s",
debugString(type).c_str());
report_fatal_error(std::move(err));
}
void Element::print(raw_ostream &os) const { value_.print(os); }
void Element::dump() const {
print(llvm::errs());
llvm::errs() << "\n";
}
} // namespace stablehlo
} // namespace mlir
<commit_msg>Generalize Element mapping logic (#190)<commit_after>/* Copyright 2022 The StableHLO Authors.
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 "stablehlo/reference/Element.h"
#include <complex>
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Support/DebugStringHelper.h"
namespace mlir {
namespace stablehlo {
namespace {
template <typename... Ts>
inline llvm::Error invalidArgument(char const *Fmt, const Ts &...Vals) {
return createStringError(llvm::errc::invalid_argument, Fmt, Vals...);
}
bool isSupportedUnsignedIntegerType(Type type) {
return type.isUnsignedInteger(4) || type.isUnsignedInteger(8) ||
type.isUnsignedInteger(16) || type.isUnsignedInteger(32) ||
type.isUnsignedInteger(64);
}
bool isSupportedSignedIntegerType(Type type) {
// TODO(#22): StableHLO, as bootstrapped from MHLO, inherits signless
// integers which was added in MHLO for legacy reasons. Going forward,
// StableHLO will adopt signfull integer semantics with signed and unsigned
// integer variants.
return type.isSignlessInteger(4) || type.isSignlessInteger(8) ||
type.isSignlessInteger(16) || type.isSignlessInteger(32) ||
type.isSignlessInteger(64);
}
bool isSupportedIntegerType(Type type) {
return isSupportedUnsignedIntegerType(type) ||
isSupportedSignedIntegerType(type);
}
bool isSupportedFloatType(Type type) {
return type.isF16() || type.isBF16() || type.isF32() || type.isF64();
}
bool isSupportedComplexType(Type type) {
auto complexTy = type.dyn_cast<mlir::ComplexType>();
if (!complexTy) return false;
auto complexElemTy = complexTy.getElementType();
return complexElemTy.isF32() || complexElemTy.isF64();
}
APFloat getFloatValue(Element element) {
return element.getValue().cast<FloatAttr>().getValue();
}
APInt getIntegerValue(Element element) {
return element.getValue().cast<IntegerAttr>().getValue();
}
std::complex<APFloat> getComplexValue(Element element) {
auto arryOfAttr = element.getValue().cast<ArrayAttr>().getValue();
return std::complex<APFloat>(arryOfAttr[0].cast<FloatAttr>().getValue(),
arryOfAttr[1].cast<FloatAttr>().getValue());
}
template <typename IntegerFn, typename FloatFn, typename ComplexFn>
Element map(const Element &el, IntegerFn integerFn, FloatFn floatFn,
ComplexFn complexFn) {
Type type = el.getType();
if (isSupportedIntegerType(type)) {
auto intEl = getIntegerValue(el);
return Element(type, IntegerAttr::get(type, integerFn(intEl)));
}
if (isSupportedFloatType(type)) {
auto floatEl = getFloatValue(el);
return Element(type, FloatAttr::get(type, floatFn(floatEl)));
}
if (isSupportedComplexType(type)) {
auto complexElemTy = type.cast<ComplexType>().getElementType();
auto complexEl = getComplexValue(el);
auto complexResult = complexFn(complexEl);
return Element(
type,
ArrayAttr::get(type.getContext(),
{FloatAttr::get(complexElemTy, complexResult.real()),
FloatAttr::get(complexElemTy, complexResult.imag())}));
}
report_fatal_error(invalidArgument("Unsupported element type: %s",
debugString(type).c_str()));
}
template <typename IntegerFn, typename FloatFn, typename ComplexFn>
Element map(const Element &lhs, const Element &rhs, IntegerFn integerFn,
FloatFn floatFn, ComplexFn complexFn) {
Type type = lhs.getType();
if (lhs.getType() != rhs.getType())
report_fatal_error(invalidArgument("Element types don't match: %s vs %s",
debugString(lhs.getType()).c_str(),
debugString(rhs.getType()).c_str()));
if (isSupportedIntegerType(type)) {
auto intLhs = getIntegerValue(lhs);
auto intRhs = getIntegerValue(rhs);
return Element(type, IntegerAttr::get(type, integerFn(intLhs, intRhs)));
}
if (isSupportedFloatType(type)) {
auto floatLhs = getFloatValue(lhs);
auto floatRhs = getFloatValue(rhs);
return Element(type, FloatAttr::get(type, floatFn(floatLhs, floatRhs)));
}
if (isSupportedComplexType(type)) {
auto complexElemTy = type.cast<ComplexType>().getElementType();
auto complexLhs = getComplexValue(lhs);
auto complexRhs = getComplexValue(rhs);
auto complexResult = complexFn(complexLhs, complexRhs);
return Element(
type,
ArrayAttr::get(type.getContext(),
{FloatAttr::get(complexElemTy, complexResult.real()),
FloatAttr::get(complexElemTy, complexResult.imag())}));
}
report_fatal_error(invalidArgument("Unsupported element type: %s",
debugString(type).c_str()));
}
template <typename FloatFn, typename ComplexFn>
Element mapWithUpcastToDouble(const Element &el, FloatFn floatFn,
ComplexFn complexFn) {
Type type = el.getType();
if (isSupportedFloatType(type)) {
APFloat elVal = getFloatValue(el);
const llvm::fltSemantics &elSemantics = elVal.getSemantics();
APFloat resultVal(floatFn(elVal.convertToDouble()));
bool roundingErr;
resultVal.convert(elSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
return Element(type, FloatAttr::get(type, resultVal));
}
if (isSupportedComplexType(type)) {
Type elType = type.cast<ComplexType>().getElementType();
auto elVal = getComplexValue(el);
const llvm::fltSemantics &elSemantics = elVal.real().getSemantics();
auto resultVal = complexFn(std::complex<double>(
elVal.real().convertToDouble(), elVal.imag().convertToDouble()));
bool roundingErr;
APFloat resultReal(resultVal.real());
resultReal.convert(elSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
APFloat resultImag(resultVal.imag());
resultImag.convert(elSemantics, APFloat::rmNearestTiesToEven, &roundingErr);
return Element(type, ArrayAttr::get(type.getContext(),
{FloatAttr::get(elType, resultReal),
FloatAttr::get(elType, resultImag)}));
}
report_fatal_error(invalidArgument("Unsupported element type: %s",
debugString(type).c_str()));
}
} // namespace
Element Element::operator+(const Element &other) const {
return map(
*this, other, [](APInt lhs, APInt rhs) { return lhs + rhs; },
[](APFloat lhs, APFloat rhs) { return lhs + rhs; },
[](std::complex<APFloat> lhs, std::complex<APFloat> rhs) {
// NOTE: lhs + rhs doesn't work for std::complex<APFloat>
// because the default implementation for the std::complex template
// needs operator+= which is not defined on APFloat.
auto resultReal = lhs.real() + rhs.real();
auto resultImag = lhs.imag() + rhs.imag();
return std::complex<APFloat>(resultReal, resultImag);
});
}
Element sine(const Element &e) {
return mapWithUpcastToDouble(
e, [](double e) { return std::sin(e); },
[](std::complex<double> e) { return std::sin(e); });
}
void Element::print(raw_ostream &os) const { value_.print(os); }
void Element::dump() const {
print(llvm::errs());
llvm::errs() << "\n";
}
} // namespace stablehlo
} // namespace mlir
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include <cling/Interpreter/Interpreter.h>
#include <cling/Interpreter/Value.h>
#include <iostream>
#include <string>
#include <sstream>
///\brief Pass a value from the compiled program into cling, let cling modify it
/// and return the modified value into the compiled program.
int setAndUpdate(int arg, cling::Interpreter& interp) {
int ret = arg; // The value that will be modified
// Update the value of ret by passing it to the interpreter.
std::ostringstream sstr;
sstr << "int& ref = *(int*)" << &ret << ';';
sstr << "ref = ref * ref;";
interp.process(sstr.str());
return ret;
}
///\brief A ridiculously complicated way of converting an int to a string.
std::unique_ptr<std::string> stringify(int value, cling::Interpreter& interp) {
// Declare the function to cling:
static const std::string codeFunc = R"CODE(
#include <string>
std::string* createAString(const char* str) {
return new std::string(str);
})CODE";
interp.declare(codeFunc);
// Call the function with "runtime" values:
std::ostringstream sstr;
sstr << "createAString(\"" << value << "\");";
cling::Value res; // Will hold the result of the expression evaluation.
interp.process(sstr.str(), &res);
// Grab the return value of `createAString()`:
std::string* resStr = static_cast<std::string*>(res.getPtr());
return std::unique_ptr<std::string>(resStr);
}
int main(int argc, const char* const* argv) {
// Create the Interpreter. LLVMDIR is provided as -D during compilation.
cling::Interpreter interp(argc, argv, LLVMDIR);
std::cout << "The square of 17 is " << setAndUpdate(17, interp) << '\n';
std::cout << "Printing a string of 42: " << *stringify(42, interp) << '\n';
return 0;
}
<commit_msg>More relevant / less obscure examples. Indent.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include <cling/Interpreter/Interpreter.h>
#include <cling/Interpreter/Value.h>
#include <cling/Utils/Casting.h>
#include <iostream>
#include <string>
#include <sstream>
/// Definitions of declarations injected also into cling.
/// NOTE: this could also stay in a header #included here and into cling, but
/// for the sake of simplicity we just redeclare them here.
int aGlobal = 42;
static float anotherGlobal = 3.141;
float getAnotherGlobal() { return anotherGlobal; };
void setAnotherGlobal(float val) { anotherGlobal = val; }
///\brief Call compiled functions from the interpreter.
void useHeader(cling::Interpreter& interp) {
// We could use a header, too...
interp.declare("int aGlobal;\n"
"float getAnotherGlobal();\n"
"void setAnotherGlobal(float val);\n");
cling::Value res; // Will hold the result of the expression evaluation.
interp.process("aGlobal;", &res);
std::cout << "aGlobal is " << res.getAs<long long>() << '\n';
interp.process("getAnotherGlobal();", &res);
std::cout << "getAnotherGlobal() returned " << res.getAs<float>() << '\n';
setAnotherGlobal(1.); // We modify the compiled value,
interp.process("getAnotherGlobal();", &res); // does the interpreter see it?
std::cout << "getAnotherGlobal() returned " << res.getAs<float>() << '\n';
// We modify using the interpreter, now the binary sees the new value.
interp.process("setAnotherGlobal(7.777); getAnotherGlobal();");
std::cout << "getAnotherGlobal() returned " << getAnotherGlobal() << '\n';
}
///\brief Call an interpreted function using its symbol address.
void useSymbolAddress(cling::Interpreter& interp) {
// Declare a function to the interpreter. Make it extern "C" to remove
// mangling from the game.
interp.declare("extern \"C\" int plutification(int siss, int sat) "
"{ return siss * sat; }");
void* addr = interp.getAddressOfGlobal("plutification");
using func_t = int(int, int);
func_t* pFunc = cling::utils::VoidToFunctionPtr<func_t*>(addr);
std::cout << "7 * 8 = " << pFunc(7, 8) << '\n';
}
///\brief Pass a pointer into cling as a string.
void usePointerLiteral(cling::Interpreter& interp) {
int res = 17; // The value that will be modified
// Update the value of res by passing it to the interpreter.
std::ostringstream sstr;
sstr << "int& ref = *(int*)" << &res << ';';
sstr << "ref = ref * ref;";
interp.process(sstr.str());
std::cout << "The square of 17 is " << res << '\n';
}
int main(int argc, const char* const* argv) {
// Create the Interpreter. LLVMDIR is provided as -D during compilation.
cling::Interpreter interp(argc, argv, LLVMDIR);
useHeader(interp);
useSymbolAddress(interp);
usePointerLiteral(interp);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUN_TO_VECTOR_HPP
#define STAN_MATH_REV_FUN_TO_VECTOR_HPP
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
namespace stan {
namespace math {
/**
* Cast a `var_value<Matrix>` to a `var_value<ColumnVector>`.
* @tparam EigMat Inner type of the `var_value` that must inherit from
* `Eigen::EigenBase`.
* @param x A var whose inner matrix type is to be cast to an Column matrix.
* @return A view of the original `x` with inner value and adjoint matrices
* mapped to a column vector.
*/
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline auto to_vector(const var_value<EigMat>& x) {
using view_type = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1>>;
return vari_view<view_type>(
view_type(x.vi_->val_.data(), x.rows() * x.cols()),
view_type(x.vi_->adj_.data(), x.rows() * x.cols()));
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fix docs<commit_after>#ifndef STAN_MATH_REV_FUN_TO_VECTOR_HPP
#define STAN_MATH_REV_FUN_TO_VECTOR_HPP
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
namespace stan {
namespace math {
/**
* Reshape a `var_value<Matrix>` to a `var_value<ColumnVector>`.
* @tparam EigMat Inner type of the `var_value` that must inherit from
* `Eigen::EigenBase`.
* @param x A var whose inner matrix type is to be cast to an Column matrix.
* @return A view of the original `x` with inner value and adjoint matrices
* mapped to a column vector.
*/
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline auto to_vector(const var_value<EigMat>& x) {
using view_type = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1>>;
return vari_view<view_type>(
view_type(x.vi_->val_.data(), x.rows() * x.cols()),
view_type(x.vi_->adj_.data(), x.rows() * x.cols()));
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>
#include "dirs.h"
#include <iostream>
#include <sstream>
#ifdef __WIN32__
#include <windows.h>
#include <shlwapi.h>
#include <shlobj.h>
#elif defined(__APPLE__)
#include <libproc.h>
#include <unistd.h>
#include <pwd.h>
#else
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
#include <boost/nowide/convert.hpp>
#include "processinfo.h"
#include "utils.h"
#include "appinfo.h"
using namespace std;
using namespace boost;
string Dirs::appDataDir()
{
static string p = "";
if (p != "")
return p;
string dir;
filesystem::path pa;
#ifdef __WIN32__
TCHAR buffer[MAX_PATH];
HRESULT ret = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, buffer);
if ( ! SUCCEEDED(ret))
{
stringstream ss;
ss << "App Data directory could not be retrieved (" << ret << ")";
throw Exception(ss.str());
}
dir = nowide::narrow(buffer);
dir += "/JASP/" + AppInfo::getShortDesc(false);//string(APP_VERSION);
pa = nowide::widen(dir);
#else
dir = string(getpwuid(getuid())->pw_dir);
dir += "/.JASP/" + AppInfo::getShortDesc(false)
pa = dir;
#endif
if ( ! filesystem::exists(pa))
{
system::error_code ec;
filesystem::create_directories(pa, ec);
if (ec)
{
stringstream ss;
ss << "App Data directory could not be created: " << dir;
throw Exception(ss.str());
}
}
p = filesystem::path(dir).generic_string();
return p;
}
string Dirs::tempDir()
{
static string p = "";
if (p != "")
return p;
string dir;
filesystem::path pa;
#ifdef __WIN32__
TCHAR buffer[MAX_PATH];
if ( ! SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, buffer)))
throw Exception("App Data directory could not be retrieved");
dir = nowide::narrow(buffer);
dir += "/JASP/temp";
pa = nowide::widen(dir);
#else
dir = string(getpwuid(getuid())->pw_dir);
dir += "/.JASP/temp";
pa = dir;
#endif
if ( ! filesystem::exists(pa))
{
system::error_code ec;
filesystem::create_directories(pa, ec);
if (ec)
{
stringstream ss;
ss << "Temp Data directory could not be created (" << ec << ") : " << dir;
throw Exception(ss.str());
}
}
p = filesystem::path(dir).generic_string();
return p;
}
string Dirs::exeDir()
{
static string p = "";
if (p != "")
return p;
#ifdef __WIN32__
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
int ret = GetModuleFileNameW(hModule, path, MAX_PATH);
if (ret == 0)
{
stringstream ss;
ss << "Executable directory could not be retrieved (" << ret << ")";
throw Exception(ss.str());
}
string r = nowide::narrow(path);
char pathbuf[MAX_PATH];
r.copy(pathbuf, MAX_PATH);
int last = 0;
for (int i = 0; i < r.length(); i++)
{
if (pathbuf[i] == '\\')
{
pathbuf[i] = '/';
last = i;
}
}
r = string(pathbuf, last);
p = r;
return r;
#elif defined(__APPLE__)
unsigned long pid = ProcessInfo::currentPID();
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
int ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
if (ret <= 0)
{
throw Exception("Executable directory could not be retrieved");
}
else
{
int last = strlen(pathbuf);
for (int i = last - 1; i > 0; i--)
{
if (pathbuf[i] == '/')
{
pathbuf[i] = '\0';
break;
}
}
p = string(pathbuf);
return p;
}
#else
char buf[512];
char linkname[512]; /* /proc/<pid>/exe */
pid_t pid;
int ret;
pid = getpid();
if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", pid) < 0)
throw Exception("Executable directory could not be retrieved");
ret = readlink(linkname, buf, sizeof(buf));
if (ret == -1)
throw Exception("Executable directory could not be retrieved");
if (ret >= sizeof(buf))
throw Exception("Executable directory could not be retrieved: insufficient buffer size");
for (int i = ret; i > 0; i--)
{
if (buf[i] == '/')
{
buf[i] = '\0'; // add null terminator
break;
}
}
return string(buf);
#endif
}
string Dirs::rHomeDir()
{
string dir = exeDir();
#ifdef __WIN32__
dir += "/R";
#elif __APPLE__
dir += "/../Frameworks/R.framework/Versions/3.1/Resources";
#else
dir += "/R";
#endif
return dir;
}
string Dirs::libraryDir()
{
string dir = exeDir();
#ifdef __WIN32__
dir += "/Library";
#elif __APPLE__
dir += "/../Resources/Library";
#else
dir += "/Library";
#endif
return dir;
}
<commit_msg>- missed a semi colon for linux<commit_after>
#include "dirs.h"
#include <iostream>
#include <sstream>
#ifdef __WIN32__
#include <windows.h>
#include <shlwapi.h>
#include <shlobj.h>
#elif defined(__APPLE__)
#include <libproc.h>
#include <unistd.h>
#include <pwd.h>
#else
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
#include <boost/nowide/convert.hpp>
#include "processinfo.h"
#include "utils.h"
#include "appinfo.h"
using namespace std;
using namespace boost;
string Dirs::appDataDir()
{
static string p = "";
if (p != "")
return p;
string dir;
filesystem::path pa;
#ifdef __WIN32__
TCHAR buffer[MAX_PATH];
HRESULT ret = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, buffer);
if ( ! SUCCEEDED(ret))
{
stringstream ss;
ss << "App Data directory could not be retrieved (" << ret << ")";
throw Exception(ss.str());
}
dir = nowide::narrow(buffer);
dir += "/JASP/" + AppInfo::getShortDesc(false);//string(APP_VERSION);
pa = nowide::widen(dir);
#else
dir = string(getpwuid(getuid())->pw_dir);
dir += "/.JASP/" + AppInfo::getShortDesc(false);
pa = dir;
#endif
if ( ! filesystem::exists(pa))
{
system::error_code ec;
filesystem::create_directories(pa, ec);
if (ec)
{
stringstream ss;
ss << "App Data directory could not be created: " << dir;
throw Exception(ss.str());
}
}
p = filesystem::path(dir).generic_string();
return p;
}
string Dirs::tempDir()
{
static string p = "";
if (p != "")
return p;
string dir;
filesystem::path pa;
#ifdef __WIN32__
TCHAR buffer[MAX_PATH];
if ( ! SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, buffer)))
throw Exception("App Data directory could not be retrieved");
dir = nowide::narrow(buffer);
dir += "/JASP/temp";
pa = nowide::widen(dir);
#else
dir = string(getpwuid(getuid())->pw_dir);
dir += "/.JASP/temp";
pa = dir;
#endif
if ( ! filesystem::exists(pa))
{
system::error_code ec;
filesystem::create_directories(pa, ec);
if (ec)
{
stringstream ss;
ss << "Temp Data directory could not be created (" << ec << ") : " << dir;
throw Exception(ss.str());
}
}
p = filesystem::path(dir).generic_string();
return p;
}
string Dirs::exeDir()
{
static string p = "";
if (p != "")
return p;
#ifdef __WIN32__
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
int ret = GetModuleFileNameW(hModule, path, MAX_PATH);
if (ret == 0)
{
stringstream ss;
ss << "Executable directory could not be retrieved (" << ret << ")";
throw Exception(ss.str());
}
string r = nowide::narrow(path);
char pathbuf[MAX_PATH];
r.copy(pathbuf, MAX_PATH);
int last = 0;
for (int i = 0; i < r.length(); i++)
{
if (pathbuf[i] == '\\')
{
pathbuf[i] = '/';
last = i;
}
}
r = string(pathbuf, last);
p = r;
return r;
#elif defined(__APPLE__)
unsigned long pid = ProcessInfo::currentPID();
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
int ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
if (ret <= 0)
{
throw Exception("Executable directory could not be retrieved");
}
else
{
int last = strlen(pathbuf);
for (int i = last - 1; i > 0; i--)
{
if (pathbuf[i] == '/')
{
pathbuf[i] = '\0';
break;
}
}
p = string(pathbuf);
return p;
}
#else
char buf[512];
char linkname[512]; /* /proc/<pid>/exe */
pid_t pid;
int ret;
pid = getpid();
if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", pid) < 0)
throw Exception("Executable directory could not be retrieved");
ret = readlink(linkname, buf, sizeof(buf));
if (ret == -1)
throw Exception("Executable directory could not be retrieved");
if (ret >= sizeof(buf))
throw Exception("Executable directory could not be retrieved: insufficient buffer size");
for (int i = ret; i > 0; i--)
{
if (buf[i] == '/')
{
buf[i] = '\0'; // add null terminator
break;
}
}
return string(buf);
#endif
}
string Dirs::rHomeDir()
{
string dir = exeDir();
#ifdef __WIN32__
dir += "/R";
#elif __APPLE__
dir += "/../Frameworks/R.framework/Versions/3.1/Resources";
#else
dir += "/R";
#endif
return dir;
}
string Dirs::libraryDir()
{
string dir = exeDir();
#ifdef __WIN32__
dir += "/Library";
#elif __APPLE__
dir += "/../Resources/Library";
#else
dir += "/Library";
#endif
return dir;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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 <boost/python.hpp>
# include <boost/python/module.hpp>
# include <boost/python/def.hpp>
# include <mapnik.hpp>
using mapnik::Image32;
using namespace boost::python;
PyObject* rawdata( Image32 const& im)
{
int size = im.width() * im.height() * 4;
return ::PyString_FromStringAndSize((const char*)im.raw_data(),size);
}
void export_image()
{
using namespace boost::python;
class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>())
.def("width",&Image32::width)
.def("height",&Image32::height)
;
def("rawdata",&rawdata);
}
<commit_msg>Make the background property of an Image available to Python.<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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 <boost/python.hpp>
# include <boost/python/module.hpp>
# include <boost/python/def.hpp>
# include <mapnik.hpp>
using mapnik::Image32;
using namespace boost::python;
PyObject* rawdata( Image32 const& im)
{
int size = im.width() * im.height() * 4;
return ::PyString_FromStringAndSize((const char*)im.raw_data(),size);
}
void export_image()
{
using namespace boost::python;
class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>())
.def("width",&Image32::width)
.def("height",&Image32::height)
.add_property("background",make_function
(&Image32::getBackground,return_value_policy<copy_const_reference>()),
&Image32::setBackground, "The background color of the image.")
;
def("rawdata",&rawdata);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: roottree.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:54:35 $
*
* 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 CONFIGMGR_ROOTTREE_HXX_
#define CONFIGMGR_ROOTTREE_HXX_
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
class SubtreeChange;
struct TreeChangeList;
//-----------------------------------------------------------------------------
namespace memory
{
class Segment;
class Accessor;
}
//-----------------------------------------------------------------------------
namespace data
{
class NodeAccess;
}
//-----------------------------------------------------------------------------
namespace configuration
{
//-----------------------------------------------------------------------------
class Tree; typedef Tree RootTree;
class TreeRef;
class TreeImpl;
class NodeRef;
class NodeChangesInformation;
class AbsolutePath;
class TemplateProvider;
typedef unsigned int NodeOffset;
typedef unsigned int TreeDepth;
//-----------------------------------------------------------------------------
RootTree createReadOnlyTree( AbsolutePath const& aRootPath,
memory::Segment const* _pDataSegment,
data::NodeAccess const& _aCacheNode,
TreeDepth nDepth,
TemplateProvider const& aTemplateProvider);
RootTree createUpdatableTree( AbsolutePath const& aRootPath,
memory::Segment const* _pDataSegment,
data::NodeAccess const& _aCacheNode,
TreeDepth nDepth,
TemplateProvider const& aTemplateProvider);
//-----------------------------------------------------------------------------
class CommitHelper : Noncopyable
{
struct Data;
std::auto_ptr<Data> m_pData;
TreeImpl* m_pTree;
public:
CommitHelper(TreeRef const& aTree);
~CommitHelper();
// collect all changes into rChangeList
bool prepareCommit(memory::Accessor const & _aAccessor, TreeChangeList& rChangeList);
// finish and clean up the changes in rChangeList after they are integrated
void finishCommit(memory::Accessor const & _aAccessor, TreeChangeList& rChangeList);
// restore the changes in rChangeList as pending
void revertCommit(memory::Accessor const & _aAccessor, TreeChangeList& rChangeList);
// throw away and clean up the changes in rChangeList after a commit failed
void failedCommit(memory::Accessor const & _aAccessor, TreeChangeList& rChangeList);
// dispose of auxiliary data for a commit operation
void reset();
};
//-----------------------------------------------------------------------------
/** adjusts <var>aTree</var> tree to the (externally produced) changes under <var>aExternalChanges</var>
and collects the changes this induces locally.
@param rLocalChanges
a collection that will hold the changes induced by <var>aExternalChanges</var>.
@param aExternalChanges
a structured change that has already been applied to the master tree.
@param aBaseTree
the Tree that contains (directly) the affected node of <var>aExternalChanges</var>.
@param aBaseNode
a NodeRef referring to the (directly) affected node of <var>aExternalChanges</var>.
@return
<TRUE/> if any changes occur in this tree (so rLocalChanges is not empty), <FALSE/> otherwise.
*/
bool adjustToChanges( NodeChangesInformation& rLocalChanges,
Tree const& aBaseTree, NodeRef const& aBaseNode,
SubtreeChange const& aExternalChange) ;
//-----------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_ROOTTREE_HXX_
<commit_msg>INTEGRATION: CWS configrefactor01 (1.12.84); FILE MERGED 2007/02/07 12:14:54 mmeeks 1.12.84.3: remove obsolete memory::Segment forward decls. 2007/01/16 12:18:21 mmeeks 1.12.84.2: Submitted by: mmeeks Kill 'memory::Segment' - no longer needed. Bin some other (empty / redundant) headers. 2007/01/12 14:50:44 mmeeks 1.12.84.1: Another big prune of memory::Accessor ...<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: roottree.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:23: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 CONFIGMGR_ROOTTREE_HXX_
#define CONFIGMGR_ROOTTREE_HXX_
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
class SubtreeChange;
struct TreeChangeList;
//-----------------------------------------------------------------------------
namespace data
{
class NodeAccess;
}
//-----------------------------------------------------------------------------
namespace configuration
{
//-----------------------------------------------------------------------------
class Tree; typedef Tree RootTree;
class TreeRef;
class TreeImpl;
class NodeRef;
class NodeChangesInformation;
class AbsolutePath;
class TemplateProvider;
typedef unsigned int NodeOffset;
typedef unsigned int TreeDepth;
//-----------------------------------------------------------------------------
RootTree createReadOnlyTree( AbsolutePath const& aRootPath,
data::NodeAccess const& _aCacheNode,
TreeDepth nDepth,
TemplateProvider const& aTemplateProvider);
RootTree createUpdatableTree( AbsolutePath const& aRootPath,
data::NodeAccess const& _aCacheNode,
TreeDepth nDepth,
TemplateProvider const& aTemplateProvider);
//-----------------------------------------------------------------------------
class CommitHelper : Noncopyable
{
struct Data;
std::auto_ptr<Data> m_pData;
TreeImpl* m_pTree;
public:
CommitHelper(TreeRef const& aTree);
~CommitHelper();
// collect all changes into rChangeList
bool prepareCommit(TreeChangeList& rChangeList);
// finish and clean up the changes in rChangeList after they are integrated
void finishCommit(TreeChangeList& rChangeList);
// restore the changes in rChangeList as pending
void revertCommit(TreeChangeList& rChangeList);
// throw away and clean up the changes in rChangeList after a commit failed
void failedCommit(TreeChangeList& rChangeList);
// dispose of auxiliary data for a commit operation
void reset();
};
//-----------------------------------------------------------------------------
/** adjusts <var>aTree</var> tree to the (externally produced) changes under <var>aExternalChanges</var>
and collects the changes this induces locally.
@param rLocalChanges
a collection that will hold the changes induced by <var>aExternalChanges</var>.
@param aExternalChanges
a structured change that has already been applied to the master tree.
@param aBaseTree
the Tree that contains (directly) the affected node of <var>aExternalChanges</var>.
@param aBaseNode
a NodeRef referring to the (directly) affected node of <var>aExternalChanges</var>.
@return
<TRUE/> if any changes occur in this tree (so rLocalChanges is not empty), <FALSE/> otherwise.
*/
bool adjustToChanges( NodeChangesInformation& rLocalChanges,
Tree const& aBaseTree, NodeRef const& aBaseNode,
SubtreeChange const& aExternalChange) ;
//-----------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_ROOTTREE_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: valueref.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:19:10 $
*
* 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 CONFIGMGR_CONFIGVALUEREF_HXX_
#define CONFIGMGR_CONFIGVALUEREF_HXX_
#ifndef CONFIGMGR_CONFIGNODE_HXX_
#include "noderef.hxx"
#endif
namespace configmgr
{
namespace node { struct Attributes; }
namespace configuration
{
//-------------------------------------------------------------------------
class Name;
//-------------------------------------------------------------------------
namespace argument { struct NoValidate; }
typedef com::sun::star::uno::Type UnoType;
typedef com::sun::star::uno::Any UnoAny;
//-------------------------------------------------------------------------
class TreeImpl;
typedef unsigned int NodeOffset;
//-------------------------------------------------------------------------
/// represents a value node in some tree
class ValueRef
{
public:
/// constructs an empty (invalid) node
ValueRef();
/// copy a node (with reference semantics)
ValueRef(ValueRef const& rOther);
/// copy a node (with reference semantics)
ValueRef& operator=(ValueRef const& rOther);
void swap(ValueRef& rOther);
~ValueRef();
/// checks, if this represents an existing node
inline bool isValid() const;
private:
friend class Tree;
friend class TreeImplHelper;
ValueRef(Name const& aName, NodeOffset nParentPos);
bool checkValidState() const;
private:
Name m_sNodeName;
NodeOffset m_nParentPos;
};
//-------------------------------------------------------------------------
/** extract the value from a plain value
*/
inline
UnoAny getSimpleValue(Tree const& aTree, ValueRef const& aNode)
{ return aTree.getNodeValue( aNode ); }
//-------------------------------------------------------------------------
inline bool ValueRef::isValid() const
{
OSL_ASSERT( m_nParentPos == 0 || checkValidState() );
return m_nParentPos != 0;
}
//-------------------------------------------------------------------------
class SubNodeID
{
public:
static SubNodeID createEmpty() { return SubNodeID(); }
SubNodeID(Tree const& rTree, ValueRef const& rNode);
SubNodeID(Tree const& rTree, NodeRef const& rParentNode, Name const& aName);
SubNodeID(TreeRef const& rTree, NodeRef const& rParentNode, Name const& aName);
SubNodeID(NodeID const& rParentNodeID, Name const& aName);
// comparison
// equality
friend bool operator==(SubNodeID const& lhs, SubNodeID const& rhs)
{ return lhs.m_aParentID == rhs.m_aParentID && lhs.m_sNodeName == rhs.m_sNodeName; }
// ordering
friend bool operator < (SubNodeID const& lhs, SubNodeID const& rhs);
// checking
bool isEmpty() const;
// checking
bool isValidNode(data::Accessor const& _accessor) const;
// hashing
size_t hashCode() const;
// containing node this
NodeID getParentID() const { return m_aParentID; }
// containing node this
Name getNodeName() const { return m_sNodeName; }
private:
SubNodeID(); // create an empty one
friend class TreeImplHelper;
Name m_sNodeName;
NodeID m_aParentID;
};
//-------------------------------------------------------------------------
typedef std::vector<SubNodeID> SubNodeIDList;
void getAllChildrenHelper(data::Accessor const& _aAccessor, NodeID const& aNode, SubNodeIDList& aList);
//-------------------------------------------------------------------------
inline bool operator!=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(lhs == rhs); }
//---------------------------------------------------------------------
inline bool operator>=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(lhs < rhs); }
//---------------------------------------------------------------------
inline bool operator > (SubNodeID const& lhs, SubNodeID const& rhs)
{ return (rhs < lhs); }
inline bool operator<=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(rhs < lhs); }
//-------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_CONFIGVALUENODE_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.194); FILE MERGED 2005/09/05 17:04:43 rt 1.3.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: valueref.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:02:40 $
*
* 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 CONFIGMGR_CONFIGVALUEREF_HXX_
#define CONFIGMGR_CONFIGVALUEREF_HXX_
#ifndef CONFIGMGR_CONFIGNODE_HXX_
#include "noderef.hxx"
#endif
namespace configmgr
{
namespace node { struct Attributes; }
namespace configuration
{
//-------------------------------------------------------------------------
class Name;
//-------------------------------------------------------------------------
namespace argument { struct NoValidate; }
typedef com::sun::star::uno::Type UnoType;
typedef com::sun::star::uno::Any UnoAny;
//-------------------------------------------------------------------------
class TreeImpl;
typedef unsigned int NodeOffset;
//-------------------------------------------------------------------------
/// represents a value node in some tree
class ValueRef
{
public:
/// constructs an empty (invalid) node
ValueRef();
/// copy a node (with reference semantics)
ValueRef(ValueRef const& rOther);
/// copy a node (with reference semantics)
ValueRef& operator=(ValueRef const& rOther);
void swap(ValueRef& rOther);
~ValueRef();
/// checks, if this represents an existing node
inline bool isValid() const;
private:
friend class Tree;
friend class TreeImplHelper;
ValueRef(Name const& aName, NodeOffset nParentPos);
bool checkValidState() const;
private:
Name m_sNodeName;
NodeOffset m_nParentPos;
};
//-------------------------------------------------------------------------
/** extract the value from a plain value
*/
inline
UnoAny getSimpleValue(Tree const& aTree, ValueRef const& aNode)
{ return aTree.getNodeValue( aNode ); }
//-------------------------------------------------------------------------
inline bool ValueRef::isValid() const
{
OSL_ASSERT( m_nParentPos == 0 || checkValidState() );
return m_nParentPos != 0;
}
//-------------------------------------------------------------------------
class SubNodeID
{
public:
static SubNodeID createEmpty() { return SubNodeID(); }
SubNodeID(Tree const& rTree, ValueRef const& rNode);
SubNodeID(Tree const& rTree, NodeRef const& rParentNode, Name const& aName);
SubNodeID(TreeRef const& rTree, NodeRef const& rParentNode, Name const& aName);
SubNodeID(NodeID const& rParentNodeID, Name const& aName);
// comparison
// equality
friend bool operator==(SubNodeID const& lhs, SubNodeID const& rhs)
{ return lhs.m_aParentID == rhs.m_aParentID && lhs.m_sNodeName == rhs.m_sNodeName; }
// ordering
friend bool operator < (SubNodeID const& lhs, SubNodeID const& rhs);
// checking
bool isEmpty() const;
// checking
bool isValidNode(data::Accessor const& _accessor) const;
// hashing
size_t hashCode() const;
// containing node this
NodeID getParentID() const { return m_aParentID; }
// containing node this
Name getNodeName() const { return m_sNodeName; }
private:
SubNodeID(); // create an empty one
friend class TreeImplHelper;
Name m_sNodeName;
NodeID m_aParentID;
};
//-------------------------------------------------------------------------
typedef std::vector<SubNodeID> SubNodeIDList;
void getAllChildrenHelper(data::Accessor const& _aAccessor, NodeID const& aNode, SubNodeIDList& aList);
//-------------------------------------------------------------------------
inline bool operator!=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(lhs == rhs); }
//---------------------------------------------------------------------
inline bool operator>=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(lhs < rhs); }
//---------------------------------------------------------------------
inline bool operator > (SubNodeID const& lhs, SubNodeID const& rhs)
{ return (rhs < lhs); }
inline bool operator<=(SubNodeID const& lhs, SubNodeID const& rhs)
{ return !(rhs < lhs); }
//-------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_CONFIGVALUENODE_HXX_
<|endoftext|> |
<commit_before>/* todo-conduit.cc Todo-Conduit for syncing KPilot and KOrganizer
**
** Copyright (C) 2002-2003 Reinhold Kainhofer
** Copyright (C) 1998-2001 Dan Pilone
** Copyright (C) 1998-2000 Preston Brown
** Copyright (C) 1998 Herwin-Jan Steehouwer
** Copyright (C) 2001 Cornelius Schumacher
**
** This file is part of the todo conduit, a conduit for KPilot that
** synchronises the Pilot's todo application with the outside world,
** which currently means KOrganizer.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <qdatetime.h>
#include <qtextcodec.h>
#include <libkcal/calendar.h>
#include <libkcal/todo.h>
#include <pilotLocalDatabase.h>
#include "todo-conduit.moc"
#include "vcalconduitSettings.h"
#include "todo-factory.h"
// define conduit versions, one for the version when categories were synced for the first time, and the current version number
#define CONDUIT_VERSION_CATEGORYSYNC 10
#define CONDUIT_VERSION 10
extern "C"
{
long version_conduit_todo = KPILOT_PLUGIN_API;
const char *id_conduit_todo = "$Id$";
}
TodoConduitPrivate::TodoConduitPrivate(KCal::Calendar *b) :
VCalConduitPrivateBase(b)
{
fAllTodos.setAutoDelete(false);
}
void TodoConduitPrivate::addIncidence(KCal::Incidence*e)
{
fAllTodos.append(static_cast<KCal::Todo*>(e));
fCalendar->addTodo(static_cast<KCal::Todo*>(e));
}
int TodoConduitPrivate::updateIncidences()
{
fAllTodos = fCalendar->todos();
fAllTodos.setAutoDelete(false);
return fAllTodos.count();
}
void TodoConduitPrivate::removeIncidence(KCal::Incidence *e)
{
fAllTodos.remove(static_cast<KCal::Todo*>(e));
fCalendar->deleteTodo(static_cast<KCal::Todo*>(e));
}
KCal::Incidence *TodoConduitPrivate::findIncidence(recordid_t id)
{
KCal::Todo::List::ConstIterator it;
for( it = fAllTodos.begin(); it != fAllTodos.end(); ++it ) {
KCal::Todo *todo = *it;
if ((recordid_t)(todo->pilotId()) == id) return todo;
}
return 0L;
}
KCal::Incidence *TodoConduitPrivate::findIncidence(PilotAppCategory*tosearch)
{
PilotTodoEntry*entry=dynamic_cast<PilotTodoEntry*>(tosearch);
if (!entry) return 0L;
QString title=entry->getDescription();
QDateTime dt=readTm( entry->getDueDate() );
KCal::Todo::List::ConstIterator it;
for( it = fAllTodos.begin(); it != fAllTodos.end(); ++it ) {
KCal::Todo *event = *it;
if ( (event->dtDue().date() == dt.date()) && (event->summary() == title) ) return event;
}
return 0L;
}
KCal::Incidence *TodoConduitPrivate::getNextIncidence()
{
if (reading) {
++fAllTodosIterator;
if ( fAllTodosIterator == fAllTodos.end() ) return 0;
} else {
reading=true;
fAllTodosIterator = fAllTodos.begin();
}
return *fAllTodosIterator;
}
KCal::Incidence *TodoConduitPrivate::getNextModifiedIncidence()
{
FUNCTIONSETUP;
KCal::Todo*e=0L;
if (!reading)
{
reading=true;
fAllTodosIterator = fAllTodos.begin();
if ( fAllTodosIterator != fAllTodos.end() ) e=*fAllTodosIterator;
}
else
{
++fAllTodosIterator;
}
while (fAllTodosIterator != fAllTodos.end() &&
e && e->syncStatus()!=KCal::Incidence::SYNCMOD)
{
e = (++fAllTodosIterator != fAllTodos.end()) ? *fAllTodosIterator : 0L;
#ifdef DEBUG
if(e)
DEBUGCONDUIT<< e->summary()<<" had SyncStatus="<<e->syncStatus()<<endl;
#endif
}
if ( fAllTodosIterator == fAllTodos.end() )
return 0;
else
return *fAllTodosIterator;
}
/****************************************************************************
* TodoConduit class *
****************************************************************************/
TodoConduit::TodoConduit(KPilotDeviceLink *d,
const char *n,
const QStringList &a) : VCalConduitBase(d,n,a)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << id_conduit_todo << endl;
#endif
fConduitName=i18n("To-do");
(void) id_conduit_todo;
}
TodoConduit::~TodoConduit()
{
// FUNCTIONSETUP;
}
void TodoConduit::_setAppInfo()
{
FUNCTIONSETUP;
// get the address application header information
int appLen = pack_ToDoAppInfo(&fTodoAppInfo, 0, 0);
unsigned char *buffer = new unsigned char[appLen];
pack_ToDoAppInfo(&fTodoAppInfo, buffer, appLen);
if (fDatabase) fDatabase->writeAppBlock(buffer, appLen);
if (fLocalDatabase) fLocalDatabase->writeAppBlock(buffer, appLen);
delete[] buffer;
}
void TodoConduit::_getAppInfo()
{
FUNCTIONSETUP;
// get the address application header information
unsigned char *buffer =
new unsigned char[PilotRecord::APP_BUFFER_SIZE];
int appLen = fDatabase->readAppBlock(buffer,PilotRecord::APP_BUFFER_SIZE);
unpack_ToDoAppInfo(&fTodoAppInfo, buffer, appLen);
delete[]buffer;
buffer = NULL;
#ifdef DEBUG
DEBUGCONDUIT << fname << " lastUniqueId"
<< fTodoAppInfo.category.lastUniqueID << endl;
#endif
for (int i = 0; i < 16; i++)
{
#ifdef DEBUG
DEBUGCONDUIT << fname << " cat " << i << " =" <<
fTodoAppInfo.category.name[i] << endl;
#endif
}
}
const QString TodoConduit::getTitle(PilotAppCategory*de)
{
PilotTodoEntry*d=dynamic_cast<PilotTodoEntry*>(de);
if (d) return QString(d->getDescription());
return QString::null;
}
void TodoConduit::readConfig()
{
FUNCTIONSETUP;
VCalConduitBase::readConfig();
// determine if the categories have ever been synce. Needed to prevent loosing the categories on the desktop.
// also use a full sync for the first time to make sure the palm categories are really transferred to the desktop
categoriesSynced = config()->conduitVersion()>=CONDUIT_VERSION_CATEGORYSYNC;
if (!categoriesSynced & !isFullSync() )
setSyncDirection(SyncAction::eFullSync);
#ifdef DEBUG
DEBUGCONDUIT<<"categoriesSynced="<<categoriesSynced<<endl;
#endif
}
void TodoConduit::postSync()
{
FUNCTIONSETUP;
VCalConduitBase::postSync();
// after this successful sync the categories have been synced for sure
config()->setConduitVersion( CONDUIT_VERSION );
config()->writeConfig();
_setAppInfo();
}
PilotRecord*TodoConduit::recordFromIncidence(PilotAppCategory*de, const KCal::Incidence*e)
{
// don't need to check for null pointers here, the recordFromIncidence(PTE*, KCal::Todo*) will do that.
PilotTodoEntry *tde = dynamic_cast<PilotTodoEntry*>(de);
const KCal::Todo *te = dynamic_cast<const KCal::Todo*>(e);
return recordFromTodo(tde, te);
}
PilotRecord*TodoConduit::recordFromTodo(PilotTodoEntry*de, const KCal::Todo*todo)
{
FUNCTIONSETUP;
if (!de || !todo) {
#ifdef DEBUG
DEBUGCONDUIT<<fname<<": NULL todo given... Skipping it"<<endl;
#endif
return NULL;
}
// set secrecy, start/end times, alarms, recurrence, exceptions, summary and description:
if (todo->secrecy()!=KCal::Todo::SecrecyPublic) de->makeSecret();
// update it from the iCalendar Todo.
if (todo->hasDueDate()) {
struct tm t = writeTm(todo->dtDue());
de->setDueDate(t);
de->setIndefinite(0);
} else {
de->setIndefinite(1);
}
// TODO: take recurrence (code in VCAlConduit) from ActionNames
setCategory(de, todo);
// TODO: sync the alarm from ActionNames. Need to extend PilotTodoEntry
de->setPriority(todo->priority());
de->setComplete(todo->isCompleted());
// what we call summary pilot calls description.
de->setDescription(todo->summary());
// what we call description pilot puts as a separate note
de->setNote(todo->description());
#ifdef DEBUG
DEBUGCONDUIT<<"-------- "<<todo->summary()<<endl;
#endif
return de->pack();
}
void TodoConduit::preRecord(PilotRecord*r)
{
FUNCTIONSETUP;
if (!categoriesSynced && r)
{
const PilotAppCategory*de=newPilotEntry(r);
KCal::Incidence *e = fP->findIncidence(r->getID());
setCategory(dynamic_cast<KCal::Todo*>(e), dynamic_cast<const PilotTodoEntry*>(de));
}
}
void TodoConduit::setCategory(PilotTodoEntry*de, const KCal::Todo*todo)
{
if (!de || !todo) return;
de->setCategory(_getCat(todo->categories(), de->getCategoryLabel()));
}
/**
* _getCat returns the id of the category from the given categories list. If none of the categories exist
* on the palm, the "Nicht abgelegt" (don't know the english name) is used.
*/
QString TodoConduit::_getCat(const QStringList cats, const QString curr) const
{
int j;
if (cats.size()<1) return QString::null;
if (cats.contains(curr)) return curr;
for ( QStringList::ConstIterator it = cats.begin(); it != cats.end(); ++it ) {
for (j=1; j<=15; j++)
{
QString catName = PilotAppCategory::codec()->
toUnicode(fTodoAppInfo.category.name[j]);
if (!(*it).isEmpty() && !(*it).compare( catName ) )
{
return catName;
}
}
}
// If we have a free label, return the first possible cat
QString lastName(fTodoAppInfo.category.name[15]);
if (lastName.isEmpty()) return cats.first();
return QString::null;
}
KCal::Incidence *TodoConduit::incidenceFromRecord(KCal::Incidence *e, const PilotAppCategory *de)
{
return dynamic_cast<KCal::Incidence*>(incidenceFromRecord(dynamic_cast<KCal::Todo*>(e), dynamic_cast<const PilotTodoEntry*>(de)));
}
KCal::Todo *TodoConduit::incidenceFromRecord(KCal::Todo *e, const PilotTodoEntry *de)
{
FUNCTIONSETUP;
KCal::Todo*vtodo=e;
if (!vtodo)
{
#ifdef DEBUG
DEBUGCONDUIT<<fname<<": null todo entry given. skipping..."<<endl;
#endif
return NULL;
}
e->setOrganizer(fCalendar->getEmail());
e->setPilotId(de->getID());
e->setSyncStatus(KCal::Incidence::SYNCNONE);
e->setSecrecy(de->isSecret() ? KCal::Todo::SecrecyPrivate : KCal::Todo::SecrecyPublic);
// we don't want to modify the vobject with pilot info, because it has
// already been modified on the desktop. The VObject's modified state
// overrides the PilotRec's modified state.
// TODO: Also include this in the vcal conduit!!!
// if (e->syncStatus() != KCal::Incidence::SYNCNONE) return e;
// otherwise, the vObject hasn't been touched. Updated it with the
// info from the PilotRec.
if (de->getIndefinite()) {
e->setHasDueDate(false);
} else {
e->setDtDue(readTm(de->getDueDate()));
e->setHasDueDate(true);
}
// Categories
// TODO: Sync categories
// first remove all categories and then add only the appropriate one
setCategory(e, de);
// PRIORITY //
e->setPriority(de->getPriority());
// COMPLETED? //
e->setCompleted(de->getComplete());
if ( de->getComplete() && !e->hasCompletedDate() ) {
e->setCompleted( QDateTime::currentDateTime() );
}
e->setSummary(de->getDescription());
e->setDescription(de->getNote());
e->setSyncStatus(KCal::Incidence::SYNCNONE);
kdDebug()<<endl<<endl<<endl<<"Todo: "<<e->summary()<<endl;
kdDebug()<<"rec->completed="<<de->getComplete() << ", e->Completed="<<e->completed()<<", e->CompletedStr="<<e->completedStr()<<endl;
return e;
}
void TodoConduit::setCategory(KCal::Todo *e, const PilotTodoEntry *de)
{
if (!e || !de) return;
QStringList cats=e->categories();
int cat=de->getCat();
if (0<cat && cat<=15)
{
QString newcat=PilotAppCategory::codec()->toUnicode(fTodoAppInfo.category.name[cat]);
if (!cats.contains(newcat))
{
cats.append( newcat );
e->setCategories(cats);
}
}
}
VCalConduitSettings *TodoConduit::config()
{
return ToDoConduitFactory::config();
}
<commit_msg>CVS_SILENT: Get rid of debug output.<commit_after>/* todo-conduit.cc Todo-Conduit for syncing KPilot and KOrganizer
**
** Copyright (C) 2002-2003 Reinhold Kainhofer
** Copyright (C) 1998-2001 Dan Pilone
** Copyright (C) 1998-2000 Preston Brown
** Copyright (C) 1998 Herwin-Jan Steehouwer
** Copyright (C) 2001 Cornelius Schumacher
**
** This file is part of the todo conduit, a conduit for KPilot that
** synchronises the Pilot's todo application with the outside world,
** which currently means KOrganizer.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <qdatetime.h>
#include <qtextcodec.h>
#include <libkcal/calendar.h>
#include <libkcal/todo.h>
#include <pilotLocalDatabase.h>
#include "todo-conduit.moc"
#include "vcalconduitSettings.h"
#include "todo-factory.h"
// define conduit versions, one for the version when categories were synced for the first time, and the current version number
#define CONDUIT_VERSION_CATEGORYSYNC 10
#define CONDUIT_VERSION 10
extern "C"
{
long version_conduit_todo = KPILOT_PLUGIN_API;
const char *id_conduit_todo = "$Id$";
}
TodoConduitPrivate::TodoConduitPrivate(KCal::Calendar *b) :
VCalConduitPrivateBase(b)
{
fAllTodos.setAutoDelete(false);
}
void TodoConduitPrivate::addIncidence(KCal::Incidence*e)
{
fAllTodos.append(static_cast<KCal::Todo*>(e));
fCalendar->addTodo(static_cast<KCal::Todo*>(e));
}
int TodoConduitPrivate::updateIncidences()
{
fAllTodos = fCalendar->todos();
fAllTodos.setAutoDelete(false);
return fAllTodos.count();
}
void TodoConduitPrivate::removeIncidence(KCal::Incidence *e)
{
fAllTodos.remove(static_cast<KCal::Todo*>(e));
fCalendar->deleteTodo(static_cast<KCal::Todo*>(e));
}
KCal::Incidence *TodoConduitPrivate::findIncidence(recordid_t id)
{
KCal::Todo::List::ConstIterator it;
for( it = fAllTodos.begin(); it != fAllTodos.end(); ++it ) {
KCal::Todo *todo = *it;
if ((recordid_t)(todo->pilotId()) == id) return todo;
}
return 0L;
}
KCal::Incidence *TodoConduitPrivate::findIncidence(PilotAppCategory*tosearch)
{
PilotTodoEntry*entry=dynamic_cast<PilotTodoEntry*>(tosearch);
if (!entry) return 0L;
QString title=entry->getDescription();
QDateTime dt=readTm( entry->getDueDate() );
KCal::Todo::List::ConstIterator it;
for( it = fAllTodos.begin(); it != fAllTodos.end(); ++it ) {
KCal::Todo *event = *it;
if ( (event->dtDue().date() == dt.date()) && (event->summary() == title) ) return event;
}
return 0L;
}
KCal::Incidence *TodoConduitPrivate::getNextIncidence()
{
if (reading) {
++fAllTodosIterator;
if ( fAllTodosIterator == fAllTodos.end() ) return 0;
} else {
reading=true;
fAllTodosIterator = fAllTodos.begin();
}
return *fAllTodosIterator;
}
KCal::Incidence *TodoConduitPrivate::getNextModifiedIncidence()
{
FUNCTIONSETUP;
KCal::Todo*e=0L;
if (!reading)
{
reading=true;
fAllTodosIterator = fAllTodos.begin();
if ( fAllTodosIterator != fAllTodos.end() ) e=*fAllTodosIterator;
}
else
{
++fAllTodosIterator;
}
while (fAllTodosIterator != fAllTodos.end() &&
e && e->syncStatus()!=KCal::Incidence::SYNCMOD)
{
e = (++fAllTodosIterator != fAllTodos.end()) ? *fAllTodosIterator : 0L;
#ifdef DEBUG
if(e)
DEBUGCONDUIT<< e->summary()<<" had SyncStatus="<<e->syncStatus()<<endl;
#endif
}
if ( fAllTodosIterator == fAllTodos.end() )
return 0;
else
return *fAllTodosIterator;
}
/****************************************************************************
* TodoConduit class *
****************************************************************************/
TodoConduit::TodoConduit(KPilotDeviceLink *d,
const char *n,
const QStringList &a) : VCalConduitBase(d,n,a)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << id_conduit_todo << endl;
#endif
fConduitName=i18n("To-do");
(void) id_conduit_todo;
}
TodoConduit::~TodoConduit()
{
// FUNCTIONSETUP;
}
void TodoConduit::_setAppInfo()
{
FUNCTIONSETUP;
// get the address application header information
int appLen = pack_ToDoAppInfo(&fTodoAppInfo, 0, 0);
unsigned char *buffer = new unsigned char[appLen];
pack_ToDoAppInfo(&fTodoAppInfo, buffer, appLen);
if (fDatabase) fDatabase->writeAppBlock(buffer, appLen);
if (fLocalDatabase) fLocalDatabase->writeAppBlock(buffer, appLen);
delete[] buffer;
}
void TodoConduit::_getAppInfo()
{
FUNCTIONSETUP;
// get the address application header information
unsigned char *buffer =
new unsigned char[PilotRecord::APP_BUFFER_SIZE];
int appLen = fDatabase->readAppBlock(buffer,PilotRecord::APP_BUFFER_SIZE);
unpack_ToDoAppInfo(&fTodoAppInfo, buffer, appLen);
delete[]buffer;
buffer = NULL;
#ifdef DEBUG
DEBUGCONDUIT << fname << " lastUniqueId"
<< fTodoAppInfo.category.lastUniqueID << endl;
#endif
for (int i = 0; i < 16; i++)
{
#ifdef DEBUG
DEBUGCONDUIT << fname << " cat " << i << " =" <<
fTodoAppInfo.category.name[i] << endl;
#endif
}
}
const QString TodoConduit::getTitle(PilotAppCategory*de)
{
PilotTodoEntry*d=dynamic_cast<PilotTodoEntry*>(de);
if (d) return QString(d->getDescription());
return QString::null;
}
void TodoConduit::readConfig()
{
FUNCTIONSETUP;
VCalConduitBase::readConfig();
// determine if the categories have ever been synce. Needed to prevent loosing the categories on the desktop.
// also use a full sync for the first time to make sure the palm categories are really transferred to the desktop
categoriesSynced = config()->conduitVersion()>=CONDUIT_VERSION_CATEGORYSYNC;
if (!categoriesSynced & !isFullSync() )
setSyncDirection(SyncAction::eFullSync);
#ifdef DEBUG
DEBUGCONDUIT<<"categoriesSynced="<<categoriesSynced<<endl;
#endif
}
void TodoConduit::postSync()
{
FUNCTIONSETUP;
VCalConduitBase::postSync();
// after this successful sync the categories have been synced for sure
config()->setConduitVersion( CONDUIT_VERSION );
config()->writeConfig();
_setAppInfo();
}
PilotRecord*TodoConduit::recordFromIncidence(PilotAppCategory*de, const KCal::Incidence*e)
{
// don't need to check for null pointers here, the recordFromIncidence(PTE*, KCal::Todo*) will do that.
PilotTodoEntry *tde = dynamic_cast<PilotTodoEntry*>(de);
const KCal::Todo *te = dynamic_cast<const KCal::Todo*>(e);
return recordFromTodo(tde, te);
}
PilotRecord*TodoConduit::recordFromTodo(PilotTodoEntry*de, const KCal::Todo*todo)
{
FUNCTIONSETUP;
if (!de || !todo) {
#ifdef DEBUG
DEBUGCONDUIT<<fname<<": NULL todo given... Skipping it"<<endl;
#endif
return NULL;
}
// set secrecy, start/end times, alarms, recurrence, exceptions, summary and description:
if (todo->secrecy()!=KCal::Todo::SecrecyPublic) de->makeSecret();
// update it from the iCalendar Todo.
if (todo->hasDueDate()) {
struct tm t = writeTm(todo->dtDue());
de->setDueDate(t);
de->setIndefinite(0);
} else {
de->setIndefinite(1);
}
// TODO: take recurrence (code in VCAlConduit) from ActionNames
setCategory(de, todo);
// TODO: sync the alarm from ActionNames. Need to extend PilotTodoEntry
de->setPriority(todo->priority());
de->setComplete(todo->isCompleted());
// what we call summary pilot calls description.
de->setDescription(todo->summary());
// what we call description pilot puts as a separate note
de->setNote(todo->description());
#ifdef DEBUG
DEBUGCONDUIT<<"-------- "<<todo->summary()<<endl;
#endif
return de->pack();
}
void TodoConduit::preRecord(PilotRecord*r)
{
FUNCTIONSETUP;
if (!categoriesSynced && r)
{
const PilotAppCategory*de=newPilotEntry(r);
KCal::Incidence *e = fP->findIncidence(r->getID());
setCategory(dynamic_cast<KCal::Todo*>(e), dynamic_cast<const PilotTodoEntry*>(de));
}
}
void TodoConduit::setCategory(PilotTodoEntry*de, const KCal::Todo*todo)
{
if (!de || !todo) return;
de->setCategory(_getCat(todo->categories(), de->getCategoryLabel()));
}
/**
* _getCat returns the id of the category from the given categories list. If none of the categories exist
* on the palm, the "Nicht abgelegt" (don't know the english name) is used.
*/
QString TodoConduit::_getCat(const QStringList cats, const QString curr) const
{
int j;
if (cats.size()<1) return QString::null;
if (cats.contains(curr)) return curr;
for ( QStringList::ConstIterator it = cats.begin(); it != cats.end(); ++it ) {
for (j=1; j<=15; j++)
{
QString catName = PilotAppCategory::codec()->
toUnicode(fTodoAppInfo.category.name[j]);
if (!(*it).isEmpty() && !(*it).compare( catName ) )
{
return catName;
}
}
}
// If we have a free label, return the first possible cat
QString lastName(fTodoAppInfo.category.name[15]);
if (lastName.isEmpty()) return cats.first();
return QString::null;
}
KCal::Incidence *TodoConduit::incidenceFromRecord(KCal::Incidence *e, const PilotAppCategory *de)
{
return dynamic_cast<KCal::Incidence*>(incidenceFromRecord(dynamic_cast<KCal::Todo*>(e), dynamic_cast<const PilotTodoEntry*>(de)));
}
KCal::Todo *TodoConduit::incidenceFromRecord(KCal::Todo *e, const PilotTodoEntry *de)
{
FUNCTIONSETUP;
KCal::Todo*vtodo=e;
if (!vtodo)
{
#ifdef DEBUG
DEBUGCONDUIT<<fname<<": null todo entry given. skipping..."<<endl;
#endif
return NULL;
}
e->setOrganizer(fCalendar->getEmail());
e->setPilotId(de->getID());
e->setSyncStatus(KCal::Incidence::SYNCNONE);
e->setSecrecy(de->isSecret() ? KCal::Todo::SecrecyPrivate : KCal::Todo::SecrecyPublic);
// we don't want to modify the vobject with pilot info, because it has
// already been modified on the desktop. The VObject's modified state
// overrides the PilotRec's modified state.
// TODO: Also include this in the vcal conduit!!!
// if (e->syncStatus() != KCal::Incidence::SYNCNONE) return e;
// otherwise, the vObject hasn't been touched. Updated it with the
// info from the PilotRec.
if (de->getIndefinite()) {
e->setHasDueDate(false);
} else {
e->setDtDue(readTm(de->getDueDate()));
e->setHasDueDate(true);
}
// Categories
// TODO: Sync categories
// first remove all categories and then add only the appropriate one
setCategory(e, de);
// PRIORITY //
e->setPriority(de->getPriority());
// COMPLETED? //
e->setCompleted(de->getComplete());
if ( de->getComplete() && !e->hasCompletedDate() ) {
e->setCompleted( QDateTime::currentDateTime() );
}
e->setSummary(de->getDescription());
e->setDescription(de->getNote());
e->setSyncStatus(KCal::Incidence::SYNCNONE);
return e;
}
void TodoConduit::setCategory(KCal::Todo *e, const PilotTodoEntry *de)
{
if (!e || !de) return;
QStringList cats=e->categories();
int cat=de->getCat();
if (0<cat && cat<=15)
{
QString newcat=PilotAppCategory::codec()->toUnicode(fTodoAppInfo.category.name[cat]);
if (!cats.contains(newcat))
{
cats.append( newcat );
e->setCategories(cats);
}
}
}
VCalConduitSettings *TodoConduit::config()
{
return ToDoConduitFactory::config();
}
<|endoftext|> |
<commit_before>#ifndef _SDD_ORDER_ORDER_HH_
#define _SDD_ORDER_ORDER_HH_
#include <algorithm> // find
#include <initializer_list>
#include <iostream>
#include <memory> // shared_ptr
#include <utility> // pair
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/order_identifier.hh"
#include "sdd/order/order_node.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
using order_positions_type = std::vector<order_position_type>;
/// @internal
using order_positions_iterator = typename order_positions_type::const_iterator;
/*------------------------------------------------------------------------------------------------*/
/// @brief Represent an order of identifiers, possibly with some hierarchy.
/// @todo Manage artificial identifiers.
///
/// It helps associate a variable (generated by the library) in an SDD to an identifiers
/// (provided to the user). An identifier should appear only once by order.
template <typename C>
class order final
{
public:
/// @brief A user's identifier type.
using identifier_type = typename C::Identifier;
/// @brief A library's variable type.
using variable_type = typename C::Variable;
private:
/// @brief A path, following hierarchies, to a node.
using path_type = typename order_node<C>::path_type;
/// @brief All nodes.
using nodes_type = std::vector<order_node<C>>;
/// @brief A shared pointer to nodes.
using nodes_ptr_type = std::shared_ptr<const nodes_type>;
/// @brief Define a mapping identifier->node.
using id_to_node_type = std::unordered_map<order_identifier<C>, const order_node<C>*>;
/// @brief The concrete order.
const nodes_ptr_type nodes_ptr_;
/// @brief Maps identifiers to nodes.
const std::shared_ptr<id_to_node_type> id_to_node_ptr_;
/// @brief The first node in the order.
const order_node<C>* head_;
public:
/// @brief Constructor.
order(const order_builder<C>& builder)
: nodes_ptr_(mk_nodes_ptr(builder))
, id_to_node_ptr_(mk_identifier_to_node(nodes_ptr_))
, head_(nodes_ptr_ ? &(nodes_ptr_->front()) : nullptr)
{}
/// @brief Tell if upper contains nested in its possibly contained hierarchy.
/// @param uppper Must belong to the current order.
/// @param nested Must belong to the current order.
bool
contains(order_position_type upper, order_position_type nested)
const noexcept
{
const auto& path = (*nodes_ptr_)[nested].path();
return std::find(path.begin(), path.end(), upper) != path.end();
}
/// @brief
const nodes_type&
identifiers()
const noexcept
{
return *nodes_ptr_;
}
/// @brief Get the variable of this order's head.
variable_type
variable()
const noexcept
{
return head_->variable();
}
/// @brief Get the identifier of this order's head.
const order_identifier<C>&
identifier()
const noexcept
{
return head_->identifier();
}
/// @brief Get the position of this order's head.
order_position_type
position()
const noexcept
{
return head_->position();
}
/// @brief Get the next order of this order's head.
order
next()
const noexcept
{
return order(nodes_ptr_, id_to_node_ptr_, head_->next());
}
/// @brief Get the nested order of this order's head.
order
nested()
const noexcept
{
return order(nodes_ptr_, id_to_node_ptr_, head_->nested());
}
/// @brief Tell if this order is empty.
bool
empty()
const noexcept
{
return head_ == nullptr;
}
/// @internal
const order_node<C>&
node(const identifier_type& id)
const
{
return *id_to_node_ptr_->at(order_identifier<C>(id));
}
/// @internal
std::size_t
hash()
const noexcept
{
std::size_t seed = 0;
util::hash_combine(seed, nodes_ptr_.get());
util::hash_combine(seed, head_);
return seed;
}
/// @internal
bool
operator==(const order& other)
const noexcept
{
return nodes_ptr_ == other.nodes_ptr_ and id_to_node_ptr_ == other.id_to_node_ptr_
and head_ == other.head_;
}
private:
/// @brief Construct whith a shallow copy an already existing order.
order( const nodes_ptr_type& nodes_ptr, const std::shared_ptr<id_to_node_type>& id_to_node
, const order_node<C>* head)
: nodes_ptr_(nodes_ptr), id_to_node_ptr_(id_to_node), head_(head)
{}
/// @brief Create the concrete order using an order_builder.
static
nodes_ptr_type
mk_nodes_ptr(const order_builder<C>& builder)
{
if (builder.empty())
{
return nullptr;
}
auto nodes_ptr = std::make_shared<nodes_type>(builder.size());
auto& nodes = *nodes_ptr;
// Ensure that identifiers appear only once.
std::unordered_set<identifier_type> unicity;
// Counter for identifiers' positions.
unsigned int pos = 0;
// To enable recursion in the lambda.
std::function<
std::pair<order_node<C>*, variable_type>
(const order_builder<C>&, const std::shared_ptr<path_type>&)
> helper;
helper = [&helper, &pos, &nodes, &unicity]
(const order_builder<C>& ob, const std::shared_ptr<path_type>& path)
-> std::pair<order_node<C>*, unsigned int>
{
const unsigned int current_position = pos++;
std::pair<order_node<C>*, variable_type> nested(nullptr, 0 /*first variable*/);
std::pair<order_node<C>*, variable_type> next(nullptr, 0 /* first variable */);
if (not ob.nested().empty())
{
const auto new_path = std::make_shared<path_type>(*path);
new_path->push_back(current_position);
new_path->shrink_to_fit();
nested = helper(ob.nested(), new_path);
}
if (not ob.next().empty())
{
next = helper(ob.next(), path);
}
const auto variable = next.second;
if (not ob.identifier().artificial() and not unicity.insert(ob.identifier().user()).second)
{
throw std::runtime_error("Duplicate order identifier " + ob.identifier().user());
}
nodes[current_position] =
order_node<C>(ob.identifier(), variable, current_position, next.first, nested.first, path);
return std::make_pair(&nodes[current_position], variable + 1);
};
// Launch the recursion.
helper(builder, std::make_shared<path_type>());
return nodes_ptr;
}
/// @brief
const std::shared_ptr<id_to_node_type>
mk_identifier_to_node(const nodes_ptr_type& nodes_ptr)
{
auto identifier_to_node_ptr = std::make_shared<id_to_node_type>();
if (nodes_ptr)
{
identifier_to_node_ptr->reserve(nodes_ptr->size());
std::for_each( nodes_ptr->begin(), nodes_ptr_->end()
, [&](const order_node<C>& n)
{identifier_to_node_ptr->emplace(n.identifier(), &n);}
);
}
return identifier_to_node_ptr;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Textual representation of an order.
/// @related order
template <typename C>
std::ostream&
operator<<(std::ostream& os, const order<C>& ord)
{
const std::function<std::ostream&(const order<C>&, unsigned int)> helper
= [&helper, &os](const order<C>& o, unsigned int indent)
-> std::ostream&
{
if (not o.empty())
{
const std::string spaces(indent, ' ');
os << spaces << o.identifier() << std::endl;
if (not o.nested().empty())
{
helper(o.nested(), indent + 2);
}
if (not o.next().empty())
{
helper(o.next(), indent);
}
}
return os;
};
return helper(ord, 0);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::order.
template <typename C>
struct hash<sdd::order<C>>
{
std::size_t
operator()(const sdd::order<C>& o)
const noexcept
{
return o.hash();
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_ORDER_ORDER_HH_
<commit_msg>Use stringstream to output user identifier.<commit_after>#ifndef _SDD_ORDER_ORDER_HH_
#define _SDD_ORDER_ORDER_HH_
#include <algorithm> // find
#include <initializer_list>
#include <iostream>
#include <memory> // shared_ptr
#include <sstream>
#include <utility> // pair
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/order_identifier.hh"
#include "sdd/order/order_node.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
using order_positions_type = std::vector<order_position_type>;
/// @internal
using order_positions_iterator = typename order_positions_type::const_iterator;
/*------------------------------------------------------------------------------------------------*/
/// @brief Represent an order of identifiers, possibly with some hierarchy.
/// @todo Manage artificial identifiers.
///
/// It helps associate a variable (generated by the library) in an SDD to an identifiers
/// (provided to the user). An identifier should appear only once by order.
template <typename C>
class order final
{
public:
/// @brief A user's identifier type.
using identifier_type = typename C::Identifier;
/// @brief A library's variable type.
using variable_type = typename C::Variable;
private:
/// @brief A path, following hierarchies, to a node.
using path_type = typename order_node<C>::path_type;
/// @brief All nodes.
using nodes_type = std::vector<order_node<C>>;
/// @brief A shared pointer to nodes.
using nodes_ptr_type = std::shared_ptr<const nodes_type>;
/// @brief Define a mapping identifier->node.
using id_to_node_type = std::unordered_map<order_identifier<C>, const order_node<C>*>;
/// @brief The concrete order.
const nodes_ptr_type nodes_ptr_;
/// @brief Maps identifiers to nodes.
const std::shared_ptr<id_to_node_type> id_to_node_ptr_;
/// @brief The first node in the order.
const order_node<C>* head_;
public:
/// @brief Constructor.
order(const order_builder<C>& builder)
: nodes_ptr_(mk_nodes_ptr(builder))
, id_to_node_ptr_(mk_identifier_to_node(nodes_ptr_))
, head_(nodes_ptr_ ? &(nodes_ptr_->front()) : nullptr)
{}
/// @brief Tell if upper contains nested in its possibly contained hierarchy.
/// @param uppper Must belong to the current order.
/// @param nested Must belong to the current order.
bool
contains(order_position_type upper, order_position_type nested)
const noexcept
{
const auto& path = (*nodes_ptr_)[nested].path();
return std::find(path.begin(), path.end(), upper) != path.end();
}
/// @brief
const nodes_type&
identifiers()
const noexcept
{
return *nodes_ptr_;
}
/// @brief Get the variable of this order's head.
variable_type
variable()
const noexcept
{
return head_->variable();
}
/// @brief Get the identifier of this order's head.
const order_identifier<C>&
identifier()
const noexcept
{
return head_->identifier();
}
/// @brief Get the position of this order's head.
order_position_type
position()
const noexcept
{
return head_->position();
}
/// @brief Get the next order of this order's head.
order
next()
const noexcept
{
return order(nodes_ptr_, id_to_node_ptr_, head_->next());
}
/// @brief Get the nested order of this order's head.
order
nested()
const noexcept
{
return order(nodes_ptr_, id_to_node_ptr_, head_->nested());
}
/// @brief Tell if this order is empty.
bool
empty()
const noexcept
{
return head_ == nullptr;
}
/// @internal
const order_node<C>&
node(const identifier_type& id)
const
{
return *id_to_node_ptr_->at(order_identifier<C>(id));
}
/// @internal
std::size_t
hash()
const noexcept
{
std::size_t seed = 0;
util::hash_combine(seed, nodes_ptr_.get());
util::hash_combine(seed, head_);
return seed;
}
/// @internal
bool
operator==(const order& other)
const noexcept
{
return nodes_ptr_ == other.nodes_ptr_ and id_to_node_ptr_ == other.id_to_node_ptr_
and head_ == other.head_;
}
private:
/// @brief Construct whith a shallow copy an already existing order.
order( const nodes_ptr_type& nodes_ptr, const std::shared_ptr<id_to_node_type>& id_to_node
, const order_node<C>* head)
: nodes_ptr_(nodes_ptr), id_to_node_ptr_(id_to_node), head_(head)
{}
/// @brief Create the concrete order using an order_builder.
static
nodes_ptr_type
mk_nodes_ptr(const order_builder<C>& builder)
{
if (builder.empty())
{
return nullptr;
}
auto nodes_ptr = std::make_shared<nodes_type>(builder.size());
auto& nodes = *nodes_ptr;
// Ensure that identifiers appear only once.
std::unordered_set<identifier_type> unicity;
// Counter for identifiers' positions.
unsigned int pos = 0;
// To enable recursion in the lambda.
std::function<
std::pair<order_node<C>*, variable_type>
(const order_builder<C>&, const std::shared_ptr<path_type>&)
> helper;
helper = [&helper, &pos, &nodes, &unicity]
(const order_builder<C>& ob, const std::shared_ptr<path_type>& path)
-> std::pair<order_node<C>*, unsigned int>
{
const unsigned int current_position = pos++;
std::pair<order_node<C>*, variable_type> nested(nullptr, 0 /*first variable*/);
std::pair<order_node<C>*, variable_type> next(nullptr, 0 /* first variable */);
if (not ob.nested().empty())
{
const auto new_path = std::make_shared<path_type>(*path);
new_path->push_back(current_position);
new_path->shrink_to_fit();
nested = helper(ob.nested(), new_path);
}
if (not ob.next().empty())
{
next = helper(ob.next(), path);
}
const auto variable = next.second;
if (not ob.identifier().artificial() and not unicity.insert(ob.identifier().user()).second)
{
// Must stream user identifier to call its operator<<().
std::stringstream ss;
ss << "Duplicate order identifier " << ob.identifier().user();
throw std::runtime_error(ss.str());
}
nodes[current_position] =
order_node<C>(ob.identifier(), variable, current_position, next.first, nested.first, path);
return std::make_pair(&nodes[current_position], variable + 1);
};
// Launch the recursion.
helper(builder, std::make_shared<path_type>());
return nodes_ptr;
}
/// @brief
const std::shared_ptr<id_to_node_type>
mk_identifier_to_node(const nodes_ptr_type& nodes_ptr)
{
auto identifier_to_node_ptr = std::make_shared<id_to_node_type>();
if (nodes_ptr)
{
identifier_to_node_ptr->reserve(nodes_ptr->size());
std::for_each( nodes_ptr->begin(), nodes_ptr_->end()
, [&](const order_node<C>& n)
{identifier_to_node_ptr->emplace(n.identifier(), &n);}
);
}
return identifier_to_node_ptr;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Textual representation of an order.
/// @related order
template <typename C>
std::ostream&
operator<<(std::ostream& os, const order<C>& ord)
{
const std::function<std::ostream&(const order<C>&, unsigned int)> helper
= [&helper, &os](const order<C>& o, unsigned int indent)
-> std::ostream&
{
if (not o.empty())
{
const std::string spaces(indent, ' ');
os << spaces << o.identifier() << std::endl;
if (not o.nested().empty())
{
helper(o.nested(), indent + 2);
}
if (not o.next().empty())
{
helper(o.next(), indent);
}
}
return os;
};
return helper(ord, 0);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::order.
template <typename C>
struct hash<sdd::order<C>>
{
std::size_t
operator()(const sdd::order<C>& o)
const noexcept
{
return o.hash();
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_ORDER_ORDER_HH_
<|endoftext|> |
<commit_before>#define AliAnalysisTaskPt_cxx
#include "TROOT.h"
#include "TChain.h"
#include "TH1.h"
#include "TCanvas.h"
#include "TSystem.h"
#include "Riostream.h"
#include "AliAnalysisTask.h"
#include "AliESD.h"
#include "AliAnalysisTaskPt.h"
ClassImp(AliAnalysisTaskPt)
//________________________________________________________________________
AliAnalysisTaskPt::AliAnalysisTaskPt(const char *name) :AliAnalysisTask(name,""), fESD(0), fHistPt(0) {
// Constructor.
// Input slot #0 works with an Ntuple
DefineInput(0, TChain::Class());
// Output slot #0 writes into a TH1 container
DefineOutput(0, TH1F::Class());
}
//________________________________________________________________________
void AliAnalysisTaskPt::ConnectInputData(Option_t *) {
printf(" ConnectInputData %s\n", GetName());
char ** address = (char **)GetBranchAddress(0, "ESD");
if (address) {
fESD = (AliESD*)(*address);
}
else {
fESD = new AliESD();
SetBranchAddress(0, "ESD", &fESD);
}
}
//________________________________________________________________________
void AliAnalysisTaskPt::CreateOutputObjects() {
if (!fHistPt) {
fHistPt = new TH1F("fHistPt","This is the Pt distribution",15,0.1,3.1);
fHistPt->SetStats(kTRUE);
fHistPt->GetXaxis()->SetTitle("P_{T} [GeV]");
fHistPt->GetYaxis()->SetTitle("#frac{dN}{dP_{T}}");
fHistPt->GetXaxis()->SetTitleColor(1);
fHistPt->SetMarkerStyle(kFullCircle);
}
}
//________________________________________________________________________
void AliAnalysisTaskPt::Exec(Option_t *) {
// Task making a pt distribution.
// Get input data
TChain *chain = (TChain*)GetInputData(0);
Long64_t ientry = chain->GetReadEntry();
if (!fESD) return;
cout<<"Entry: "<<ientry<<" - Tracks: "<<fESD->GetNumberOfTracks()<<endl;
for(Int_t iTracks = 0; iTracks < fESD->GetNumberOfTracks(); iTracks++) {
AliESDtrack * ESDTrack = fESD->GetTrack(iTracks);
//UInt_t status = ESDTrack->GetStatus();
Double_t momentum[3];
ESDTrack->GetPxPyPz(momentum);
Double_t Pt = sqrt(pow(momentum[0],2) + pow(momentum[1],2));
fHistPt->Fill(Pt);
}//track loop
// Post final data. It will be written to a file with option "RECREATE"
PostData(0, fHistPt);
}
//________________________________________________________________________
void AliAnalysisTaskPt::Terminate(Option_t *) {
// Draw some histogram at the end.
if (!gROOT->IsBatch()) {
TCanvas *c1 = new TCanvas("c1","Pt",10,10,310,310);
c1->SetFillColor(10);
c1->SetHighLightColor(10);
c1->cd(1)->SetLeftMargin(0.15);
c1->cd(1)->SetBottomMargin(0.15);
c1->cd(1)->SetLogy();
//fHistPt = (TH1F*)GetOutputData(0);
if (fHistPt) fHistPt->DrawCopy("E");
}
}
<commit_msg>Getting the output histigram in terminate (needed for proof)<commit_after>#define AliAnalysisTaskPt_cxx
#include "TROOT.h"
#include "TChain.h"
#include "TH1.h"
#include "TCanvas.h"
#include "TSystem.h"
#include "Riostream.h"
#include "AliAnalysisTask.h"
#include "AliESD.h"
#include "AliAnalysisTaskPt.h"
ClassImp(AliAnalysisTaskPt)
//________________________________________________________________________
AliAnalysisTaskPt::AliAnalysisTaskPt(const char *name) :AliAnalysisTask(name,""), fESD(0), fHistPt(0) {
// Constructor.
// Input slot #0 works with an Ntuple
DefineInput(0, TChain::Class());
// Output slot #0 writes into a TH1 container
DefineOutput(0, TH1F::Class());
}
//________________________________________________________________________
void AliAnalysisTaskPt::ConnectInputData(Option_t *) {
printf(" ConnectInputData %s\n", GetName());
char ** address = (char **)GetBranchAddress(0, "ESD");
if (address) {
fESD = (AliESD*)(*address);
}
else {
fESD = new AliESD();
SetBranchAddress(0, "ESD", &fESD);
}
}
//________________________________________________________________________
void AliAnalysisTaskPt::CreateOutputObjects() {
if (!fHistPt) {
fHistPt = new TH1F("fHistPt","This is the Pt distribution",15,0.1,3.1);
fHistPt->SetStats(kTRUE);
fHistPt->GetXaxis()->SetTitle("P_{T} [GeV]");
fHistPt->GetYaxis()->SetTitle("#frac{dN}{dP_{T}}");
fHistPt->GetXaxis()->SetTitleColor(1);
fHistPt->SetMarkerStyle(kFullCircle);
}
}
//________________________________________________________________________
void AliAnalysisTaskPt::Exec(Option_t *) {
// Task making a pt distribution.
// Get input data
TChain *chain = (TChain*)GetInputData(0);
Long64_t ientry = chain->GetReadEntry();
if (!fESD) return;
cout<<"Entry: "<<ientry<<" - Tracks: "<<fESD->GetNumberOfTracks()<<endl;
for(Int_t iTracks = 0; iTracks < fESD->GetNumberOfTracks(); iTracks++) {
AliESDtrack * track = fESD->GetTrack(iTracks);
//UInt_t status = track->GetStatus();
Double_t momentum[3];
track->GetPxPyPz(momentum);
Double_t Pt = sqrt(pow(momentum[0],2) + pow(momentum[1],2));
fHistPt->Fill(Pt);
}//track loop
// Post final data. It will be written to a file with option "RECREATE"
PostData(0, fHistPt);
}
//________________________________________________________________________
void AliAnalysisTaskPt::Terminate(Option_t *) {
// Draw some histogram at the end.
if (!gROOT->IsBatch()) {
TCanvas *c1 = new TCanvas("c1","Pt",10,10,510,510);
c1->SetFillColor(10); c1->SetHighLightColor(10);
c1->cd(1)->SetLeftMargin(0.15); c1->cd(1)->SetBottomMargin(0.15);
c1->cd(1)->SetLogy();
fHistPt = (TH1F*)GetOutputData(0);
if (fHistPt) fHistPt->DrawCopy("E");
}
}
<|endoftext|> |
<commit_before>{
//load libraries
gROOT->Macro("initGlauberMC.C");
//run the example code:
//AliGlauberMC::runAndSaveNucleons(10000,"Pb","Pb",72);
AliGlauberMC::runAndSaveNtuple(10000,"Pb","Pb",72);
}
<commit_msg>document a few settings<commit_after>{
//load libraries
gROOT->Macro("initGlauberMC.C");
Int_t nevents = 10000; // number of events to simulate
// supported systems are e.g. "p", "d", "Si", "Au", "Pb", "U"
Option_t *sysA="Pb";
Option_t *sysB="Pb";
Double_t signn=72; // inelastic nucleon nucleon cross section
const char *fname="GlauberMC_PbPb_ntuple.root"; // name output file
// run the code to produce an ntuple:
// AliGlauberMC::runAndSaveNucleons(10000,"Pb","Pb",72);
Double_t mind=0.4;
AliGlauberMC::runAndSaveNtuple(nevents,sysA,sysB,signn,mind,fname);
}
<|endoftext|> |
<commit_before>
AliAnalysisTask *AddTaskTPCTOFpA(Int_t identifier = 0, Bool_t isMC = kFALSE, Bool_t isTPConly = kFALSE, Bool_t writeOwnFile = kFALSE, Bool_t saveMotherPDG = kFALSE, Bool_t useEvenDcaBinning = kFALSE, Bool_t smallTHnSparse = kFALSE, Double_t nSigmaTPCLow= -3., Double_t nSigmaTPCHigh = 3., Double_t rapidityLow = -0.5, Double_t rapidityHigh = 0.5, Bool_t ispA=kTRUE, Bool_t rapCMS = kFALSE, TString multEst = "V0M", Bool_t setTrackCuts = kFALSE, AliESDtrackCuts *ESDtrackCuts = 0){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_janielsk_TPCTOFpA", "No analysis manager found.");
return 0;
}
//============= Set Task Name ===================
//TString taskName=("AliAnalysisTPCTOFpA.cxx+g");
//===============================================
// Load the task
//gROOT->LoadMacro(taskName.Data());
//========= Add task to the ANALYSIS manager =====
//normal tracks
AliAnalysisTPCTOFpA *task = new AliAnalysisTPCTOFpA("janielskTaskTPCTOFpA");
task->SelectCollisionCandidates(AliVEvent::kCINT5);
//switches
if (isMC) task->SetIsMCtrue(isMC);
if (isTPConly)task->SetUseTPConlyTracks(isTPConly);
if (saveMotherPDG) task->SetSaveMotherPDG(saveMotherPDG);
if (useEvenDcaBinning) task->SetEvenDCAbinning(kTRUE);
if (smallTHnSparse){
task->SetSmallTHnSparse(kTRUE);
task->SetTPCnSigmaCuts(nSigmaTPCLow,nSigmaTPCHigh);
task->SetRapidityCuts(rapidityLow,rapidityHigh);
}
if (ispA) task->SetIspA(kTRUE);
if (rapCMS) task->SetRapCMS(kTRUE);
task->SetCentEst(multEst.Data());
//initialize task
task->Initialize();
//esd cuts need to be set after initialize or cuts will be replaced by standard cuts in initialize
if (setTrackCuts) task->SetESDtrackCuts(ESDtrackCuts);
//add task to manager
mgr->AddTask(task);
//================================================
// data containers
//================================================
// find input container
//below the trunk version
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
/*
//dumm output container
AliAnalysisDataContainer *coutput0 =
mgr->CreateContainer(Form("akalweit_tree%i",identifier),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
Form("akalweit_default%i",identifier));
//define output containers, please use 'username'_'somename'
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("akalweit_TPCTOFpA%i",identifier), TList::Class(),
AliAnalysisManager::kOutputContainer,Form("akalweit_TPCTOFpA%i.root",identifier));
*/
if (!writeOwnFile) {
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("janielsk_TPCTOFpA%i",identifier), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:janielsk_TPCTOFpA", AliAnalysisManager::GetCommonFileName()));
}
else {
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("janielsk_TPCTOFpA%i",identifier), TList::Class(), AliAnalysisManager::kOutputContainer, Form("janielsk_TPCTOFpA.root"));
}
//connect containers
//
mgr->ConnectInput (task, 0, cinput );
//mgr->ConnectOutput (task, 0, coutput0);
mgr->ConnectOutput (task, 1, coutput1);
return task;
}
<commit_msg>Slight change in the output container.<commit_after>
AliAnalysisTask *AddTaskTPCTOFpA(Int_t identifier = 0, Bool_t isMC = kFALSE, Bool_t isTPConly = kFALSE, Bool_t writeOwnFile = kFALSE, Bool_t saveMotherPDG = kFALSE, Bool_t useEvenDcaBinning = kFALSE, Bool_t smallTHnSparse = kFALSE, Double_t nSigmaTPCLow= -3., Double_t nSigmaTPCHigh = 3., Double_t rapidityLow = -0.5, Double_t rapidityHigh = 0.5, Bool_t ispA=kTRUE, Bool_t rapCMS = kFALSE, TString multEst = "V0M", Bool_t setTrackCuts = kFALSE, AliESDtrackCuts *ESDtrackCuts = 0){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_janielsk_TPCTOFpA", "No analysis manager found.");
return 0;
}
//============= Set Task Name ===================
//TString taskName=("AliAnalysisTPCTOFpA.cxx+g");
//===============================================
// Load the task
//gROOT->LoadMacro(taskName.Data());
//========= Add task to the ANALYSIS manager =====
//normal tracks
AliAnalysisTPCTOFpA *task = new AliAnalysisTPCTOFpA("janielskTaskTPCTOFpA");
task->SelectCollisionCandidates(AliVEvent::kCINT5);
//switches
if (isMC) task->SetIsMCtrue(isMC);
if (isTPConly)task->SetUseTPConlyTracks(isTPConly);
if (saveMotherPDG) task->SetSaveMotherPDG(saveMotherPDG);
if (useEvenDcaBinning) task->SetEvenDCAbinning(kTRUE);
if (smallTHnSparse){
task->SetSmallTHnSparse(kTRUE);
task->SetTPCnSigmaCuts(nSigmaTPCLow,nSigmaTPCHigh);
task->SetRapidityCuts(rapidityLow,rapidityHigh);
}
if (ispA) task->SetIspA(kTRUE);
if (rapCMS) task->SetRapCMS(kTRUE);
task->SetCentEst(multEst.Data());
//initialize task
task->Initialize();
//esd cuts need to be set after initialize or cuts will be replaced by standard cuts in initialize
if (setTrackCuts) task->SetESDtrackCuts(ESDtrackCuts);
//add task to manager
mgr->AddTask(task);
//================================================
// data containers
//================================================
// find input container
//below the trunk version
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
/*
//dumm output container
AliAnalysisDataContainer *coutput0 =
mgr->CreateContainer(Form("akalweit_tree%i",identifier),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
Form("akalweit_default%i",identifier));
//define output containers, please use 'username'_'somename'
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("akalweit_TPCTOFpA%i",identifier), TList::Class(),
AliAnalysisManager::kOutputContainer,Form("akalweit_TPCTOFpA%i.root",identifier));
*/
AliAnalysisDataContainer *coutput1;
if (!writeOwnFile) {
coutput1 = mgr->CreateContainer(Form("janielsk_TPCTOFpA%i",identifier), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:janielsk_TPCTOFpA", AliAnalysisManager::GetCommonFileName()));
}
else {
coutput1 = mgr->CreateContainer(Form("janielsk_TPCTOFpA%i",identifier), TList::Class(), AliAnalysisManager::kOutputContainer, Form("janielsk_TPCTOFpA.root"));
}
//connect containers
//
mgr->ConnectInput (task, 0, cinput );
//mgr->ConnectOutput (task, 0, coutput0);
mgr->ConnectOutput (task, 1, coutput1);
return task;
}
<|endoftext|> |
<commit_before>// QmitkFctMediator.cpp: implementation of the QmitkFctMediator class.
//
//////////////////////////////////////////////////////////////////////
#include "QmitkFctMediator.h"
#include <qwidgetstack.h>
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qtoolbar.h>
#include <qaction.h>
#include <qabstractlayout.h>
#include <qlayout.h>
#include <qsplitter.h>
#include <stdio.h>
#include <qapplication.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
const QSizePolicy ignored(QSizePolicy::Ignored, QSizePolicy::Ignored);
const QSizePolicy preferred(QSizePolicy::Preferred, QSizePolicy::Preferred);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
QmitkFctMediator::QmitkFctMediator(QObject *parent, const char *name) : QObject(parent, name),
m_MainStack(NULL), m_ControlStack(NULL), m_ButtonMenu(NULL), m_ToolBar(NULL), m_DefaultMain(NULL),
m_FunctionalityActionGroup(NULL),
m_NumOfFuncs(0), m_CurrentFunctionality(0), m_LayoutTemplate(NULL)
{
}
QmitkFctMediator::~QmitkFctMediator()
{
/* QmitkFunctionality *functionality;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next() )
delete functionality;
qfl.clear();*/
}
void QmitkFctMediator::initialize(QWidget *aLayoutTemplate)
{
if(aLayoutTemplate==NULL)
return;
m_LayoutTemplate = static_cast<QWidget*>(aLayoutTemplate->child("LayoutTemplate", "QmitkControlsRightFctLayoutTemplate"));
QWidget *w;
if((w=static_cast<QWidget*>(aLayoutTemplate->child("MainParent", "QWidget")))!=NULL)
{
QHBoxLayout* hlayout=new QHBoxLayout(w);
hlayout->setAutoAdd(true);
m_MainStack = new QWidgetStack(w, "QmitkFctMediator::mainStack");
//m_MainStack->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum, 1, 0, m_MainStack->sizePolicy().hasHeightForWidth()) );
m_DefaultMain = new QWidget(m_MainStack,"QmitkFctMediator::m_DefaultMain");
m_MainStack->addWidget(m_DefaultMain);
connect( m_MainStack, SIGNAL(aboutToShow(int)), this, SLOT(functionalitySelected(int)) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ControlParent", "QWidget")))!=NULL)
{
QHBoxLayout* hlayout=new QHBoxLayout(w);
hlayout->setAutoAdd(true);
m_ControlStack = new QWidgetStack(w, "QmitkFctMediator::controlStack");
//m_ControlStack->setSizePolicy( QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum, 0, 1, m_ControlStack->sizePolicy().hasHeightForWidth()) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ButtonMenuParent", "QButtonGroup")))!=NULL)
{
m_ButtonMenu=static_cast<QButtonGroup*>(w);
m_ButtonMenu->setExclusive(true);
if(m_ButtonMenu!=NULL)
connect( m_ButtonMenu, SIGNAL(clicked(int)), this, SLOT(raiseFunctionality(int)) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ToolBar", "QWidget")))!=NULL)
{
m_ToolBar=w;
m_FunctionalityActionGroup = new QActionGroup( this );
m_FunctionalityActionGroup->setExclusive( TRUE );
connect( m_FunctionalityActionGroup, SIGNAL( selected( QAction* ) ), this, SLOT( raiseFunctionality( QAction* ) ) );
}
}
bool QmitkFctMediator::addFunctionality(QmitkFunctionality * functionality)
{
if(functionality==NULL)
{
if(m_ButtonMenu!=NULL)
{
QLayout * menuLayout = m_ButtonMenu->layout();
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
menuLayout->addItem( spacer );
}
return true;
}
qfl.append(functionality);
connect(functionality, SIGNAL(availabilityChanged()), this, SLOT(checkAvailability()));
QPushButton* funcButton=NULL;
if(m_ButtonMenu!=NULL)
{
QLayout * menuLayout = m_ButtonMenu->layout();
if(menuLayout==NULL)
{
menuLayout = new QVBoxLayout(m_ButtonMenu,0,10);
menuLayout->setSpacing( 2 );
menuLayout->setMargin( 11 );
}
char number[20]; sprintf(number,"%d",m_NumOfFuncs);
funcButton = new QPushButton(functionality->getFunctionalityName(), m_ButtonMenu, number);
funcButton->setToggleButton(true);
menuLayout->addItem(new QWidgetItem(funcButton));
if((qfl.count()>1) && (functionality->isAvailable()==false))
funcButton->setEnabled(false);
}
QAction* action=NULL;
if(m_FunctionalityActionGroup!=NULL)
{
action = functionality->createAction(m_FunctionalityActionGroup);
if(action!=NULL)
{
action->setToggleAction( true );
if(m_ToolBar!=NULL)
action->addTo( m_ToolBar );
}
}
qal.append(action);
if(m_MainStack!=NULL)
{
QWidget * mainWidget = functionality->createMainWidget(m_MainStack);
if((mainWidget!=NULL) && (mainWidget->parent()!=m_DefaultMain))
{
mainWidget->setSizePolicy(ignored);
m_MainStack->addWidget(mainWidget, m_NumOfFuncs+1);
}
else
m_MainStack->addWidget(new QWidget(m_MainStack, "QmitkFctMediator::dummyMain"), m_NumOfFuncs+1);
}
if(m_ControlStack!=NULL)
{
QWidget * controlWidget = functionality->createControlWidget(m_ControlStack);
if(controlWidget!=NULL)
{
controlWidget->setSizePolicy(ignored);
m_ControlStack->addWidget(controlWidget, m_NumOfFuncs);
}
else
m_ControlStack->addWidget(new QWidget(m_ControlStack, "QmitkFctMediator::dummyControl"), m_NumOfFuncs);
}
if(m_NumOfFuncs==0)
{
if(funcButton!=NULL)
funcButton->setOn(true);
if(action!=NULL)
action->setOn(true);
if(m_ControlStack!=NULL)
m_ControlStack->raiseWidget(0);
if((m_MainStack!=NULL) && (strcmp(m_MainStack->widget(0+1)->name(),"QmitkFctMediator::dummyMain")!=0))
m_MainStack->raiseWidget(0+1);
}
functionality->createConnections();
++m_NumOfFuncs;
return true;
}
QWidget * QmitkFctMediator::getControlParent()
{
return m_ControlStack;
}
QWidget * QmitkFctMediator::getMainParent()
{
return m_MainStack;
}
QButtonGroup * QmitkFctMediator::getButtonMenu()
{
return m_ButtonMenu;
}
QWidget * QmitkFctMediator::getToolBar()
{
return m_ToolBar;
}
QWidget * QmitkFctMediator::getDefaultMain()
{
return m_DefaultMain;
}
void QmitkFctMediator::selecting(int id)
{
if(id!=m_CurrentFunctionality)
qfl.at(m_CurrentFunctionality)->deactivated();
}
void QmitkFctMediator::functionalitySelected(int id)
{
if(id==0) return;
m_CurrentFunctionality=id-1; //kommt von m_MainStack und der hat einen Eintrag mehr (wg. m_DefaultMain)
qfl.at(m_CurrentFunctionality)->activated();
}
QmitkFunctionality* QmitkFctMediator::getFunctionalityByName(const char *name)
{
QmitkFunctionality *functionality;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next() )
if(strcmp(functionality->getFunctionalityName().ascii(),name)==0)
return functionality;
return NULL;
}
void QmitkFctMediator::raiseFunctionality(int id)
{
QAction *action;
action=qal.at(id);
if((action!=NULL) && (action->isOn()==false))
{
action->setOn(true);
return; //we will come into this method again ...
}
if(m_ButtonMenu!=NULL)
((QButtonGroup*)m_ButtonMenu)->setButton(id);
if(m_ToolBar!=NULL)
((QButtonGroup*)m_ToolBar)->setButton(id);
selecting(id);
QWidget *oldVisibleWidget, *newVisibleWidget;
QSize osize, nsize;
oldVisibleWidget = m_ControlStack->visibleWidget();
newVisibleWidget = m_ControlStack->widget(id);
if((oldVisibleWidget!=NULL) && (oldVisibleWidget!=newVisibleWidget))
{
osize=oldVisibleWidget->minimumSizeHint();
oldVisibleWidget->setSizePolicy(ignored);
newVisibleWidget->setSizePolicy(preferred);
}
m_ControlStack->raiseWidget(newVisibleWidget);
m_LayoutTemplate->layout()->activate();
nsize=newVisibleWidget->minimumSizeHint();
oldVisibleWidget = m_MainStack->visibleWidget();
newVisibleWidget = m_MainStack->widget(id+1);
if(strcmp(newVisibleWidget->name(),"QmitkFctMediator::dummyMain")==0)
newVisibleWidget = m_MainStack->widget(0);
if((oldVisibleWidget!=NULL) && (oldVisibleWidget!=newVisibleWidget))
{
oldVisibleWidget->setSizePolicy(ignored);
newVisibleWidget->setSizePolicy(preferred);
}
m_MainStack->raiseWidget(newVisibleWidget);
if(m_LayoutTemplate!=NULL)
((QmitkControlsRightFctLayoutTemplate*)m_LayoutTemplate)->setControlSizeHint(&nsize);
// QApplication::sendPostedEvents(0, QEvent::LayoutHint);
functionalitySelected(id+1);
}
void QmitkFctMediator::raiseFunctionality(QAction* action)
{
int id=qal.find(action);
if(id>=0)
raiseFunctionality(id);
}
void QmitkFctMediator::raiseFunctionality(QmitkFunctionality* aFunctionality)
{
QmitkFunctionality *functionality;
int id=0;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next(),++id )
if(functionality==aFunctionality)
{
raiseFunctionality(id);
return;
}
}
void QmitkFctMediator::checkAvailability()
{
QmitkFunctionality *functionality;
int id;
if(m_ButtonMenu!=NULL)
for ( functionality=qfl.first(), id=0; functionality != 0; functionality=qfl.next(),++id )
((QButtonGroup*)m_ButtonMenu)->find(id)->setEnabled(functionality->isAvailable());
}
void QmitkFctMediator::hideControls(bool hide)
{
if(m_ControlStack==NULL) return;
QWidget *controlStackParent = dynamic_cast<QWidget*>(m_ControlStack->parent());
if(controlStackParent==NULL) return;
if(hide)
controlStackParent->hide();
else
controlStackParent->show();
}
void QmitkFctMediator::hideMenu(bool hide)
{
if(m_ButtonMenu=NULL) return;
if(hide)
m_ButtonMenu->hide();
else
m_ButtonMenu->show();
}
<commit_msg>*** empty log message ***<commit_after>
// QmitkFctMediator.cpp: implementation of the QmitkFctMediator class.
//
//////////////////////////////////////////////////////////////////////
#include "QmitkFctMediator.h"
#include <qwidgetstack.h>
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qtoolbar.h>
#include <qaction.h>
#include <qabstractlayout.h>
#include <qlayout.h>
#include <qsplitter.h>
#include <stdio.h>
#include <qapplication.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
const QSizePolicy ignored(QSizePolicy::Ignored, QSizePolicy::Ignored);
const QSizePolicy preferred(QSizePolicy::Preferred, QSizePolicy::Preferred);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
QmitkFctMediator::QmitkFctMediator(QObject *parent, const char *name) : QObject(parent, name),
m_MainStack(NULL), m_ControlStack(NULL), m_ButtonMenu(NULL), m_ToolBar(NULL), m_DefaultMain(NULL),
m_FunctionalityActionGroup(NULL),
m_NumOfFuncs(0), m_CurrentFunctionality(0), m_LayoutTemplate(NULL)
{
}
QmitkFctMediator::~QmitkFctMediator()
{
/* QmitkFunctionality *functionality;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next() )
delete functionality;
qfl.clear();*/
}
void QmitkFctMediator::initialize(QWidget *aLayoutTemplate)
{
if(aLayoutTemplate==NULL)
return;
m_LayoutTemplate = static_cast<QWidget*>(aLayoutTemplate->child("LayoutTemplate", "QmitkControlsRightFctLayoutTemplate"));
QWidget *w;
if((w=static_cast<QWidget*>(aLayoutTemplate->child("MainParent", "QWidget")))!=NULL)
{
QHBoxLayout* hlayout=new QHBoxLayout(w);
hlayout->setAutoAdd(true);
m_MainStack = new QWidgetStack(w, "QmitkFctMediator::mainStack");
//m_MainStack->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum, 1, 0, m_MainStack->sizePolicy().hasHeightForWidth()) );
m_DefaultMain = new QWidget(m_MainStack,"QmitkFctMediator::m_DefaultMain");
m_MainStack->addWidget(m_DefaultMain);
connect( m_MainStack, SIGNAL(aboutToShow(int)), this, SLOT(functionalitySelected(int)) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ControlParent", "QWidget")))!=NULL)
{
QHBoxLayout* hlayout=new QHBoxLayout(w);
hlayout->setAutoAdd(true);
m_ControlStack = new QWidgetStack(w, "QmitkFctMediator::controlStack");
//m_ControlStack->setSizePolicy( QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum, 0, 1, m_ControlStack->sizePolicy().hasHeightForWidth()) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ButtonMenuParent", "QButtonGroup")))!=NULL)
{
m_ButtonMenu=static_cast<QButtonGroup*>(w);
m_ButtonMenu->setExclusive(true);
if(m_ButtonMenu!=NULL)
connect( m_ButtonMenu, SIGNAL(clicked(int)), this, SLOT(raiseFunctionality(int)) );
}
if((w=static_cast<QWidget*>(aLayoutTemplate->child("ToolBar", "QWidget")))!=NULL)
{
m_ToolBar=w;
m_FunctionalityActionGroup = new QActionGroup( this );
m_FunctionalityActionGroup->setExclusive( TRUE );
connect( m_FunctionalityActionGroup, SIGNAL( selected( QAction* ) ), this, SLOT( raiseFunctionality( QAction* ) ) );
}
}
bool QmitkFctMediator::addFunctionality(QmitkFunctionality * functionality)
{
if(functionality==NULL)
{
if(m_ButtonMenu!=NULL)
{
QLayout * menuLayout = m_ButtonMenu->layout();
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
menuLayout->addItem( spacer );
}
return true;
}
qfl.append(functionality);
connect(functionality, SIGNAL(availabilityChanged()), this, SLOT(checkAvailability()));
QPushButton* funcButton=NULL;
if(m_ButtonMenu!=NULL)
{
QLayout * menuLayout = m_ButtonMenu->layout();
if(menuLayout==NULL)
{
menuLayout = new QVBoxLayout(m_ButtonMenu,0,10);
menuLayout->setSpacing( 2 );
menuLayout->setMargin( 11 );
}
char number[20]; sprintf(number,"%d",m_NumOfFuncs);
funcButton = new QPushButton(functionality->getFunctionalityName(), m_ButtonMenu, number);
funcButton->setToggleButton(true);
menuLayout->addItem(new QWidgetItem(funcButton));
if((qfl.count()>1) && (functionality->isAvailable()==false))
funcButton->setEnabled(false);
}
QAction* action=NULL;
if(m_FunctionalityActionGroup!=NULL)
{
action = functionality->createAction(m_FunctionalityActionGroup);
if(action!=NULL)
{
action->setToggleAction( true );
if(m_ToolBar!=NULL)
action->addTo( m_ToolBar );
}
}
qal.append(action);
if(m_MainStack!=NULL)
{
QWidget * mainWidget = functionality->createMainWidget(m_MainStack);
if((mainWidget!=NULL) && (mainWidget->parent()!=m_DefaultMain))
{
mainWidget->setSizePolicy(ignored);
m_MainStack->addWidget(mainWidget, m_NumOfFuncs+1);
}
else
m_MainStack->addWidget(new QWidget(m_MainStack, "QmitkFctMediator::dummyMain"), m_NumOfFuncs+1);
}
if(m_ControlStack!=NULL)
{
QWidget * controlWidget = functionality->createControlWidget(m_ControlStack);
if(controlWidget!=NULL)
{
controlWidget->setSizePolicy(ignored);
m_ControlStack->addWidget(controlWidget, m_NumOfFuncs);
}
else
m_ControlStack->addWidget(new QWidget(m_ControlStack, "QmitkFctMediator::dummyControl"), m_NumOfFuncs);
}
if(m_NumOfFuncs==0)
{
if(funcButton!=NULL)
funcButton->setOn(true);
if(action!=NULL)
action->setOn(true);
if(m_ControlStack!=NULL)
m_ControlStack->raiseWidget(0);
if((m_MainStack!=NULL) && (strcmp(m_MainStack->widget(0+1)->name(),"QmitkFctMediator::dummyMain")!=0))
m_MainStack->raiseWidget(0+1);
}
functionality->createConnections();
++m_NumOfFuncs;
return true;
}
QWidget * QmitkFctMediator::getControlParent()
{
return m_ControlStack;
}
QWidget * QmitkFctMediator::getMainParent()
{
return m_MainStack;
}
QButtonGroup * QmitkFctMediator::getButtonMenu()
{
return m_ButtonMenu;
}
QWidget * QmitkFctMediator::getToolBar()
{
return m_ToolBar;
}
QWidget * QmitkFctMediator::getDefaultMain()
{
return m_DefaultMain;
}
void QmitkFctMediator::selecting(int id)
{
if(id!=m_CurrentFunctionality)
qfl.at(m_CurrentFunctionality)->deactivated();
}
void QmitkFctMediator::functionalitySelected(int id)
{
if(id==0) return;
m_CurrentFunctionality=id-1; //kommt von m_MainStack und der hat einen Eintrag mehr (wg. m_DefaultMain)
qfl.at(m_CurrentFunctionality)->activated();
}
QmitkFunctionality* QmitkFctMediator::getFunctionalityByName(const char *name)
{
QmitkFunctionality *functionality;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next() )
if(strcmp(functionality->getFunctionalityName().ascii(),name)==0)
return functionality;
return NULL;
}
void QmitkFctMediator::raiseFunctionality(int id)
{
QAction *action;
action=qal.at(id);
if((action!=NULL) && (action->isOn()==false))
{
action->setOn(true);
return; //we will come into this method again ...
}
if(m_ButtonMenu!=NULL)
((QButtonGroup*)m_ButtonMenu)->setButton(id);
if(m_ToolBar!=NULL)
((QButtonGroup*)m_ToolBar)->setButton(id);
selecting(id);
QWidget *oldVisibleWidget, *newVisibleWidget;
QSize osize, nsize;
oldVisibleWidget = m_ControlStack->visibleWidget();
newVisibleWidget = m_ControlStack->widget(id);
if((oldVisibleWidget!=NULL) && (oldVisibleWidget!=newVisibleWidget))
{
osize=oldVisibleWidget->minimumSizeHint();
oldVisibleWidget->setSizePolicy(ignored);
newVisibleWidget->setSizePolicy(preferred);
}
m_ControlStack->raiseWidget(newVisibleWidget);
m_LayoutTemplate->layout()->activate();
nsize=newVisibleWidget->minimumSizeHint();
oldVisibleWidget = m_MainStack->visibleWidget();
newVisibleWidget = m_MainStack->widget(id+1);
if(strcmp(newVisibleWidget->name(),"QmitkFctMediator::dummyMain")==0)
newVisibleWidget = m_MainStack->widget(0);
if((oldVisibleWidget!=NULL) && (oldVisibleWidget!=newVisibleWidget))
{
oldVisibleWidget->setSizePolicy(ignored);
newVisibleWidget->setSizePolicy(preferred);
}
m_MainStack->raiseWidget(newVisibleWidget);
if(m_LayoutTemplate!=NULL)
((QmitkControlsRightFctLayoutTemplate*)m_LayoutTemplate)->setControlSizeHint(&nsize);
// QApplication::sendPostedEvents(0, QEvent::LayoutHint);
functionalitySelected(id+1);
}
void QmitkFctMediator::raiseFunctionality(QAction* action)
{
int id=qal.find(action);
if(id>=0)
raiseFunctionality(id);
}
void QmitkFctMediator::raiseFunctionality(QmitkFunctionality* aFunctionality)
{
QmitkFunctionality *functionality;
int id=0;
for ( functionality=qfl.first(); functionality != 0; functionality=qfl.next(),++id )
if(functionality==aFunctionality)
{
raiseFunctionality(id);
return;
}
}
void QmitkFctMediator::checkAvailability()
{
QmitkFunctionality *functionality;
int id;
if(m_ButtonMenu!=NULL)
for ( functionality=qfl.first(), id=0; functionality != 0; functionality=qfl.next(),++id )
((QButtonGroup*)m_ButtonMenu)->find(id)->setEnabled(functionality->isAvailable());
}
void QmitkFctMediator::hideControls(bool hide)
{
if(m_ControlStack==NULL) return;
QWidget *controlStackParent = dynamic_cast<QWidget*>(m_ControlStack->parent());
if(controlStackParent==NULL) return;
if(hide)
controlStackParent->hide();
else
controlStackParent->show();
}
void QmitkFctMediator::hideMenu(bool hide)
{
if(m_ButtonMenu=NULL) return;
if(hide)
m_ButtonMenu->hide();
else
m_ButtonMenu->show();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _VCL_WMADAPTOR_HXX_
#define _VCL_WMADAPTOR_HXX_
#include <tools/string.hxx>
#include <tools/gen.hxx>
#ifndef _PREX_H
#include <prex.h>
#include <X11/Xlib.h>
#include <postx.h>
#endif
#include <vclpluginapi.h>
#include <vector>
class SalDisplay;
class X11SalFrame;
namespace vcl_sal {
class VCLPLUG_GEN_PUBLIC WMAdaptor
{
public:
enum WMAtom {
// atoms for types
UTF8_STRING,
// atoms for extended WM hints
NET_SUPPORTED,
NET_SUPPORTING_WM_CHECK,
NET_WM_NAME,
NET_WM_DESKTOP,
NET_WM_ICON_NAME,
NET_WM_PID,
NET_WM_PING,
NET_WM_STATE,
NET_WM_STATE_MAXIMIZED_HORZ,
NET_WM_STATE_MAXIMIZED_VERT,
NET_WM_STATE_MODAL,
NET_WM_STATE_SHADED,
NET_WM_STATE_SKIP_PAGER,
NET_WM_STATE_SKIP_TASKBAR,
NET_WM_STATE_STAYS_ON_TOP,
NET_WM_STATE_STICKY,
NET_WM_STATE_FULLSCREEN,
NET_WM_STRUT,
NET_WM_STRUT_PARTIAL,
NET_WM_USER_TIME,
NET_WM_WINDOW_TYPE,
NET_WM_WINDOW_TYPE_DESKTOP,
NET_WM_WINDOW_TYPE_DIALOG,
NET_WM_WINDOW_TYPE_DOCK,
NET_WM_WINDOW_TYPE_MENU,
NET_WM_WINDOW_TYPE_NORMAL,
NET_WM_WINDOW_TYPE_TOOLBAR,
KDE_NET_WM_WINDOW_TYPE_OVERRIDE,
NET_WM_WINDOW_TYPE_SPLASH,
NET_WM_WINDOW_TYPE_UTILITY,
NET_NUMBER_OF_DESKTOPS,
NET_CURRENT_DESKTOP,
NET_WORKAREA,
// atoms for Gnome WM hints
WIN_SUPPORTING_WM_CHECK,
WIN_PROTOCOLS,
WIN_WORKSPACE_COUNT,
WIN_WORKSPACE,
WIN_LAYER,
WIN_STATE,
WIN_HINTS,
WIN_APP_STATE,
WIN_EXPANDED_SIZE,
WIN_ICONS,
WIN_WORKSPACE_NAMES,
WIN_CLIENT_LIST,
// atoms for general WM hints
WM_STATE,
MOTIF_WM_HINTS,
WM_PROTOCOLS,
WM_DELETE_WINDOW,
WM_TAKE_FOCUS,
WM_CLIENT_LEADER,
WM_COMMAND,
WM_LOCALE_NAME,
WM_TRANSIENT_FOR,
// special atoms
SAL_QUITEVENT,
SAL_USEREVENT,
SAL_EXTTEXTEVENT,
SAL_GETTIMEEVENT,
DTWM_IS_RUNNING,
VCL_SYSTEM_SETTINGS,
XSETTINGS,
XEMBED,
XEMBED_INFO,
NetAtomMax
};
/*
* flags for frame decoration
*/
static const int decoration_Title = 0x00000001;
static const int decoration_Border = 0x00000002;
static const int decoration_Resize = 0x00000004;
static const int decoration_MinimizeBtn = 0x00000008;
static const int decoration_MaximizeBtn = 0x00000010;
static const int decoration_CloseBtn = 0x00000020;
static const int decoration_All = 0x10000000;
/*
* window type
*/
enum WMWindowType
{
windowType_Normal,
windowType_ModalDialogue,
windowType_ModelessDialogue,
windowType_Utility,
windowType_Splash,
windowType_Toolbar,
windowType_Dock
};
protected:
SalDisplay* m_pSalDisplay; // Display to use
Display* m_pDisplay; // X Display of SalDisplay
String m_aWMName;
Atom m_aWMAtoms[ NetAtomMax];
int m_nDesktops;
bool m_bEqualWorkAreas;
::std::vector< Rectangle >
m_aWMWorkAreas;
bool m_bTransientBehaviour;
bool m_bEnableAlwaysOnTopWorks;
bool m_bLegacyPartialFullscreen;
int m_nWinGravity;
int m_nInitWinGravity;
bool m_bWMshouldSwitchWorkspace;
bool m_bWMshouldSwitchWorkspaceInit;
WMAdaptor( SalDisplay * )
;
void initAtoms();
bool getNetWmName();
/*
* returns whether this instance is useful
* only useful for createWMAdaptor
*/
virtual bool isValid() const;
bool getWMshouldSwitchWorkspace() const;
public:
virtual ~WMAdaptor();
/*
* creates a vaild WMAdaptor instance for the SalDisplay
*/
static WMAdaptor* createWMAdaptor( SalDisplay* );
/*
* may return an empty string if the window manager could
* not be identified.
*/
const String& getWindowManagerName() const
{ return m_aWMName; }
/*
* gets the number of workareas
*/
int getWorkAreaCount() const
{ return m_aWMWorkAreas.size(); }
/*
* gets the current work area/desktop number: [0,m_nDesktops[ or -1 if unknown
*/
int getCurrentWorkArea() const;
/*
* gets the workarea the specified window is on (or -1)
*/
int getWindowWorkArea( XLIB_Window aWindow ) const;
/*
* gets the specified workarea
*/
const Rectangle& getWorkArea( int n ) const
{ return m_aWMWorkAreas[n]; }
/*
* attemp to switch the desktop to a certain workarea
* if bConsiderWM is true, then on some WMs the call will not result in any action
*/
void switchToWorkArea( int nWorkArea, bool bConsiderWM = true ) const;
/*
* sets window title
*/
virtual void setWMName( X11SalFrame* pFrame, const String& rWMName ) const;
/*
* set NET_WM_PID
*/
virtual void setPID( X11SalFrame* pFrame ) const;
/*
* set WM_CLIENT_MACHINE
*/
virtual void setClientMachine( X11SalFrame* pFrame ) const;
virtual void answerPing( X11SalFrame*, XClientMessageEvent* ) const;
/*
* maximizes frame
* maximization can be toggled in either direction
* to get the original position and size
* use maximizeFrame( pFrame, false, false )
*/
virtual void maximizeFrame( X11SalFrame* pFrame, bool bHorizontal = true, bool bVertical = true ) const;
/*
* start/stop fullscreen mode on a frame
*/
virtual void showFullScreen( X11SalFrame* pFrame, bool bFullScreen ) const;
/*
* tell whether legacy partial full screen handling is necessary
* see #i107249#: NET_WM_STATE_FULLSCREEN is not well defined, but de facto
* modern WM's interpret it the "right" way, namely they make "full screen"
* taking twin view or Xinerama into accound and honor the positioning hints
* to see which screen actually was meant to use for fullscreen.
*/
bool isLegacyPartialFullscreen() const
{ return m_bLegacyPartialFullscreen; }
/*
* set window struts
*/
virtual void setFrameStruts( X11SalFrame*pFrame,
int left, int right, int top, int bottom,
int left_start_y, int left_end_y,
int right_start_y, int right_end_y,
int top_start_x, int top_end_x,
int bottom_start_x, int bottom_end_x ) const;
/*
* set _NET_WM_USER_TIME property, if NetWM
*/
virtual void setUserTime( X11SalFrame* i_pFrame, long i_nUserTime ) const;
/*
* tells whether fullscreen mode is supported by WM
*/
bool supportsFullScreen() const { return m_aWMAtoms[ NET_WM_STATE_FULLSCREEN ] != 0; }
/*
* shade/unshade frame
*/
virtual void shade( X11SalFrame* pFrame, bool bToShaded ) const;
/*
* set hints what decoration is needed;
* must be called before showing the frame
*/
virtual void setFrameTypeAndDecoration( X11SalFrame* pFrame, WMWindowType eType, int nDecorationFlags, X11SalFrame* pTransientFrame = NULL ) const;
/*
* tells whether there is WM support for splash screens
*/
bool supportsSplash() const { return m_aWMAtoms[ NET_WM_WINDOW_TYPE_SPLASH ] != 0; }
/*
* tells whteher there is WM support for NET_WM_WINDOW_TYPE_TOOLBAR
*/
bool supportsToolbar() const { return m_aWMAtoms[ NET_WM_WINDOW_TYPE_TOOLBAR ] != 0; }
/*
* enables always on top or equivalent if possible
*/
virtual void enableAlwaysOnTop( X11SalFrame* pFrame, bool bEnable ) const;
/*
* tells whether enableAlwaysOnTop actually works with this WM
*/
bool isAlwaysOnTopOK() const { return m_bEnableAlwaysOnTopWorks; }
/*
* handle WM messages (especially WM state changes)
*/
virtual int handlePropertyNotify( X11SalFrame* pFrame, XPropertyEvent* pEvent ) const;
/*
* called by SalFrame::Show: time to update state properties
*/
virtual void frameIsMapping( X11SalFrame* ) const;
/*
* gets a WM atom
*/
Atom getAtom( WMAtom eAtom ) const
{ return m_aWMAtoms[ eAtom ]; }
int getPositionWinGravity () const
{ return m_nWinGravity; }
int getInitWinGravity() const
{ return m_nInitWinGravity; }
/*
* expected behaviour is that the WM will not allow transient
* windows to get stacked behind the windows they are transient for
*/
bool isTransientBehaviourAsExpected() const
{ return m_bTransientBehaviour; }
/*
* changes the transient hint of a window to reference frame
* if reference frame is NULL the root window is used instead
*/
void changeReferenceFrame( X11SalFrame* pFrame, X11SalFrame* pReferenceFrame ) const;
};
} // namespace
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>clarify a different meaning of WorkArea.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _VCL_WMADAPTOR_HXX_
#define _VCL_WMADAPTOR_HXX_
#include <tools/string.hxx>
#include <tools/gen.hxx>
#ifndef _PREX_H
#include <prex.h>
#include <X11/Xlib.h>
#include <postx.h>
#endif
#include <vclpluginapi.h>
#include <vector>
class SalDisplay;
class X11SalFrame;
namespace vcl_sal {
class VCLPLUG_GEN_PUBLIC WMAdaptor
{
public:
enum WMAtom {
// atoms for types
UTF8_STRING,
// atoms for extended WM hints
NET_SUPPORTED,
NET_SUPPORTING_WM_CHECK,
NET_WM_NAME,
NET_WM_DESKTOP,
NET_WM_ICON_NAME,
NET_WM_PID,
NET_WM_PING,
NET_WM_STATE,
NET_WM_STATE_MAXIMIZED_HORZ,
NET_WM_STATE_MAXIMIZED_VERT,
NET_WM_STATE_MODAL,
NET_WM_STATE_SHADED,
NET_WM_STATE_SKIP_PAGER,
NET_WM_STATE_SKIP_TASKBAR,
NET_WM_STATE_STAYS_ON_TOP,
NET_WM_STATE_STICKY,
NET_WM_STATE_FULLSCREEN,
NET_WM_STRUT,
NET_WM_STRUT_PARTIAL,
NET_WM_USER_TIME,
NET_WM_WINDOW_TYPE,
NET_WM_WINDOW_TYPE_DESKTOP,
NET_WM_WINDOW_TYPE_DIALOG,
NET_WM_WINDOW_TYPE_DOCK,
NET_WM_WINDOW_TYPE_MENU,
NET_WM_WINDOW_TYPE_NORMAL,
NET_WM_WINDOW_TYPE_TOOLBAR,
KDE_NET_WM_WINDOW_TYPE_OVERRIDE,
NET_WM_WINDOW_TYPE_SPLASH,
NET_WM_WINDOW_TYPE_UTILITY,
NET_NUMBER_OF_DESKTOPS,
NET_CURRENT_DESKTOP,
NET_WORKAREA,
// atoms for Gnome WM hints
WIN_SUPPORTING_WM_CHECK,
WIN_PROTOCOLS,
WIN_WORKSPACE_COUNT,
WIN_WORKSPACE,
WIN_LAYER,
WIN_STATE,
WIN_HINTS,
WIN_APP_STATE,
WIN_EXPANDED_SIZE,
WIN_ICONS,
WIN_WORKSPACE_NAMES,
WIN_CLIENT_LIST,
// atoms for general WM hints
WM_STATE,
MOTIF_WM_HINTS,
WM_PROTOCOLS,
WM_DELETE_WINDOW,
WM_TAKE_FOCUS,
WM_CLIENT_LEADER,
WM_COMMAND,
WM_LOCALE_NAME,
WM_TRANSIENT_FOR,
// special atoms
SAL_QUITEVENT,
SAL_USEREVENT,
SAL_EXTTEXTEVENT,
SAL_GETTIMEEVENT,
DTWM_IS_RUNNING,
VCL_SYSTEM_SETTINGS,
XSETTINGS,
XEMBED,
XEMBED_INFO,
NetAtomMax
};
/*
* flags for frame decoration
*/
static const int decoration_Title = 0x00000001;
static const int decoration_Border = 0x00000002;
static const int decoration_Resize = 0x00000004;
static const int decoration_MinimizeBtn = 0x00000008;
static const int decoration_MaximizeBtn = 0x00000010;
static const int decoration_CloseBtn = 0x00000020;
static const int decoration_All = 0x10000000;
/*
* window type
*/
enum WMWindowType
{
windowType_Normal,
windowType_ModalDialogue,
windowType_ModelessDialogue,
windowType_Utility,
windowType_Splash,
windowType_Toolbar,
windowType_Dock
};
protected:
SalDisplay* m_pSalDisplay; // Display to use
Display* m_pDisplay; // X Display of SalDisplay
String m_aWMName;
Atom m_aWMAtoms[ NetAtomMax];
int m_nDesktops;
bool m_bEqualWorkAreas;
::std::vector< Rectangle >
m_aWMWorkAreas;
bool m_bTransientBehaviour;
bool m_bEnableAlwaysOnTopWorks;
bool m_bLegacyPartialFullscreen;
int m_nWinGravity;
int m_nInitWinGravity;
bool m_bWMshouldSwitchWorkspace;
bool m_bWMshouldSwitchWorkspaceInit;
WMAdaptor( SalDisplay * )
;
void initAtoms();
bool getNetWmName();
/*
* returns whether this instance is useful
* only useful for createWMAdaptor
*/
virtual bool isValid() const;
bool getWMshouldSwitchWorkspace() const;
public:
virtual ~WMAdaptor();
/*
* creates a vaild WMAdaptor instance for the SalDisplay
*/
static WMAdaptor* createWMAdaptor( SalDisplay* );
/*
* may return an empty string if the window manager could
* not be identified.
*/
const String& getWindowManagerName() const
{ return m_aWMName; }
/*
* gets the number of workareas (virtual desktops)
*/
int getWorkAreaCount() const
{ return m_aWMWorkAreas.size(); }
/*
* gets the current work area/desktop number: [0,m_nDesktops[ or -1 if unknown
*/
int getCurrentWorkArea() const;
/*
* gets the workarea the specified window is on (or -1)
*/
int getWindowWorkArea( XLIB_Window aWindow ) const;
/*
* gets the specified workarea
*/
const Rectangle& getWorkArea( int n ) const
{ return m_aWMWorkAreas[n]; }
/*
* attempt to switch the desktop to a certain workarea (ie. virtual desktops)
* if bConsiderWM is true, then on some WMs the call will not result in any action
*/
void switchToWorkArea( int nWorkArea, bool bConsiderWM = true ) const;
/*
* sets window title
*/
virtual void setWMName( X11SalFrame* pFrame, const String& rWMName ) const;
/*
* set NET_WM_PID
*/
virtual void setPID( X11SalFrame* pFrame ) const;
/*
* set WM_CLIENT_MACHINE
*/
virtual void setClientMachine( X11SalFrame* pFrame ) const;
virtual void answerPing( X11SalFrame*, XClientMessageEvent* ) const;
/*
* maximizes frame
* maximization can be toggled in either direction
* to get the original position and size
* use maximizeFrame( pFrame, false, false )
*/
virtual void maximizeFrame( X11SalFrame* pFrame, bool bHorizontal = true, bool bVertical = true ) const;
/*
* start/stop fullscreen mode on a frame
*/
virtual void showFullScreen( X11SalFrame* pFrame, bool bFullScreen ) const;
/*
* tell whether legacy partial full screen handling is necessary
* see #i107249#: NET_WM_STATE_FULLSCREEN is not well defined, but de facto
* modern WM's interpret it the "right" way, namely they make "full screen"
* taking twin view or Xinerama into accound and honor the positioning hints
* to see which screen actually was meant to use for fullscreen.
*/
bool isLegacyPartialFullscreen() const
{ return m_bLegacyPartialFullscreen; }
/*
* set window struts
*/
virtual void setFrameStruts( X11SalFrame*pFrame,
int left, int right, int top, int bottom,
int left_start_y, int left_end_y,
int right_start_y, int right_end_y,
int top_start_x, int top_end_x,
int bottom_start_x, int bottom_end_x ) const;
/*
* set _NET_WM_USER_TIME property, if NetWM
*/
virtual void setUserTime( X11SalFrame* i_pFrame, long i_nUserTime ) const;
/*
* tells whether fullscreen mode is supported by WM
*/
bool supportsFullScreen() const { return m_aWMAtoms[ NET_WM_STATE_FULLSCREEN ] != 0; }
/*
* shade/unshade frame
*/
virtual void shade( X11SalFrame* pFrame, bool bToShaded ) const;
/*
* set hints what decoration is needed;
* must be called before showing the frame
*/
virtual void setFrameTypeAndDecoration( X11SalFrame* pFrame, WMWindowType eType, int nDecorationFlags, X11SalFrame* pTransientFrame = NULL ) const;
/*
* tells whether there is WM support for splash screens
*/
bool supportsSplash() const { return m_aWMAtoms[ NET_WM_WINDOW_TYPE_SPLASH ] != 0; }
/*
* tells whteher there is WM support for NET_WM_WINDOW_TYPE_TOOLBAR
*/
bool supportsToolbar() const { return m_aWMAtoms[ NET_WM_WINDOW_TYPE_TOOLBAR ] != 0; }
/*
* enables always on top or equivalent if possible
*/
virtual void enableAlwaysOnTop( X11SalFrame* pFrame, bool bEnable ) const;
/*
* tells whether enableAlwaysOnTop actually works with this WM
*/
bool isAlwaysOnTopOK() const { return m_bEnableAlwaysOnTopWorks; }
/*
* handle WM messages (especially WM state changes)
*/
virtual int handlePropertyNotify( X11SalFrame* pFrame, XPropertyEvent* pEvent ) const;
/*
* called by SalFrame::Show: time to update state properties
*/
virtual void frameIsMapping( X11SalFrame* ) const;
/*
* gets a WM atom
*/
Atom getAtom( WMAtom eAtom ) const
{ return m_aWMAtoms[ eAtom ]; }
int getPositionWinGravity () const
{ return m_nWinGravity; }
int getInitWinGravity() const
{ return m_nInitWinGravity; }
/*
* expected behaviour is that the WM will not allow transient
* windows to get stacked behind the windows they are transient for
*/
bool isTransientBehaviourAsExpected() const
{ return m_bTransientBehaviour; }
/*
* changes the transient hint of a window to reference frame
* if reference frame is NULL the root window is used instead
*/
void changeReferenceFrame( X11SalFrame* pFrame, X11SalFrame* pReferenceFrame ) const;
};
} // namespace
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2013 Hyperceptive, LLC
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
#include "DisplayUpdater.h"
#include "RgbMatrix.h"
#include "RgbMatrixContainer.h"
#include "Thread.h"
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
// Data Visualization of CDIP Buoy Data on a 32x32 RGB LED Matrix.
class LedMatrixBuoyViz : public RgbMatrixContainer
{
public:
LedMatrixBuoyViz(RgbMatrix *m) : RgbMatrixContainer(m) {}
static const int SwellFontSize = 2;
static const int SwellFontWidth = 4;
void run()
{
Color red;
red.red = 255;
Color green;
green.green = 255;
Color blue;
blue.blue = 255;
//Dominant Swell
_matrix->putChar(0, 0, 'W', 2, green);
_matrix->putChar(7, 0, '1', 2, green);
_matrix->putChar(11, 0, '0', 2, green);
_matrix->putChar(15, 0, '\'', 2, green);
_matrix->putChar(20, 0, '1', 2, green);
_matrix->putChar(24, 0, '2', 2, green);
_matrix->putChar(29, 1, 's', 1, green);
//Secondary Swell
_matrix->putChar(0, 26, 'N', 2, blue);
_matrix->putChar(5, 26, 'W', 2, blue);
_matrix->putChar(14, 26, '3', 2, blue);
_matrix->putChar(18, 26, '\'', 2, blue);
_matrix->putChar(24, 26, '5', 2, blue);
_matrix->putChar(29, 27, 's', 1, blue);
/*
_matrix->setTextCursor(0, 27);
_matrix->setFontColor(blue);
_matrix->writeLetter('N');
_matrix->writeLetter('W');
_matrix->writeLetter(' ');
_matrix->writeLetter('3');
_matrix->writeLetter('\'');
_matrix->writeLetter(' ');
_matrix->writeLetter('5');
_matrix->writeLetter('s');
*/
_matrix->drawWedge(16, 16, 8, 180, 270, blue);
_matrix->drawWedge(16, 16, 12, 135, 225, green);
/*
Color white;
white.red = 80;
white.green = 80;
white.blue = 80;
_matrix->drawLine(3, 16, 16, 16, white);
*/
_matrix->fillCircle(16, 16, 1, red);
}
};
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
GpioProxy io;
if (!io.initialize())
return 1;
RgbMatrix *m = NULL;
m = new RgbMatrix(&io);
RgbMatrixContainer *display = NULL;
RgbMatrixContainer *updater = NULL;
display = new LedMatrixBuoyViz(m);
updater = new DisplayUpdater(m);
printf("\nRunning the Buoy Data Visualization.\n\n");
updater->start(10);
display->start();
printf("Press <RETURN> when done.\n");
getchar();
// Stop threads and wait for them to join.
if (display) delete display;
if (updater) delete updater;
// Clear and refresh the display.
m->clearDisplay();
m->updateDisplay();
delete m;
return 0;
}
<commit_msg>Setup Visualization<commit_after>// Copyright (c) 2013 Hyperceptive, LLC
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
#include "DisplayUpdater.h"
#include "RgbMatrix.h"
#include "RgbMatrixContainer.h"
#include "Thread.h"
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
// Data Visualization of CDIP Buoy Data on a 32x32 RGB LED Matrix.
class LedMatrixBuoyViz : public RgbMatrixContainer
{
public:
LedMatrixBuoyViz(RgbMatrix *m) : RgbMatrixContainer(m) {}
static const int SwellFontSize = 2;
static const int SwellFontWidth = 4;
void run()
{
Color red;
red.red = 255;
Color green;
green.green = 255;
Color blue;
blue.blue = 255;
Color white;
white.red = 255;
white.green = 255;
white.blue = 255;
// Different Stats to Display
// 1: Primary Swell
// 2: Seconday Swell
// 3: Tide
// 4: Wind
// 5: Time & Sunrise/Sunset
// 6: Temp: Air / Water
const int NumStats = 6;
int curStat = 1;
while (!isDone())
{
switch (curStat)
{
case 1:
// Dominant Swell
_matrix->putChar(0, 26, 'W', 2, green);
_matrix->putChar(7, 26, '1', 2, green);
_matrix->putChar(11, 26, '0', 2, green);
_matrix->putChar(15, 26, '\'', 2, green);
_matrix->putChar(20, 26, '1', 2, green);
_matrix->putChar(24, 26, '2', 2, green);
_matrix->putChar(29, 27, 's', 1, green);
_matrix->drawWedge(16, 11, 12, 135, 225, green);
_matrix->fillCircle(16, 11, 1, red); //buoy location
sleep(5);
_matrix->fadeDisplay();
sleep(1);
break;
case 2:
// Secondary Swell
_matrix->putChar(0, 26, 'N', 2, blue);
_matrix->putChar(5, 26, 'W', 2, blue);
_matrix->putChar(14, 26, '3', 2, blue);
_matrix->putChar(18, 26, '\'', 2, blue);
_matrix->putChar(24, 26, '5', 2, blue);
_matrix->putChar(29, 27, 's', 1, blue);
_matrix->drawWedge(16, 11, 8, 180, 270, blue);
_matrix->fillCircle(16, 11, 1, red); //buoy location
sleep(5);
_matrix->fadeDisplay();
sleep(1);
break;
case 3:
// TODO: Tide
break;
case 4:
// TODO: Wind
break;
case 5:
// TODO: Time & Sunrise / Sunset
_matrix->setTextCursor(0, 0);
_matrix->setFontSize(2);
_matrix->setFontColor(white);
_matrix->writeChar('9');
_matrix->writeChar(':');
_matrix->writeChar('5');
_matrix->writeChar('2');
_matrix->setTextCursor(21, 1);
_matrix->setFontSize(1);
_matrix->writeChar('P');
_matrix->writeChar('M');
sleep(5);
_matrix->fadeDisplay();
sleep(1);
break;
case 6:
// TODO: Temp: Air / Water
break;
}
//TODO: Sleep
curStat++;
if (curStat > NumStats) curStat = 1;
}
}
};
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
GpioProxy io;
if (!io.initialize())
return 1;
RgbMatrix *m = NULL;
m = new RgbMatrix(&io);
RgbMatrixContainer *display = NULL;
RgbMatrixContainer *updater = NULL;
display = new LedMatrixBuoyViz(m);
updater = new DisplayUpdater(m);
printf("\nRunning the Buoy Data Visualization.\n\n");
updater->start(10);
display->start();
printf("Press <RETURN> when done.\n");
getchar();
printf("Signaling visualization to stop.\n\n");
// Stop threads and wait for them to join.
if (display) delete display;
if (updater) delete updater;
// Clear and refresh the display.
m->clearDisplay();
m->updateDisplay();
delete m;
return 0;
}
<|endoftext|> |
<commit_before>// handle.cpp
#include "handle.h"
#include <GL/glew.h>
namespace gl = virvo::gl;
void gl::Buffer::destroy()
{
glDeleteBuffers(1, &name);
}
void gl::Framebuffer::destroy()
{
glDeleteFramebuffers(1, &name);
}
void gl::Renderbuffer::destroy()
{
glDeleteRenderbuffers(1, &name);
}
void gl::Texture::destroy()
{
glDeleteTextures(1, &name);
}
unsigned gl::createBuffer()
{
unsigned n = 0;
glGenBuffers(1, &n);
return n;
}
unsigned gl::createFramebuffer()
{
unsigned n = 0;
glGenFramebuffers(1, &n);
return n;
}
unsigned gl::createRenderbuffer()
{
unsigned n = 0;
glGenRenderbuffers(1, &n);
return n;
}
unsigned gl::createTexture()
{
unsigned n = 0;
glGenTextures(1, &n);
return n;
}
<commit_msg>Add copyright notice<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "handle.h"
#include <GL/glew.h>
namespace gl = virvo::gl;
void gl::Buffer::destroy()
{
glDeleteBuffers(1, &name);
}
void gl::Framebuffer::destroy()
{
glDeleteFramebuffers(1, &name);
}
void gl::Renderbuffer::destroy()
{
glDeleteRenderbuffers(1, &name);
}
void gl::Texture::destroy()
{
glDeleteTextures(1, &name);
}
unsigned gl::createBuffer()
{
unsigned n = 0;
glGenBuffers(1, &n);
return n;
}
unsigned gl::createFramebuffer()
{
unsigned n = 0;
glGenFramebuffers(1, &n);
return n;
}
unsigned gl::createRenderbuffer()
{
unsigned n = 0;
glGenRenderbuffers(1, &n);
return n;
}
unsigned gl::createTexture()
{
unsigned n = 0;
glGenTextures(1, &n);
return n;
}
<|endoftext|> |
<commit_before>#include "Organism.h"
//Constructor
Organism::Organism()
{
//Keep track of id numbers
static unsigned long int next_id = 0;
id = next_id;
++next_id;
//First and Last name lengths
int fNameLen = GetDistribution(std::uniform_int_distribution<int>(3, 8));
int lNameLen = GetDistribution(std::uniform_int_distribution<int>(4, 12));
//Generate name
for (int i = 0; i < fNameLen; ++i) {
fName += static_cast<char>(GetDistribution( std::uniform_int_distribution<int>(65, 90) ));
}
for (int i = 0; i < lNameLen; ++i) {
lName += static_cast<char>(GetDistribution( std::uniform_int_distribution<int>(65, 90) ));
}
//Organism is not asleep at creation
asleep = false;
asleepSince = -1.0;
//Organisms begin with energy normally distributed around 50% of their maximum
energy = std::max(unsigned int(GetDistribution(std::normal_distribution<float>(maxEnergy() / 2, maxEnergy() / 10))), maxEnergy());
//In case above energy distribution does not work out
//energy = GetDistribution(std::uniform_int_distribution<int>(0, maxEnergy() ));
age = 0.0;
for (int i = 0; i < ENUMSIZE; ++i){
float priority = GetDistribution(std::normal_distribution<float>(0.5f, 0.1));
if (priority < 0) priority = 0;
if (priority > 1) priority = 1;
priorities.insert(std::make_pair(priority, static_cast<Action>(i)));
}
}
//Destructor
Organism::~Organism()
{
}
//Get Organism's name
std::string Organism::getName() const {
return fName + ' ' + lName;
}
//Approximate "Species" of Organism by hashing its member variables
unsigned int Organism::getSpecies() const {
//Add hashing function here
//unsigned int seed = 487159078;
unsigned int hashsum = 0;
for (unsigned int i = 0; i < appendages.size(); ++i) {
hashsum += static_cast<unsigned int>(appendages[i]);
//Alternate casting option: Reinterpret
//const void * p = &appendages[i];
//const unsigned int * q = static_cast<const unsigned int *>(p);
//hashsum += *q;
}
return 0;
}
//Compare "Species" of 2 Organisms
bool Organism::compareSpecies(Organism other) const {
unsigned int otherSpecies = other.getSpecies();
unsigned int Species = getSpecies();
//Add comparison of hash values here
if ((std::max(Species, otherSpecies) -
std::min(Species, otherSpecies)) > DELTA) {
return false;
}
else {
return true;
}
}
//Attempt to eat given resource
//Note: Add ersource parameter to function
bool Organism::eat() {
//Determine if Organism has enough energy to digest food
//Note: May want to change this multiplier to be variable
//based on the Anatomy of the Organism
if (!evalEnergy(0.03)) return false;
return false;
}
//Attempt to Sleep
bool Organism::sleep(float curTime) {
//Organism is already asleep
if (asleep) return false;
//Organism is well rested, so sleep is unnecessary
if (energy > maxEnergy() / 2) return false;
asleepSince = curTime;
asleep = true;
return true;
}
//Attempt to Awaken from Sleep
bool Organism::wakeUp(float curTime) {
//Organism is Already Awake
if (!asleep) return false;
//Organism has not yet rested enough
if (energy < 9 * maxEnergy() / 10) return false;
//Note: Tweak Sleep Energy Gain multiplier
energy += (curTime - asleepSince) * 0.05;
//Adjust energy to maximum energy for Organism
energy = std::max(energy, maxEnergy());
asleep = false;
asleepSince = -1.0;
return true;
}
//Attempt to reproduce with another Organism
bool Organism::reproduce(Organism other) {
//Organisms of different species cannot reproduce
if (!compareSpecies(other)) {
return false;
}
//Organism needs enough energy to reproduce
if (!evalEnergy(0.85)) {
return false;
}
/*
Insert reproduction code here
*/
return true;
}
bool Organism::mutate() {
return false;
}
//Determine if Organism has enough energy for specified action
//Assumes mult > 0
bool Organism::evalEnergy(float mult) const {
//Minimum required energy to execute action
//Note: Update this as function of getSpecies() later
float minEnergy = 150 * mult;
return ((energy > minEnergy - EPSILON) && energy > 0);
}
//Maximum Energy the Organism may store
unsigned int Organism::maxEnergy() const {
//Note: may want to update/tweak this in the future (add multiplier)
return getSpecies();
}
//Preform Top Priority
bool Organism::act(Organism Other) {
auto itr = priorities.rbegin();
Action a = itr->second;
bool success;
switch (a) {
case SLEEP : success = sleep(time(NULL)); break; //Correct time usage?
case EAT : success = eat(); break;
case REPRODUCE : success = reproduce(Other); break;
case WAKEUP: success = wakeUp(time(NULL)); break; //Correct time usage?
}
PriorityType::iterator itr2 = priorities.begin();
std::pair<float, Action> tmp = std::make_pair((itr2->first) / 2, itr->second);
//priorities.erase(itr);
priorities.insert(tmp);
return success;
}<commit_msg>Fixed Action Syntax Error<commit_after>#include "Organism.h"
//Constructor
Organism::Organism()
{
//Keep track of id numbers
static unsigned long int next_id = 0;
id = next_id;
++next_id;
//First and Last name lengths
int fNameLen = GetDistribution(std::uniform_int_distribution<int>(3, 8));
int lNameLen = GetDistribution(std::uniform_int_distribution<int>(4, 12));
//Generate name
for (int i = 0; i < fNameLen; ++i) {
fName += static_cast<char>(GetDistribution( std::uniform_int_distribution<int>(65, 90) ));
}
for (int i = 0; i < lNameLen; ++i) {
lName += static_cast<char>(GetDistribution( std::uniform_int_distribution<int>(65, 90) ));
}
//Organism is not asleep at creation
asleep = false;
asleepSince = -1.0;
//Organisms begin with energy normally distributed around 50% of their maximum
energy = std::max(unsigned int(GetDistribution(std::normal_distribution<float>(maxEnergy() / 2, maxEnergy() / 10))), maxEnergy());
//In case above energy distribution does not work out
//energy = GetDistribution(std::uniform_int_distribution<int>(0, maxEnergy() ));
age = 0.0;
for (int i = 0; i < ENUMSIZE; ++i){
float priority = GetDistribution(std::normal_distribution<float>(0.5f, 0.1));
if (priority < 0) priority = 0;
if (priority > 1) priority = 1;
priorities.insert(std::make_pair(priority, static_cast<Action>(i)));
}
}
//Destructor
Organism::~Organism()
{
}
//Get Organism's name
std::string Organism::getName() const {
return fName + ' ' + lName;
}
//Approximate "Species" of Organism by hashing its member variables
unsigned int Organism::getSpecies() const {
//Add hashing function here
//unsigned int seed = 487159078;
unsigned int hashsum = 0;
for (unsigned int i = 0; i < appendages.size(); ++i) {
hashsum += static_cast<unsigned int>(appendages[i]);
//Alternate casting option: Reinterpret
//const void * p = &appendages[i];
//const unsigned int * q = static_cast<const unsigned int *>(p);
//hashsum += *q;
}
return 0;
}
//Compare "Species" of 2 Organisms
bool Organism::compareSpecies(Organism other) const {
unsigned int otherSpecies = other.getSpecies();
unsigned int Species = getSpecies();
//Add comparison of hash values here
if ((std::max(Species, otherSpecies) -
std::min(Species, otherSpecies)) > DELTA) {
return false;
}
else {
return true;
}
}
//Attempt to eat given resource
//Note: Add ersource parameter to function
bool Organism::eat() {
//Determine if Organism has enough energy to digest food
//Note: May want to change this multiplier to be variable
//based on the Anatomy of the Organism
//if (!evalEnergy(0.03)) return false;
return false;
}
//Attempt to Sleep
bool Organism::sleep(float curTime) {
//Organism is already asleep
if (asleep) return false;
//Organism is well rested, so sleep is unnecessary
//if (energy > maxEnergy() / 2) return false;
asleepSince = curTime;
asleep = true;
return true;
}
//Attempt to Awaken from Sleep
bool Organism::wakeUp(float curTime) {
//Organism is Already Awake
if (!asleep) return false;
//Organism has not yet rested enough
//if (energy < 9 * maxEnergy() / 10) return false;
//Note: Tweak Sleep Energy Gain multiplier
energy += (curTime - asleepSince) * 0.05;
//Adjust energy to maximum energy for Organism
energy = std::max(energy, maxEnergy());
asleep = false;
asleepSince = -1.0;
return true;
}
//Attempt to reproduce with another Organism
bool Organism::reproduce(Organism other) {
//Organisms of different species cannot reproduce
if (!compareSpecies(other)) {
return false;
}
//Organism needs enough energy to reproduce
/*if (!evalEnergy(0.85)) {
return false;
}*/
/*
Insert reproduction code here
*/
return true;
}
bool Organism::mutate() {
return false;
}
//Determine if Organism has enough energy for specified action
//Assumes mult > 0
bool Organism::evalEnergy(float mult) const {
//Minimum required energy to execute action
//Note: Update this as function of getSpecies() later
float minEnergy = 150 * mult;
return ((energy > minEnergy - EPSILON) && energy > 0);
}
//Maximum Energy the Organism may store
unsigned int Organism::maxEnergy() const {
//Note: may want to update/tweak this in the future (add multiplier)
return getSpecies();
}
//Preform Top Priority
bool Organism::act(Organism Other) {
auto itr = priorities.rbegin();
Action a = itr->second;
bool success;
switch (a) {
case SLEEP : success = sleep(time(NULL)); break; //Correct time usage?
case EAT : success = eat(); break;
case REPRODUCE : success = reproduce(Other); break;
case WAKEUP : success = wakeUp(time(NULL)); break; //Correct time usage?
}
PriorityType::iterator itr2 = priorities.begin();
std::pair<float, Action> tmp = std::make_pair((itr2->first) / 2, itr->second);
priorities.erase(std::next(itr).base());
priorities.insert(tmp);
return success;
}<|endoftext|> |
<commit_before>//
// parser_tables.cpp
// Parse
//
// Created by Andrew Hunter on 07/05/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <algorithm>
#include "parser_tables.h"
using namespace std;
using namespace contextfree;
using namespace lr;
/// \brief Ranks actions in the order they should appear in the final table
static inline int action_score(int action) {
switch (action) {
case lr_action::act_guard:
// Guard actions are always evaluated first, so we can substitute the guard symbol if it's matched
return 0;
case lr_action::act_weakreduce:
// Weak reduce actions come first as they should always be performed if their symbol will produce a shift
return 1;
case lr_action::act_shift:
case lr_action::act_divert:
// Shift actions are preferred if there's a conflict
return 2;
case lr_action::act_reduce:
// Reduce actions have the lowest priority
return 3;
case lr_action::act_goto:
// Gotos never actually produce a clash
return 4;
default:
return 5;
}
}
static inline bool compare_actions(const parser_tables::action& a, const parser_tables::action& b) {
// First, compare on symbol IDs
if (a.m_SymbolId < b.m_SymbolId) return true;
if (a.m_SymbolId > b.m_SymbolId) return false;
// Next, compare on action types
int aScore = action_score(a.m_Type);
int bScore = action_score(b.m_Type);
if (aScore < bScore) return true;
if (aScore > bScore) return false;
// Actions are equal
return false;
}
/// \brief Creates a parser from the result of the specified builder class
parser_tables::parser_tables(const lalr_builder& builder) {
// Allocate the tables
m_NumStates = builder.count_states();
m_NonterminalActions = new action*[m_NumStates];
m_TerminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
contextfree::end_of_input eoi;
contextfree::end_of_guard eog;
m_EndOfInput = builder.gram().identifier_for_item(eoi);
m_EndOfGuard = builder.gram().identifier_for_item(eog);
const grammar& gram = builder.gram();
map<int, int> ruleIds; // Maps their rule IDs to our rule IDs
vector<int> eogStates; // The end of guard states
// Build up the tables for each state
for (int stateId = 0; stateId < m_NumStates; stateId++) {
// Get the actions for this state
const lr_action_set& actions = builder.actions_for_state(stateId);
// Count the number of terminal and nonterminal actions
int termCount = 0;
int nontermCount = 0;
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
if ((*nextAction)->item()->type() == item::terminal) {
termCount++;
} else {
nontermCount++;
}
}
// Allocate action tables of the appropriate size
action* termActions = new action[termCount];
action* nontermActions = new action[nontermCount];
int termPos = 0; // Current item in the terminal table
int nontermPos = 0; // Current item in the nonterminal table
// Fill up the actions (not in order)
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
// Get the next state
int nextState = (*nextAction)->next_state();
int type = (*nextAction)->type();
// If the next action is a reduce action, then the next state should actually be the rule to reduce
if (type == lr_action::act_reduce || type == lr_action::act_weakreduce || type == lr_action::act_accept) {
// Look up the ID we assigned this rule
int ruleId = (*nextAction)->rule()->identifier(gram);
map<int, int>::iterator found = ruleIds.find(ruleId);
if (found == ruleIds.end()) {
nextState = (int)ruleIds.size();
ruleIds[ruleId] = nextState;
} else {
nextState = found->second;
}
}
if ((*nextAction)->item()->type() == item::terminal) {
// Add a new terminal action
termActions[termPos].m_Type = type;
termActions[termPos].m_NextState = nextState;
termActions[termPos].m_SymbolId = (*nextAction)->item()->symbol();
termPos++;
} else {
// Add a new nonterminal action
nontermActions[nontermPos].m_Type = type;
nontermActions[nontermPos].m_NextState = nextState;
nontermActions[nontermPos].m_SymbolId = gram.identifier_for_item((*nextAction)->item());
nontermPos++;
if (nontermActions[nontermPos].m_SymbolId == m_EndOfGuard) {
eogStates.push_back(stateId);
}
}
}
// Store the end of guard state table (we evaluate states in order, so this is already sorted)
m_NumEndOfGuards = (int) eogStates.size();
m_EndGuardStates = new int[m_NumEndOfGuards];
for (int x=0; x<m_NumEndOfGuards; x++) {
m_EndGuardStates[x] = eogStates[x];
}
// Sort the actions for this state
std::sort(termActions, termActions + termCount, compare_actions);
std::sort(nontermActions, nontermActions + nontermCount, compare_actions);
// Store the actions in the table
m_TerminalActions[stateId] = termActions;
m_NonterminalActions[stateId] = nontermActions;
m_Counts[stateId].m_NumTerms = termCount;
m_Counts[stateId].m_NumNonterms = nontermCount;
}
// Fill in the rule table
m_NumRules = (int)ruleIds.size();
m_Rules = new reduce_rule[ruleIds.size()];
for (map<int, int>::iterator ruleId = ruleIds.begin(); ruleId != ruleIds.end(); ruleId++) {
const rule_container& rule = gram.rule_with_identifier(ruleId->first);
m_Rules[ruleId->second].m_Identifier = gram.identifier_for_item(rule->nonterminal());
m_Rules[ruleId->second].m_Length = (int)rule->items().size();
}
}
/// \brief Copy constructor
parser_tables::parser_tables(const parser_tables& copyFrom)
: m_NumStates(copyFrom.m_NumStates)
, m_NumRules(copyFrom.m_NumRules)
, m_EndOfInput(copyFrom.m_EndOfInput)
, m_EndOfGuard(copyFrom.m_EndOfGuard) {
// Allocate the action tables
m_TerminalActions = new action*[m_NumStates];
m_NonterminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
// Copy the states
for (int stateId=0; stateId<m_NumStates; stateId++) {
// Copy the counts
m_Counts[stateId] = copyFrom.m_Counts[stateId];
// Allocate the array for this state
m_TerminalActions[stateId] = new action[m_Counts[stateId].m_NumTerms];
m_NonterminalActions[stateId] = new action[m_Counts[stateId].m_NumNonterms];
// Copy the terminals and nonterminals
for (int x=0; x<m_Counts[stateId].m_NumTerms; x++) {
m_TerminalActions[stateId][x] = copyFrom.m_TerminalActions[stateId][x];
}
for (int x=0; x<m_Counts[stateId].m_NumNonterms; x++) {
m_NonterminalActions[stateId][x] = copyFrom.m_NonterminalActions[stateId][x];
}
}
// Allocate the rule table
m_Rules = new reduce_rule[m_NumRules];
for (int ruleId=0; ruleId<m_NumRules; ruleId++) {
m_Rules[ruleId] = copyFrom.m_Rules[ruleId];
}
// Allocate the end of guard state table
m_NumEndOfGuards = copyFrom.m_NumEndOfGuards;
m_EndGuardStates = new int[m_NumEndOfGuards];
// Copy the states
for (int x=0; x<m_NumEndOfGuards; x++) {
m_EndGuardStates[x] = copyFrom.m_EndGuardStates[x];
}
}
/// \brief Assignment
parser_tables& parser_tables::operator=(const parser_tables& copyFrom) {
if (©From == this) return *this;
// TODO
return *this;
}
/// \brief Destructor
parser_tables::~parser_tables() {
// Destroy each entry in the parser table
for (int x=0; x<m_NumStates; x++) {
delete[] m_NonterminalActions[x];
delete[] m_TerminalActions[x];
}
// Destroy the tables themselves
delete[] m_NonterminalActions;
delete[] m_TerminalActions;
delete[] m_Rules;
delete[] m_Counts;
delete[] m_EndGuardStates;
}
<commit_msg>Whoops, was comparing something after a pointer had been updated.<commit_after>//
// parser_tables.cpp
// Parse
//
// Created by Andrew Hunter on 07/05/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <algorithm>
#include "parser_tables.h"
using namespace std;
using namespace contextfree;
using namespace lr;
/// \brief Ranks actions in the order they should appear in the final table
static inline int action_score(int action) {
switch (action) {
case lr_action::act_guard:
// Guard actions are always evaluated first, so we can substitute the guard symbol if it's matched
return 0;
case lr_action::act_weakreduce:
// Weak reduce actions come first as they should always be performed if their symbol will produce a shift
return 1;
case lr_action::act_shift:
case lr_action::act_divert:
// Shift actions are preferred if there's a conflict
return 2;
case lr_action::act_reduce:
// Reduce actions have the lowest priority
return 3;
case lr_action::act_goto:
// Gotos never actually produce a clash
return 4;
default:
return 5;
}
}
static inline bool compare_actions(const parser_tables::action& a, const parser_tables::action& b) {
// First, compare on symbol IDs
if (a.m_SymbolId < b.m_SymbolId) return true;
if (a.m_SymbolId > b.m_SymbolId) return false;
// Next, compare on action types
int aScore = action_score(a.m_Type);
int bScore = action_score(b.m_Type);
if (aScore < bScore) return true;
if (aScore > bScore) return false;
// Actions are equal
return false;
}
/// \brief Creates a parser from the result of the specified builder class
parser_tables::parser_tables(const lalr_builder& builder) {
// Allocate the tables
m_NumStates = builder.count_states();
m_NonterminalActions = new action*[m_NumStates];
m_TerminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
contextfree::end_of_input eoi;
contextfree::end_of_guard eog;
m_EndOfInput = builder.gram().identifier_for_item(eoi);
m_EndOfGuard = builder.gram().identifier_for_item(eog);
const grammar& gram = builder.gram();
map<int, int> ruleIds; // Maps their rule IDs to our rule IDs
vector<int> eogStates; // The end of guard states
// Build up the tables for each state
for (int stateId = 0; stateId < m_NumStates; stateId++) {
// Get the actions for this state
const lr_action_set& actions = builder.actions_for_state(stateId);
// Count the number of terminal and nonterminal actions
int termCount = 0;
int nontermCount = 0;
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
if ((*nextAction)->item()->type() == item::terminal) {
termCount++;
} else {
nontermCount++;
}
}
// Allocate action tables of the appropriate size
action* termActions = new action[termCount];
action* nontermActions = new action[nontermCount];
int termPos = 0; // Current item in the terminal table
int nontermPos = 0; // Current item in the nonterminal table
// Fill up the actions (not in order)
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
// Get the next state
int nextState = (*nextAction)->next_state();
int type = (*nextAction)->type();
// If the next action is a reduce action, then the next state should actually be the rule to reduce
if (type == lr_action::act_reduce || type == lr_action::act_weakreduce || type == lr_action::act_accept) {
// Look up the ID we assigned this rule
int ruleId = (*nextAction)->rule()->identifier(gram);
map<int, int>::iterator found = ruleIds.find(ruleId);
if (found == ruleIds.end()) {
nextState = (int)ruleIds.size();
ruleIds[ruleId] = nextState;
} else {
nextState = found->second;
}
}
if ((*nextAction)->item()->type() == item::terminal) {
// Add a new terminal action
termActions[termPos].m_Type = type;
termActions[termPos].m_NextState = nextState;
termActions[termPos].m_SymbolId = (*nextAction)->item()->symbol();
termPos++;
} else {
// Add a new nonterminal action
nontermActions[nontermPos].m_Type = type;
nontermActions[nontermPos].m_NextState = nextState;
nontermActions[nontermPos].m_SymbolId = gram.identifier_for_item((*nextAction)->item());
if (nontermActions[nontermPos].m_SymbolId == m_EndOfGuard) {
eogStates.push_back(stateId);
}
nontermPos++;
}
}
// Store the end of guard state table (we evaluate states in order, so this is already sorted)
m_NumEndOfGuards = (int) eogStates.size();
m_EndGuardStates = new int[m_NumEndOfGuards];
for (int x=0; x<m_NumEndOfGuards; x++) {
m_EndGuardStates[x] = eogStates[x];
}
// Sort the actions for this state
std::sort(termActions, termActions + termCount, compare_actions);
std::sort(nontermActions, nontermActions + nontermCount, compare_actions);
// Store the actions in the table
m_TerminalActions[stateId] = termActions;
m_NonterminalActions[stateId] = nontermActions;
m_Counts[stateId].m_NumTerms = termCount;
m_Counts[stateId].m_NumNonterms = nontermCount;
}
// Fill in the rule table
m_NumRules = (int)ruleIds.size();
m_Rules = new reduce_rule[ruleIds.size()];
for (map<int, int>::iterator ruleId = ruleIds.begin(); ruleId != ruleIds.end(); ruleId++) {
const rule_container& rule = gram.rule_with_identifier(ruleId->first);
m_Rules[ruleId->second].m_Identifier = gram.identifier_for_item(rule->nonterminal());
m_Rules[ruleId->second].m_Length = (int)rule->items().size();
}
}
/// \brief Copy constructor
parser_tables::parser_tables(const parser_tables& copyFrom)
: m_NumStates(copyFrom.m_NumStates)
, m_NumRules(copyFrom.m_NumRules)
, m_EndOfInput(copyFrom.m_EndOfInput)
, m_EndOfGuard(copyFrom.m_EndOfGuard) {
// Allocate the action tables
m_TerminalActions = new action*[m_NumStates];
m_NonterminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
// Copy the states
for (int stateId=0; stateId<m_NumStates; stateId++) {
// Copy the counts
m_Counts[stateId] = copyFrom.m_Counts[stateId];
// Allocate the array for this state
m_TerminalActions[stateId] = new action[m_Counts[stateId].m_NumTerms];
m_NonterminalActions[stateId] = new action[m_Counts[stateId].m_NumNonterms];
// Copy the terminals and nonterminals
for (int x=0; x<m_Counts[stateId].m_NumTerms; x++) {
m_TerminalActions[stateId][x] = copyFrom.m_TerminalActions[stateId][x];
}
for (int x=0; x<m_Counts[stateId].m_NumNonterms; x++) {
m_NonterminalActions[stateId][x] = copyFrom.m_NonterminalActions[stateId][x];
}
}
// Allocate the rule table
m_Rules = new reduce_rule[m_NumRules];
for (int ruleId=0; ruleId<m_NumRules; ruleId++) {
m_Rules[ruleId] = copyFrom.m_Rules[ruleId];
}
// Allocate the end of guard state table
m_NumEndOfGuards = copyFrom.m_NumEndOfGuards;
m_EndGuardStates = new int[m_NumEndOfGuards];
// Copy the states
for (int x=0; x<m_NumEndOfGuards; x++) {
m_EndGuardStates[x] = copyFrom.m_EndGuardStates[x];
}
}
/// \brief Assignment
parser_tables& parser_tables::operator=(const parser_tables& copyFrom) {
if (©From == this) return *this;
// TODO
return *this;
}
/// \brief Destructor
parser_tables::~parser_tables() {
// Destroy each entry in the parser table
for (int x=0; x<m_NumStates; x++) {
delete[] m_NonterminalActions[x];
delete[] m_TerminalActions[x];
}
// Destroy the tables themselves
delete[] m_NonterminalActions;
delete[] m_TerminalActions;
delete[] m_Rules;
delete[] m_Counts;
delete[] m_EndGuardStates;
}
<|endoftext|> |
<commit_before>#ifndef MTL_REMOTE_POINTER
#define MTL_REMOTE_POINTER
#include <string>
namespace mtl
{
namespace remote
{
//this is adequate only for testing AND/OR internal tools, with this client can easily crash server
template<typename T>
struct raw_pointer_unsafe
{
raw_pointer_unsafe() {}
raw_pointer_unsafe(uint64_t data) : _data(data) {}
uint64_t get() const
{
return _data;
}
void set(uint64_t d)
{
_data = d;
}
protected:
uint64_t _data;
};
template<typename T>
struct class_traits
{
using pointer_type = void;
};
template<typename R>
struct TransformType
{
using type = R;
};
template<typename R>
struct TransformType<R*>
{
using type = typename class_traits<R>::pointer_type;
};
namespace impl
{
template<typename OUT, typename IN>
struct type_wrapper
{
static const OUT& wrap_type(const IN& t)
{
return t;
}
static OUT&& wrap_type(IN&& t)
{
return std::move(t);
}
};
template<typename IN>
struct type_wrapper<raw_pointer_unsafe<IN>, IN*>
{
static raw_pointer_unsafe<IN> wrap_type(IN* t)
{
raw_pointer_unsafe<IN> p;
p.set((uint64_t)&t);
return p;
}
};
template<typename IN>
struct type_wrapper<IN*, raw_pointer_unsafe<IN>>
{
static IN* wrap_type(raw_pointer_unsafe<IN> p)
{
return (IN*)p.get();
}
};
}
template<typename OUT, typename IN>
OUT unwrap_type(IN t)
{
return impl::type_wrapper<OUT, IN>::wrap_type(t);
}
template<typename OUT, typename IN>
OUT wrap_type(IN t)
{
return impl::type_wrapper<OUT, IN>::wrap_type(t);
}
}
}
#endif<commit_msg>found ya, bug<commit_after>#ifndef MTL_REMOTE_POINTER
#define MTL_REMOTE_POINTER
#include <string>
namespace mtl
{
namespace remote
{
//this is adequate only for testing AND/OR internal tools, with this client can easily crash server
template<typename T>
struct raw_pointer_unsafe
{
raw_pointer_unsafe() {}
raw_pointer_unsafe(uint64_t data) : _data(data) {}
uint64_t get() const
{
return _data;
}
void set(uint64_t d)
{
_data = d;
}
protected:
uint64_t _data;
};
template<typename T>
struct class_traits
{
using pointer_type = void;
};
template<typename R>
struct TransformType
{
using type = R;
};
template<typename R>
struct TransformType<R*>
{
using type = typename class_traits<R>::pointer_type;
};
namespace impl
{
template<typename OUT, typename IN>
struct type_wrapper
{
static const OUT& wrap_type(const IN& t)
{
return t;
}
static OUT&& wrap_type(IN&& t)
{
return std::move(t);
}
};
template<typename IN>
struct type_wrapper<raw_pointer_unsafe<IN>, IN*>
{
static raw_pointer_unsafe<IN> wrap_type(IN* t)
{
raw_pointer_unsafe<IN> p;
p.set((uint64_t)t);
return p;
}
};
template<typename IN>
struct type_wrapper<IN*, raw_pointer_unsafe<IN>>
{
static IN* wrap_type(raw_pointer_unsafe<IN> p)
{
return (IN*)p.get();
}
};
}
template<typename OUT, typename IN>
OUT unwrap_type(IN t)
{
return impl::type_wrapper<OUT, IN>::wrap_type(t);
}
template<typename OUT, typename IN>
OUT wrap_type(IN t)
{
return impl::type_wrapper<OUT, IN>::wrap_type(t);
}
}
}
#endif<|endoftext|> |
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "db/compaction_picker.h"
#include <string>
#include "util/logging.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace rocksdb {
class CountingLogger : public Logger {
public:
virtual void Logv(const char* format, va_list ap) override { log_count++; }
size_t log_count;
};
class CompactionPickerTest {
public:
const Comparator* ucmp;
InternalKeyComparator icmp;
Options options;
ImmutableCFOptions ioptions;
MutableCFOptions mutable_cf_options;
LevelCompactionPicker level_compaction_picker;
std::string cf_name;
CountingLogger logger;
LogBuffer log_buffer;
VersionStorageInfo vstorage;
uint32_t file_num;
CompactionOptionsFIFO fifo_options;
std::vector<uint64_t> size_being_compacted;
CompactionPickerTest()
: ucmp(BytewiseComparator()),
icmp(ucmp),
ioptions(options),
mutable_cf_options(options, ioptions),
level_compaction_picker(ioptions, &icmp),
cf_name("dummy"),
log_buffer(InfoLogLevel::INFO_LEVEL, &logger),
vstorage(&icmp, ucmp, options.num_levels, kCompactionStyleLevel,
nullptr),
file_num(1) {
fifo_options.max_table_files_size = 1;
mutable_cf_options.RefreshDerivedOptions(ioptions);
size_being_compacted.resize(options.num_levels);
}
~CompactionPickerTest() {
auto* files = vstorage.GetFiles();
for (int i = 0; i < vstorage.NumberLevels(); i++) {
for (auto* f : files[i]) {
delete f;
}
}
}
void Add(int level, uint32_t file_number, const char* smallest,
const char* largest, uint64_t file_size = 0, uint32_t path_id = 0,
SequenceNumber smallest_seq = 100,
SequenceNumber largest_seq = 100) {
assert(level < vstorage.NumberLevels());
auto& files = vstorage.GetFiles()[level];
FileMetaData* f = new FileMetaData;
f->fd = FileDescriptor(file_number, path_id, file_size);
f->smallest = InternalKey(smallest, smallest_seq, kTypeValue);
f->largest = InternalKey(largest, largest_seq, kTypeValue);
f->compensated_file_size = file_size;
files.push_back(f);
}
void UpdateVersionStorageInfo() {
vstorage.ComputeCompactionScore(mutable_cf_options, fifo_options,
size_being_compacted);
vstorage.UpdateFilesBySize();
vstorage.UpdateNumNonEmptyLevels();
vstorage.GenerateFileIndexer();
vstorage.GenerateLevelFilesBrief();
vstorage.SetFinalized();
}
};
TEST(CompactionPickerTest, Empty) {
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() == nullptr);
}
TEST(CompactionPickerTest, Single) {
mutable_cf_options.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "p", "q");
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() == nullptr);
}
TEST(CompactionPickerTest, Level0Trigger) {
mutable_cf_options.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "150", "200");
Add(0, 2U, "200", "250");
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(2, compaction->num_input_files(0));
ASSERT_EQ(1U, compaction->input(0, 0)->fd.GetNumber());
ASSERT_EQ(2U, compaction->input(0, 1)->fd.GetNumber());
}
TEST(CompactionPickerTest, Level1Trigger) {
Add(1, 66U, "150", "200", 1000000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber());
}
TEST(CompactionPickerTest, Level1Trigger2) {
Add(1, 66U, "150", "200", 1000000000U);
Add(1, 88U, "201", "300", 1000000000U);
Add(2, 6U, "150", "179", 1000000000U);
Add(2, 7U, "180", "220", 1000000000U);
Add(2, 8U, "221", "300", 1000000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(2, compaction->num_input_files(1));
ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber());
ASSERT_EQ(6U, compaction->input(1, 0)->fd.GetNumber());
ASSERT_EQ(7U, compaction->input(1, 1)->fd.GetNumber());
}
TEST(CompactionPickerTest, LevelMaxScore) {
mutable_cf_options.target_file_size_base = 10000000;
mutable_cf_options.target_file_size_multiplier = 10;
Add(0, 1U, "150", "200", 1000000000U);
// Level 1 score 1.2
Add(1, 66U, "150", "200", 6000000U);
Add(1, 88U, "201", "300", 6000000U);
// Level 2 score 1.8. File 7 is the largest. Should be picked
Add(2, 6U, "150", "179", 60000000U);
Add(2, 7U, "180", "220", 60000001U);
Add(2, 8U, "221", "300", 60000000U);
// Level 3 score slightly larger than 1
Add(3, 26U, "150", "170", 260000000U);
Add(3, 27U, "171", "179", 260000000U);
Add(3, 28U, "191", "220", 260000000U);
Add(3, 29U, "221", "300", 260000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(7U, compaction->input(0, 0)->fd.GetNumber());
}
} // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); }
<commit_msg>Fix CompactionPickerTest.Level1Trigger2<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "db/compaction_picker.h"
#include <string>
#include "util/logging.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace rocksdb {
class CountingLogger : public Logger {
public:
virtual void Logv(const char* format, va_list ap) override { log_count++; }
size_t log_count;
};
class CompactionPickerTest {
public:
const Comparator* ucmp;
InternalKeyComparator icmp;
Options options;
ImmutableCFOptions ioptions;
MutableCFOptions mutable_cf_options;
LevelCompactionPicker level_compaction_picker;
std::string cf_name;
CountingLogger logger;
LogBuffer log_buffer;
VersionStorageInfo vstorage;
uint32_t file_num;
CompactionOptionsFIFO fifo_options;
std::vector<uint64_t> size_being_compacted;
CompactionPickerTest()
: ucmp(BytewiseComparator()),
icmp(ucmp),
ioptions(options),
mutable_cf_options(options, ioptions),
level_compaction_picker(ioptions, &icmp),
cf_name("dummy"),
log_buffer(InfoLogLevel::INFO_LEVEL, &logger),
vstorage(&icmp, ucmp, options.num_levels, kCompactionStyleLevel,
nullptr),
file_num(1) {
fifo_options.max_table_files_size = 1;
mutable_cf_options.RefreshDerivedOptions(ioptions);
size_being_compacted.resize(options.num_levels);
}
~CompactionPickerTest() {
auto* files = vstorage.GetFiles();
for (int i = 0; i < vstorage.NumberLevels(); i++) {
for (auto* f : files[i]) {
delete f;
}
}
}
void Add(int level, uint32_t file_number, const char* smallest,
const char* largest, uint64_t file_size = 0, uint32_t path_id = 0,
SequenceNumber smallest_seq = 100,
SequenceNumber largest_seq = 100) {
assert(level < vstorage.NumberLevels());
auto& files = vstorage.GetFiles()[level];
FileMetaData* f = new FileMetaData;
f->fd = FileDescriptor(file_number, path_id, file_size);
f->smallest = InternalKey(smallest, smallest_seq, kTypeValue);
f->largest = InternalKey(largest, largest_seq, kTypeValue);
f->compensated_file_size = file_size;
files.push_back(f);
}
void UpdateVersionStorageInfo() {
vstorage.ComputeCompactionScore(mutable_cf_options, fifo_options,
size_being_compacted);
vstorage.UpdateFilesBySize();
vstorage.UpdateNumNonEmptyLevels();
vstorage.GenerateFileIndexer();
vstorage.GenerateLevelFilesBrief();
vstorage.SetFinalized();
}
};
TEST(CompactionPickerTest, Empty) {
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() == nullptr);
}
TEST(CompactionPickerTest, Single) {
mutable_cf_options.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "p", "q");
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() == nullptr);
}
TEST(CompactionPickerTest, Level0Trigger) {
mutable_cf_options.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "150", "200");
Add(0, 2U, "200", "250");
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(2, compaction->num_input_files(0));
ASSERT_EQ(1U, compaction->input(0, 0)->fd.GetNumber());
ASSERT_EQ(2U, compaction->input(0, 1)->fd.GetNumber());
}
TEST(CompactionPickerTest, Level1Trigger) {
Add(1, 66U, "150", "200", 1000000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber());
}
TEST(CompactionPickerTest, Level1Trigger2) {
Add(1, 66U, "150", "200", 1000000001U);
Add(1, 88U, "201", "300", 1000000000U);
Add(2, 6U, "150", "179", 1000000000U);
Add(2, 7U, "180", "220", 1000000000U);
Add(2, 8U, "221", "300", 1000000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(2, compaction->num_input_files(1));
ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber());
ASSERT_EQ(6U, compaction->input(1, 0)->fd.GetNumber());
ASSERT_EQ(7U, compaction->input(1, 1)->fd.GetNumber());
}
TEST(CompactionPickerTest, LevelMaxScore) {
mutable_cf_options.target_file_size_base = 10000000;
mutable_cf_options.target_file_size_multiplier = 10;
Add(0, 1U, "150", "200", 1000000000U);
// Level 1 score 1.2
Add(1, 66U, "150", "200", 6000000U);
Add(1, 88U, "201", "300", 6000000U);
// Level 2 score 1.8. File 7 is the largest. Should be picked
Add(2, 6U, "150", "179", 60000000U);
Add(2, 7U, "180", "220", 60000001U);
Add(2, 8U, "221", "300", 60000000U);
// Level 3 score slightly larger than 1
Add(3, 26U, "150", "170", 260000000U);
Add(3, 27U, "171", "179", 260000000U);
Add(3, 28U, "191", "220", 260000000U);
Add(3, 29U, "221", "300", 260000000U);
UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
cf_name, mutable_cf_options, &vstorage, &log_buffer));
ASSERT_TRUE(compaction.get() != nullptr);
ASSERT_EQ(1, compaction->num_input_files(0));
ASSERT_EQ(7U, compaction->input(0, 0)->fd.GetNumber());
}
} // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); }
<|endoftext|> |
<commit_before>/*
* createcomp.cpp
*
* Created on: 2015. 9. 6.
* Author: hwang-linux
*/
#include "createcomp.hpp"
#include "../../include/logger.hpp"
#include <popt.h>
#include <boost/filesystem.hpp>
#include <string>
#include "../../include/base/configreader.hpp"
using namespace std;
using namespace boost;
namespace cossb {
/**
* @brief use utility interface macro
*/
USE_UTILITY_INTERFACE_EXECUTE(cossb::createcomp)
createcomp::createcomp() {
// TODO Auto-generated constructor stub
}
createcomp::~createcomp() {
// TODO Auto-generated destructor stub
}
bool createcomp::execute(int argc, char* argv[])
{
const int arg_offset = 2; //ignore the 2 args from the first
int argcc = argc - arg_offset;
char** argvv = &argv[arg_offset];
if(argcc>1)
{
string path = cossb_config->get_path()->find("component")->second;
path.append(argvv[1]);
filesystem::path fullpath = filesystem::system_complete(path);
boost::filesystem::create_directories(fullpath);
cossb_log->log(log::loglevel::INFO, fmt::format("Create directory {}", fullpath).c_str());
return true;
}
else
return false;
}
} /* namespace cossb */
<commit_msg>minimal update<commit_after>/*
* createcomp.cpp
*
* Created on: 2015. 9. 6.
* Author: hwang-linux
*/
#include "createcomp.hpp"
#include "../../include/logger.hpp"
#include <popt.h>
#include <boost/filesystem.hpp>
#include <string>
#include "../../include/base/configreader.hpp"
using namespace std;
using namespace boost;
namespace cossb {
/**
* @brief use utility interface macro
*/
USE_UTILITY_INTERFACE_EXECUTE(cossb::createcomp)
createcomp::createcomp() {
// TODO Auto-generated constructor stub
}
createcomp::~createcomp() {
// TODO Auto-generated destructor stub
}
bool createcomp::execute(int argc, char* argv[])
{
const int arg_offset = 2; //ignore the 2 args from the first
int argcc = argc - arg_offset;
char** argvv = &argv[arg_offset];
if(argcc>1)
{
string path = cossb_config->get_path().find("component")->second;
path.append(argvv[1]);
filesystem::path fullpath = filesystem::system_complete(path);
boost::filesystem::create_directories(fullpath);
cossb_log->log(log::loglevel::INFO, fmt::format("Create directory {}", fullpath).c_str());
return true;
}
else
return false;
}
} /* namespace cossb */
<|endoftext|> |
<commit_before>#include "memory_manager.h"
const long SHRINK_NPAGES = 1024;
const long INCREASE_SIZE = 1024 * 1024 * 128;
memory_manager::memory_manager(
long max_size): slab_allocator(PAGE_SIZE,
INCREASE_SIZE <= max_size ? INCREASE_SIZE : max_size , max_size) {
pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);
}
/**
* get `npages' pages for `request_cache'.
* In the case of shrinking caches, it makes no sense
* to shrink the cache that is requesting free pages.
*/
bool memory_manager::get_free_pages(int npages,
char **pages, page_cache *request_cache) {
pthread_spin_lock(&lock);
int ret = slab_allocator::alloc(pages, npages);
/*
* slab_allocator allocates either all required number of
* pages or none of them.
*/
if (ret == 0) {
long size = 0;
page_cache *cache = NULL;
pthread_spin_unlock(&lock);
/* shrink the cache of the largest size */
for (unsigned int i = 0; i < caches.size(); i++) {
if (size < caches[i]->size()) {
size = caches[i]->size();
cache = caches[i];
}
}
/*
* if we are going to shrink the cache that requests
* free pages, it just fails.
*/
if (request_cache == cache) {
return false;
}
int num_shrink = SHRINK_NPAGES;
if (num_shrink < npages)
num_shrink = npages;
char *buf[num_shrink];
if (!cache->shrink(num_shrink, buf)) {
return false;
}
pthread_spin_lock(&lock);
slab_allocator::free(buf, num_shrink);
/* now it's guaranteed that we have enough free pages. */
ret = slab_allocator::alloc(pages, npages);
}
pthread_spin_unlock(&lock);
return true;
}
void memory_manager::free_pages(int npages, char **pages) {
pthread_spin_lock(&lock);
slab_allocator::free(pages, npages);
pthread_spin_unlock(&lock);
}
<commit_msg>Fix a minor bug in memory manager.<commit_after>#include "memory_manager.h"
const long SHRINK_NPAGES = 1024;
const long INCREASE_SIZE = 1024 * 1024 * 128;
memory_manager::memory_manager(
long max_size): slab_allocator(PAGE_SIZE,
INCREASE_SIZE <= max_size ? INCREASE_SIZE : max_size , max_size) {
pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);
}
/**
* get `npages' pages for `request_cache'.
* In the case of shrinking caches, it makes no sense
* to shrink the cache that is requesting free pages.
*/
bool memory_manager::get_free_pages(int npages,
char **pages, page_cache *request_cache) {
pthread_spin_lock(&lock);
int ret = slab_allocator::alloc(pages, npages);
/*
* slab_allocator allocates either all required number of
* pages or none of them.
*/
if (ret == 0) {
long size = 0;
page_cache *cache = NULL;
pthread_spin_unlock(&lock);
/* shrink the cache of the largest size */
for (unsigned int i = 0; i < caches.size(); i++) {
if (size < caches[i]->size()) {
size = caches[i]->size();
cache = caches[i];
}
}
if (cache == NULL)
return false;
/*
* if we are going to shrink the cache that requests
* free pages, it just fails.
*/
if (request_cache == cache) {
return false;
}
int num_shrink = SHRINK_NPAGES;
if (num_shrink < npages)
num_shrink = npages;
char *buf[num_shrink];
if (!cache->shrink(num_shrink, buf)) {
return false;
}
pthread_spin_lock(&lock);
slab_allocator::free(buf, num_shrink);
/* now it's guaranteed that we have enough free pages. */
ret = slab_allocator::alloc(pages, npages);
}
pthread_spin_unlock(&lock);
return true;
}
void memory_manager::free_pages(int npages, char **pages) {
pthread_spin_lock(&lock);
slab_allocator::free(pages, npages);
pthread_spin_unlock(&lock);
}
<|endoftext|> |
<commit_before>#include <iostream> //cout
#include <cstdlib> //rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
using namespace std;
/* Total [13/20] */
/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
cout << scalar << endl;
} //working
void print_scalar(const COMPLEX scalar, const string name){
cout << name << ":" << scalar << endl;
} //working
void print_array(const COMPLEX array[], int len){
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_array(const COMPLEX array[], int len, const string name){
cout << name << ":" << endl;
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_matrix(const LaGenMatComplex& matrix){
cout << matrix << endl;
} //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
cout << name << ":" << endl << matrix << endl;
} //working
/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
A.r = rand() % x; //1 to x
A.i = rand() % x;
} //working
void generate_scalar(int A, const int x){
A = rand() % x; //1 to x
} //working
void generate_array(COMPLEX array[], const int len, const int x){
srand(time(NULL)); //seed
for(int i = 0; i < len; i++){
array[i].r = rand() % x; //1 to x
array[i].i = rand() % x;
}
} //working
/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
for(int i = 0; i < len; i++){
array[i] = vector(i);
}
} //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
diag = 0;
for(int i = 0; i < len; i++){
diag(i, i) = array[i];
}
} //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
COMPLEX array[len];
vec_to_array(vector, len, array);
array_to_diag(array, len, diag);
} //working
/* Scalar manipulation [5/8] */
int factorial(int x){
if(x <= 1){
return 1;
}else{
return x * factorial(x - 1);
}
} //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
result.r = A.r + B.r;
result.i = A.i + B.i;
} //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
result.r += addition.r;
result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r * B;
result.i = A.i * B;
} //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA * laB;
result = laResult.toCOMPLEX();
} //to test
scalar_product(const COMPLEX& total, const COMPLEX& number){
COMPLEX part;
part.r = (total.r * number.r) - (total.i * number.i);
part.i = (total.r * number.i) + (total.i * number.r);
total = part;
}
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r / B;
result.i = A.i / B;
} //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA / laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
la::complex<double> laResult = la::complex<double>(number);
la::complex<double> laNumber = la::complex<double>(number);
for(int i = 1; i < power; i++){
laResult *= laNumber;
}
result = laResult.toCOMPLEX();
} //to test
void scalar_exponential_main(const COMPLEX& number, const int iterations, COMPLEX& result){
COMPLEX division, total_division, A;
result.r = 1;
result.i = 1;
for(int step = 1; step <= iterations; step++){ //sum (from 1 to n)
division.r = 0;
division.i = 0;
total_division.r = 1;
total_division.i = 0;
for(int i = 1; i <= step; i++){ // ( num^n / n!)
cout << "division = " << division << endl;
cout << "total_division = " << total_division << endl;
scalar_division(number, i, division);
scalar_product(total_division, division);
}
scalar_addition(result, total_division);
cout << "sum = " << result << endl;
}
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
// COMPLEX result, division, multiplication;
// if(step <= 1){
// result.r = 1;
// return result;
// }else{
// scalar_division(number,step,division);
// scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication);
// return multiplication;
// }
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
/*
for(int i = 0; i < len; i++){
array[i] = complex_power(array[i], power, result);
}
*/
} //empty
/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){ //empty
//...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
//LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){ //working
// LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
LaVectorLongInt PIV = LaVectorLongInt(len);
LUFactorizeIP(matrix, PIV);
LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){ //empty
//
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
//LaGenMatComplex step = LaGenMatComplex
} //empty
/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
COMPLEX compA;
generate_scalar(compA, max_rand);
COMPLEX compB;
generate_scalar(compB, max_rand);
int realB;
generate_scalar(realB, max_rand);
COMPLEX result;
for(int i = 1; i < 5; i++){ //factorials
cout << "factorial(" << i << "): " << factorial(i) << endl;
}
scalar_addition(compA, compB, result); //addition/subtraction
cout << "scalar addition: " << result << endl << endl;
scalar_multiplication(compA, realB, result); //multiplication
cout << "scalar multiplication by scalar: " << result << endl << endl;
scalar_multiplication(compA, compB, result);
cout << "scalar multiplication by complex: " << result << endl << endl;
scalar_division(compA, realB, result); //division
cout << "scalar division by scalar: " << result << endl << endl;
scalar_division(compA, compB, result);
cout << "scalar division by complex: " << result << endl << endl;
for(int i = 1; i < 5; i++){
scalar_powers(compA, i, result);
cout << "scalar powers - A^" << i << " = " << result << endl;
}
COMPLEX sum;
sum.r = 0;
sum.i = 0;
for(int i = 0; i < 5; i++){
cout << "sum(" << i << ") = " << sum << endl;
test_scalar_sum(COMPLEX sum, const COMPLEX compA);
}
cout << "sum = " << sum << endl;
} //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff
LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff
vec_to_diag(eigenvalueVec, size, eigenvalues);
print_matrix(eigenvalues, "eigenvalue matrix");
print_matrix(eigenvectors, "eigenvector matrix");
} //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
LaGenMatComplex inverseMatrix;
inverseMatrix = initialMatrix.copy();
matrix_inverse(inverseMatrix, size);
print_matrix(inverseMatrix, "inverse matrix");
} //to test
void test_scalar_sum(const int max_rand, const int iterations){
COMPLEX number, step;
generate_scalar(number, max_rand);
step = number;
for(int i = 0; i < iterations; i++){
cout << step << endl;
scalar_addition(number, step);
}
cout << number << endl;
}
void test_scalar_product(const int max_rand, const int iterations){
void test_scalar_exponential(const int iterations, const int max_rand){
COMPLEX number, result;
generate_scalar(number, max_rand);
cout << endl << "scalar exponential test no.: " << number << endl << endl;
scalar_exponential_main(number, iterations, result);
cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
//...
}
/* Main Program */
int main(){
// int matrix_size = 3, max_rand = 9;
// int matrix_volume = matrix_size * matrix_size;
/* generate the matrix */
// COMPLEX elements[matrix_volume];
// generate_array(elements, matrix_volume, max_rand);
// LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );
// print_matrix(initialMatrix, "initial matrix");
/* test eigenvalues */
// test_eigenvalues(initialMatrix, matrix_size);
/* test scalar manipulation */
test_scalar_manipulation(4);
/* test scalar product */
/* test scalar exponentials */
// test_scalar_exponential(3,4);
/* test inversion */
// test_inverse(initialMatrix, matrix_size);
}
<commit_msg>testing<commit_after>#include <iostream> //cout
#include <cstdlib> //rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
using namespace std;
/* Total [13/20] */
/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
cout << scalar << endl;
} //working
void print_scalar(const COMPLEX scalar, const string name){
cout << name << ":" << scalar << endl;
} //working
void print_array(const COMPLEX array[], int len){
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_array(const COMPLEX array[], int len, const string name){
cout << name << ":" << endl;
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_matrix(const LaGenMatComplex& matrix){
cout << matrix << endl;
} //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
cout << name << ":" << endl << matrix << endl;
} //working
/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
A.r = rand() % x; //1 to x
A.i = rand() % x;
} //working
void generate_scalar(int A, const int x){
A = rand() % x; //1 to x
} //working
void generate_array(COMPLEX array[], const int len, const int x){
srand(time(NULL)); //seed
for(int i = 0; i < len; i++){
array[i].r = rand() % x; //1 to x
array[i].i = rand() % x;
}
} //working
/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
for(int i = 0; i < len; i++){
array[i] = vector(i);
}
} //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
diag = 0;
for(int i = 0; i < len; i++){
diag(i, i) = array[i];
}
} //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
COMPLEX array[len];
vec_to_array(vector, len, array);
array_to_diag(array, len, diag);
} //working
/* Scalar manipulation [5/8] */
int factorial(int x){
if(x <= 1){
return 1;
}else{
return x * factorial(x - 1);
}
} //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
result.r = A.r + B.r;
result.i = A.i + B.i;
} //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
result.r += addition.r;
result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r * B;
result.i = A.i * B;
} //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA * laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_product(const COMPLEX& total, const COMPLEX& number){
COMPLEX part;
part.r = (total.r * number.r) - (total.i * number.i);
part.i = (total.r * number.i) + (total.i * number.r);
total = part;
}
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r / B;
result.i = A.i / B;
} //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA / laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
la::complex<double> laResult = la::complex<double>(number);
la::complex<double> laNumber = la::complex<double>(number);
for(int i = 1; i < power; i++){
laResult *= laNumber;
}
result = laResult.toCOMPLEX();
} //to test
void scalar_exponential_main(const COMPLEX& number, const int iterations, COMPLEX& result){
COMPLEX division, total_division;
result.r = 1;
result.i = 1;
for(int step = 1; step <= iterations; step++){ //sum (from 1 to n)
division.r = 0;
division.i = 0;
total_division.r = 1;
total_division.i = 0;
for(int i = 1; i <= step; i++){ // ( num^n / n!)
cout << "division = " << division << endl;
cout << "total_division = " << total_division << endl;
scalar_division(number, i, division);
scalar_product(total_division, division);
}
scalar_addition(result, total_division);
cout << "sum = " << result << endl;
}
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
// COMPLEX result, division, multiplication;
// if(step <= 1){
// result.r = 1;
// return result;
// }else{
// scalar_division(number,step,division);
// scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication);
// return multiplication;
// }
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
/*
for(int i = 0; i < len; i++){
array[i] = complex_power(array[i], power, result);
}
*/
} //empty
/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){ //empty
//...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
//LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){ //working
// LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
LaVectorLongInt PIV = LaVectorLongInt(len);
LUFactorizeIP(matrix, PIV);
LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){ //empty
//
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
//LaGenMatComplex step = LaGenMatComplex
} //empty
/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
COMPLEX compA;
generate_scalar(compA, max_rand);
COMPLEX compB;
generate_scalar(compB, max_rand);
int realB;
generate_scalar(realB, max_rand);
COMPLEX result;
for(int i = 1; i < 5; i++){ //factorials
cout << "factorial(" << i << "): " << factorial(i) << endl;
}
scalar_addition(compA, compB, result); //addition/subtraction
cout << "scalar addition: " << result << endl << endl;
scalar_multiplication(compA, realB, result); //multiplication
cout << "scalar multiplication by scalar: " << result << endl << endl;
scalar_multiplication(compA, compB, result);
cout << "scalar multiplication by complex: " << result << endl << endl;
scalar_division(compA, realB, result); //division
cout << "scalar division by scalar: " << result << endl << endl;
scalar_division(compA, compB, result);
cout << "scalar division by complex: " << result << endl << endl;
for(int i = 1; i < 5; i++){
scalar_powers(compA, i, result);
cout << "scalar powers - A^" << i << " = " << result << endl;
}
COMPLEX sum;
sum.r = 0;
sum.i = 0;
for(int i = 0; i < 5; i++){
cout << "sum(" << i << ") = " << sum << endl;
scalar_addition(COMPLEX sum, const COMPLEX compA);
}
cout << "sum = " << sum << endl;
} //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff
LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff
vec_to_diag(eigenvalueVec, size, eigenvalues);
print_matrix(eigenvalues, "eigenvalue matrix");
print_matrix(eigenvectors, "eigenvector matrix");
} //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
LaGenMatComplex inverseMatrix;
inverseMatrix = initialMatrix.copy();
matrix_inverse(inverseMatrix, size);
print_matrix(inverseMatrix, "inverse matrix");
} //to test
void test_scalar_sum(const int max_rand, const int iterations){
COMPLEX number, step;
generate_scalar(number, max_rand);
step = number;
for(int i = 0; i < iterations; i++){
cout << step << endl;
scalar_addition(number, step);
}
cout << number << endl;
}
void test_scalar_product(const int max_rand, const int iterations){
//...
}
void test_scalar_exponential(const int iterations, const int max_rand){
COMPLEX number, result;
generate_scalar(number, max_rand);
cout << endl << "scalar exponential test no.: " << number << endl << endl;
scalar_exponential_main(number, iterations, result);
cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
//...
}
/* Main Program */
int main(){
// int matrix_size = 3, max_rand = 9;
// int matrix_volume = matrix_size * matrix_size;
/* generate the matrix */
// COMPLEX elements[matrix_volume];
// generate_array(elements, matrix_volume, max_rand);
// LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );
// print_matrix(initialMatrix, "initial matrix");
/* test eigenvalues */
// test_eigenvalues(initialMatrix, matrix_size);
/* test scalar manipulation */
test_scalar_manipulation(4);
/* test scalar product */
/* test scalar exponentials */
// test_scalar_exponential(3,4);
/* test inversion */
// test_inverse(initialMatrix, matrix_size);
}
<|endoftext|> |
<commit_before>#include <iostream> //cout
#include <cstdlib> //rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
using namespace std;
/* Total [13/20] */
/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
cout << scalar << endl;
} //working
void print_scalar(const COMPLEX scalar, const string name){
cout << name << ":" << scalar << endl;
} //working
void print_array(const COMPLEX array[], int len){
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_array(const COMPLEX array[], int len, const string name){
cout << name << ":" << endl;
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_matrix(const LaGenMatComplex& matrix){
cout << matrix << endl;
} //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
cout << name << ":" << endl << matrix << endl;
} //working
/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
A.r = rand() % x; //1 to x
A.i = rand() % x;
} //working
void generate_scalar(int A, const int x){
A = rand() % x; //1 to x
} //working
void generate_array(COMPLEX array[], const int len, const int x){
srand(time(NULL)); //seed
for(int i = 0; i < len; i++){
array[i].r = rand() % x; //1 to x
array[i].i = rand() % x;
}
} //working
/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
for(int i = 0; i < len; i++){
array[i] = vector(i);
}
} //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
diag = 0;
for(int i = 0; i < len; i++){
diag(i, i) = array[i];
}
} //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
COMPLEX array[len];
vec_to_array(vector, len, array);
array_to_diag(array, len, diag);
} //working
/* Scalar manipulation [5/8] */
int factorial(int x){
if(x <= 1){
return 1;
}else{
return x * factorial(x - 1);
}
} //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
result.r = A.r + B.r;
result.i = A.i + B.i;
} //working
void scalar_sum(){
//...
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r * B;
result.i = A.i * B;
} //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA * laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r / B;
result.i = A.i / B;
} //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA / laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
la::complex<double> laResult = la::complex<double>(number);
la::complex<double> laNumber = la::complex<double>(number);
for(int i = 1; i < power; i++){
laResult *= laNumber;
}
result = laResult.toCOMPLEX();
} //to test
void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){
COMPLEX division, total_division, A, B;
result.r = 1;
result.i = 1;
for(int step = 1; step <= iterations; step++){ //sum (from 1 to n)
division.r = 0;
division.i = 0;
total_division.r = 1;
total_division.i = 0;
for(int i = 1; i <= step; i++){ // ( num^n / n!)
cout << "division = " << division << endl;
cout << "total_division = " << total_division << endl;
A = total_division;
scalar_division(number, i, division);
scalar_multiplication(A, division, total_division);
}
B = result;
scalar_addition(B, total_division, result);
cout << "sum = " << result << endl;
}
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
// COMPLEX result, division, multiplication;
// if(step <= 1){
// result.r = 1;
// return result;
// }else{
// scalar_division(number,step,division);
// scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication);
// return multiplication;
// }
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
/*
for(int i = 0; i < len; i++){
array[i] = complex_power(array[i], power, result);
}
*/
} //empty
/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){ //empty
//...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
//LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){ //working
// LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
LaVectorLongInt PIV = LaVectorLongInt(len);
LUFactorizeIP(matrix, PIV);
LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){ //empty
//
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
//LaGenMatComplex step = LaGenMatComplex
} //empty
/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
COMPLEX compA; //initialisation
generate_scalar(compA, max_rand);
COMPLEX compB;
generate_scalar(compB, max_rand);
int realB;
generate_scalar(realB, max_rand);
COMPLEX result;
for(int i = 1; i < 5; i++){ //factorials
cout << "factorial(" << i << "): " << factorial(i) << endl;
}
scalar_addition(compA, compB, result); //addition/subtraction
cout << "scalar addition: " << result << endl << endl;
scalar_multiplication(compA, realB, result); //multiplication
cout << "scalar multiplication by scalar: " << result << endl << endl;
scalar_multiplication(compA, compB, result);
cout << "scalar multiplication by complex: " << result << endl << endl;
scalar_division(compA, realB, result); //division
cout << "scalar division by scalar: " << result << endl << endl;
scalar_division(compA, compB, result);
cout << "scalar division by complex: " << result << endl << endl;
for(int i = 1; i < 5; i++){
scalar_powers(compA, i, result);
cout << "scalar powers - A^" << i << " = " << result << endl;
}
} //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff
LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff
vec_to_diag(eigenvalueVec, size, eigenvalues);
print_matrix(eigenvalues, "eigenvalue matrix");
print_matrix(eigenvectors, "eigenvector matrix");
} //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
LaGenMatComplex inverseMatrix;
inverseMatrix = initialMatrix.copy();
matrix_inverse(inverseMatrix, size);
print_matrix(inverseMatrix, "inverse matrix");
} //to test
void test_scalar_exponential(const int iterations, const int max_rand){
COMPLEX number, result;
generate_scalar(number, max_rand);
cout << endl << "scalar exponential test no.: " << number << endl << endl;
scalar_exponential_1(number, iterations, result);
cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
//...
}
/* Main Program */
int main(){
// int matrix_size = 3, max_rand = 9;
// int matrix_volume = matrix_size * matrix_size;
/* generate the matrix */
// COMPLEX elements[matrix_volume];
// generate_array(elements, matrix_volume, max_rand);
// LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );
// print_matrix(initialMatrix, "initial matrix");
/* test eigenvalues */
// test_eigenvalues(initialMatrix, matrix_size);
/* test scalar manipulation */
// test_scalar_manipulation(4);
/* test scalar sum */
COMPLEX A, B, C;
A.r = 2; A.i = 1;
B.r = 1; B.i = 1;
for(int i = 0; i < 4; i++){
scalar_addition(A, B, C); // A + B = C
A = C
}
/* test scalar product */
/* test scalar exponentials */
// test_scalar_exponential(3,4);
/* test inversion */
// test_inverse(initialMatrix, matrix_size);
}
<commit_msg>testing<commit_after>#include <iostream> //cout
#include <cstdlib> //rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
using namespace std;
/* Total [13/20] */
/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
cout << scalar << endl;
} //working
void print_scalar(const COMPLEX scalar, const string name){
cout << name << ":" << scalar << endl;
} //working
void print_array(const COMPLEX array[], int len){
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_array(const COMPLEX array[], int len, const string name){
cout << name << ":" << endl;
for(int i = 0; i < len; i++){
cout << array[i] << endl;
}
} //working
void print_matrix(const LaGenMatComplex& matrix){
cout << matrix << endl;
} //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
cout << name << ":" << endl << matrix << endl;
} //working
/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
A.r = rand() % x; //1 to x
A.i = rand() % x;
} //working
void generate_scalar(int A, const int x){
A = rand() % x; //1 to x
} //working
void generate_array(COMPLEX array[], const int len, const int x){
srand(time(NULL)); //seed
for(int i = 0; i < len; i++){
array[i].r = rand() % x; //1 to x
array[i].i = rand() % x;
}
} //working
/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
for(int i = 0; i < len; i++){
array[i] = vector(i);
}
} //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
diag = 0;
for(int i = 0; i < len; i++){
diag(i, i) = array[i];
}
} //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
COMPLEX array[len];
vec_to_array(vector, len, array);
array_to_diag(array, len, diag);
} //working
/* Scalar manipulation [5/8] */
int factorial(int x){
if(x <= 1){
return 1;
}else{
return x * factorial(x - 1);
}
} //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
result.r = A.r + B.r;
result.i = A.i + B.i;
} //working
void scalar_sum(){
//...
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r * B;
result.i = A.i * B;
} //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA * laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
result.r = A.r / B;
result.i = A.i / B;
} //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
la::complex<double> laB = la::complex<double>(B);
la::complex<double> laResult = la::complex<double>(result);
laResult = laA / laB;
result = laResult.toCOMPLEX();
} //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
la::complex<double> laResult = la::complex<double>(number);
la::complex<double> laNumber = la::complex<double>(number);
for(int i = 1; i < power; i++){
laResult *= laNumber;
}
result = laResult.toCOMPLEX();
} //to test
void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){
COMPLEX division, total_division, A, B;
result.r = 1;
result.i = 1;
for(int step = 1; step <= iterations; step++){ //sum (from 1 to n)
division.r = 0;
division.i = 0;
total_division.r = 1;
total_division.i = 0;
for(int i = 1; i <= step; i++){ // ( num^n / n!)
cout << "division = " << division << endl;
cout << "total_division = " << total_division << endl;
A = total_division;
scalar_division(number, i, division);
scalar_multiplication(A, division, total_division);
}
B = result;
scalar_addition(B, total_division, result);
cout << "sum = " << result << endl;
}
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
// COMPLEX result, division, multiplication;
// if(step <= 1){
// result.r = 1;
// return result;
// }else{
// scalar_division(number,step,division);
// scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication);
// return multiplication;
// }
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
//COMPLEX power;
//COMPLEX division;
//result.r = 0;
//result.i = 0;
//for(int i = 0; i < iter; i++){
// scalar_powers(number, i, power);
// scalar_division(power, factorial(i), division);
// scalar_addition(result, division, result);
//}
} //empty
/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
/*
for(int i = 0; i < len; i++){
array[i] = complex_power(array[i], power, result);
}
*/
} //empty
/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){ //empty
//...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
//LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){ //working
// LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
LaVectorLongInt PIV = LaVectorLongInt(len);
LUFactorizeIP(matrix, PIV);
LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){ //empty
//
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
//LaGenMatComplex step = LaGenMatComplex
} //empty
/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
COMPLEX compA; //initialisation
generate_scalar(compA, max_rand);
COMPLEX compB;
generate_scalar(compB, max_rand);
int realB;
generate_scalar(realB, max_rand);
COMPLEX result;
for(int i = 1; i < 5; i++){ //factorials
cout << "factorial(" << i << "): " << factorial(i) << endl;
}
scalar_addition(compA, compB, result); //addition/subtraction
cout << "scalar addition: " << result << endl << endl;
scalar_multiplication(compA, realB, result); //multiplication
cout << "scalar multiplication by scalar: " << result << endl << endl;
scalar_multiplication(compA, compB, result);
cout << "scalar multiplication by complex: " << result << endl << endl;
scalar_division(compA, realB, result); //division
cout << "scalar division by scalar: " << result << endl << endl;
scalar_division(compA, compB, result);
cout << "scalar division by complex: " << result << endl << endl;
for(int i = 1; i < 5; i++){
scalar_powers(compA, i, result);
cout << "scalar powers - A^" << i << " = " << result << endl;
}
} //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff
LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff
vec_to_diag(eigenvalueVec, size, eigenvalues);
print_matrix(eigenvalues, "eigenvalue matrix");
print_matrix(eigenvectors, "eigenvector matrix");
} //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
LaGenMatComplex inverseMatrix;
inverseMatrix = initialMatrix.copy();
matrix_inverse(inverseMatrix, size);
print_matrix(inverseMatrix, "inverse matrix");
} //to test
void test_scalar_exponential(const int iterations, const int max_rand){
COMPLEX number, result;
generate_scalar(number, max_rand);
cout << endl << "scalar exponential test no.: " << number << endl << endl;
scalar_exponential_1(number, iterations, result);
cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
//...
}
/* Main Program */
int main(){
// int matrix_size = 3, max_rand = 9;
// int matrix_volume = matrix_size * matrix_size;
/* generate the matrix */
// COMPLEX elements[matrix_volume];
// generate_array(elements, matrix_volume, max_rand);
// LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );
// print_matrix(initialMatrix, "initial matrix");
/* test eigenvalues */
// test_eigenvalues(initialMatrix, matrix_size);
/* test scalar manipulation */
// test_scalar_manipulation(4);
/* test scalar sum */
COMPLEX A, B, C;
A.r = 2; A.i = 1;
B.r = 1; B.i = 1;
for(int i = 0; i < 4; i++){
scalar_addition(A, B, C); // A + B = C
A = C;
}
/* test scalar product */
/* test scalar exponentials */
// test_scalar_exponential(3,4);
/* test inversion */
// test_inverse(initialMatrix, matrix_size);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: saltimer.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:44:24 $
*
* 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_vcl.hxx"
#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALTIMER_H
#include <saltimer.h>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
// =======================================================================
// Maximale Periode
#define MAX_SYSPERIOD 65533
// =======================================================================
void ImplSalStartTimer( ULONG nMS, BOOL bMutex )
{
SalData* pSalData = GetSalData();
// Remenber the time of the timer
pSalData->mnTimerMS = nMS;
if ( !bMutex )
pSalData->mnTimerOrgMS = nMS;
// Periode darf nicht zu gross sein, da Windows mit USHORT arbeitet
if ( nMS > MAX_SYSPERIOD )
nMS = MAX_SYSPERIOD;
// Gibt es einen Timer, dann zerstoren
if ( pSalData->mnTimerId )
KillTimer( 0, pSalData->mnTimerId );
// Make a new timer with new period
pSalData->mnTimerId = SetTimer( 0, 0, (UINT)nMS, SalTimerProc );
pSalData->mnNextTimerTime = pSalData->mnLastEventTime + nMS;
}
// -----------------------------------------------------------------------
WinSalTimer::~WinSalTimer()
{
}
void WinSalTimer::Start( ULONG nMS )
{
// switch to main thread
SalData* pSalData = GetSalData();
if ( pSalData->mpFirstInstance )
{
if ( pSalData->mnAppThreadId != GetCurrentThreadId() )
ImplPostMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS );
else
ImplSendMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS );
}
else
ImplSalStartTimer( nMS, FALSE );
}
void WinSalTimer::Stop()
{
SalData* pSalData = GetSalData();
// If we have a timer, than
if ( pSalData->mnTimerId )
{
KillTimer( 0, pSalData->mnTimerId );
pSalData->mnTimerId = 0;
pSalData->mnNextTimerTime = 0;
}
}
// -----------------------------------------------------------------------
void CALLBACK SalTimerProc( HWND, UINT, UINT_PTR nId, DWORD )
{
__try
{
SalData* pSalData = GetSalData();
ImplSVData* pSVData = ImplGetSVData();
// Test for MouseLeave
SalTestMouseLeave();
bool bRecursive = pSalData->mbInTimerProc && (nId != SALTIMERPROC_RECURSIVE);
if ( pSVData->mpSalTimer && ! bRecursive )
{
// Try to aquire the mutex. If we don't get the mutex then we
// try this a short time later again.
if ( ImplSalYieldMutexTryToAcquire() )
{
bRecursive = pSalData->mbInTimerProc && (nId != SALTIMERPROC_RECURSIVE);
if ( pSVData->mpSalTimer && ! bRecursive )
{
pSalData->mbInTimerProc = TRUE;
pSVData->mpSalTimer->CallCallback();
pSalData->mbInTimerProc = FALSE;
ImplSalYieldMutexRelease();
// Run the timer in the correct time, if we start this
// with a small timeout, because we don't get the mutex
if ( pSalData->mnTimerId &&
(pSalData->mnTimerMS != pSalData->mnTimerOrgMS) )
ImplSalStartTimer( pSalData->mnTimerOrgMS, FALSE );
}
}
else
ImplSalStartTimer( 10, TRUE );
}
}
__except(WinSalInstance::WorkaroundExceptionHandlingInUSER32Lib(GetExceptionCode(), GetExceptionInformation()))
{
}
}
<commit_msg>INTEGRATION: CWS mingwport03 (1.9.164); FILE MERGED 2006/11/08 14:50:23 vg 1.9.164.3: RESYNC: (1.9-1.10); FILE MERGED 2006/10/24 13:25:22 vg 1.9.164.2: #i53572# MinGW port 2006/09/07 15:19:05 vg 1.9.164.1: #i53572# MinGW port<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: saltimer.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2007-03-26 14:40: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_vcl.hxx"
#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif
#ifdef __MINGW32__
#include <excpt.h>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALTIMER_H
#include <saltimer.h>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
// =======================================================================
// Maximale Periode
#define MAX_SYSPERIOD 65533
// =======================================================================
void ImplSalStartTimer( ULONG nMS, BOOL bMutex )
{
SalData* pSalData = GetSalData();
// Remenber the time of the timer
pSalData->mnTimerMS = nMS;
if ( !bMutex )
pSalData->mnTimerOrgMS = nMS;
// Periode darf nicht zu gross sein, da Windows mit USHORT arbeitet
if ( nMS > MAX_SYSPERIOD )
nMS = MAX_SYSPERIOD;
// Gibt es einen Timer, dann zerstoren
if ( pSalData->mnTimerId )
KillTimer( 0, pSalData->mnTimerId );
// Make a new timer with new period
pSalData->mnTimerId = SetTimer( 0, 0, (UINT)nMS, SalTimerProc );
pSalData->mnNextTimerTime = pSalData->mnLastEventTime + nMS;
}
// -----------------------------------------------------------------------
WinSalTimer::~WinSalTimer()
{
}
void WinSalTimer::Start( ULONG nMS )
{
// switch to main thread
SalData* pSalData = GetSalData();
if ( pSalData->mpFirstInstance )
{
if ( pSalData->mnAppThreadId != GetCurrentThreadId() )
ImplPostMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS );
else
ImplSendMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS );
}
else
ImplSalStartTimer( nMS, FALSE );
}
void WinSalTimer::Stop()
{
SalData* pSalData = GetSalData();
// If we have a timer, than
if ( pSalData->mnTimerId )
{
KillTimer( 0, pSalData->mnTimerId );
pSalData->mnTimerId = 0;
pSalData->mnNextTimerTime = 0;
}
}
// -----------------------------------------------------------------------
void CALLBACK SalTimerProc( HWND, UINT, UINT_PTR nId, DWORD )
{
#ifdef __MINGW32__
jmp_buf jmpbuf;
__SEHandler han;
if (__builtin_setjmp(jmpbuf) == 0)
{
han.Set(jmpbuf, NULL, (__SEHandler::PF)EXCEPTION_EXECUTE_HANDLER);
#else
__try
{
#endif
SalData* pSalData = GetSalData();
ImplSVData* pSVData = ImplGetSVData();
// Test for MouseLeave
SalTestMouseLeave();
bool bRecursive = pSalData->mbInTimerProc && (nId != SALTIMERPROC_RECURSIVE);
if ( pSVData->mpSalTimer && ! bRecursive )
{
// Try to aquire the mutex. If we don't get the mutex then we
// try this a short time later again.
if ( ImplSalYieldMutexTryToAcquire() )
{
bRecursive = pSalData->mbInTimerProc && (nId != SALTIMERPROC_RECURSIVE);
if ( pSVData->mpSalTimer && ! bRecursive )
{
pSalData->mbInTimerProc = TRUE;
pSVData->mpSalTimer->CallCallback();
pSalData->mbInTimerProc = FALSE;
ImplSalYieldMutexRelease();
// Run the timer in the correct time, if we start this
// with a small timeout, because we don't get the mutex
if ( pSalData->mnTimerId &&
(pSalData->mnTimerMS != pSalData->mnTimerOrgMS) )
ImplSalStartTimer( pSalData->mnTimerOrgMS, FALSE );
}
}
else
ImplSalStartTimer( 10, TRUE );
}
}
#ifdef __MINGW32__
han.Reset();
#else
__except(WinSalInstance::WorkaroundExceptionHandlingInUSER32Lib(GetExceptionCode(), GetExceptionInformation()))
{
}
#endif
}
<|endoftext|> |
<commit_before>#ifndef VIENNADATA_CONTAINER_ACCESS_HPP
#define VIENNADATA_CONTAINER_ACCESS_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaData - The Vienna Data Library
-----------------
Authors: Florian Rudolf rudolf@iue.tuwien.ac.at
Karl Rupp rupp@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <map>
#include "viennadata/forwards.hpp"
#include "viennadata/meta/result_of.hpp"
namespace viennadata
{
/** @brief Class that manages container access, depends on container_type, access_type and access_tag */
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access;
/** @brief Default implementation: random access container using offset */
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access
{
typedef ContainerType container_type;
typedef AccessType access_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
static pointer find(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (static_cast<offset_type>(container.size()) > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static const_pointer find(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (static_cast<offset_type>(container.size()) > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static reference lookup_unchecked(container_type & container, access_type const & element) // no offset checking
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return container[offset];
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
assert( static_cast<offset_type>(container.size()) > offset ); // no release-runtime check for accessing elements outside container
return container[offset];
}
static reference lookup(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
typedef typename container_type::size_type size_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
if ( static_cast<offset_type>(container.size()) <= offset) container.resize(offset+1); // ensure that container is big enough
return container[offset];
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element)
{
lookup(container, dst_element) = lookup(container, src_element);
}
static void erase(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
if (offset-1 == static_cast<offset_type>(container.size())) // container is shrinked only when deleting data for last element
container.resize(container.size()-1);
}
static void clear(container_type & container)
{
container.clear();
}
static void resize(container_type & container, std::size_t size)
{
container.resize( size );
}
};
// const container specialization
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access<const ContainerType, AccessType, AccessTag>
{
typedef ContainerType container_type;
typedef AccessType access_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
static const_pointer find(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (container.size() > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
assert( static_cast<offset_type>(container.size()) > offset ); // no release-runtime check for accessing elements outside container
return container[offset];
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element);
static void erase(container_type & container, access_type const & element);
static void clear(container_type & container);
static void resize(container_type & container, std::size_t size);
};
// specialization for std::map
template<typename KeyType, typename ValueType , typename Compare, typename Alloc, typename AccessType, typename AccessTag>
struct container_access<std::map<KeyType, ValueType, Compare, Alloc>, AccessType, AccessTag>
{
typedef KeyType key_type;
typedef std::map<KeyType, ValueType, Compare, Alloc> container_type;
typedef AccessType access_type;
typedef ValueType value_type;
typedef value_type & reference;
typedef value_type const & const_reference;
typedef value_type * pointer;
typedef value_type const * const_pointer;
static pointer find(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static const_pointer find(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static reference lookup_unchecked(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
return container[access];
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
assert(it != container.end()); // no release-runtime check for accessing elements outside container
return it->second;
}
static reference lookup(container_type & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element)
{
lookup(container, dst_element) = lookup(container, src_element);
}
static void erase(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::iterator it = container.find(access);
if (it != container.end())
container.erase(it);
}
static void clear(container_type & container)
{
container.clear();
}
static void resize(container_type &, std::size_t) {} // not supported
};
// const map specialization
template<typename KeyType, typename ValueType , typename Compare, typename Alloc, typename AccessType, typename AccessTag>
struct container_access<const std::map<KeyType, ValueType, Compare, Alloc>, AccessType, AccessTag>
{
typedef KeyType key_type;
typedef std::map<KeyType, ValueType, Compare, Alloc> container_type;
typedef AccessType access_type;
typedef ValueType value_type;
typedef value_type & reference;
typedef value_type const & const_reference;
typedef value_type * pointer;
typedef value_type const * const_pointer;
static const_pointer find(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
assert(it != container.end()); // no release-runtime check for accessing elements outside container
return it->second;
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element);
static void erase(container_type & container, access_type const & element);
static void clear(container_type & container);
static void resize(container_type & container, std::size_t size);
};
} // namespace viennadata
#endif
<commit_msg>bug fix with erasing elements in dense containers<commit_after>#ifndef VIENNADATA_CONTAINER_ACCESS_HPP
#define VIENNADATA_CONTAINER_ACCESS_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaData - The Vienna Data Library
-----------------
Authors: Florian Rudolf rudolf@iue.tuwien.ac.at
Karl Rupp rupp@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <map>
#include "viennadata/forwards.hpp"
#include "viennadata/meta/result_of.hpp"
namespace viennadata
{
/** @brief Class that manages container access, depends on container_type, access_type and access_tag */
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access;
/** @brief Default implementation: random access container using offset */
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access
{
typedef ContainerType container_type;
typedef AccessType access_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
static pointer find(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (static_cast<offset_type>(container.size()) > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static const_pointer find(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (static_cast<offset_type>(container.size()) > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static reference lookup_unchecked(container_type & container, access_type const & element) // no offset checking
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return container[offset];
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
assert( static_cast<offset_type>(container.size()) > offset ); // no release-runtime check for accessing elements outside container
return container[offset];
}
static reference lookup(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
typedef typename container_type::size_type size_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
if ( static_cast<offset_type>(container.size()) <= offset) container.resize(offset+1); // ensure that container is big enough
return container[offset];
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element)
{
lookup(container, dst_element) = lookup(container, src_element);
}
static void erase(container_type & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
if (offset+1 == static_cast<offset_type>(container.size())) // container is shrinked only when deleting data for last element
container.resize(container.size()-1);
}
static void clear(container_type & container)
{
container.clear();
}
static void resize(container_type & container, std::size_t size)
{
container.resize( size );
}
};
// const container specialization
template<typename ContainerType, typename AccessType, typename AccessTag>
struct container_access<const ContainerType, AccessType, AccessTag>
{
typedef ContainerType container_type;
typedef AccessType access_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
static const_pointer find(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
return (container.size() > offset) ? (&container[offset]) : NULL; // return NULL if not found
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typedef typename result_of::offset< typename access_type::id_type >::type offset_type;
offset_type offset = result_of::offset< typename access_type::id_type >::get(element.id());
assert( static_cast<offset_type>(container.size()) > offset ); // no release-runtime check for accessing elements outside container
return container[offset];
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element);
static void erase(container_type & container, access_type const & element);
static void clear(container_type & container);
static void resize(container_type & container, std::size_t size);
};
// specialization for std::map
template<typename KeyType, typename ValueType , typename Compare, typename Alloc, typename AccessType, typename AccessTag>
struct container_access<std::map<KeyType, ValueType, Compare, Alloc>, AccessType, AccessTag>
{
typedef KeyType key_type;
typedef std::map<KeyType, ValueType, Compare, Alloc> container_type;
typedef AccessType access_type;
typedef ValueType value_type;
typedef value_type & reference;
typedef value_type const & const_reference;
typedef value_type * pointer;
typedef value_type const * const_pointer;
static pointer find(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static const_pointer find(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static reference lookup_unchecked(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
return container[access];
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
assert(it != container.end()); // no release-runtime check for accessing elements outside container
return it->second;
}
static reference lookup(container_type & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element)
{
lookup(container, dst_element) = lookup(container, src_element);
}
static void erase(container_type & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::iterator it = container.find(access);
if (it != container.end())
container.erase(it);
}
static void clear(container_type & container)
{
container.clear();
}
static void resize(container_type &, std::size_t) {} // not supported
};
// const map specialization
template<typename KeyType, typename ValueType , typename Compare, typename Alloc, typename AccessType, typename AccessTag>
struct container_access<const std::map<KeyType, ValueType, Compare, Alloc>, AccessType, AccessTag>
{
typedef KeyType key_type;
typedef std::map<KeyType, ValueType, Compare, Alloc> container_type;
typedef AccessType access_type;
typedef ValueType value_type;
typedef value_type & reference;
typedef value_type const & const_reference;
typedef value_type * pointer;
typedef value_type const * const_pointer;
static const_pointer find(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
return (it != container.end()) ? &it->second : NULL; // return NULL if not found
}
static const_reference lookup_unchecked(container_type const & container, access_type const & element)
{
typename result_of::access_type<access_type, AccessTag>::type access(element);
typename container_type::const_iterator it = container.find(access);
assert(it != container.end()); // no release-runtime check for accessing elements outside container
return it->second;
}
static const_reference lookup(container_type const & container, access_type const & element)
{
return lookup_unchecked(container, element); // using unchecked lookup
}
static void copy(container_type & container, access_type const & src_element, access_type const & dst_element);
static void erase(container_type & container, access_type const & element);
static void clear(container_type & container);
static void resize(container_type & container, std::size_t size);
};
} // namespace viennadata
#endif
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_TOPOLOGY_SIMPLEX_HPP
#define VIENNAGRID_TOPOLOGY_SIMPLEX_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
#include "viennagrid/topology/point.hpp"
#include "viennagrid/topology/line.hpp"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/algorithm/norm.hpp"
/** @file topology/simplex.hpp
@brief Provides the topological definition of an arbitrary simplex element
*/
namespace viennagrid
{
namespace meta //TODO: agree on handling meta stuff
{
template <long n, long k>
struct n_over_k
{
enum { value = n_over_k<n-1, k-1>::value + n_over_k<n-1, k>::value };
};
template <long n>
struct n_over_k<n, 0>
{
enum { value = 1 };
};
template <long k>
struct n_over_k<0, k>
{
enum { value = 0 };
};
template <>
struct n_over_k<0, 0>
{
enum { value = 1 };
};
}
/** @brief Topological description of an n-simplex.*/
template <long n>
struct simplex_tag
{
typedef simplex_tag<n-1> facet_tag;
enum{ dim = n };
static std::string name()
{
std::stringstream ss;
ss << n << "-simplex";
return ss.str();
}
};
namespace topology
{
/** @brief Topological description of the boundary k-cells an n-simplex */
template <long n, long k>
struct bndcells<simplex_tag<n>, k>
{
typedef simplex_tag<k> tag;
typedef static_layout_tag layout_tag;
enum{ num = meta::n_over_k<n+1, k+1>::value };
};
template <long n, long k>
struct boundary_cells<simplex_tag<n>, simplex_tag<k> >
{
typedef simplex_tag<k> tag;
typedef static_layout_tag layout_tag;
enum{ num = meta::n_over_k<n+1, k+1>::value };
};
///////////////////////////////// Generator for boundary cell elements ///////////////////////////////////
template<long n, typename bnd_cell_type>
struct bndcell_generator<simplex_tag<n>, 0, bnd_cell_type>
{
template<typename element_type, typename inserter_type>
static void create_bnd_cells(element_type & element, inserter_type & inserter)
{}
};
template<long n, typename bnd_cell_type>
struct bndcell_generator<simplex_tag<n>, 1, bnd_cell_type>
{
template<typename element_type, typename inserter_type>
static void create_bnd_cells(element_type & element, inserter_type & inserter)
{
bnd_cell_type bnd_cell( inserter.get_physical_container_collection() );
int index = 0;
for (int i = 0; i < bndcells<simplex_tag<n>, 0>::num; ++i)
for (int j = i+1; j < bndcells<simplex_tag<n>, 0>::num; ++j)
{
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(i), 0 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(j), 1 );
element.set_bnd_cell( bnd_cell, inserter(bnd_cell), index++ );
}
}
};
template<long n, typename bnd_cell_type>
struct bndcell_generator<simplex_tag<n>, 2, bnd_cell_type>
{
template<typename element_type, typename inserter_type>
static void create_bnd_cells(element_type & element, inserter_type & inserter)
{
bnd_cell_type bnd_cell( inserter.get_physical_container_collection() );
int index = 0;
for (int i = 0; i < bndcells<simplex_tag<n>, 0>::num; ++i)
for (int j = i+1; j < bndcells<simplex_tag<n>, 0>::num; ++j)
for (int k = j+1; k < bndcells<simplex_tag<n>, 0>::num; ++k)
{
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(i), 0 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(j), 1 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(k), 2 );
element.set_bnd_cell( bnd_cell, inserter(bnd_cell), index++ );
}
}
};
// similarly for higher topological dimensions...
} //topology
}
#endif
<commit_msg>bndcell_generator now takes 2 typenames<commit_after>#ifndef VIENNAGRID_TOPOLOGY_SIMPLEX_HPP
#define VIENNAGRID_TOPOLOGY_SIMPLEX_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
#include "viennagrid/topology/point.hpp"
#include "viennagrid/topology/line.hpp"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/algorithm/norm.hpp"
/** @file topology/simplex.hpp
@brief Provides the topological definition of an arbitrary simplex element
*/
namespace viennagrid
{
namespace meta //TODO: agree on handling meta stuff
{
template <long n, long k>
struct n_over_k
{
enum { value = n_over_k<n-1, k-1>::value + n_over_k<n-1, k>::value };
};
template <long n>
struct n_over_k<n, 0>
{
enum { value = 1 };
};
template <long k>
struct n_over_k<0, k>
{
enum { value = 0 };
};
template <>
struct n_over_k<0, 0>
{
enum { value = 1 };
};
}
/** @brief Topological description of an n-simplex.*/
template <long n>
struct simplex_tag
{
typedef simplex_tag<n-1> facet_tag;
enum{ dim = n };
static std::string name()
{
std::stringstream ss;
ss << n << "-simplex";
return ss.str();
}
};
namespace topology
{
/** @brief Topological description of the boundary k-cells an n-simplex */
template <long n, long k>
struct bndcells<simplex_tag<n>, k>
{
typedef simplex_tag<k> tag;
typedef static_layout_tag layout_tag;
enum{ num = meta::n_over_k<n+1, k+1>::value };
};
template <long n, long k>
struct boundary_cells<simplex_tag<n>, simplex_tag<k> >
{
//typedef simplex_tag<k> tag;
typedef static_layout_tag layout_tag;
enum{ num = meta::n_over_k<n+1, k+1>::value };
};
///////////////////////////////// Generator for boundary cell elements ///////////////////////////////////
template<long n, typename bnd_cell_type>
struct bndcell_generator<simplex_tag<n>, simplex_tag<1>, bnd_cell_type>
{
template<typename element_type, typename inserter_type>
static void create_bnd_cells(element_type & element, inserter_type & inserter)
{
bnd_cell_type bnd_cell( inserter.get_physical_container_collection() );
int index = 0;
for (int i = 0; i < bndcells<simplex_tag<n>, 0>::num; ++i)
for (int j = i+1; j < bndcells<simplex_tag<n>, 0>::num; ++j)
{
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(i), 0 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(j), 1 );
element.set_bnd_cell( bnd_cell, inserter(bnd_cell), index++ );
}
}
};
template<long n, typename bnd_cell_type>
struct bndcell_generator<simplex_tag<n>, simplex_tag<2>, bnd_cell_type>
{
template<typename element_type, typename inserter_type>
static void create_bnd_cells(element_type & element, inserter_type & inserter)
{
bnd_cell_type bnd_cell( inserter.get_physical_container_collection() );
int index = 0;
for (int i = 0; i < bndcells<simplex_tag<n>, 0>::num; ++i)
for (int j = i+1; j < bndcells<simplex_tag<n>, 0>::num; ++j)
for (int k = j+1; k < bndcells<simplex_tag<n>, 0>::num; ++k)
{
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(i), 0 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(j), 1 );
bnd_cell.container(dimension_tag<0>()).set_hook( element.container( dimension_tag<0>() ).hook_at(k), 2 );
element.set_bnd_cell( bnd_cell, inserter(bnd_cell), index++ );
}
}
};
// similarly for higher topological dimensions...
} //topology
}
#endif
<|endoftext|> |
<commit_before>#ifndef VPP_OPENCV_UTILS_HH_
# define VPP_OPENCV_UTILS_HH_
# include <iostream>
# include <regex>
# include <opencv2/highgui/highgui.hpp>
# include <vpp/core/boxNd.hh>
# include <vpp/core/image2d.hh>
inline bool open_videocapture(const char* str, cv::VideoCapture& cap)
{
if (std::regex_match(str, std::regex("[0-9]+")))
cap.open(atoi(str));
else cap.open(str);
if (!cap.isOpened())
{
std::cerr << "Error: Cannot open " << str << std::endl;
return false;
}
return true;
}
inline vpp::box2d videocapture_domain(cv::VideoCapture& cap)
{
return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT),
cap.get(CV_CAP_PROP_FRAME_WIDTH));
}
inline vpp::box2d videocapture_domain(const char* f)
{
cv::VideoCapture cap;
open_videocapture(f, cap);
return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT),
cap.get(CV_CAP_PROP_FRAME_WIDTH));
}
struct foreach_videoframe
{
foreach_videoframe(const char* f)
{
open_videocapture(f, cap_);
frame_ = vpp::image2d<vpp::vuchar3>(videocapture_domain(cap_));
cvframe_ = to_opencv(frame_);
}
template <typename F>
void operator| (F f)
{
while (cap_.read(cvframe_)) f(frame_);
}
private:
cv::Mat cvframe_;
vpp::image2d<vpp::vuchar3> frame_;
cv::VideoCapture cap_;
};
#endif
<commit_msg>Fix missing include in opencv_utils.<commit_after>#ifndef VPP_OPENCV_UTILS_HH_
# define VPP_OPENCV_UTILS_HH_
# include <iostream>
# include <regex>
# include <opencv2/highgui/highgui.hpp>
# include <vpp/core/boxNd.hh>
# include <vpp/core/image2d.hh>
# include <vpp/utils/opencv_bridge.hh>
inline bool open_videocapture(const char* str, cv::VideoCapture& cap)
{
if (std::regex_match(str, std::regex("[0-9]+")))
cap.open(atoi(str));
else cap.open(str);
if (!cap.isOpened())
{
std::cerr << "Error: Cannot open " << str << std::endl;
return false;
}
return true;
}
inline vpp::box2d videocapture_domain(cv::VideoCapture& cap)
{
return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT),
cap.get(CV_CAP_PROP_FRAME_WIDTH));
}
inline vpp::box2d videocapture_domain(const char* f)
{
cv::VideoCapture cap;
open_videocapture(f, cap);
return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT),
cap.get(CV_CAP_PROP_FRAME_WIDTH));
}
struct foreach_videoframe
{
foreach_videoframe(const char* f)
{
open_videocapture(f, cap_);
frame_ = vpp::image2d<vpp::vuchar3>(videocapture_domain(cap_));
cvframe_ = to_opencv(frame_);
}
template <typename F>
void operator| (F f)
{
while (cap_.read(cvframe_)) f(frame_);
}
private:
cv::Mat cvframe_;
vpp::image2d<vpp::vuchar3> frame_;
cv::VideoCapture cap_;
};
#endif
<|endoftext|> |
<commit_before>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <queue>
#include "google/protobuf/descriptor.h"
#include "boost/asio.hpp"
#include "boost/chrono.hpp"
#include "boost/thread.hpp"
#include "boost/thread/shared_mutex.hpp"
#include "boost/thread/condition_variable.hpp"
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-sizepack-policy.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-condition-queues.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"
#include "vtrc-common/vtrc-call-keeper.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "protocol/vtrc-service.pb.h"
#include "vtrc-memory.h"
#include "vtrc-chrono.h"
#include "vtrc-thread.h"
#include "vtrc-server/vtrc-channels.h"
namespace ba = boost::asio;
using namespace vtrc;
struct work_time {
typedef boost::chrono::high_resolution_clock::time_point time_point;
time_point start_;
work_time( )
:start_(boost::chrono::high_resolution_clock::now( ))
{}
~work_time( )
{
time_point stop(boost::chrono::high_resolution_clock::now( ));
std::cout << "call time: " << stop - start_ << "\n";
}
};
void test_send( common::connection_iface *connection,
vtrc::server::application &app, int count )
{
common::connection_iface_sptr s(connection->shared_from_this());
vtrc::shared_ptr<google::protobuf::RpcChannel> ev(
vtrc::server
::channels::unicast
::create_event_channel( s, true ));
if(common::call_context::get( s ))
const vtrc_rpc::lowlevel_unit *pllu =
common::call_context::get( s )->get_lowlevel_message( );
// vtrc_rpc_lowlevel::lowlevel_unit llu;
// s->get_protocol( ).send_message( llu );
vtrc_service::internal::Stub ping( ev.get( ));
vtrc_service::ping_req preq;
vtrc_service::pong_res pres;
// for( int i=0; i<100; ++i )
// ping.ping( NULL, &preq, &pres, NULL );
try {
//for( ;; )
{
// std::cout << "ping 2 " << vtrc::this_thread::get_id( ) << "\n";
while( count-- )
ping.ping( NULL, &preq, &pres, NULL );
}
} catch( std::exception const &ex ) {
// std::cout << "png error " << ex.what( ) << "\n";
}
}
void call_delayed_test( const boost::system::error_code &err,
::google::protobuf::RpcController* controller,
const ::vtrc_rpc::message_info* request,
::vtrc_rpc::message_info* response,
::google::protobuf::Closure* done,
unsigned id,
common::connection_iface *c_,
vtrc::server::application &app_)
{
common::closure_holder ch(done);
response->set_message_type( id );
test_send(c_, app_, 1);
}
void test_keeper_call( const boost::system::error_code &ecode,
common::call_keeper_sptr ck,
::vtrc_service::test_message* response,
uint64_t id,
common::connection_iface *c,
vtrc::server::application &app)
{
response->set_id( id );
test_send(c, app, 1);
}
class test_impl: public vtrc_service::test_rpc {
common::connection_iface *c_;
vtrc::server::application &app_;
unsigned id_;
common::delayed_call dc_;
public:
test_impl( common::connection_iface *c, vtrc::server::application &app )
:c_(c)
,app_(app)
,id_(0)
,dc_(app_.get_rpc_service( ))
{ }
void test(::google::protobuf::RpcController* controller,
const ::vtrc_service::test_message* request,
::vtrc_service::test_message* response,
::google::protobuf::Closure* done)
{
// c_->impersonate( );
// c_->revert( );
{
//common::call_keeper_sptr ck(common::call_keeper::create(c_));
common::closure_holder ch(done);
if( (id_++ % 100) == 0 )
throw std::runtime_error( "oops 10 =)" );
// dc_.call_from_now( vtrc::bind( test_keeper_call, _1,
// ck,
// response, id_,
// c_, vtrc::ref(app_)),
// boost::posix_time::milliseconds( 0 ));
response->set_id( id_ );
//std::cout << id_ << "\n";
// connection_->get_io_service( ).dispatch(
// vtrc::bind(test_send, connection_));
// boost::thread(test_send, connection_).detach( );
test_send(c_, app_, 5);
}
}
virtual void test2(::google::protobuf::RpcController* controller,
const ::vtrc_service::test_message* request,
::vtrc_service::test_message* response,
::google::protobuf::Closure* done)
{
common::closure_holder ch(done);
const vtrc::common::call_context *cc =
vtrc::common::call_context::get( c_ );
// std::cout << "test 2 " << vtrc::this_thread::get_id( ) << "\n\n";
// std::cout << std::setw(8) << id_ << " stack: ";
// while (cc) {
// std::cout << cc->get_lowlevel_message( )->call( ).method_id( )
// << " <- ";
// cc = cc->next( );
// }
// std::cout << "\n";
}
};
class main_app: public vtrc::server::application
{
public:
main_app( common::pool_pair &pp )
:application(pp)
{ }
void attach_listener( vtrc::shared_ptr<server::listener> nl )
{
nl->get_on_start( ).connect(
vtrc::bind(&main_app::on_endpoint_started, this, nl.get( )));
nl->get_on_stop( ).connect(
vtrc::bind(&main_app::on_endpoint_stopped, this, nl.get( )));
nl->get_on_new_connection( ).connect(
vtrc::bind(&main_app::on_new_connection, this, _1, nl.get( )));
nl->get_on_stop_connection( ).connect(
vtrc::bind(&main_app::on_stop_connection, this, _1, nl.get( )));
}
private:
void on_new_connection( const common::connection_iface *c,
vtrc::server::listener *ep)
{
std::cout << "new connection: ep = " << ep->name( )
<< "; count: " << ep->clients_count( )
<< "; c = " << c->name( ) << "\n";
}
void on_stop_connection( const common::connection_iface *c,
vtrc::server::listener *ep )
{
std::cout << "stop connection: ep = " << ep->name( )
<< "; count: " << ep->clients_count( )
<< "; c = " << c->name( ) << "\n";
}
void on_endpoint_started( vtrc::server::listener *ep )
{
std::cout << "Start endpoint: " << ep->name( ) << "\n";
}
void on_endpoint_stopped( vtrc::server::listener *ep )
{
std::cout << "Stop endpoint: " << ep->name( ) << "\n";
}
std::string get_session_key( vtrc::common::connection_iface *connection,
const std::string &id)
{
return "1234";
}
vtrc::common::rpc_service_wrapper_sptr get_service_by_name(
vtrc::common::connection_iface *connection,
const std::string &service_name)
{
if( service_name == test_impl::descriptor( )->full_name( ) ) {
return common::rpc_service_wrapper_sptr(
new common::rpc_service_wrapper(
new test_impl(connection, *this) ) );
}
return common::rpc_service_wrapper_sptr( );
}
};
int main( ) try {
common::pool_pair pp(1, 1);
main_app app(pp);
vtrc::shared_ptr<vtrc::server::listener> tcp4_ep
(vtrc::server::listeners::tcp::create(app, "0.0.0.0", 44667, true ));
vtrc::shared_ptr<vtrc::server::listener> tcp6_ep
(vtrc::server::listeners::tcp::create(app, "::", 44668, true));
#ifndef _WIN32
std::string file_name("/tmp/test.socket");
#else
std::string file_name("\\\\.\\pipe\\test_pipe");
#endif
vtrc::shared_ptr<vtrc::server::listener> local_listen
(vtrc::server::listeners::local::create(app, file_name));
app.attach_listener( tcp4_ep );
app.attach_listener( tcp6_ep );
app.attach_listener( local_listen );
local_listen->start( );
tcp4_ep->start( );
tcp6_ep->start( );
vtrc::this_thread::sleep_for( vtrc::chrono::seconds( 10999999 ) );
std::cout << "Stoppped. Wait ... \n";
local_listen->stop( );
tcp4_ep->stop( );
tcp6_ep->stop( );
app.stop_all_clients( );
std::cout << "Stoppped. Wait ... \n";
pp.stop_all( );
pp.join_all( );
google::protobuf::ShutdownProtobufLibrary( );
return 0;
} catch( const std::exception &ex ) {
google::protobuf::ShutdownProtobufLibrary( );
std::cout << "general error: " << ex.what( ) << "\n";
return 0;
}
//////////
<commit_msg>local listener<commit_after>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <queue>
#include "google/protobuf/descriptor.h"
#include "boost/asio.hpp"
#include "boost/chrono.hpp"
#include "boost/thread.hpp"
#include "boost/thread/shared_mutex.hpp"
#include "boost/thread/condition_variable.hpp"
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-sizepack-policy.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-condition-queues.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"
#include "vtrc-common/vtrc-call-keeper.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "protocol/vtrc-service.pb.h"
#include "vtrc-memory.h"
#include "vtrc-chrono.h"
#include "vtrc-thread.h"
#include "vtrc-server/vtrc-channels.h"
namespace ba = boost::asio;
using namespace vtrc;
struct work_time {
typedef boost::chrono::high_resolution_clock::time_point time_point;
time_point start_;
work_time( )
:start_(boost::chrono::high_resolution_clock::now( ))
{}
~work_time( )
{
time_point stop(boost::chrono::high_resolution_clock::now( ));
std::cout << "call time: " << stop - start_ << "\n";
}
};
void test_send( common::connection_iface *connection,
vtrc::server::application &app, int count )
{
common::connection_iface_sptr s(connection->shared_from_this());
vtrc::shared_ptr<google::protobuf::RpcChannel> ev(
vtrc::server
::channels::unicast
::create_event_channel( s, true ));
if(common::call_context::get( s ))
const vtrc_rpc::lowlevel_unit *pllu =
common::call_context::get( s )->get_lowlevel_message( );
// vtrc_rpc_lowlevel::lowlevel_unit llu;
// s->get_protocol( ).send_message( llu );
vtrc_service::internal::Stub ping( ev.get( ));
vtrc_service::ping_req preq;
vtrc_service::pong_res pres;
// for( int i=0; i<100; ++i )
// ping.ping( NULL, &preq, &pres, NULL );
try {
//for( ;; )
{
// std::cout << "ping 2 " << vtrc::this_thread::get_id( ) << "\n";
while( count-- )
ping.ping( NULL, &preq, &pres, NULL );
}
} catch( std::exception const &ex ) {
// std::cout << "png error " << ex.what( ) << "\n";
}
}
void call_delayed_test( const boost::system::error_code &err,
::google::protobuf::RpcController* controller,
const ::vtrc_rpc::message_info* request,
::vtrc_rpc::message_info* response,
::google::protobuf::Closure* done,
unsigned id,
common::connection_iface *c_,
vtrc::server::application &app_)
{
common::closure_holder ch(done);
response->set_message_type( id );
test_send(c_, app_, 1);
}
void test_keeper_call( const boost::system::error_code &ecode,
common::call_keeper_sptr ck,
::vtrc_service::test_message* response,
uint64_t id,
common::connection_iface *c,
vtrc::server::application &app)
{
response->set_id( id );
test_send(c, app, 1);
}
class test_impl: public vtrc_service::test_rpc {
common::connection_iface *c_;
vtrc::server::application &app_;
unsigned id_;
common::delayed_call dc_;
public:
test_impl( common::connection_iface *c, vtrc::server::application &app )
:c_(c)
,app_(app)
,id_(0)
,dc_(app_.get_rpc_service( ))
{ }
void test(::google::protobuf::RpcController* controller,
const ::vtrc_service::test_message* request,
::vtrc_service::test_message* response,
::google::protobuf::Closure* done)
{
// c_->impersonate( );
// c_->revert( );
{
//common::call_keeper_sptr ck(common::call_keeper::create(c_));
common::closure_holder ch(done);
if( (id_++ % 100) == 0 )
throw std::runtime_error( "oops 10 =)" );
// dc_.call_from_now( vtrc::bind( test_keeper_call, _1,
// ck,
// response, id_,
// c_, vtrc::ref(app_)),
// boost::posix_time::milliseconds( 0 ));
response->set_id( id_ );
//std::cout << id_ << "\n";
// connection_->get_io_service( ).dispatch(
// vtrc::bind(test_send, connection_));
// boost::thread(test_send, connection_).detach( );
test_send(c_, app_, 5);
}
}
virtual void test2(::google::protobuf::RpcController* controller,
const ::vtrc_service::test_message* request,
::vtrc_service::test_message* response,
::google::protobuf::Closure* done)
{
common::closure_holder ch(done);
const vtrc::common::call_context *cc =
vtrc::common::call_context::get( c_ );
// std::cout << "test 2 " << vtrc::this_thread::get_id( ) << "\n\n";
// std::cout << std::setw(8) << id_ << " stack: ";
// while (cc) {
// std::cout << cc->get_lowlevel_message( )->call( ).method_id( )
// << " <- ";
// cc = cc->next( );
// }
// std::cout << "\n";
}
};
class main_app: public vtrc::server::application
{
public:
main_app( common::pool_pair &pp )
:application(pp)
{ }
void attach_listener( vtrc::shared_ptr<server::listener> nl )
{
nl->get_on_start( ).connect(
vtrc::bind(&main_app::on_endpoint_started, this, nl.get( )));
nl->get_on_stop( ).connect(
vtrc::bind(&main_app::on_endpoint_stopped, this, nl.get( )));
nl->get_on_new_connection( ).connect(
vtrc::bind(&main_app::on_new_connection, this, _1, nl.get( )));
nl->get_on_stop_connection( ).connect(
vtrc::bind(&main_app::on_stop_connection, this, _1, nl.get( )));
}
private:
void on_new_connection( const common::connection_iface *c,
vtrc::server::listener *ep)
{
std::cout << "new connection: ep = " << ep->name( )
<< "; count: " << ep->clients_count( )
<< "; c = " << c->name( ) << "\n";
}
void on_stop_connection( const common::connection_iface *c,
vtrc::server::listener *ep )
{
std::cout << "stop connection: ep = " << ep->name( )
<< "; count: " << ep->clients_count( )
<< "; c = " << c->name( ) << "\n";
}
void on_endpoint_started( vtrc::server::listener *ep )
{
std::cout << "Start endpoint: " << ep->name( ) << "\n";
}
void on_endpoint_stopped( vtrc::server::listener *ep )
{
std::cout << "Stop endpoint: " << ep->name( ) << "\n";
}
std::string get_session_key( vtrc::common::connection_iface *connection,
const std::string &id)
{
return "1234";
}
vtrc::common::rpc_service_wrapper_sptr get_service_by_name(
vtrc::common::connection_iface *connection,
const std::string &service_name)
{
if( service_name == test_impl::descriptor( )->full_name( ) ) {
return common::rpc_service_wrapper_sptr(
new common::rpc_service_wrapper(
new test_impl(connection, *this) ) );
}
return common::rpc_service_wrapper_sptr( );
}
};
int main( ) try {
common::pool_pair pp(1, 1);
main_app app(pp);
vtrc::shared_ptr<vtrc::server::listener> tcp4_ep
(vtrc::server::listeners::tcp::create(app, "0.0.0.0", 44667, true ));
vtrc::shared_ptr<vtrc::server::listener> tcp6_ep
(vtrc::server::listeners::tcp::create(app, "::", 44668, true));
#ifndef _WIN32
std::string file_name("/tmp/test.socket");
#else
std::string file_name("\\\\.\\pipe\\test_pipe");
#endif
vtrc::shared_ptr<vtrc::server::listener> local_listen
(vtrc::server::listeners::local::create(app, file_name));
app.attach_listener( tcp4_ep );
app.attach_listener( tcp6_ep );
app.attach_listener( local_listen );
local_listen->start( );
tcp4_ep->start( );
tcp6_ep->start( );
vtrc::this_thread::sleep_for( vtrc::chrono::seconds( 10999999 ) );
std::cout << "Stoppped. Wait ... \n";
local_listen->stop( );
tcp4_ep->stop( );
tcp6_ep->stop( );
app.stop_all_clients( );
std::cout << "Stoppped. Wait ... \n";
pp.stop_all( );
pp.join_all( );
google::protobuf::ShutdownProtobufLibrary( );
return 0;
} catch( const std::exception &ex ) {
google::protobuf::ShutdownProtobufLibrary( );
std::cout << "general error: " << ex.what( ) << "\n";
return 0;
}
//////////
<|endoftext|> |
<commit_before>#include <nanyc/library.h>
#include <nanyc/program.h>
#include <yuni/yuni.h>
#include <yuni/core/getopt.h>
#include <yuni/core/string.h>
#include <yuni/io/filename-manipulation.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/system/console/console.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <random>
#include "libnanyc.h"
namespace ny {
namespace unittests {
namespace {
struct Entry final {
yuni::String module;
yuni::String name;
};
struct App final {
App();
App(App&&) = default;
~App();
void importFilenames(const std::vector<AnyString>&);
void fetch(bool nsl);
void run(const Entry&);
int run();
void statstics(int64_t duration) const;
void setcolor(yuni::System::Console::Color) const;
void resetcolor() const;
struct final {
uint32_t total = 0;
uint32_t passing = 0;
uint32_t failed = 0;
}
stats;
nycompile_opts_t opts;
bool interactive = true;
bool colors = true;
uint32_t loops = 1;
bool shuffle = false;
std::vector<Entry> unittests;
std::vector<yuni::String> filenames;
private:
void startEntry(const Entry&);
void endEntry(const Entry&, bool, int64_t);
};
App::App() {
memset(&opts, 0x0, sizeof(opts));
opts.userdata = this;;
}
App::~App() {
free(opts.sources.items);
}
void App::setcolor(yuni::System::Console::Color c) const {
if (colors)
yuni::System::Console::SetTextColor(std::cout, c);
}
void App::resetcolor() const {
if (colors)
yuni::System::Console::ResetTextColor(std::cout);
}
auto now() {
return yuni::DateTime::NowMilliSeconds();
}
bool operator < (const Entry& a, const Entry& b) {
return std::tie(a.module, a.name) < std::tie(b.module, b.name);
}
const char* plurals(auto count, const char* single, const char* many) {
return (count <= 1) ? single : many;
}
void App::importFilenames(const std::vector<AnyString>& list) {
uint32_t count = static_cast<uint32_t>(list.size());
filenames.resize(count);
std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String {
return std::move(yuni::IO::Canonicalize(item));
});
opts.sources.count = count;
opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t));
if (unlikely(!opts.sources.items))
throw std::bad_alloc();
for (uint32_t i = 0; i != count; ++i) {
opts.sources.items[i].filename.len = filenames[i].size();
opts.sources.items[i].filename.c_str = filenames[i].c_str();
}
}
void App::fetch(bool nsl) {
unittests.reserve(512); // arbitrary
opts.with_nsl_unittests = nsl ? nytrue : nyfalse;
opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) {
auto& self = *reinterpret_cast<App*>(userdata);
self.unittests.emplace_back();
auto& entry = self.unittests.back();
entry.module.assign(mod, mlen);
entry.name.assign(name, nlen);
};
std::cout << "searching for unittests in all source files...\n";
auto start = now();
nyprogram_compile(&opts);
opts.on_unittest = nullptr;
std::sort(std::begin(unittests), std::end(unittests));
auto duration = now() - start;
std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests");
std::cout << " found (in " << duration << "ms)\n";
}
void App::startEntry(const Entry& entry) {
if (interactive) {
setcolor(yuni::System::Console::bold);
std::cout << " running ";
resetcolor();
std::cout << entry.module << '/' << entry.name;
std::cout << "... " << std::flush;
}
}
void App::endEntry(const Entry& entry, bool success, int64_t duration) {
++stats.total;
++(success ? stats.passing : stats.failed);
if (interactive)
std::cout << '\r'; // back to begining of the line
if (success) {
setcolor(yuni::System::Console::green);
#ifndef YUNI_OS_WINDOWS
std::cout << " \u2713 ";
#else
std::cout << " OK ";
#endif
resetcolor();
}
else {
setcolor(yuni::System::Console::red);
std::cout << " ERR ";
resetcolor();
}
std::cout << entry.module << '/' << entry.name;
setcolor(yuni::System::Console::lightblue);
std::cout << " (" << duration << "ms)";
resetcolor();
std::cout << " \n";
}
void App::statstics(int64_t duration) const {
std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests");
if (stats.passing != 0) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.passing << " passing";
resetcolor();
}
if (stats.failed) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.failed << " failed";
resetcolor();
}
std::cout << " (";
if (duration < 10000)
std::cout << duration << "ms)";
else
std::cout << (duration / 1000) << "s)";
std::cout << "\n\n";
}
void App::run(const Entry& entry) {
startEntry(entry);
auto start = now();
auto* program = nyprogram_compile(&opts);
bool success = program != nullptr;
if (program) {
nyprogram_free(program);
}
auto duration = now() - start;
endEntry(entry, success, duration);
}
void shuffleDeck(std::vector<Entry>& unittests) {
std::cout << "shuffling the tests...\n" << std::flush;
auto seed = now();
auto useed = static_cast<uint32_t>(seed);
std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed));
}
int App::run() {
std::cout << '\n';
auto start = now();
for (uint32_t l = 0; l != loops; ++l) {
if (unlikely(shuffle))
shuffleDeck(unittests);
for (auto& entry: unittests)
run(entry);
}
auto duration = now() - start;
statstics(duration);
bool success = stats.failed == 0 and stats.total != 0;
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
int printVersion() {
std::cout << libnanyc_version_to_cstr() << '\n';
return EXIT_SUCCESS;
}
int printBugreport() {
uint32_t length;
auto* text = libnanyc_get_bugreportdetails(&length);
if (text) {
std::cout.write(text, length);
free(text);
}
std::cout << '\n';
return EXIT_SUCCESS;
}
App prepare(int argc, char** argv) {
App app;
bool version = false;
bool bugreport = false;
bool nsl = false;
bool verbose = false;
bool nocolors = false;
std::vector<AnyString> filenames;
yuni::GetOpt::Parser options;
options.addFlag(filenames, 'i', "", "Input nanyc source files");
options.addFlag(nsl, ' ', "nsl", "Import NSL unittests");
options.addParagraph("\nEntropy");
options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)");
options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests");
options.addParagraph("\nDisplay");
options.addFlag(nocolors, ' ', "no-colors", "Disable color output");
options.addParagraph("\nHelp");
options.addFlag(verbose, 'v', "verbose", "More stuff on the screen");
options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug");
options.addFlag(version, ' ', "version", "Print the version");
options.remainingArguments(filenames);
if (not options(argc, argv)) {
if (options.errors())
throw std::runtime_error("Abort due to error");
throw EXIT_SUCCESS;
}
if (unlikely(version))
throw printVersion();
if (unlikely(bugreport))
throw printBugreport();
if (unlikely(verbose))
printBugreport();
app.interactive = yuni::System::Console::IsStdoutTTY();
app.colors = (not nocolors) and app.interactive;
app.importFilenames(filenames);
app.fetch(nsl);
return app;
}
} // namespace
} // namespace unittests
} // namespace ny
int main(int argc, char** argv) {
try {
auto app = ny::unittests::prepare(argc, argv);
return app.run();
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << '\n';
}
catch (int e) {
return e;
}
return EXIT_FAILURE;;
}
<commit_msg>unittests: prepare the file list before any other other operation<commit_after>#include <nanyc/library.h>
#include <nanyc/program.h>
#include <yuni/yuni.h>
#include <yuni/core/getopt.h>
#include <yuni/core/string.h>
#include <yuni/io/filename-manipulation.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/system/console/console.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <random>
#include "libnanyc.h"
namespace ny {
namespace unittests {
namespace {
struct Entry final {
yuni::String module;
yuni::String name;
};
struct App final {
App();
App(App&&) = default;
~App();
void importFilenames(const std::vector<AnyString>&);
void fetch(bool nsl);
void run(const Entry&);
int run();
void statstics(int64_t duration) const;
void setcolor(yuni::System::Console::Color) const;
void resetcolor() const;
struct final {
uint32_t total = 0;
uint32_t passing = 0;
uint32_t failed = 0;
}
stats;
nycompile_opts_t opts;
bool interactive = true;
bool colors = true;
uint32_t loops = 1;
bool shuffle = false;
std::vector<Entry> unittests;
std::vector<yuni::String> filenames;
private:
void startEntry(const Entry&);
void endEntry(const Entry&, bool, int64_t);
};
App::App() {
memset(&opts, 0x0, sizeof(opts));
opts.userdata = this;;
}
App::~App() {
free(opts.sources.items);
}
void App::setcolor(yuni::System::Console::Color c) const {
if (colors)
yuni::System::Console::SetTextColor(std::cout, c);
}
void App::resetcolor() const {
if (colors)
yuni::System::Console::ResetTextColor(std::cout);
}
auto now() {
return yuni::DateTime::NowMilliSeconds();
}
bool operator < (const Entry& a, const Entry& b) {
return std::tie(a.module, a.name) < std::tie(b.module, b.name);
}
const char* plurals(auto count, const char* single, const char* many) {
return (count <= 1) ? single : many;
}
void App::importFilenames(const std::vector<AnyString>& list) {
uint32_t count = static_cast<uint32_t>(list.size());
filenames.resize(count);
std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String {
return std::move(yuni::IO::Canonicalize(item));
});
opts.sources.count = count;
opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t));
if (unlikely(!opts.sources.items))
throw std::bad_alloc();
for (uint32_t i = 0; i != count; ++i) {
opts.sources.items[i].filename.len = filenames[i].size();
opts.sources.items[i].filename.c_str = filenames[i].c_str();
}
}
void App::fetch(bool nsl) {
unittests.reserve(512); // arbitrary
opts.with_nsl_unittests = nsl ? nytrue : nyfalse;
opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) {
auto& self = *reinterpret_cast<App*>(userdata);
self.unittests.emplace_back();
auto& entry = self.unittests.back();
entry.module.assign(mod, mlen);
entry.name.assign(name, nlen);
};
std::cout << "searching for unittests in all source files...\n";
auto start = now();
nyprogram_compile(&opts);
opts.on_unittest = nullptr;
std::sort(std::begin(unittests), std::end(unittests));
auto duration = now() - start;
std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests");
std::cout << " found (in " << duration << "ms)\n";
}
void App::startEntry(const Entry& entry) {
if (interactive) {
setcolor(yuni::System::Console::bold);
std::cout << " running ";
resetcolor();
std::cout << entry.module << '/' << entry.name;
std::cout << "... " << std::flush;
}
}
void App::endEntry(const Entry& entry, bool success, int64_t duration) {
++stats.total;
++(success ? stats.passing : stats.failed);
if (interactive)
std::cout << '\r'; // back to begining of the line
if (success) {
setcolor(yuni::System::Console::green);
#ifndef YUNI_OS_WINDOWS
std::cout << " \u2713 ";
#else
std::cout << " OK ";
#endif
resetcolor();
}
else {
setcolor(yuni::System::Console::red);
std::cout << " ERR ";
resetcolor();
}
std::cout << entry.module << '/' << entry.name;
setcolor(yuni::System::Console::lightblue);
std::cout << " (" << duration << "ms)";
resetcolor();
std::cout << " \n";
}
void App::statstics(int64_t duration) const {
std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests");
if (stats.passing != 0) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.passing << " passing";
resetcolor();
}
if (stats.failed) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.failed << " failed";
resetcolor();
}
std::cout << " (";
if (duration < 10000)
std::cout << duration << "ms)";
else
std::cout << (duration / 1000) << "s)";
std::cout << "\n\n";
}
void App::run(const Entry& entry) {
startEntry(entry);
auto start = now();
auto* program = nyprogram_compile(&opts);
bool success = program != nullptr;
if (program) {
nyprogram_free(program);
}
auto duration = now() - start;
endEntry(entry, success, duration);
}
void shuffleDeck(std::vector<Entry>& unittests) {
std::cout << "shuffling the tests...\n" << std::flush;
auto seed = now();
auto useed = static_cast<uint32_t>(seed);
std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed));
}
int App::run() {
std::cout << '\n';
auto start = now();
for (uint32_t l = 0; l != loops; ++l) {
if (unlikely(shuffle))
shuffleDeck(unittests);
for (auto& entry: unittests)
run(entry);
}
auto duration = now() - start;
statstics(duration);
bool success = stats.failed == 0 and stats.total != 0;
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
int printVersion() {
std::cout << libnanyc_version_to_cstr() << '\n';
return EXIT_SUCCESS;
}
int printBugreport() {
uint32_t length;
auto* text = libnanyc_get_bugreportdetails(&length);
if (text) {
std::cout.write(text, length);
free(text);
}
std::cout << '\n';
return EXIT_SUCCESS;
}
App prepare(int argc, char** argv) {
App app;
bool version = false;
bool bugreport = false;
bool nsl = false;
bool verbose = false;
bool nocolors = false;
std::vector<AnyString> filenames;
yuni::GetOpt::Parser options;
options.addFlag(filenames, 'i', "", "Input nanyc source files");
options.addFlag(nsl, ' ', "nsl", "Import NSL unittests");
options.addParagraph("\nEntropy");
options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)");
options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests");
options.addParagraph("\nDisplay");
options.addFlag(nocolors, ' ', "no-colors", "Disable color output");
options.addParagraph("\nHelp");
options.addFlag(verbose, 'v', "verbose", "More stuff on the screen");
options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug");
options.addFlag(version, ' ', "version", "Print the version");
options.remainingArguments(filenames);
if (not options(argc, argv)) {
if (options.errors())
throw std::runtime_error("Abort due to error");
throw EXIT_SUCCESS;
}
if (unlikely(version))
throw printVersion();
if (unlikely(bugreport))
throw printBugreport();
if (unlikely(verbose))
printBugreport();
app.importFilenames(filenames);
app.interactive = yuni::System::Console::IsStdoutTTY();
app.colors = (not nocolors) and app.interactive;
app.fetch(nsl);
return app;
}
} // namespace
} // namespace unittests
} // namespace ny
int main(int argc, char** argv) {
try {
auto app = ny::unittests::prepare(argc, argv);
return app.run();
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << '\n';
}
catch (int e) {
return e;
}
return EXIT_FAILURE;;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 <stdint.h>
#include <ros/ros.h>
#include <OgreCamera.h>
#include <OgrePlane.h>
#include <OgreQuaternion.h>
#include <OgreRay.h>
#include <OgreSceneNode.h>
#include <OgreVector3.h>
#include <OgreViewport.h>
#include "rviz/display_context.h"
#include "rviz/ogre_helpers/shape.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/vector_property.h"
#include "rviz/viewport_mouse_event.h"
#include "rviz/default_plugin/view_controllers/third_person_follower_view_controller.h"
namespace rviz
{
// move camera up so the focal point appears in the lower image half
static const float CAMERA_OFFSET = 0.2;
void ThirdPersonFollowerViewController::onInitialize()
{
OrbitViewController::onInitialize();
focal_shape_->setColor(0.0f, 1.0f, 1.0f, 0.5f);
}
bool ThirdPersonFollowerViewController::intersectGroundPlane( Ogre::Ray mouse_ray, Ogre::Vector3 &intersection_3d )
{
//convert rays into reference frame
mouse_ray.setOrigin( target_scene_node_->convertWorldToLocalPosition( mouse_ray.getOrigin() ) );
mouse_ray.setDirection( target_scene_node_->convertWorldToLocalOrientation( Ogre::Quaternion::IDENTITY ) * mouse_ray.getDirection() );
Ogre::Plane ground_plane( Ogre::Vector3::UNIT_Z, 0 );
std::pair<bool, Ogre::Real> intersection = mouse_ray.intersects(ground_plane);
if (!intersection.first)
{
return false;
}
intersection_3d = mouse_ray.getPoint(intersection.second);
return true;
}
void ThirdPersonFollowerViewController::handleMouseEvent(ViewportMouseEvent& event)
{
if ( event.shift() )
{
setStatus( "<b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Zoom." );
}
else
{
setStatus( "<b>Left-Click:</b> Rotate. <b>Middle-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z. <b>Shift</b>: More options." );
}
int32_t diff_x = 0;
int32_t diff_y = 0;
bool moved = false;
if( event.type == QEvent::MouseButtonPress )
{
focal_shape_->getRootNode()->setVisible(true);
moved = true;
}
else if( event.type == QEvent::MouseButtonRelease )
{
focal_shape_->getRootNode()->setVisible(false);
moved = true;
}
else if( event.type == QEvent::MouseMove )
{
diff_x = event.x - event.last_x;
diff_y = event.y - event.last_y;
moved = true;
}
if( event.left() && !event.shift() )
{
setCursor( Rotate3D );
yaw( diff_x*0.005 );
pitch( -diff_y*0.005 );
}
else if( event.middle() || (event.left() && event.shift()) )
{
setCursor( MoveXY );
// handle mouse movement
int width = event.viewport->getActualWidth();
int height = event.viewport->getActualHeight();
Ogre::Ray mouse_ray = event.viewport->getCamera()->getCameraToViewportRay( event.x / (float) width,
event.y / (float) height );
Ogre::Ray last_mouse_ray =
event.viewport->getCamera()->getCameraToViewportRay( event.last_x / (float) width,
event.last_y / (float) height );
Ogre::Vector3 last_intersect, intersect;
if( intersectGroundPlane( last_mouse_ray, last_intersect ) &&
intersectGroundPlane( mouse_ray, intersect ))
{
Ogre::Vector3 motion = last_intersect - intersect;
// When dragging near the horizon, the motion can get out of
// control. This throttles it to an arbitrary limit per mouse
// event.
float motion_distance_limit = 1; /*meter*/
if( motion.length() > motion_distance_limit )
{
motion.normalise();
motion *= motion_distance_limit;
}
focal_point_property_->add( motion );
emitConfigChanged();
}
}
else if( event.right() )
{
setCursor( Zoom );
zoom( -diff_y * 0.1 * (distance_property_->getFloat() / 10.0f) );
}
else
{
setCursor( event.shift() ? MoveXY : Rotate3D );
}
if( event.wheel_delta != 0 )
{
int diff = event.wheel_delta;
zoom( diff * 0.001 * distance_property_->getFloat() );
moved = true;
}
if( moved )
{
context_->queueRender();
}
}
void ThirdPersonFollowerViewController::mimic( ViewController* source_view )
{
FramePositionTrackingViewController::mimic( source_view );
Ogre::Camera* source_camera = source_view->getCamera();
// do some trigonometry
Ogre::Ray camera_dir_ray( source_camera->getRealPosition(), source_camera->getRealDirection() );
Ogre::Ray camera_down_ray( source_camera->getRealPosition(), -1.0 * source_camera->getRealUp() );
Ogre::Vector3 a,b;
if( intersectGroundPlane( camera_dir_ray, b ) &&
intersectGroundPlane( camera_down_ray, a ) )
{
float l_a = source_camera->getPosition().distance( b );
float l_b = source_camera->getPosition().distance( a );
distance_property_->setFloat(( l_a * l_b ) / ( CAMERA_OFFSET * l_a + l_b ));
float distance = distance_property_->getFloat();
camera_dir_ray.setOrigin( source_camera->getRealPosition() - source_camera->getRealUp() * distance * CAMERA_OFFSET );
Ogre::Vector3 new_focal_point;
intersectGroundPlane( camera_dir_ray, new_focal_point );
focal_point_property_->setVector( new_focal_point );
calculatePitchYawFromPosition( source_camera->getPosition() - source_camera->getUp() * distance * CAMERA_OFFSET );
}
}
void ThirdPersonFollowerViewController::updateCamera()
{
OrbitViewController::updateCamera();
camera_->setPosition( camera_->getPosition() + camera_->getUp() * distance_property_->getFloat() * CAMERA_OFFSET );
}
void ThirdPersonFollowerViewController::updateTargetSceneNode()
{
if ( FramePositionTrackingViewController::getNewTransform() )
{
target_scene_node_->setPosition( reference_position_ );
target_scene_node_->setOrientation( reference_orientation_ );
context_->queueRender();
}
}
void ThirdPersonFollowerViewController::lookAt( const Ogre::Vector3& point )
{
Ogre::Vector3 camera_position = camera_->getPosition();
Ogre::Vector3 new_focal_point = target_scene_node_->getOrientation().Inverse() * (point - target_scene_node_->getPosition());
new_focal_point.z = 0;
distance_property_->setFloat( new_focal_point.distance( camera_position ));
focal_point_property_->setVector( new_focal_point );
calculatePitchYawFromPosition(camera_position);
}
} // end namespace rviz
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::ThirdPersonFollowerViewController, rviz::ViewController )
<commit_msg>changed third person follower such that it only uses the yaw of the reference frame<commit_after>/*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 <stdint.h>
#include <ros/ros.h>
#include <OgreCamera.h>
#include <OgrePlane.h>
#include <OgreQuaternion.h>
#include <OgreRay.h>
#include <OgreSceneNode.h>
#include <OgreVector3.h>
#include <OgreViewport.h>
#include <OgreMath.h>
#include "rviz/display_context.h"
#include "rviz/ogre_helpers/shape.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/vector_property.h"
#include "rviz/viewport_mouse_event.h"
#include "rviz/default_plugin/view_controllers/third_person_follower_view_controller.h"
namespace rviz
{
// move camera up so the focal point appears in the lower image half
static const float CAMERA_OFFSET = 0.2;
void ThirdPersonFollowerViewController::onInitialize()
{
OrbitViewController::onInitialize();
focal_shape_->setColor(0.0f, 1.0f, 1.0f, 0.5f);
}
bool ThirdPersonFollowerViewController::intersectGroundPlane( Ogre::Ray mouse_ray, Ogre::Vector3 &intersection_3d )
{
//convert rays into reference frame
mouse_ray.setOrigin( target_scene_node_->convertWorldToLocalPosition( mouse_ray.getOrigin() ) );
mouse_ray.setDirection( target_scene_node_->convertWorldToLocalOrientation( Ogre::Quaternion::IDENTITY ) * mouse_ray.getDirection() );
Ogre::Plane ground_plane( Ogre::Vector3::UNIT_Z, 0 );
std::pair<bool, Ogre::Real> intersection = mouse_ray.intersects(ground_plane);
if (!intersection.first)
{
return false;
}
intersection_3d = mouse_ray.getPoint(intersection.second);
return true;
}
void ThirdPersonFollowerViewController::handleMouseEvent(ViewportMouseEvent& event)
{
if ( event.shift() )
{
setStatus( "<b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Zoom." );
}
else
{
setStatus( "<b>Left-Click:</b> Rotate. <b>Middle-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z. <b>Shift</b>: More options." );
}
int32_t diff_x = 0;
int32_t diff_y = 0;
bool moved = false;
if( event.type == QEvent::MouseButtonPress )
{
focal_shape_->getRootNode()->setVisible(true);
moved = true;
}
else if( event.type == QEvent::MouseButtonRelease )
{
focal_shape_->getRootNode()->setVisible(false);
moved = true;
}
else if( event.type == QEvent::MouseMove )
{
diff_x = event.x - event.last_x;
diff_y = event.y - event.last_y;
moved = true;
}
if( event.left() && !event.shift() )
{
setCursor( Rotate3D );
yaw( diff_x*0.005 );
pitch( -diff_y*0.005 );
}
else if( event.middle() || (event.left() && event.shift()) )
{
setCursor( MoveXY );
// handle mouse movement
int width = event.viewport->getActualWidth();
int height = event.viewport->getActualHeight();
Ogre::Ray mouse_ray = event.viewport->getCamera()->getCameraToViewportRay( event.x / (float) width,
event.y / (float) height );
Ogre::Ray last_mouse_ray =
event.viewport->getCamera()->getCameraToViewportRay( event.last_x / (float) width,
event.last_y / (float) height );
Ogre::Vector3 last_intersect, intersect;
if( intersectGroundPlane( last_mouse_ray, last_intersect ) &&
intersectGroundPlane( mouse_ray, intersect ))
{
Ogre::Vector3 motion = last_intersect - intersect;
// When dragging near the horizon, the motion can get out of
// control. This throttles it to an arbitrary limit per mouse
// event.
float motion_distance_limit = 1; /*meter*/
if( motion.length() > motion_distance_limit )
{
motion.normalise();
motion *= motion_distance_limit;
}
focal_point_property_->add( motion );
emitConfigChanged();
}
}
else if( event.right() )
{
setCursor( Zoom );
zoom( -diff_y * 0.1 * (distance_property_->getFloat() / 10.0f) );
}
else
{
setCursor( event.shift() ? MoveXY : Rotate3D );
}
if( event.wheel_delta != 0 )
{
int diff = event.wheel_delta;
zoom( diff * 0.001 * distance_property_->getFloat() );
moved = true;
}
if( moved )
{
context_->queueRender();
}
}
void ThirdPersonFollowerViewController::mimic( ViewController* source_view )
{
FramePositionTrackingViewController::mimic( source_view );
Ogre::Camera* source_camera = source_view->getCamera();
// do some trigonometry
Ogre::Ray camera_dir_ray( source_camera->getRealPosition(), source_camera->getRealDirection() );
Ogre::Ray camera_down_ray( source_camera->getRealPosition(), -1.0 * source_camera->getRealUp() );
Ogre::Vector3 a,b;
if( intersectGroundPlane( camera_dir_ray, b ) &&
intersectGroundPlane( camera_down_ray, a ) )
{
float l_a = source_camera->getPosition().distance( b );
float l_b = source_camera->getPosition().distance( a );
distance_property_->setFloat(( l_a * l_b ) / ( CAMERA_OFFSET * l_a + l_b ));
float distance = distance_property_->getFloat();
camera_dir_ray.setOrigin( source_camera->getRealPosition() - source_camera->getRealUp() * distance * CAMERA_OFFSET );
Ogre::Vector3 new_focal_point;
intersectGroundPlane( camera_dir_ray, new_focal_point );
focal_point_property_->setVector( new_focal_point );
calculatePitchYawFromPosition( source_camera->getPosition() - source_camera->getUp() * distance * CAMERA_OFFSET );
}
}
void ThirdPersonFollowerViewController::updateCamera()
{
OrbitViewController::updateCamera();
camera_->setPosition( camera_->getPosition() + camera_->getUp() * distance_property_->getFloat() * CAMERA_OFFSET );
}
void ThirdPersonFollowerViewController::updateTargetSceneNode()
{
if ( FramePositionTrackingViewController::getNewTransform() )
{
target_scene_node_->setPosition( reference_position_ );
Ogre::Radian ref_yaw = reference_orientation_.getYaw();
Ogre::Quaternion ref_yaw_quat(Ogre::Math::Cos(ref_yaw/2), 0, 0, Ogre::Math::Sin(ref_yaw/2));
target_scene_node_->setOrientation( ref_yaw_quat );
context_->queueRender();
}
}
void ThirdPersonFollowerViewController::lookAt( const Ogre::Vector3& point )
{
Ogre::Vector3 camera_position = camera_->getPosition();
Ogre::Vector3 new_focal_point = target_scene_node_->getOrientation().Inverse() * (point - target_scene_node_->getPosition());
new_focal_point.z = 0;
distance_property_->setFloat( new_focal_point.distance( camera_position ));
focal_point_property_->setVector( new_focal_point );
calculatePitchYawFromPosition(camera_position);
}
} // end namespace rviz
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::ThirdPersonFollowerViewController, rviz::ViewController )
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Orbit 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 <gtest/gtest.h>
#include <cstring>
#include "PickingManager.h"
class PickableMock : public Pickable {
public:
void OnPick(int, int) override { picked_ = true; }
void OnDrag(int, int) override { dragging_ = true; }
void OnRelease() override {
dragging_ = false;
picked_ = false;
}
void Draw(GlCanvas*, PickingMode) override {}
bool Draggable() override { return true; }
bool picked_ = false;
bool dragging_ = false;
void Reset() {
picked_ = false;
dragging_ = false;
}
};
class UndraggableMock : public PickableMock {
bool Draggable() override { return false; }
};
TEST(PickingManager, PickableMock) {
PickableMock pickable = PickableMock();
ASSERT_FALSE(pickable.dragging_);
ASSERT_FALSE(pickable.picked_);
pickable.OnPick(0, 0);
ASSERT_TRUE(pickable.picked_);
pickable.OnDrag(0, 0);
ASSERT_TRUE(pickable.dragging_);
pickable.OnRelease();
ASSERT_FALSE(pickable.dragging_);
pickable.Reset();
ASSERT_FALSE(pickable.picked_);
}
// Simulate "rendering" the picking color into a uint32_t target
PickingID MockRenderPickingColor(const Color& col_vec) {
uint32_t col;
std::memcpy(&col, &col_vec[0], sizeof(uint32_t));
PickingID picking_id = PickingID::Get(col);
return picking_id;
}
TEST(PickingManager, BasicFunctionality) {
auto pickable1 = std::make_shared<PickableMock>();
auto pickable2 = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec1 = pm.GetPickableColor(pickable1, PickingID::BatcherId::kUi);
Color col_vec2 = pm.GetPickableColor(pickable2, PickingID::BatcherId::kUi);
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec1).id_).lock(),
pickable1);
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec2).id_).lock(),
pickable2);
ASSERT_TRUE(pm.GetPickableFromId(0xdeadbeef).expired());
pm.Reset();
ASSERT_TRUE(
pm.GetPickableFromId(MockRenderPickingColor(col_vec1).id_).expired());
ASSERT_TRUE(
pm.GetPickableFromId(MockRenderPickingColor(col_vec2).id_).expired());
}
TEST(PickingManager, Callbacks) {
auto pickable = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pickable->picked_);
ASSERT_FALSE(pm.IsThisElementPicked(pickable.get()));
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pickable->picked_);
ASSERT_TRUE(pm.IsThisElementPicked(pickable.get()));
pm.Release();
ASSERT_FALSE(pickable->picked_);
ASSERT_FALSE(pm.IsThisElementPicked(pickable.get()));
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
pm.Drag(10, 10);
ASSERT_TRUE(pm.IsDragging());
ASSERT_TRUE(pickable->dragging_);
pm.Release();
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
}
TEST(PickingManager, Undraggable) {
auto pickable = std::make_shared<UndraggableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
pm.Drag(10, 10);
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
}
TEST(PickingManager, RobustnessOnReset) {
std::shared_ptr<PickableMock> pickable = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pickable->picked_);
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pickable->picked_);
pm.Drag(10, 10);
ASSERT_TRUE(pickable->dragging_);
pickable.reset();
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec).id_).lock(),
std::shared_ptr<PickableMock>());
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pm.GetPicked().expired());
pickable = std::make_shared<PickableMock>();
col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
id = MockRenderPickingColor(col_vec);
pickable.reset(new PickableMock());
}
<commit_msg>Formatting fixes of PickingManagerTest<commit_after>// Copyright (c) 2020 The Orbit 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 <gtest/gtest.h>
#include <cstring>
#include "PickingManager.h"
class PickableMock : public Pickable {
public:
void OnPick(int, int) override { picked_ = true; }
void OnDrag(int, int) override { dragging_ = true; }
void OnRelease() override {
dragging_ = false;
picked_ = false;
}
void Draw(GlCanvas*, PickingMode) override {}
bool Draggable() override { return true; }
bool picked_ = false;
bool dragging_ = false;
void Reset() {
picked_ = false;
dragging_ = false;
}
};
class UndraggableMock : public PickableMock {
bool Draggable() override { return false; }
};
TEST(PickingManager, PickableMock) {
PickableMock pickable = PickableMock();
ASSERT_FALSE(pickable.dragging_);
ASSERT_FALSE(pickable.picked_);
pickable.OnPick(0, 0);
ASSERT_TRUE(pickable.picked_);
pickable.OnDrag(0, 0);
ASSERT_TRUE(pickable.dragging_);
pickable.OnRelease();
ASSERT_FALSE(pickable.dragging_);
pickable.Reset();
ASSERT_FALSE(pickable.picked_);
}
// Simulate "rendering" the picking color into a uint32_t target
PickingID MockRenderPickingColor(const Color& col_vec) {
uint32_t col;
std::memcpy(&col, &col_vec[0], sizeof(uint32_t));
PickingID picking_id = PickingID::Get(col);
return picking_id;
}
TEST(PickingManager, BasicFunctionality) {
auto pickable1 = std::make_shared<PickableMock>();
auto pickable2 = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec1 = pm.GetPickableColor(pickable1, PickingID::BatcherId::kUi);
Color col_vec2 = pm.GetPickableColor(pickable2, PickingID::BatcherId::kUi);
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec1).id_).lock(),
pickable1);
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec2).id_).lock(),
pickable2);
ASSERT_TRUE(pm.GetPickableFromId(0xdeadbeef).expired());
pm.Reset();
ASSERT_TRUE(
pm.GetPickableFromId(MockRenderPickingColor(col_vec1).id_).expired());
ASSERT_TRUE(
pm.GetPickableFromId(MockRenderPickingColor(col_vec2).id_).expired());
}
TEST(PickingManager, Callbacks) {
auto pickable = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pickable->picked_);
ASSERT_FALSE(pm.IsThisElementPicked(pickable.get()));
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pickable->picked_);
ASSERT_TRUE(pm.IsThisElementPicked(pickable.get()));
pm.Release();
ASSERT_FALSE(pickable->picked_);
ASSERT_FALSE(pm.IsThisElementPicked(pickable.get()));
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
pm.Drag(10, 10);
ASSERT_TRUE(pm.IsDragging());
ASSERT_TRUE(pickable->dragging_);
pm.Release();
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
}
TEST(PickingManager, Undraggable) {
auto pickable = std::make_shared<UndraggableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
pm.Drag(10, 10);
ASSERT_FALSE(pm.IsDragging());
ASSERT_FALSE(pickable->dragging_);
}
TEST(PickingManager, RobustnessOnReset) {
std::shared_ptr<PickableMock> pickable = std::make_shared<PickableMock>();
PickingManager pm;
Color col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
PickingID id = MockRenderPickingColor(col_vec);
ASSERT_FALSE(pickable->picked_);
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pickable->picked_);
pm.Drag(10, 10);
ASSERT_TRUE(pickable->dragging_);
pickable.reset();
ASSERT_EQ(pm.GetPickableFromId(MockRenderPickingColor(col_vec).id_).lock(),
std::shared_ptr<PickableMock>());
ASSERT_FALSE(pm.IsDragging());
pm.Pick(id.id_, 0, 0);
ASSERT_TRUE(pm.GetPicked().expired());
pickable = std::make_shared<PickableMock>();
col_vec = pm.GetPickableColor(pickable, PickingID::BatcherId::kUi);
id = MockRenderPickingColor(col_vec);
pickable.reset(new PickableMock());
}
<|endoftext|> |
<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** Connection.h
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CSocket::CSocket(bool gameSocket)
: WISP_NETWORK::CConnection(), m_GameSocket(gameSocket)
{
}
//----------------------------------------------------------------------------------
CSocket::~CSocket()
{
}
//----------------------------------------------------------------------------------
bool CSocket::Connect(const string &address, const int &port)
{
WISPFUN_DEBUG("c158_f1");
LOG("Connecting...%s:%i\n", address.c_str(), port);
if (m_UseProxy)
{
if (m_Connected)
return false;
LOG("using proxy %s:%d\n", m_ProxyAddress.c_str(), m_ProxyPort);
if (!CConnection::Connect(m_ProxyAddress, m_ProxyPort))
{
LOG("Can't connect to proxy\n");
return WISP_NETWORK::CConnection::Connect(address, port);
}
ushort serverPort = htons(port);
uint serverIP = inet_addr(address.c_str());
if (serverIP == 0xFFFFFFFF)
{
struct hostent *uohe = gethostbyname(address.c_str());
if (uohe != NULL)
{
sockaddr_in caddr;
memcpy(&caddr.sin_addr, uohe->h_addr, uohe->h_length);
serverIP = caddr.sin_addr.S_un.S_addr;
}
}
if (serverIP == 0xFFFFFFFF)
{
LOG("Unknowm server address\n");
return WISP_NETWORK::CConnection::Connect(address, port);
}
if (!m_ProxySocks5)
{
LOG("proxy connection open\n");
char str[9] = { 0 };
str[0] = 4;
str[1] = 1;
memcpy(&str[2], &serverPort, 2);
memcpy(&str[4], &serverIP, 4);
::send(m_Socket, str, 9, 0);
int recvSize = ::recv(m_Socket, str, 8, 0);
if (recvSize != 8)
{
LOG("proxy error != 8\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return WISP_NETWORK::CConnection::Connect(address, port);
}
}
else
{
LOG("proxy connection open (auth)\n");
char str[255] = { 0 };
str[0] = 5;
str[1] = 2;
str[2] = 0;
str[3] = 2;
::send(m_Socket, str, 4, 0);
int num = ::recv(m_Socket, str, 255, 0);
if ((str[0] != 5) || (num != 2))
{
LOG("proxy error != 2\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return WISP_NETWORK::CConnection::Connect(address, port);
}
else
{
if (str[1])
{
if (str[1] == 2)
{
int totalSize = 3 + (int)m_ProxyAccount.length() + (int)m_ProxyPassword.length();
vector<char> buffer(totalSize, 0);
sprintf(&buffer[0], " %s %s", m_ProxyAccount.c_str(), m_ProxyPassword.c_str());
buffer[0] = 1;
buffer[1] = (char)m_ProxyAccount.length();
buffer[2 + (int)m_ProxyAccount.length()] = (char)m_ProxyPassword.length();
::send(m_Socket, &buffer[0], totalSize, 0);
::recv(m_Socket, str, 255, 0);
if (str[1] != 0)
{
LOG("proxy error != 2 (2)\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return WISP_NETWORK::CConnection::Connect(address, port);
}
}
}
memset(str, 0, 10);
str[0] = 5;
str[1] = 1;
str[2] = 0;
str[3] = 1;
memcpy(&str[4], &serverIP, 4);
memcpy(&str[8], &serverPort, 2);
::send(m_Socket, str, 10, 0);
num = ::recv(m_Socket, str, 255, 0);
if (str[1] != 0)
{
switch (str[1])
{
case 1:
LOG("general SOCKS server failure\n");
break;
case 2:
LOG("connection not allowed by ruleset\n");
break;
case 3:
LOG("Network unreachable\n");
break;
case 4:
LOG("Host unreachable\n");
break;
case 5:
LOG("Connection refused\n");
break;
case 6:
LOG("TTL expired\n");
break;
case 7:
LOG("Command not supported\n");
break;
case 8:
LOG("Address type not supported\n");
break;
case 9:
LOG("to X'FF' unassigned\n");
break;
default:
LOG("proxy error != 10 <%d>\n", num);
}
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return WISP_NETWORK::CConnection::Connect(address, port);
}
LOG("Connected to server via proxy\n");
m_Connected = true;
WSASetLastError(0);
m_MessageParser->Clear();
}
}
}
else
return WISP_NETWORK::CConnection::Connect(address, port);
return true;
}
//----------------------------------------------------------------------------------
UCHAR_LIST CSocket::Decompression(UCHAR_LIST data)
{
WISPFUN_DEBUG("c158_f2");
if (m_GameSocket)
{
intptr_t inSize = (intptr_t)data.size();
if (g_NetworkPostAction != NULL)
g_NetworkPostAction(&data[0], &data[0], (int)inSize);
UCHAR_LIST decBuf(inSize * 4 + 2);
int outSize = 65536;
m_Decompressor((char*)&decBuf[0], (char*)&data[0], outSize, inSize);
if (inSize != data.size())
{
DebugMsg("decompression buffer too small\n");
Disconnect();
}
else
decBuf.resize(outSize);
return decBuf;
}
return data;
}
//----------------------------------------------------------------------------------
<commit_msg>Added some LOGs For Proxy Connections<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** Connection.h
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CSocket::CSocket(bool gameSocket)
: WISP_NETWORK::CConnection(), m_GameSocket(gameSocket)
{
}
//----------------------------------------------------------------------------------
CSocket::~CSocket()
{
}
//----------------------------------------------------------------------------------
bool CSocket::Connect(const string &address, const int &port)
{
WISPFUN_DEBUG("c158_f1");
LOG("Connecting...%s:%i\n", address.c_str(), port);
if (m_UseProxy)
{
if (m_Connected)
return false;
LOG("Connecting using proxy %s:%d\n", m_ProxyAddress.c_str(), m_ProxyPort);
if (!CConnection::Connect(m_ProxyAddress, m_ProxyPort))
{
LOG("Can't connect to proxy\n");
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
ushort serverPort = htons(port);
uint serverIP = inet_addr(address.c_str());
if (serverIP == 0xFFFFFFFF)
{
struct hostent *uohe = gethostbyname(address.c_str());
if (uohe != NULL)
{
sockaddr_in caddr;
memcpy(&caddr.sin_addr, uohe->h_addr, uohe->h_length);
serverIP = caddr.sin_addr.S_un.S_addr;
}
}
if (serverIP == 0xFFFFFFFF)
{
LOG("Unknowm server address\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
if (m_ProxySocks5)
{
LOG("Proxy Server Version 5 Selected\n");
char str[255] = { 0 };
str[0] = 5; //Proxy Version
str[1] = 2; //Number of authentication method
str[2] = 0; //No auth required
str[3] = 2; //Username/Password auth
::send(m_Socket, str, 4, 0);
int num = ::recv(m_Socket, str, 255, 0);
if ((str[0] != 5) || (num != 2))
{
LOG("Proxy Server Version Missmatch\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
else
{
if ((str[1] == 0) || (str[1] == 2))
{
if (str[1] == 2)
{
LOG("Proxy wants Username/Password\n");
int totalSize = 3 + (int)m_ProxyAccount.length() + (int)m_ProxyPassword.length();
vector<char> buffer(totalSize, 0);
sprintf(&buffer[0], " %s %s", m_ProxyAccount.c_str(), m_ProxyPassword.c_str());
buffer[0] = 1;
buffer[1] = (char)m_ProxyAccount.length();
buffer[2 + (int)m_ProxyAccount.length()] = (char)m_ProxyPassword.length();
::send(m_Socket, &buffer[0], totalSize, 0);
::recv(m_Socket, str, 255, 0);
if (str[1] != 0)
{
LOG("Wrong Username/Password\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
}
memset(str, 0, 10);
str[0] = 5;
str[1] = 1;
str[2] = 0;
str[3] = 1;
memcpy(&str[4], &serverIP, 4);
memcpy(&str[8], &serverPort, 2);
::send(m_Socket, str, 10, 0);
num = ::recv(m_Socket, str, 255, 0);
if (str[1] != 0)
{
switch (str[1])
{
case 1:
LOG("general SOCKS server failure\n");
break;
case 2:
LOG("connection not allowed by ruleset\n");
break;
case 3:
LOG("Network unreachable\n");
break;
case 4:
LOG("Host unreachable\n");
break;
case 5:
LOG("Connection refused\n");
break;
case 6:
LOG("TTL expired\n");
break;
case 7:
LOG("Command not supported\n");
break;
case 8:
LOG("Address type not supported\n");
break;
case 9:
LOG("to X'FF' unassigned\n");
break;
default:
LOG("Unknown Error <%d> recieved\n", str[1]);
}
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
LOG("Connected to server via proxy\n");
}
else
{
LOG("No acceptable methods\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
}
}
else
{
LOG("Proxy Server Version 4 Selected\n");
char str[9] = { 0 };
str[0] = 4;
str[1] = 1;
memcpy(&str[2], &serverPort, 2);
memcpy(&str[4], &serverIP, 4);
::send(m_Socket, str, 9, 0);
int recvSize = ::recv(m_Socket, str, 8, 0);
if ((recvSize != 8) || (str[0] != 0) || (str[1] != 90))
{
if (str[0] == 5)
{
LOG("Proxy Server Version is 5\n");
LOG("Trying SOCKS5\n");
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
m_ProxySocks5 = true;
return Connect(address, port);
}
switch (str[1])
{
case 1:
case 91:
LOG("Proxy request rejected or failed\n");
break;
case 2:
case 92:
LOG("Proxy rejected becasue SOCKS server cannot connect to identd on the client\n");
break;
case 3:
case 93:
LOG("Proxy rejected becasue SOCKS server cannot connect to identd on the client\n");
break;
default:
LOG("Unknown Error <%d> recieved\n", str[1]);
break;
}
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
m_Connected = false;
LOG("Connecting...%s:%i\n", address.c_str(), port);
return WISP_NETWORK::CConnection::Connect(address, port);
}
LOG("Connected to server via proxy\n");
}
}
else
return WISP_NETWORK::CConnection::Connect(address, port);
return true;
}
//----------------------------------------------------------------------------------
UCHAR_LIST CSocket::Decompression(UCHAR_LIST data)
{
WISPFUN_DEBUG("c158_f2");
if (m_GameSocket)
{
intptr_t inSize = (intptr_t)data.size();
if (g_NetworkPostAction != NULL)
g_NetworkPostAction(&data[0], &data[0], (int)inSize);
UCHAR_LIST decBuf(inSize * 4 + 2);
int outSize = 65536;
m_Decompressor((char*)&decBuf[0], (char*)&data[0], outSize, inSize);
if (inSize != data.size())
{
DebugMsg("decompression buffer too small\n");
Disconnect();
}
else
decBuf.resize(outSize);
return decBuf;
}
return data;
}
//----------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>//===--- SILCombine -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = &*BBI;
++BBI;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, BBI,
false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(&*F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder.setInsertionPoint(I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
assert(&*std::prev(SILBasicBlock::iterator(I)) == Result &&
"Expected new instruction inserted before existing instruction!");
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
auto &TrackingList = *Builder.getTrackingList();
for (SILInstruction *I : TrackingList) {
DEBUG(llvm::dbgs() << "SC: add " << *I <<
" from tracking list to worklist\n");
Worklist.add(I);
}
TrackingList.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.resize(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replaceable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we cannot rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
SILBasicBlock::iterator &InstIter,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(onlyHaveDebugUses(&I) && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist) {
for (auto &OpI : I.getAllOperands()) {
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get())) {
DEBUG(llvm::dbgs() << "SC: add op " << *Op <<
" from erased inst to worklist\n");
Worklist.add(Op);
}
}
}
for (Operand *DU : getDebugUses(&I))
Worklist.remove(DU->getUser());
Worklist.remove(&I);
eraseFromParentWithDebugInsts(&I, InstIter);
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
llvm::SmallVector<SILInstruction *, 64> TrackingList;
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Create a SILBuilder with a tracking list for newly added
// instructions, which we will periodically move to our worklist.
SILBuilder B(*getFunction(), &TrackingList);
SILCombiner Combiner(B, AA, getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
assert(TrackingList.empty() &&
"TrackingList should be fully processed by SILCombiner");
if (Changed) {
// Invalidate everything.
invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
}
}
virtual void handleDeleteNotification(ValueBase *I) override {
// Linear searching the tracking list doesn't hurt because usually it only
// contains a few elements.
auto Iter = std::find(TrackingList.begin(), TrackingList.end(), I);
if (Iter != TrackingList.end())
TrackingList.erase(Iter);
}
virtual bool needsNotifications() override { return true; }
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<commit_msg>[upstream-update] API rename llvm::DenseMap::reserve => llvm::DenseMap::resize.<commit_after>//===--- SILCombine -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = &*BBI;
++BBI;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, BBI,
false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(&*F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder.setInsertionPoint(I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
assert(&*std::prev(SILBasicBlock::iterator(I)) == Result &&
"Expected new instruction inserted before existing instruction!");
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
auto &TrackingList = *Builder.getTrackingList();
for (SILInstruction *I : TrackingList) {
DEBUG(llvm::dbgs() << "SC: add " << *I <<
" from tracking list to worklist\n");
Worklist.add(I);
}
TrackingList.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.reserve(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replaceable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we cannot rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
SILBasicBlock::iterator &InstIter,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(onlyHaveDebugUses(&I) && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist) {
for (auto &OpI : I.getAllOperands()) {
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get())) {
DEBUG(llvm::dbgs() << "SC: add op " << *Op <<
" from erased inst to worklist\n");
Worklist.add(Op);
}
}
}
for (Operand *DU : getDebugUses(&I))
Worklist.remove(DU->getUser());
Worklist.remove(&I);
eraseFromParentWithDebugInsts(&I, InstIter);
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
llvm::SmallVector<SILInstruction *, 64> TrackingList;
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Create a SILBuilder with a tracking list for newly added
// instructions, which we will periodically move to our worklist.
SILBuilder B(*getFunction(), &TrackingList);
SILCombiner Combiner(B, AA, getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
assert(TrackingList.empty() &&
"TrackingList should be fully processed by SILCombiner");
if (Changed) {
// Invalidate everything.
invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
}
}
virtual void handleDeleteNotification(ValueBase *I) override {
// Linear searching the tracking list doesn't hurt because usually it only
// contains a few elements.
auto Iter = std::find(TrackingList.begin(), TrackingList.end(), I);
if (Iter != TrackingList.end())
TrackingList.erase(Iter);
}
virtual bool needsNotifications() override { return true; }
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: miscopt.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 19:28:24 $
*
* 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 INCLUDED_SVTOOLS_MISCOPT_HXX
#define INCLUDED_SVTOOLS_MISCOPT_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtMiscOptions_Impl;
class Link;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about misc group
@descr -
@implements -
@base -
@ATTENTION This class is partially threadsafe.
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVL_DLLPUBLIC SvtMiscOptions: public svt::detail::Options
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtMiscOptions();
virtual ~SvtMiscOptions();
void AddListener( const Link& rLink );
void RemoveListener( const Link& rLink );
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
sal_Bool UseSystemFileDialog() const;
void SetUseSystemFileDialog( sal_Bool bSet );
sal_Bool IsUseSystemFileDialogReadOnly() const;
sal_Bool IsPluginsEnabled() const;
void SetPluginsEnabled( sal_Bool bEnable );
sal_Bool IsPluginsEnabledReadOnly() const;
sal_Int16 GetSymbolsSize() const;
void SetSymbolsSize( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsSize() const;
bool AreCurrentSymbolsLarge() const;
sal_Bool IsGetSymbolsSizeReadOnly() const;
sal_Int16 GetSymbolsStyle() const;
void SetSymbolsStyle( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsStyle() const;
::rtl::OUString GetCurrentSymbolsStyleName() const;
sal_Bool IsGetSymbolsStyleReadOnly() const;
sal_Int16 GetToolboxStyle() const;
void SetToolboxStyle( sal_Int16 nStyle );
sal_Bool IsGetToolboxStyleReadOnly() const;
sal_Bool IsModifyByPrinting() const;
void SetModifyByPrinting(sal_Bool bSet );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class is partially threadsafe (for de-/initialization only).
All access methods are'nt safe!
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVL_DLLPRIVATE static ::osl::Mutex& GetInitMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtMiscOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtMiscOptions
#endif // #ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
<commit_msg>INTEGRATION: CWS jl67 (1.2.100); FILE MERGED 2007/07/05 15:22:23 jl 1.2.100.2: #i77886# remove dependency on vcl in svl 2007/07/05 12:43:24 jl 1.2.100.1: #i77886# remove dependency on vcl in svl<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: miscopt.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-07-26 08:41:43 $
*
* 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 INCLUDED_SVTOOLS_MISCOPT_HXX
#define INCLUDED_SVTOOLS_MISCOPT_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtMiscOptions_Impl;
class Link;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about misc group
@descr -
@implements -
@base -
@ATTENTION This class is partially threadsafe.
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVT_DLLPUBLIC SvtMiscOptions: public svt::detail::Options
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtMiscOptions();
virtual ~SvtMiscOptions();
void AddListener( const Link& rLink );
void RemoveListener( const Link& rLink );
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
sal_Bool UseSystemFileDialog() const;
void SetUseSystemFileDialog( sal_Bool bSet );
sal_Bool IsUseSystemFileDialogReadOnly() const;
sal_Bool IsPluginsEnabled() const;
void SetPluginsEnabled( sal_Bool bEnable );
sal_Bool IsPluginsEnabledReadOnly() const;
sal_Int16 GetSymbolsSize() const;
void SetSymbolsSize( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsSize() const;
bool AreCurrentSymbolsLarge() const;
sal_Bool IsGetSymbolsSizeReadOnly() const;
sal_Int16 GetSymbolsStyle() const;
void SetSymbolsStyle( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsStyle() const;
::rtl::OUString GetCurrentSymbolsStyleName() const;
sal_Bool IsGetSymbolsStyleReadOnly() const;
sal_Int16 GetToolboxStyle() const;
void SetToolboxStyle( sal_Int16 nStyle );
sal_Bool IsGetToolboxStyleReadOnly() const;
sal_Bool IsModifyByPrinting() const;
void SetModifyByPrinting(sal_Bool bSet );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class is partially threadsafe (for de-/initialization only).
All access methods are'nt safe!
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVT_DLLPRIVATE static ::osl::Mutex& GetInitMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtMiscOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtMiscOptions
#endif // #ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: eertfpar.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mt $ $Date: 2002-11-06 12:25:15 $
*
* 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 _EERTFPAR_HXX
#define _EERTFPAR_HXX
#include <svxrtf.hxx>
#include <editdoc.hxx>
#include <impedit.hxx>
#ifndef SVX_LIGHT
class EditNodeIdx : public SvxNodeIdx
{
private:
ContentNode* pNode;
ImpEditEngine* pImpEditEngine;
public:
EditNodeIdx( ImpEditEngine* pIEE, ContentNode* pNd = 0)
{ pImpEditEngine = pIEE; pNode = pNd; }
virtual ULONG GetIdx() const;
virtual SvxNodeIdx* Clone() const;
ContentNode* GetNode() { return pNode; }
};
class EditPosition : public SvxPosition
{
private:
EditSelection* pCurSel;
ImpEditEngine* pImpEditEngine;
public:
EditPosition( ImpEditEngine* pIEE, EditSelection* pSel )
{ pImpEditEngine = pIEE; pCurSel = pSel; }
virtual ULONG GetNodeIdx() const;
virtual USHORT GetCntIdx() const;
// erzeuge von sich selbst eine Kopie
virtual SvxPosition* Clone() const;
// erzeuge vom NodeIndex eine Kopie
virtual SvxNodeIdx* MakeNodeIdx() const;
};
#define ACTION_INSERTTEXT 1
#define ACTION_INSERTPARABRK 2
class EditRTFParser : public SvxRTFParser
{
private:
EditSelection aCurSel;
ImpEditEngine* pImpEditEngine;
CharSet eDestCharSet;
MapMode aRTFMapMode;
MapMode aEditMapMode;
USHORT nDefFont;
USHORT nDefTab;
USHORT nDefFontHeight;
BYTE nLastAction;
protected:
virtual void InsertPara();
virtual void InsertText();
virtual void MovePos( int bForward = TRUE );
virtual void SetEndPrevPara( SvxNodeIdx*& rpNodePos,
USHORT& rCntPos );
virtual void UnknownAttrToken( int nToken, SfxItemSet* pSet );
virtual void NextToken( int nToken );
virtual void SetAttrInDoc( SvxRTFItemStackType &rSet );
inline long TwipsToLogic( long n );
virtual int IsEndPara( SvxNodeIdx* pNd, USHORT nCnt ) const;
virtual void CalcValue();
void CreateStyleSheets();
SfxStyleSheet* CreateStyleSheet( SvxRTFStyleType* pRTFStyle );
SvxRTFStyleType* FindStyleSheet( const String& rName );
void AddRTFDefaultValues( const EditPaM& rStart, const EditPaM& rEnd );
void ReadField();
void SkipGroup();
public:
EditRTFParser( SvStream& rIn, EditSelection aCurSel, SfxItemPool& rAttrPool, ImpEditEngine* pImpEditEngine );
~EditRTFParser();
virtual SvParserState CallParser();
void SetDestCharSet( CharSet eCharSet ) { eDestCharSet = eCharSet; }
CharSet GetDestCharSet() const { return eDestCharSet; }
USHORT GetDefTab() const { return nDefTab; }
Font GetDefFont() { return GetFont( nDefFont ); }
EditPaM GetCurPaM() const { return aCurSel.Max(); }
};
SV_DECL_REF( EditRTFParser );
SV_IMPL_REF( EditRTFParser );
inline long EditRTFParser::TwipsToLogic( long nTwps )
{
Size aSz( nTwps, 0 );
aSz = pImpEditEngine->GetRefDevice()->LogicToLogic( aSz, &aRTFMapMode, &aEditMapMode );
return aSz.Width();
}
#endif // !SVX_LIGH
#endif //_EERTFPAR_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1624); FILE MERGED 2005/09/05 14:23:57 rt 1.2.1624.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: eertfpar.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:32: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
*
************************************************************************/
#ifndef _EERTFPAR_HXX
#define _EERTFPAR_HXX
#include <svxrtf.hxx>
#include <editdoc.hxx>
#include <impedit.hxx>
#ifndef SVX_LIGHT
class EditNodeIdx : public SvxNodeIdx
{
private:
ContentNode* pNode;
ImpEditEngine* pImpEditEngine;
public:
EditNodeIdx( ImpEditEngine* pIEE, ContentNode* pNd = 0)
{ pImpEditEngine = pIEE; pNode = pNd; }
virtual ULONG GetIdx() const;
virtual SvxNodeIdx* Clone() const;
ContentNode* GetNode() { return pNode; }
};
class EditPosition : public SvxPosition
{
private:
EditSelection* pCurSel;
ImpEditEngine* pImpEditEngine;
public:
EditPosition( ImpEditEngine* pIEE, EditSelection* pSel )
{ pImpEditEngine = pIEE; pCurSel = pSel; }
virtual ULONG GetNodeIdx() const;
virtual USHORT GetCntIdx() const;
// erzeuge von sich selbst eine Kopie
virtual SvxPosition* Clone() const;
// erzeuge vom NodeIndex eine Kopie
virtual SvxNodeIdx* MakeNodeIdx() const;
};
#define ACTION_INSERTTEXT 1
#define ACTION_INSERTPARABRK 2
class EditRTFParser : public SvxRTFParser
{
private:
EditSelection aCurSel;
ImpEditEngine* pImpEditEngine;
CharSet eDestCharSet;
MapMode aRTFMapMode;
MapMode aEditMapMode;
USHORT nDefFont;
USHORT nDefTab;
USHORT nDefFontHeight;
BYTE nLastAction;
protected:
virtual void InsertPara();
virtual void InsertText();
virtual void MovePos( int bForward = TRUE );
virtual void SetEndPrevPara( SvxNodeIdx*& rpNodePos,
USHORT& rCntPos );
virtual void UnknownAttrToken( int nToken, SfxItemSet* pSet );
virtual void NextToken( int nToken );
virtual void SetAttrInDoc( SvxRTFItemStackType &rSet );
inline long TwipsToLogic( long n );
virtual int IsEndPara( SvxNodeIdx* pNd, USHORT nCnt ) const;
virtual void CalcValue();
void CreateStyleSheets();
SfxStyleSheet* CreateStyleSheet( SvxRTFStyleType* pRTFStyle );
SvxRTFStyleType* FindStyleSheet( const String& rName );
void AddRTFDefaultValues( const EditPaM& rStart, const EditPaM& rEnd );
void ReadField();
void SkipGroup();
public:
EditRTFParser( SvStream& rIn, EditSelection aCurSel, SfxItemPool& rAttrPool, ImpEditEngine* pImpEditEngine );
~EditRTFParser();
virtual SvParserState CallParser();
void SetDestCharSet( CharSet eCharSet ) { eDestCharSet = eCharSet; }
CharSet GetDestCharSet() const { return eDestCharSet; }
USHORT GetDefTab() const { return nDefTab; }
Font GetDefFont() { return GetFont( nDefFont ); }
EditPaM GetCurPaM() const { return aCurSel.Max(); }
};
SV_DECL_REF( EditRTFParser );
SV_IMPL_REF( EditRTFParser );
inline long EditRTFParser::TwipsToLogic( long nTwps )
{
Size aSz( nTwps, 0 );
aSz = pImpEditEngine->GetRefDevice()->LogicToLogic( aSz, &aRTFMapMode, &aEditMapMode );
return aSz.Width();
}
#endif // !SVX_LIGH
#endif //_EERTFPAR_HXX
<|endoftext|> |
<commit_before>//
// steps.cpp
// yamcmc++
//
// Created by Brandon Kelly on 3/2/13.
// Copyright (c) 2013 Brandon Kelly. All rights reserved.
//
#include <boost/timer.hpp>
// Local includes
#include "include/steps.hpp"
// Global random number generator object, instantiated in random.cpp
extern boost::random::mt19937 rng;
// Object containing some common random number generators.
RandomGenerator RandGen;
/* ****** Methods of AdaptiveMetro class ********* */
// Constructor, requires a parameter object, a proposal object, an initial
// covariance matrix for the multivariate proposals, a target acceptance rate,
// and the maximum number of iterations to perform the adaptations for.
AdaptiveMetro::AdaptiveMetro(Parameter<arma::vec>& parameter, Proposal<double>& proposal,
arma::mat proposal_covar, double target_rate, int maxiter) :
parameter_(parameter), proposal_(proposal),
target_rate_(target_rate), maxiter_(maxiter)
{
gamma_ = 2.0 / 3.0;
niter_ = 0;
naccept_ = 0;
chol_factor_ = arma::chol(proposal_covar);
}
// Method to calculate whether the proposal is accepted
bool AdaptiveMetro::Accept(arma::vec new_value, arma::vec old_value) {
// MH accept/reject criteria: Proposal must be symmetric!!
alpha_ = (parameter_.LogDensity(new_value) - parameter_.LogDensity(old_value)) / parameter_.GetTemperature();
if (!arma::is_finite(alpha_)) {
// New value of the log-posterior is not finite, so reject this
// proposal
alpha_ = 0.0;
return false;
}
double unif = uniform_(rng);
alpha_ = std::min(exp(alpha_), 1.0);
if (unif < alpha_) {
naccept_++;
return true;
} else {
return false;
}
}
// Method to perform the RAM step. This involves a standard Metropolis-Hastings update, followed
// by an update to the proposal scale matrix so long as niter < maxiter
void AdaptiveMetro::DoStep()
{
arma::vec old_value = parameter_.Value();
// Draw a new parameter vector
arma::vec unit_proposal(old_value.n_rows);
for (int i=0; i<old_value.n_rows; i++) {
// Unscaled proposal
unit_proposal(i) = proposal_.Draw(0.0);
}
// Scaled proposal vector
arma::vec scaled_proposal = chol_factor_.t() * unit_proposal;
arma::vec new_value = old_value + scaled_proposal;
// MH accept/reject criteria
if (Accept(new_value, old_value)) {
parameter_.Save(new_value);
}
double step_size, unit_norm;
if ((niter_ < maxiter_) && arma::is_finite(alpha_)) {
// Still in the adaptive stage, so update the scale matrix cholesky factor
// The step size sequence for the scale matrix update. This is eta_n in the
// notation of Vihola (2012)
step_size = std::min(1.0, new_value.n_rows / pow(niter_, gamma_));
unit_norm = arma::norm(unit_proposal, 2);
// Rescale the proposal vector for updating the scale matrix cholesky factor
scaled_proposal = sqrt(step_size * fabs(alpha_ - target_rate_)) / unit_norm * scaled_proposal;
// Update or downdate the Cholesky factor?
bool downdate = (alpha_ < target_rate_);
// Perform the rank-1 update (downdate) of the scale matrix Cholesky factor
CholUpdateR1(chol_factor_, scaled_proposal, downdate);
}
niter_++;
if (niter_ == maxiter_) {
double arate = ((double)(naccept_)) / ((double)(niter_));
std::cout << "Average RAM Acceptance Rate is " << arate << std::endl;
}
}
// Function to perform the rank-1 Cholesky update, needed for updating the
// proposal covariance matrix
void CholUpdateR1(arma::mat& L, arma::vec& v, bool downdate)
{
double sign = 1.0;
if (downdate) {
// Perform the downdate instead
sign = -1.0;
}
for (int k=0; k<L.n_rows; k++) {
double r = sqrt( L(k,k) * L(k,k) + sign * v(k) * v(k) );
double c = r / L(k,k);
double s = v(k) / L(k,k);
L(k,k) = r;
if (k < L.n_rows-1) {
L(k,arma::span(k+1,L.n_rows-1)) = (L(k,arma::span(k+1,L.n_rows-1)) +
sign * s * v(arma::span(k+1,v.n_elem-1)).t()) / c;
v(arma::span(k+1,v.n_elem-1)) = c * v(arma::span(k+1,v.n_elem-1)) -
s * L(k,arma::span(k+1,L.n_rows-1)).t();
}
}
}
<commit_msg>Minor change<commit_after>//
// steps.cpp
// yamcmc++
//
// Created by Brandon Kelly on 3/2/13.
// Copyright (c) 2013 Brandon Kelly. All rights reserved.
//
#include <boost/timer.hpp>
// Local includes
#include "include/steps.hpp"
// Global random number generator object, instantiated in random.cpp
extern boost::random::mt19937 rng;
// Object containing some common random number generators.
RandomGenerator RandGen;
/* ****** Methods of AdaptiveMetro class ********* */
// Constructor, requires a parameter object, a proposal object, an initial
// covariance matrix for the multivariate proposals, a target acceptance rate,
// and the maximum number of iterations to perform the adaptations for.
AdaptiveMetro::AdaptiveMetro(Parameter<arma::vec>& parameter, Proposal<double>& proposal,
arma::mat proposal_covar, double target_rate, int maxiter) :
parameter_(parameter), proposal_(proposal),
target_rate_(target_rate), maxiter_(maxiter)
{
gamma_ = 2.0 / 3.0;
niter_ = 0;
naccept_ = 0;
chol_factor_ = arma::chol(proposal_covar);
}
// Method to calculate whether the proposal is accepted
bool AdaptiveMetro::Accept(arma::vec new_value, arma::vec old_value) {
// MH accept/reject criteria: Proposal must be symmetric!!
alpha_ = (parameter_.LogDensity(new_value) - parameter_.LogDensity(old_value)) / parameter_.GetTemperature();
if (!arma::is_finite(alpha_)) {
// New value of the log-posterior is not finite, so reject this
// proposal
alpha_ = 0.0;
return false;
}
double unif = uniform_(rng);
alpha_ = std::min(exp(alpha_), 1.0);
if (unif < alpha_) {
naccept_++;
return true;
} else {
return false;
}
}
// Method to perform the RAM step. This involves a standard Metropolis-Hastings update, followed
// by an update to the proposal scale matrix so long as niter < maxiter
void AdaptiveMetro::DoStep()
{
arma::vec old_value = parameter_.Value();
// Draw a new parameter vector
arma::vec unit_proposal(old_value.n_rows);
for (int i=0; i<old_value.n_rows; i++) {
// Unscaled proposal
unit_proposal(i) = proposal_.Draw(0.0);
}
// Scaled proposal vector
arma::vec scaled_proposal = chol_factor_.t() * unit_proposal;
arma::vec new_value = old_value + scaled_proposal;
// MH accept/reject criteria
if (Accept(new_value, old_value)) {
parameter_.Save(new_value);
}
double step_size, unit_norm;
if ((niter_ < maxiter_) && arma::is_finite(alpha_)) {
// Still in the adaptive stage, so update the scale matrix cholesky factor
// The step size sequence for the scale matrix update. This is eta_n in the
// notation of Vihola (2012)
step_size = std::min(1.0, new_value.n_rows / pow(niter_, gamma_));
unit_norm = arma::norm(unit_proposal, 2);
// Rescale the proposal vector for updating the scale matrix cholesky factor
scaled_proposal = sqrt(step_size * fabs(alpha_ - target_rate_)) / unit_norm * scaled_proposal;
// Update or downdate the Cholesky factor?
bool downdate = (alpha_ < target_rate_);
// Perform the rank-1 update (downdate) of the scale matrix Cholesky factor
CholUpdateR1(chol_factor_, scaled_proposal, downdate);
}
niter_++;
if (niter_ == maxiter_) {
double arate = ((double)(naccept_)) / ((double)(niter_));
std::cout << "Average RAM Acceptance Rate is " << arate << std::endl;
}
}
// Function to perform the rank-1 Cholesky update, needed for updating the
// proposal covariance matrix
void CholUpdateR1(arma::mat& L, arma::vec& v, bool downdate)
{
double sign = 1.0;
if (downdate) {
// Perform the downdate instead
sign = -1.0;
}
for (int k=0; k<L.n_rows; k++) {
double r = sqrt( L(k,k) * L(k,k) + sign * v(k) * v(k) );
double c = r / L(k,k);
double s = v(k) / L(k,k);
L(k,k) = r;
if (k < L.n_rows-1) {
L(k,arma::span(k+1,L.n_rows-1)) = (L(k,arma::span(k+1,L.n_rows-1)) +
sign * s * v(arma::span(k+1,v.n_elem-1)).t()) / c;
v(arma::span(k+1,v.n_elem-1)) = c * v(arma::span(k+1,v.n_elem-1)) -
s * L(k,arma::span(k+1,L.n_rows-1)).t();
}
}
}
<|endoftext|> |
<commit_before>#ifndef OMALG_TRANSFORM_TO_OMEGA_SEMIGROUP
#define OMALG_TRANSFORM_TO_OMEGA_SEMIGROUP
#include <list>
#include <unordered_map>
#include <iostream>
#include "OmegaSemigroup.h"
#include "Morphism.h"
#include "Node.h"
#include "TransitionProfiles/TransitionProfile.h"
namespace omalg {
/**
* Transform given automaton into equivalent omega semigroup. The algorithm
* is parametrized by the automaton's acceptance condition, as a fitting
* transition profile structured is used according to the type.
* @param Automaton The automaton to transform.
* @return pointer to resulting omega semigroup.
*/
template<class T> OmegaSemigroup* TransformToOmegaSemigroup(T const& Automaton) {
/**
* Initialization of data structures.
**/
//Transition profile for the empty word.
TransitionProfile<T> epsilonProfile(Automaton.getEpsilonProfile());
//Index counter for each newly created node.
size_t nodeIndex = 0;
//"root" Node in the Cayley graph. Aqquired on the heap for consistency.
Node<TransitionProfile<T> >* epsilonNode = new Node<TransitionProfile<T> >(epsilonProfile, Automaton.alphabetSize(), 0, nodeIndex);
++nodeIndex;
//Signifies whether the epsilon profile is part of the final semigroup.
bool epsilonInSemigroup = false;
//List storing pointers to all nodes. Used for iteration, keeping track of
//already processed nodes, and also for memory management.
std::list<Node<TransitionProfile<T> >*> nodeList;
nodeList.insert(nodeList.end(), epsilonNode);
//Iterator to first element that still needs to be processed of the lists in the node.
typename std::list<Node<TransitionProfile<T> >*>::const_iterator nextToProcess = nodeList.begin();
//Alphabet for element names
std::vector<std::string> alphabet = Automaton.getAlphabet();
//Get transition profiles of each letter once for efficiency.
//TODO check if initializing each with the epsilon profile is a performance killer.
std::vector<TransitionProfile<T> > letterProfiles(Automaton.alphabetSize(), epsilonProfile);
for (size_t letter = 0; letter < Automaton.alphabetSize(); ++letter) {
letterProfiles[letter] = Automaton.getTransitionProfileForLetter(letter);
}
/**
* Main loop for building the Cayley Graph.
**/
while (nextToProcess != nodeList.end()) {
TransitionProfile<T> current = (*nextToProcess)->getValue();
//Generate successor for each letter.
for (size_t letter = 0; letter < Automaton.alphabetSize(); ++letter) {
TransitionProfile<T> letterSuccessor = current.concat(letterProfiles[letter]);
//Check if this successor is new and add link.
bool found = false;
for (auto listIter = nodeList.begin(); listIter != nodeList.end() && !found; ++listIter) {
if ((*listIter)->equalToValue(letterSuccessor)) {
//"Old" successor.
(*nextToProcess)->setSuccessor(letter, *listIter, false);
found = true;
//Check if epsilonNode was rediscovered.
if (listIter == nodeList.begin()) {
epsilonInSemigroup = true;
}
}
}
if (!found) {
//"New" successor, add to list.
Node<TransitionProfile<T> >* newNode = new Node<TransitionProfile<T> >(letterSuccessor, Automaton.alphabetSize(), *nextToProcess, nodeIndex);
++nodeIndex;
nodeList.insert(nodeList.end(), newNode);
(*nextToProcess)->setSuccessor(letter, newNode, true);
}
}
//Advance process iterator.
++nextToProcess;
}
/**
* Build product table.
**/
size_t tableSize = (epsilonInSemigroup ? nodeList.size() : nodeList.size() - 1);
std::vector<std::vector<size_t> > productTable(tableSize, std::vector<size_t>(tableSize));
std::vector<std::string> elementNames(tableSize);
size_t columnIndex = 0;
//rowBegin is 0 if epsilon is not in the table. Otherwise rows start at index 1.
size_t rowBegin = (epsilonInSemigroup ? 1 : 0);
size_t rowOffset = 1 - rowBegin;
typename std::list<Node<TransitionProfile<T> >*>::const_iterator listBegin = nodeList.begin();
if (!epsilonInSemigroup) {
++listBegin;
}
//Traverse Cayley graph along true edges.
//Special Case: "root". Fill first row and column.
if (epsilonInSemigroup) {
for (size_t index = 0; index < tableSize; ++index) {
productTable[0][index] = index;
productTable[index][0] = index;
elementNames[0] = "tp(eps)";
}
}
//Set up for traversal.
std::list<size_t> letterList;
int nextIndex = -1;
Node<TransitionProfile<T> >* currentNode = epsilonNode;
bool done = false;
//Traversal loop. Nodes are processed when added to the list.
while(!done) {
nextIndex = currentNode->nextTrueSucessor(nextIndex + 1);
if (nextIndex == -1) {
if (letterList.empty()) {
done = true;
}
else {
nextIndex = letterList.back();
letterList.pop_back();
currentNode = currentNode->getParent();
}
}
else {
currentNode = (*currentNode)[nextIndex].first;
letterList.insert(letterList.end(), nextIndex);
nextIndex = -1;
//Subtract one from column index if epsilon is not in semigroup.
columnIndex = currentNode->getIndex() - rowOffset;
//Get element name
std::string newName = "tp(";
for(auto pathIter = letterList.begin(); pathIter != letterList.end(); ++pathIter) {
newName += alphabet[*pathIter];
}
newName += ")";
elementNames[columnIndex] = newName;
//Update table
size_t rowIndex = rowBegin;
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
Node<TransitionProfile<T> >* targetNode = *listIter;
for(auto pathIter = letterList.begin(); pathIter != letterList.end(); ++pathIter) {
targetNode = (*targetNode)[*pathIter].first;
}
productTable[rowIndex][columnIndex] = targetNode->getIndex() - rowOffset;
++rowIndex;
}
}
}
//Table now finished. Create semigroup.
Semigroup Splus(elementNames, productTable);
/*
* Building the omega part.
*/
//Omega iteration of semigroup elements.
//TODO: This is a bit complicated and might not be the most efficient way.
std::vector<OmegaProfile> omegaIters(tableSize, std::vector<bool>(tableSize));
size_t omegaIndex = 0;
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
omegaIters[omegaIndex] = (*listIter)->getValue().omegaIteration();
++omegaIndex;
}
//Map of omega profiles to their indices.
std::unordered_map<OmegaProfile, size_t, OmegaProfileHash> omegaProfiles;
//List of omega names, will later be turned into vector.
std::list<std::string> omegaNames;
//Fill the map with omega iterations.
omegaIndex = 0;
for (auto vecIter = omegaIters.begin(); vecIter != omegaIters.end(); ++vecIter) {
if (omegaProfiles.find(*vecIter) == omegaProfiles.end()) {
omegaProfiles[*vecIter] = omegaIndex;
std::string newName = "(" + elementNames[vecIter - omegaIters.begin()] + ")^w";
omegaNames.insert(omegaNames.end(), newName);
++omegaIndex;
}
}
size_t boundary = omegaIndex;
//Fill the map with all mixed products. Keep partial mixed product table.
std::vector<std::vector<size_t> > partialMixedTable(tableSize, std::vector<size_t>(omegaProfiles.size()));
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
for (auto vecIter = omegaIters.begin(); vecIter != omegaIters.end(); ++vecIter) {
OmegaProfile mixedProduct = (*listIter)->getValue().mixedProduct(*vecIter);
if (omegaProfiles.find(mixedProduct) == omegaProfiles.end()) {
omegaProfiles[mixedProduct] = omegaIndex;
std::string newName = elementNames[(*listIter)->getIndex()] + "(" + elementNames[vecIter - omegaIters.begin()] + ")^w";
omegaNames.insert(omegaNames.end(), newName);
++omegaIndex;
}
//Update mixed table
//Subtract 1 from finite index if epsilon is not in the table
size_t finIndex = (*listIter)->getIndex() - rowOffset;
size_t omIndex = omegaProfiles[*vecIter];
partialMixedTable[finIndex][omIndex] = omegaProfiles[mixedProduct];
}
}
//Create real mixed table.
std::vector<std::vector<size_t> > mixedTable(tableSize, std::vector<size_t>(omegaProfiles.size()));
//Copy values from old table.
for (size_t splusIndex = 0; splusIndex < tableSize; ++splusIndex) {
for (size_t somegaIndex = 0; somegaIndex < boundary; ++somegaIndex) {
mixedTable[splusIndex][somegaIndex] = partialMixedTable[splusIndex][somegaIndex];
}
}
//Fill rest of mixed table.
for (auto mapIter = omegaProfiles.begin(); mapIter != omegaProfiles.end(); ++mapIter) {
if (mapIter->second >= boundary) {
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
OmegaProfile mixedProduct = (*listIter)->getValue().mixedProduct(mapIter->first);
mixedTable[(*listIter)->getIndex()][mapIter->second] = omegaProfiles[mixedProduct];
}
}
}
//Fill omega table.
std::vector<size_t> omegaTable(tableSize);
for (size_t splusIndex = 0; splusIndex < tableSize; ++splusIndex) {
omegaTable[splusIndex] = omegaProfiles[omegaIters[splusIndex]];
}
/*
* Additional work: morphism and acceptance.
*/
//Create set P.
std::vector<bool> P(omegaProfiles.size(), false);
size_t initial = Automaton.getInitialState();
for (auto mapIter = omegaProfiles.begin(); mapIter != omegaProfiles.end(); ++mapIter) {
if (mapIter->first[initial]) {
P[mapIter->second] = true;
}
}
//Create morphism phi.
std::vector<size_t> phiValues(alphabet.size());
for (size_t letter = 0; letter < alphabet.size(); ++letter) {
phiValues[letter] = (*epsilonNode)[letter].first->getIndex() - rowOffset;
}
Morphism phi(phiValues, alphabet);
//Turn names from list into vector.
std::vector<std::string> nameVector(omegaNames.begin(), omegaNames.end());
//Create omega semigroup.
OmegaSemigroup* result = new OmegaSemigroup(Splus, nameVector, mixedTable, omegaTable, P, phi);
/*
* Cleanup
*/
for (auto listIter = nodeList.begin(); listIter != nodeList.end(); ++listIter) {
delete *listIter;
}
return result;
}
}
#endif
<commit_msg>Fixed bug in a2os<commit_after>#ifndef OMALG_TRANSFORM_TO_OMEGA_SEMIGROUP
#define OMALG_TRANSFORM_TO_OMEGA_SEMIGROUP
#include <list>
#include <unordered_map>
#include <iostream>
#include "OmegaSemigroup.h"
#include "Morphism.h"
#include "Node.h"
#include "TransitionProfiles/TransitionProfile.h"
namespace omalg {
/**
* Transform given automaton into equivalent omega semigroup. The algorithm
* is parametrized by the automaton's acceptance condition, as a fitting
* transition profile structured is used according to the type.
* @param Automaton The automaton to transform.
* @return pointer to resulting omega semigroup.
*/
template<class T> OmegaSemigroup* TransformToOmegaSemigroup(T const& Automaton) {
/**
* Initialization of data structures.
**/
//Transition profile for the empty word.
TransitionProfile<T> epsilonProfile(Automaton.getEpsilonProfile());
//Index counter for each newly created node.
size_t nodeIndex = 0;
//"root" Node in the Cayley graph. Aqquired on the heap for consistency.
Node<TransitionProfile<T> >* epsilonNode = new Node<TransitionProfile<T> >(epsilonProfile, Automaton.alphabetSize(), 0, nodeIndex);
++nodeIndex;
//Signifies whether the epsilon profile is part of the final semigroup.
bool epsilonInSemigroup = false;
//List storing pointers to all nodes. Used for iteration, keeping track of
//already processed nodes, and also for memory management.
std::list<Node<TransitionProfile<T> >*> nodeList;
nodeList.insert(nodeList.end(), epsilonNode);
//Iterator to first element that still needs to be processed of the lists in the node.
typename std::list<Node<TransitionProfile<T> >*>::const_iterator nextToProcess = nodeList.begin();
//Alphabet for element names
std::vector<std::string> alphabet = Automaton.getAlphabet();
//Get transition profiles of each letter once for efficiency.
//TODO check if initializing each with the epsilon profile is a performance killer.
std::vector<TransitionProfile<T> > letterProfiles(Automaton.alphabetSize(), epsilonProfile);
for (size_t letter = 0; letter < Automaton.alphabetSize(); ++letter) {
letterProfiles[letter] = Automaton.getTransitionProfileForLetter(letter);
}
/**
* Main loop for building the Cayley Graph.
**/
while (nextToProcess != nodeList.end()) {
TransitionProfile<T> current = (*nextToProcess)->getValue();
//Generate successor for each letter.
for (size_t letter = 0; letter < Automaton.alphabetSize(); ++letter) {
TransitionProfile<T> letterSuccessor = current.concat(letterProfiles[letter]);
//Check if this successor is new and add link.
bool found = false;
for (auto listIter = nodeList.begin(); listIter != nodeList.end() && !found; ++listIter) {
if ((*listIter)->equalToValue(letterSuccessor)) {
//"Old" successor.
(*nextToProcess)->setSuccessor(letter, *listIter, false);
found = true;
//Check if epsilonNode was rediscovered.
if (listIter == nodeList.begin()) {
epsilonInSemigroup = true;
}
}
}
if (!found) {
//"New" successor, add to list.
Node<TransitionProfile<T> >* newNode = new Node<TransitionProfile<T> >(letterSuccessor, Automaton.alphabetSize(), *nextToProcess, nodeIndex);
++nodeIndex;
nodeList.insert(nodeList.end(), newNode);
(*nextToProcess)->setSuccessor(letter, newNode, true);
}
}
//Advance process iterator.
++nextToProcess;
}
/**
* Build product table.
**/
size_t tableSize = (epsilonInSemigroup ? nodeList.size() : nodeList.size() - 1);
std::vector<std::vector<size_t> > productTable(tableSize, std::vector<size_t>(tableSize));
std::vector<std::string> elementNames(tableSize);
size_t columnIndex = 0;
//rowBegin is 0 if epsilon is not in the table. Otherwise rows start at index 1.
size_t rowBegin = (epsilonInSemigroup ? 1 : 0);
size_t rowOffset = 1 - rowBegin;
typename std::list<Node<TransitionProfile<T> >*>::const_iterator listBegin = nodeList.begin();
if (!epsilonInSemigroup) {
++listBegin;
}
//Traverse Cayley graph along true edges.
//Special Case: "root". Fill first row and column.
if (epsilonInSemigroup) {
for (size_t index = 0; index < tableSize; ++index) {
productTable[0][index] = index;
productTable[index][0] = index;
elementNames[0] = "tp(eps)";
}
}
//Set up for traversal.
std::list<size_t> letterList;
int nextIndex = -1;
Node<TransitionProfile<T> >* currentNode = epsilonNode;
bool done = false;
//Traversal loop. Nodes are processed when added to the list.
while(!done) {
nextIndex = currentNode->nextTrueSucessor(nextIndex + 1);
if (nextIndex == -1) {
if (letterList.empty()) {
done = true;
}
else {
nextIndex = letterList.back();
letterList.pop_back();
currentNode = currentNode->getParent();
}
}
else {
currentNode = (*currentNode)[nextIndex].first;
letterList.insert(letterList.end(), nextIndex);
nextIndex = -1;
//Subtract one from column index if epsilon is not in semigroup.
columnIndex = currentNode->getIndex() - rowOffset;
//Get element name
std::string newName = "tp(";
for(auto pathIter = letterList.begin(); pathIter != letterList.end(); ++pathIter) {
newName += alphabet[*pathIter];
}
newName += ")";
elementNames[columnIndex] = newName;
//Update table
size_t rowIndex = rowBegin;
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
Node<TransitionProfile<T> >* targetNode = *listIter;
for(auto pathIter = letterList.begin(); pathIter != letterList.end(); ++pathIter) {
targetNode = (*targetNode)[*pathIter].first;
}
productTable[rowIndex][columnIndex] = targetNode->getIndex() - rowOffset;
++rowIndex;
}
}
}
//Table now finished. Create semigroup.
Semigroup Splus(elementNames, productTable);
/*
* Building the omega part.
*/
//Omega iteration of semigroup elements.
//TODO: This is a bit complicated and might not be the most efficient way.
std::vector<OmegaProfile> omegaIters(tableSize, std::vector<bool>(tableSize));
size_t omegaIndex = 0;
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
omegaIters[omegaIndex] = (*listIter)->getValue().omegaIteration();
++omegaIndex;
}
//Map of omega profiles to their indices.
std::unordered_map<OmegaProfile, size_t, OmegaProfileHash> omegaProfiles;
//List of omega names, will later be turned into vector.
std::list<std::string> omegaNames;
//Fill the map with omega iterations.
omegaIndex = 0;
for (auto vecIter = omegaIters.begin(); vecIter != omegaIters.end(); ++vecIter) {
if (omegaProfiles.find(*vecIter) == omegaProfiles.end()) {
omegaProfiles[*vecIter] = omegaIndex;
std::string newName = "(" + elementNames[vecIter - omegaIters.begin()] + ")^w";
omegaNames.insert(omegaNames.end(), newName);
++omegaIndex;
}
}
size_t boundary = omegaIndex;
//Fill the map with all mixed products. Keep partial mixed product table.
std::vector<std::vector<size_t> > partialMixedTable(tableSize, std::vector<size_t>(omegaProfiles.size()));
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
for (auto vecIter = omegaIters.begin(); vecIter != omegaIters.end(); ++vecIter) {
OmegaProfile mixedProduct = (*listIter)->getValue().mixedProduct(*vecIter);
if (omegaProfiles.find(mixedProduct) == omegaProfiles.end()) {
omegaProfiles[mixedProduct] = omegaIndex;
std::string newName = elementNames[(*listIter)->getIndex() - rowOffset] + "(" + elementNames[vecIter - omegaIters.begin()] + ")^w";
omegaNames.insert(omegaNames.end(), newName);
++omegaIndex;
}
//Update mixed table
//Subtract 1 from finite index if epsilon is not in the table
size_t finIndex = (*listIter)->getIndex() - rowOffset;
size_t omIndex = omegaProfiles[*vecIter];
partialMixedTable[finIndex][omIndex] = omegaProfiles[mixedProduct];
}
}
//Create real mixed table.
std::vector<std::vector<size_t> > mixedTable(tableSize, std::vector<size_t>(omegaProfiles.size()));
//Copy values from old table.
for (size_t splusIndex = 0; splusIndex < tableSize; ++splusIndex) {
for (size_t somegaIndex = 0; somegaIndex < boundary; ++somegaIndex) {
mixedTable[splusIndex][somegaIndex] = partialMixedTable[splusIndex][somegaIndex];
}
}
//Fill rest of mixed table.
for (auto mapIter = omegaProfiles.begin(); mapIter != omegaProfiles.end(); ++mapIter) {
if (mapIter->second >= boundary) {
for (auto listIter = listBegin; listIter != nodeList.end(); ++listIter) {
OmegaProfile mixedProduct = (*listIter)->getValue().mixedProduct(mapIter->first);
//Subtract 1 from finite index if epsilon is not in the table
size_t finIndex = (*listIter)->getIndex() - rowOffset;
mixedTable[finIndex][mapIter->second] = omegaProfiles[mixedProduct];
}
}
}
//Fill omega table.
std::vector<size_t> omegaTable(tableSize);
for (size_t splusIndex = 0; splusIndex < tableSize; ++splusIndex) {
omegaTable[splusIndex] = omegaProfiles[omegaIters[splusIndex]];
}
/*
* Additional work: morphism and acceptance.
*/
//Create set P.
std::vector<bool> P(omegaProfiles.size(), false);
size_t initial = Automaton.getInitialState();
for (auto mapIter = omegaProfiles.begin(); mapIter != omegaProfiles.end(); ++mapIter) {
if (mapIter->first[initial]) {
P[mapIter->second] = true;
}
}
//Create morphism phi.
std::vector<size_t> phiValues(alphabet.size());
for (size_t letter = 0; letter < alphabet.size(); ++letter) {
phiValues[letter] = (*epsilonNode)[letter].first->getIndex() - rowOffset;
}
Morphism phi(phiValues, alphabet);
//Turn names from list into vector.
std::vector<std::string> nameVector(omegaNames.begin(), omegaNames.end());
//Create omega semigroup.
OmegaSemigroup* result = new OmegaSemigroup(Splus, nameVector, mixedTable, omegaTable, P, phi);
/*
* Cleanup
*/
for (auto listIter = nodeList.begin(); listIter != nodeList.end(); ++listIter) {
delete *listIter;
}
return result;
}
}
#endif
<|endoftext|> |
<commit_before>// @(#)root/minuit2:$Name: $:$Id: TFitterFumili.cxx,v 1.3 2005/11/29 14:43:31 moneta Exp $
// Author: L. Moneta 10/2005
/**********************************************************************
* *
* Copyright (c) 2005 ROOT Foundation, CERN/PH-SFT *
* *
**********************************************************************/
#include "TROOT.h"
#include "TFitterFumili.h"
#include "TMath.h"
#include "TF1.h"
#include "TH1.h"
#include "TGraph.h"
#include "TFumiliFCN.h"
#include "Minuit2/FumiliMinimizer.h"
#include "Minuit2/FunctionMinimum.h"
#include "Minuit2/MnStrategy.h"
#include "Minuit2/MnPrint.h"
using namespace ROOT::Minuit2;
//#define DEBUG 1
ClassImp(TFitterFumili);
TFitterFumili* gFumili2 = 0;
TFitterFumili::TFitterFumili() {
SetName("Fumili2");
gFumili2 = this;
gROOT->GetListOfSpecials()->Add(gFumili2);
}
// needed this additional contructor ?
TFitterFumili::TFitterFumili(Int_t /* maxpar */) {
SetName("Fumili2");
gFumili2 = this;
gROOT->GetListOfSpecials()->Add(gFumili2);
}
// create the minimizer engine and register the plugin in ROOT
// what ever we specify only Fumili is created
void TFitterFumili::CreateMinimizer(EMinimizerType ) {
if (PrintLevel() >=1 )
std::cout<<"TFitterFumili: Minimize using new Fumili algorithm "<<std::endl;
const ModularFunctionMinimizer * minimizer = GetMinimizer();
if (!minimizer) delete minimizer;
SetMinimizer( new FumiliMinimizer() );
SetStrategy(2);
// Fumili cannot deal with tolerance too smalls (10-3 corrsponds to 10-7 in FumiliBuilder)
SetMinimumTolerance(0.001);
#ifdef DEBUG
SetPrintLevel(3);
#endif
}
Double_t TFitterFumili::Chisquare(Int_t npar, Double_t *params) const {
// do chisquare calculations in case of likelihood fits
const TFumiliBinLikelihoodFCN * fcn = dynamic_cast<const TFumiliBinLikelihoodFCN *> ( GetMinuitFCN() );
std::vector<double> p(npar);
for (int i = 0; i < npar; ++i)
p[i] = params[i];
return fcn->Chi2(p);
}
void TFitterFumili::CreateChi2FCN() {
SetMinuitFCN(new TFumiliChi2FCN( *this,GetStrategy()) );
}
void TFitterFumili::CreateChi2ExtendedFCN() {
//for Fumili use normal method
SetMinuitFCN(new TFumiliChi2FCN(*this, GetStrategy()));
}
void TFitterFumili::CreateBinLikelihoodFCN() {
SetMinuitFCN( new TFumiliBinLikelihoodFCN( *this, GetStrategy()) );
}
<commit_msg>set default strategy to 1 (faster derivatives computation)<commit_after>// @(#)root/minuit2:$Name: $:$Id: TFitterFumili.cxx,v 1.4 2006/04/26 10:40:09 moneta Exp $
// Author: L. Moneta 10/2005
/**********************************************************************
* *
* Copyright (c) 2005 ROOT Foundation, CERN/PH-SFT *
* *
**********************************************************************/
#include "TROOT.h"
#include "TFitterFumili.h"
#include "TMath.h"
#include "TF1.h"
#include "TH1.h"
#include "TGraph.h"
#include "TFumiliFCN.h"
#include "Minuit2/FumiliMinimizer.h"
#include "Minuit2/FunctionMinimum.h"
#include "Minuit2/MnStrategy.h"
#include "Minuit2/MnPrint.h"
using namespace ROOT::Minuit2;
//#define DEBUG 1
ClassImp(TFitterFumili);
TFitterFumili* gFumili2 = 0;
TFitterFumili::TFitterFumili() {
SetName("Fumili2");
gFumili2 = this;
gROOT->GetListOfSpecials()->Add(gFumili2);
}
// needed this additional contructor ?
TFitterFumili::TFitterFumili(Int_t /* maxpar */) {
SetName("Fumili2");
gFumili2 = this;
gROOT->GetListOfSpecials()->Add(gFumili2);
}
// create the minimizer engine and register the plugin in ROOT
// what ever we specify only Fumili is created
void TFitterFumili::CreateMinimizer(EMinimizerType ) {
if (PrintLevel() >=1 )
std::cout<<"TFitterFumili: Minimize using new Fumili algorithm "<<std::endl;
const ModularFunctionMinimizer * minimizer = GetMinimizer();
if (!minimizer) delete minimizer;
SetMinimizer( new FumiliMinimizer() );
SetStrategy(1);
// Fumili cannot deal with tolerance too smalls (10-3 corrsponds to 10-7 in FumiliBuilder)
SetMinimumTolerance(0.001);
#ifdef DEBUG
SetPrintLevel(3);
#endif
}
Double_t TFitterFumili::Chisquare(Int_t npar, Double_t *params) const {
// do chisquare calculations in case of likelihood fits
const TFumiliBinLikelihoodFCN * fcn = dynamic_cast<const TFumiliBinLikelihoodFCN *> ( GetMinuitFCN() );
std::vector<double> p(npar);
for (int i = 0; i < npar; ++i)
p[i] = params[i];
return fcn->Chi2(p);
}
void TFitterFumili::CreateChi2FCN() {
SetMinuitFCN(new TFumiliChi2FCN( *this,GetStrategy()) );
}
void TFitterFumili::CreateChi2ExtendedFCN() {
//for Fumili use normal method
SetMinuitFCN(new TFumiliChi2FCN(*this, GetStrategy()));
}
void TFitterFumili::CreateBinLikelihoodFCN() {
SetMinuitFCN( new TFumiliBinLikelihoodFCN( *this, GetStrategy()) );
}
<|endoftext|> |
<commit_before>/************************************************
* permutation.hpp
* DICT
*
* Copyright (c) 2015-2017, Chi-En Wu
* Distributed under The BSD 3-Clause License
************************************************/
#ifndef DICT_INTERNAL_PERMUTATION_HPP_
#define DICT_INTERNAL_PERMUTATION_HPP_
#include "rbtree.hpp"
namespace dict {
namespace internal {
/************************************************
* Declaration: class permutation
************************************************/
class permutation {
public: // Public Type(s)
using size_type = std::size_t;
using value_type = std::size_t;
public: // Public Method(s)
permutation();
~permutation();
void insert(size_type i, size_type j);
void erase(size_type i);
void move(size_type from, size_type to);
size_type size() const;
size_type at(size_type i) const;
size_type rank(size_type j) const;
size_type operator[](size_type i) const;
private: // Private Type(s)
struct link_and_rank;
struct ranks_updater;
using bstree = rbtree<link_and_rank, ranks_updater>;
private: // Private Static Method(s)
static typename bstree::const_iterator
find_node(typename bstree::const_iterator it, size_type i);
static size_type access(typename bstree::const_iterator it, size_type i);
static void update_ranks(typename bstree::iterator it);
private: // Private Property(ies)
bstree tree_, inv_tree_;
size_type size_;
}; // class permutation
/************************************************
* Declaration: struct permutation::link_and_rank
************************************************/
struct permutation::link_and_rank {
link_and_rank() : rank(1) {
// do nothing
}
bstree::iterator link;
size_type rank;
}; // struct permutation::link_and_rank
/************************************************
* Declaration: struct permutation::ranks_updater
************************************************/
struct permutation::ranks_updater {
void operator()(typename bstree::iterator it) const {
update_ranks(it);
}
}; // struct permutation::ranks_updater
/************************************************
* Implementation: class permutation
************************************************/
inline permutation::permutation()
: size_(0) {
// do nothing
}
inline permutation::~permutation() {
// do nothing
}
inline permutation::size_type permutation::size() const {
return size_;
}
inline permutation::size_type permutation::at(size_type i) const {
return access(tree_.root(), i);
}
inline permutation::size_type permutation::rank(size_type j) const {
return access(inv_tree_.root(), j);
}
inline permutation::size_type permutation::operator[](size_type i) const {
return at(i);
}
} // namespace internal
} // namespace dict
#endif // DICT_INTERNAL_PERMUTATION_HPP_
<commit_msg>Remove user-defined destructor of `permutation`<commit_after>/************************************************
* permutation.hpp
* DICT
*
* Copyright (c) 2015-2017, Chi-En Wu
* Distributed under The BSD 3-Clause License
************************************************/
#ifndef DICT_INTERNAL_PERMUTATION_HPP_
#define DICT_INTERNAL_PERMUTATION_HPP_
#include "rbtree.hpp"
namespace dict {
namespace internal {
/************************************************
* Declaration: class permutation
************************************************/
class permutation {
public: // Public Type(s)
using size_type = std::size_t;
using value_type = std::size_t;
public: // Public Method(s)
permutation();
void insert(size_type i, size_type j);
void erase(size_type i);
void move(size_type from, size_type to);
size_type size() const;
size_type at(size_type i) const;
size_type rank(size_type j) const;
size_type operator[](size_type i) const;
private: // Private Type(s)
struct link_and_rank;
struct ranks_updater;
using bstree = rbtree<link_and_rank, ranks_updater>;
private: // Private Static Method(s)
static typename bstree::const_iterator
find_node(typename bstree::const_iterator it, size_type i);
static size_type access(typename bstree::const_iterator it, size_type i);
static void update_ranks(typename bstree::iterator it);
private: // Private Property(ies)
bstree tree_, inv_tree_;
size_type size_;
}; // class permutation
/************************************************
* Declaration: struct permutation::link_and_rank
************************************************/
struct permutation::link_and_rank {
link_and_rank() : rank(1) {
// do nothing
}
bstree::iterator link;
size_type rank;
}; // struct permutation::link_and_rank
/************************************************
* Declaration: struct permutation::ranks_updater
************************************************/
struct permutation::ranks_updater {
void operator()(typename bstree::iterator it) const {
update_ranks(it);
}
}; // struct permutation::ranks_updater
/************************************************
* Implementation: class permutation
************************************************/
inline permutation::permutation()
: size_(0) {
// do nothing
}
inline permutation::size_type permutation::size() const {
return size_;
}
inline permutation::size_type permutation::at(size_type i) const {
return access(tree_.root(), i);
}
inline permutation::size_type permutation::rank(size_type j) const {
return access(inv_tree_.root(), j);
}
inline permutation::size_type permutation::operator[](size_type i) const {
return at(i);
}
} // namespace internal
} // namespace dict
#endif // DICT_INTERNAL_PERMUTATION_HPP_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: extinput.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: jp $ $Date: 2001-03-13 16:40:33 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SV_KEYCODES_HXX
#include <vcl/keycodes.hxx>
#endif
#ifndef _VCL_CMDEVT_HXX
#include <vcl/cmdevt.hxx>
#endif
#ifndef _EXTINPUT_HXX
#include <extinput.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _INDEX_HXX
#include <index.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _TXTFRM_HXX
#include <txtfrm.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
SwExtTextInput::SwExtTextInput( const SwPaM& rPam, Ring* pRing )
: SwPaM( *rPam.GetPoint(), (SwPaM*)pRing )
{
bIsOverwriteCursor = FALSE;
bInsText = TRUE;
}
SwExtTextInput::~SwExtTextInput()
{
SwTxtNode* pTNd = GetPoint()->nNode.GetNode().GetTxtNode();
if( pTNd )
{
xub_StrLen nEndCnt = GetPoint()->nContent.GetIndex(),
nSttCnt = GetMark()->nContent.GetIndex();
if( nEndCnt != nSttCnt )
{
if( nEndCnt < nSttCnt )
{
xub_StrLen n = nEndCnt; nEndCnt = nSttCnt; nSttCnt = n;
}
// damit Undo / Redlining usw. richtig funktioniert,
// muss ueber die Doc-Schnittstellen gegangen werden !!!
SwIndex aIdx( pTNd, nSttCnt );
String sTxt( pTNd->GetTxt().Copy( nSttCnt, nEndCnt - nSttCnt ));
pTNd->Erase( aIdx, nEndCnt - nSttCnt );
if( bInsText )
GetDoc()->Insert( *this, sTxt );
}
}
}
void SwExtTextInput::SetInputData( const CommandExtTextInputData& rData )
{
SwTxtNode* pTNd = GetPoint()->nNode.GetNode().GetTxtNode();
if( pTNd )
{
xub_StrLen nEndCnt = GetPoint()->nContent.GetIndex(),
nSttCnt = GetMark()->nContent.GetIndex();
if( nEndCnt < nSttCnt )
{
xub_StrLen n = nEndCnt; nEndCnt = nSttCnt; nSttCnt = n;
}
SwIndex aIdx( pTNd, nSttCnt );
if( nSttCnt < nEndCnt )
pTNd->Erase( aIdx, nEndCnt - nSttCnt );
pTNd->Insert( rData.GetText(), aIdx, INS_EMPTYEXPAND );
SetMark();
GetPoint()->nContent = nSttCnt;
if( aAttrs.Count() )
aAttrs.Remove( 0, aAttrs.Count() );
if( rData.GetTextAttr() )
aAttrs.Insert( rData.GetTextAttr(), rData.GetText().Len(), 0 );
}
}
void SwExtTextInput::SetFontForPos( USHORT nPos, Font& rFont )
{
}
void SwExtTextInput::InvalidateRange() // das Layout anstossen
{
ULONG nSttNd = GetMark()->nNode.GetIndex(),
nEndNd = GetPoint()->nNode.GetIndex();
xub_StrLen nSttCnt = GetMark()->nContent.GetIndex(),
nEndCnt = GetPoint()->nContent.GetIndex();
if( nSttNd > nEndNd || ( nSttNd == nEndNd && nSttCnt > nEndCnt ))
{
ULONG nTmp = nSttNd; nSttNd = nEndNd; nEndNd = nTmp;
nTmp = nSttCnt; nSttCnt = nEndCnt; nEndCnt = (xub_StrLen)nTmp;
}
SwUpdateAttr aHt( 0, 0, RES_FMT_CHG );
SwNodes& rNds = GetDoc()->GetNodes();
SwNode* pNd;
for( ULONG n = nSttNd; n <= nEndNd; ++n )
if( ND_TEXTNODE == ( pNd = rNds[ n ] )->GetNodeType() )
{
aHt.nStart = n == nSttNd ? nSttCnt : 0;
aHt.nEnd = n == nEndNd ? nEndCnt : ((SwTxtNode*)pNd)->GetTxt().Len();
((SwTxtNode*)pNd)->Modify( &aHt, &aHt );
}
}
// die Doc Schnittstellen:
SwExtTextInput* SwDoc::CreateExtTextInput( const SwPaM& rPam )
{
SwExtTextInput* pNew = new SwExtTextInput( rPam, pExtInputRing );
if( !pExtInputRing )
pExtInputRing = pNew;
pNew->SetMark();
return pNew;
}
void SwDoc::DeleteExtTextInput( SwExtTextInput* pDel )
{
if( pDel == pExtInputRing )
{
if( pDel->GetNext() != pExtInputRing )
pExtInputRing = (SwPaM*)pDel->GetNext();
else
pExtInputRing = 0;
}
// das Layout benachrichtigen
if( pDel->HasMark() )
{
}
delete pDel;
}
SwExtTextInput* SwDoc::GetExtTextInput( const SwNode& rNd,
xub_StrLen nCntntPos ) const
{
SwExtTextInput* pRet = 0;
if( pExtInputRing )
{
ULONG nNdIdx = rNd.GetIndex();
SwExtTextInput* pTmp = (SwExtTextInput*)pExtInputRing;
do {
ULONG nPt = pTmp->GetPoint()->nNode.GetIndex(),
nMk = pTmp->GetMark()->nNode.GetIndex();
xub_StrLen nPtCnt = pTmp->GetPoint()->nContent.GetIndex(),
nMkCnt = pTmp->GetMark()->nContent.GetIndex();
if( nPt < nMk || ( nPt == nMk && nPtCnt < nMkCnt ))
{
ULONG nTmp = nMk; nMk = nPt; nPt = nTmp;
nTmp = nMkCnt; nMkCnt = nPtCnt; nPtCnt = (xub_StrLen)nTmp;
}
if( nMk <= nNdIdx && nNdIdx <= nPt &&
( STRING_NOTFOUND == nCntntPos ||
( nMkCnt <= nCntntPos && nCntntPos <= nPtCnt )))
{
pRet = pTmp;
break;
}
} while( pExtInputRing != (pTmp = (SwExtTextInput*)pExtInputRing ) );
}
return pRet;
}
<commit_msg>Bug #86377#: cache the original string for overwrite mode and handle this mode<commit_after>/*************************************************************************
*
* $RCSfile: extinput.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: jp $ $Date: 2001-06-08 13:39:07 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SV_KEYCODES_HXX
#include <vcl/keycodes.hxx>
#endif
#ifndef _VCL_CMDEVT_HXX
#include <vcl/cmdevt.hxx>
#endif
#ifndef _EXTINPUT_HXX
#include <extinput.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _INDEX_HXX
#include <index.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _TXTFRM_HXX
#include <txtfrm.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
SwExtTextInput::SwExtTextInput( const SwPaM& rPam, Ring* pRing )
: SwPaM( *rPam.GetPoint(), (SwPaM*)pRing )
{
bIsOverwriteCursor = FALSE;
bInsText = TRUE;
}
SwExtTextInput::~SwExtTextInput()
{
SwTxtNode* pTNd = GetPoint()->nNode.GetNode().GetTxtNode();
if( pTNd )
{
SwIndex& rIdx = GetPoint()->nContent;
xub_StrLen nSttCnt = rIdx.GetIndex(),
nEndCnt = GetMark()->nContent.GetIndex();
if( nEndCnt != nSttCnt )
{
if( nEndCnt < nSttCnt )
{
xub_StrLen n = nEndCnt; nEndCnt = nSttCnt; nSttCnt = n;
}
// damit Undo / Redlining usw. richtig funktioniert,
// muss ueber die Doc-Schnittstellen gegangen werden !!!
SwDoc* pDoc = GetDoc();
rIdx = nSttCnt;
String sTxt( pTNd->GetTxt().Copy( nSttCnt, nEndCnt - nSttCnt ));
if( bIsOverwriteCursor && sOverwriteText.Len() )
{
xub_StrLen nLen = sTxt.Len();
if( nLen > sOverwriteText.Len() )
{
rIdx += sOverwriteText.Len();
pTNd->Erase( rIdx, nLen - sOverwriteText.Len() );
rIdx = nSttCnt;
pTNd->Replace( rIdx, sOverwriteText.Len(),
sOverwriteText );
if( bInsText )
{
rIdx = nSttCnt;
pDoc->StartUndo( UNDO_OVERWRITE );
pDoc->Overwrite( *this, sTxt.Copy( 0,
sOverwriteText.Len() ));
pDoc->Insert( *this, sTxt.Copy( sOverwriteText.Len() ));
pDoc->EndUndo( UNDO_OVERWRITE );
}
}
else
{
pTNd->Replace( rIdx, nLen, sOverwriteText.Copy( 0, nLen ));
if( bInsText )
pDoc->Overwrite( *this, sTxt );
}
}
else
{
pTNd->Erase( rIdx, nEndCnt - nSttCnt );
if( bInsText )
pDoc->Insert( *this, sTxt );
}
}
}
}
void SwExtTextInput::SetInputData( const CommandExtTextInputData& rData )
{
SwTxtNode* pTNd = GetPoint()->nNode.GetNode().GetTxtNode();
if( pTNd )
{
xub_StrLen nSttCnt = GetPoint()->nContent.GetIndex(),
nEndCnt = GetMark()->nContent.GetIndex();
if( nEndCnt < nSttCnt )
{
xub_StrLen n = nEndCnt; nEndCnt = nSttCnt; nSttCnt = n;
}
SwIndex aIdx( pTNd, nSttCnt );
const String& rNewStr = rData.GetText();
if( bIsOverwriteCursor && sOverwriteText.Len() )
{
xub_StrLen nReplace = nEndCnt - nSttCnt;
if( rNewStr.Len() < nReplace )
{
// then we must insert from the saved original text
// some characters
nReplace -= rNewStr.Len();
aIdx += rNewStr.Len();
pTNd->Replace( aIdx, nReplace,
sOverwriteText.Copy( rNewStr.Len(), nReplace ));
aIdx = nSttCnt;
nReplace = rNewStr.Len();
}
else if( sOverwriteText.Len() < nReplace )
{
nReplace -= sOverwriteText.Len();
aIdx += sOverwriteText.Len();
pTNd->Erase( aIdx, nReplace );
aIdx = nSttCnt;
nReplace = sOverwriteText.Len();
}
else if( (nReplace = sOverwriteText.Len()) > rNewStr.Len() )
nReplace = rNewStr.Len();
pTNd->Replace( aIdx, nReplace, rNewStr );
if( !HasMark() )
SetMark();
GetMark()->nContent = aIdx;
}
else
{
if( nSttCnt < nEndCnt )
pTNd->Erase( aIdx, nEndCnt - nSttCnt );
pTNd->Insert( rNewStr, aIdx, INS_EMPTYEXPAND );
if( !HasMark() )
SetMark();
}
GetPoint()->nContent = nSttCnt;
if( aAttrs.Count() )
aAttrs.Remove( 0, aAttrs.Count() );
if( rData.GetTextAttr() )
aAttrs.Insert( rData.GetTextAttr(), rData.GetText().Len(), 0 );
}
}
void SwExtTextInput::SetFontForPos( USHORT nPos, Font& rFont )
{
}
void SwExtTextInput::InvalidateRange() // das Layout anstossen
{
ULONG nEndNd = GetMark()->nNode.GetIndex(),
nSttNd = GetPoint()->nNode.GetIndex();
xub_StrLen nEndCnt = GetMark()->nContent.GetIndex(),
nSttCnt = GetPoint()->nContent.GetIndex();
if( nSttNd > nEndNd || ( nSttNd == nEndNd && nSttCnt > nEndCnt ))
{
ULONG nTmp = nSttNd; nSttNd = nEndNd; nEndNd = nTmp;
nTmp = nSttCnt; nSttCnt = nEndCnt; nEndCnt = (xub_StrLen)nTmp;
}
SwUpdateAttr aHt( 0, 0, RES_FMT_CHG );
SwNodes& rNds = GetDoc()->GetNodes();
SwNode* pNd;
for( ULONG n = nSttNd; n <= nEndNd; ++n )
if( ND_TEXTNODE == ( pNd = rNds[ n ] )->GetNodeType() )
{
aHt.nStart = n == nSttNd ? nSttCnt : 0;
aHt.nEnd = n == nEndNd ? nEndCnt : ((SwTxtNode*)pNd)->GetTxt().Len();
((SwTxtNode*)pNd)->Modify( &aHt, &aHt );
}
}
void SwExtTextInput::SetOverwriteCursor( BOOL bFlag )
{
bIsOverwriteCursor = bFlag;
SwTxtNode* pTNd;
if( bIsOverwriteCursor &&
0 != (pTNd = GetPoint()->nNode.GetNode().GetTxtNode()) )
{
xub_StrLen nSttCnt = GetPoint()->nContent.GetIndex(),
nEndCnt = GetMark()->nContent.GetIndex();
sOverwriteText = pTNd->GetTxt().Copy( nEndCnt < nSttCnt ? nEndCnt
: nSttCnt );
if( sOverwriteText.Len() )
{
xub_StrLen nInWrdAttrPos = sOverwriteText.Search( CH_TXTATR_INWORD ),
nWrdAttrPos = sOverwriteText.Search( CH_TXTATR_BREAKWORD );
if( nWrdAttrPos < nInWrdAttrPos )
nInWrdAttrPos = nWrdAttrPos;
if( STRING_NOTFOUND != nInWrdAttrPos )
sOverwriteText.Erase( nInWrdAttrPos );
}
}
}
// die Doc Schnittstellen:
SwExtTextInput* SwDoc::CreateExtTextInput( const SwPaM& rPam )
{
SwExtTextInput* pNew = new SwExtTextInput( rPam, pExtInputRing );
if( !pExtInputRing )
pExtInputRing = pNew;
pNew->SetMark();
return pNew;
}
void SwDoc::DeleteExtTextInput( SwExtTextInput* pDel )
{
if( pDel == pExtInputRing )
{
if( pDel->GetNext() != pExtInputRing )
pExtInputRing = (SwPaM*)pDel->GetNext();
else
pExtInputRing = 0;
}
// das Layout benachrichtigen
if( pDel->HasMark() )
{
}
delete pDel;
}
SwExtTextInput* SwDoc::GetExtTextInput( const SwNode& rNd,
xub_StrLen nCntntPos ) const
{
SwExtTextInput* pRet = 0;
if( pExtInputRing )
{
ULONG nNdIdx = rNd.GetIndex();
SwExtTextInput* pTmp = (SwExtTextInput*)pExtInputRing;
do {
ULONG nPt = pTmp->GetPoint()->nNode.GetIndex(),
nMk = pTmp->GetMark()->nNode.GetIndex();
xub_StrLen nPtCnt = pTmp->GetPoint()->nContent.GetIndex(),
nMkCnt = pTmp->GetMark()->nContent.GetIndex();
if( nPt < nMk || ( nPt == nMk && nPtCnt < nMkCnt ))
{
ULONG nTmp = nMk; nMk = nPt; nPt = nTmp;
nTmp = nMkCnt; nMkCnt = nPtCnt; nPtCnt = (xub_StrLen)nTmp;
}
if( nMk <= nNdIdx && nNdIdx <= nPt &&
( STRING_NOTFOUND == nCntntPos ||
( nMkCnt <= nCntntPos && nCntntPos <= nPtCnt )))
{
pRet = pTmp;
break;
}
} while( pExtInputRing != (pTmp = (SwExtTextInput*)pExtInputRing ) );
}
return pRet;
}
<|endoftext|> |
<commit_before>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/render/FragmentShader.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef EOS_FRAGMENT_SHADER_HPP
#define EOS_FRAGMENT_SHADER_HPP
#include "eos/render/detail/Vertex.hpp"
#include "eos/render/detail/texturing.hpp"
#include "eos/cpp17/optional.hpp"
#include "glm/vec3.hpp"
#include "glm/vec4.hpp"
// Fragment shaders are a more accurate name for the same functionality as Pixel shaders. They aren't pixels
// yet, since the output still has to past several tests (depth, alpha, stencil) as well as the fact that one
// may be using anti-aliasing, which renders one-fragment-to-one-pixel non-true.
// The "pixel" in "pixel shader" is a misnomer because the pixel shader doesn't operate on pixels directly.
// The pixel shader operates on "fragments" which may or may not end up as actual pixels, depending on several
// factors outside of the pixel shader.
// The shaders *can not* depend on any state - they have to be able to run independently and in parallel!
// But can they really? What about the z-test? It happens earlier at the moment - which is good?
namespace eos {
namespace render {
/**
* @brief A simple fragment shader that does vertex-colouring.
*
* Uses the vertex colour data to shade the given fragment / pixel location.
*/
class VertexColoringFragmentShader
{
public:
/**
* @brief Todo.
*
* X
* lambda is not perspectively corrected. Note: In our case, it is, as we do it in the raster loop at
* the moment?
* Note/TODO: We should document in what range we expect ::color to be! Eg specify that Mesh should be
* [0,255]? But don't we then lose precision sometimes (e.g. superres)? I think we can leave Mesh /
* everything in [0,1] and convert at the very end.
*
* @param[in] x X.
* @ return RGBA... in [0, 1]?
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx, float dudy,
float dvdx, float dvdy)
{
// attributes interpolation
glm::tvec3<T, P> color_persp =
lambda[0] * point_a.color + lambda[1] * point_b.color + lambda[2] * point_c.color;
return glm::tvec4<T, P>(color_persp, T(1));
};
};
/**
* @brief A fragment shader that textures...
*
* X.
*/
class TexturingFragmentShader
{
public:
/**
* @brief Todo.
*
* See comments above about lambda (persp. corrected?) and the colour range.
*
* @param[in] x X.
* @ return RGBA... in [0, 1]?
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx,
float dudy, float dvdx, float dvdy)
{
glm::tvec2<T, P> texcoords_persp =
lambda[0] * point_a.texcoords + lambda[1] * point_b.texcoords + lambda[2] * point_c.texcoords;
// The Texture is in BGR, thus tex2D returns BGR
// Todo: Think about changing that.
glm::tvec3<T, P> texture_color =
detail::tex2d(texcoords_persp, texture.get(), dudx, dudy, dvdx, dvdy); // uses the current texture
glm::tvec3<T, P> pixel_color = glm::tvec3<T, P>(texture_color[2], texture_color[1], texture_color[0]);
// other: color.mul(tex2D(texture, texCoord));
return glm::tvec4<T, P>(pixel_color, T(1));
};
};
/**
* @brief X.
*
* X.
* Inverts the perspective texture mapping. Can be derived using some tedious algebra.
* Todo: Probably move to a texturing file, internal/detail one, where we will also put the tex2d, mipmapping
* etc stuff?
*
* @param[in] X X.
* @return X.
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec3<T, P> compute_inverse_perspectively_correct_lambda(const glm::tvec3<T, P>& lambda_world,
const T& one_over_w0, const T& one_over_w1,
const T& one_over_w2)
{
float w0 = 1 / one_over_w0;
float w1 = 1 / one_over_w1;
float w2 = 1 / one_over_w2;
float d = w0 - (w0 - w1) * lambda_world.y - (w0 - w2) * lambda_world.z;
if (d == 0)
return lambda_world;
glm::tvec3<T, P> lambda;
lambda.z = lambda_world.z * w2 / d;
lambda.y = lambda_world.y * w1 / d;
lambda.x = 1 - lambda.y - lambda.z;
return lambda;
};
class ExtractionFragmentShader
{
public:
/**
* @brief X.
*
* X.
* Inverts the perspective texture mapping. Can be derived using some tedious algebra.
* NOTE: This one actually takes/needs the perspectively corrected lambda I think!
*
* Todo: Probably move to a texturing file, internal/detail one, where we will also put the tex2d,
* mipmapping etc stuff?
*
* @param[in] X X.
* @return X.
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx, float dudy,
float dvdx, float dvdy)
{
auto corrected_lambda = compute_inverse_perspectively_correct_lambda(
lambda, point_a.position.w, point_b.position.w, point_c.position.w);
glm::tvec2<T, P> texcoords_persp = corrected_lambda[0] * point_a.texcoords +
corrected_lambda[1] * point_b.texcoords +
corrected_lambda[2] * point_c.texcoords;
// Texturing, no mipmapping:
glm::vec2 image_tex_coords = detail::texcoord_wrap(texcoords_persp);
image_tex_coords[0] *= texture->mipmaps[0].width();
image_tex_coords[1] *= texture->mipmaps[0].height();
glm::vec3 texture_color = detail::tex2d_linear(image_tex_coords, 0, texture.value()) / 255.0f;
glm::tvec3<T, P> pixel_color = glm::tvec3<T, P>(texture_color[2], texture_color[1], texture_color[0]);
return glm::tvec4<T, P>(pixel_color, T(1));
};
};
} /* namespace render */
} /* namespace eos */
#endif /* EOS_FRAGMENT_SHADER_HPP */
<commit_msg>Updated TexturingFragmentShader to compile again<commit_after>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/render/FragmentShader.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef EOS_FRAGMENT_SHADER_HPP
#define EOS_FRAGMENT_SHADER_HPP
#include "eos/render/detail/Vertex.hpp"
#include "eos/render/detail/texturing.hpp"
#include "eos/cpp17/optional.hpp"
#include "glm/vec3.hpp"
#include "glm/vec4.hpp"
// Fragment shaders are a more accurate name for the same functionality as Pixel shaders. They aren't pixels
// yet, since the output still has to past several tests (depth, alpha, stencil) as well as the fact that one
// may be using anti-aliasing, which renders one-fragment-to-one-pixel non-true.
// The "pixel" in "pixel shader" is a misnomer because the pixel shader doesn't operate on pixels directly.
// The pixel shader operates on "fragments" which may or may not end up as actual pixels, depending on several
// factors outside of the pixel shader.
// The shaders *can not* depend on any state - they have to be able to run independently and in parallel!
// But can they really? What about the z-test? It happens earlier at the moment - which is good?
namespace eos {
namespace render {
/**
* @brief A simple fragment shader that does vertex-colouring.
*
* Uses the vertex colour data to shade the given fragment / pixel location.
*/
class VertexColoringFragmentShader
{
public:
/**
* @brief Todo.
*
* X
* lambda is not perspectively corrected. Note: In our case, it is, as we do it in the raster loop at
* the moment?
* Note/TODO: We should document in what range we expect ::color to be! Eg specify that Mesh should be
* [0,255]? But don't we then lose precision sometimes (e.g. superres)? I think we can leave Mesh /
* everything in [0,1] and convert at the very end.
*
* @param[in] x X.
* @ return RGBA... in [0, 1]?
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx, float dudy,
float dvdx, float dvdy)
{
// attributes interpolation
glm::tvec3<T, P> color_persp =
lambda[0] * point_a.color + lambda[1] * point_b.color + lambda[2] * point_c.color;
return glm::tvec4<T, P>(color_persp, T(1));
};
};
/**
* @brief A fragment shader that textures...
*
* X.
*/
class TexturingFragmentShader
{
public:
/**
* @brief Todo.
*
* See comments above about lambda (persp. corrected?) and the colour range.
*
* @param[in] x X.
* @ return RGBA... in [0, 1]?
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx,
float dudy, float dvdx, float dvdy)
{
glm::tvec2<T, P> texcoords_persp =
lambda[0] * point_a.texcoords + lambda[1] * point_b.texcoords + lambda[2] * point_c.texcoords;
// The Texture is in BGR, thus tex2D returns BGR
// Todo: Think about changing that.
glm::tvec3<T, P> texture_color =
detail::tex2d(texcoords_persp, texture.value(), dudx, dudy, dvdx, dvdy); // uses the current texture
glm::tvec3<T, P> pixel_color = glm::tvec3<T, P>(texture_color[2], texture_color[1], texture_color[0]);
// other: color.mul(tex2D(texture, texCoord));
return glm::tvec4<T, P>(pixel_color, T(1));
};
};
/**
* @brief X.
*
* X.
* Inverts the perspective texture mapping. Can be derived using some tedious algebra.
* Todo: Probably move to a texturing file, internal/detail one, where we will also put the tex2d, mipmapping
* etc stuff?
*
* @param[in] X X.
* @return X.
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec3<T, P> compute_inverse_perspectively_correct_lambda(const glm::tvec3<T, P>& lambda_world,
const T& one_over_w0, const T& one_over_w1,
const T& one_over_w2)
{
float w0 = 1 / one_over_w0;
float w1 = 1 / one_over_w1;
float w2 = 1 / one_over_w2;
float d = w0 - (w0 - w1) * lambda_world.y - (w0 - w2) * lambda_world.z;
if (d == 0)
return lambda_world;
glm::tvec3<T, P> lambda;
lambda.z = lambda_world.z * w2 / d;
lambda.y = lambda_world.y * w1 / d;
lambda.x = 1 - lambda.y - lambda.z;
return lambda;
};
class ExtractionFragmentShader
{
public:
/**
* @brief X.
*
* X.
* Inverts the perspective texture mapping. Can be derived using some tedious algebra.
* NOTE: This one actually takes/needs the perspectively corrected lambda I think!
*
* Todo: Probably move to a texturing file, internal/detail one, where we will also put the tex2d,
* mipmapping etc stuff?
*
* @param[in] X X.
* @return X.
*/
template <typename T, glm::precision P = glm::defaultp>
glm::tvec4<T, P> shade_triangle_pixel(int x, int y, const detail::Vertex<T, P>& point_a,
const detail::Vertex<T, P>& point_b,
const detail::Vertex<T, P>& point_c, const glm::tvec3<T, P>& lambda,
const cpp17::optional<Texture>& texture, float dudx, float dudy,
float dvdx, float dvdy)
{
auto corrected_lambda = compute_inverse_perspectively_correct_lambda(
lambda, point_a.position.w, point_b.position.w, point_c.position.w);
glm::tvec2<T, P> texcoords_persp = corrected_lambda[0] * point_a.texcoords +
corrected_lambda[1] * point_b.texcoords +
corrected_lambda[2] * point_c.texcoords;
// Texturing, no mipmapping:
glm::vec2 image_tex_coords = detail::texcoord_wrap(texcoords_persp);
image_tex_coords[0] *= texture->mipmaps[0].width();
image_tex_coords[1] *= texture->mipmaps[0].height();
glm::vec3 texture_color = detail::tex2d_linear(image_tex_coords, 0, texture.value()) / 255.0f;
glm::tvec3<T, P> pixel_color = glm::tvec3<T, P>(texture_color[2], texture_color[1], texture_color[0]);
return glm::tvec4<T, P>(pixel_color, T(1));
};
};
} /* namespace render */
} /* namespace eos */
#endif /* EOS_FRAGMENT_SHADER_HPP */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_DISK_IO_THREAD
#define TORRENT_DISK_IO_THREAD
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
#include <fstream>
#endif
#include "libtorrent/storage.hpp"
#include "libtorrent/allocator.hpp"
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_array.hpp>
#include <list>
#include "libtorrent/config.hpp"
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
#include <boost/pool/pool.hpp>
#endif
#include "libtorrent/session_settings.hpp"
namespace libtorrent
{
struct cached_piece_info
{
int piece;
std::vector<bool> blocks;
ptime last_use;
enum kind_t { read_cache = 0, write_cache = 1 };
kind_t kind;
};
struct disk_io_job
{
disk_io_job()
: action(read)
, buffer(0)
, buffer_size(0)
, piece(0)
, offset(0)
, priority(0)
{}
enum action_t
{
read
, write
, hash
, move_storage
, release_files
, delete_files
, check_fastresume
, check_files
, save_resume_data
, rename_file
, abort_thread
, clear_read_cache
, abort_torrent
, update_settings
, read_and_hash
};
action_t action;
char* buffer;
int buffer_size;
boost::intrusive_ptr<piece_manager> storage;
// arguments used for read and write
int piece, offset;
// used for move_storage and rename_file. On errors, this is set
// to the error message
std::string str;
// on error, this is set to the path of the
// file the disk operation failed on
std::string error_file;
// priority decides whether or not this
// job will skip entries in the queue or
// not. It always skips in front of entries
// with lower priority
int priority;
boost::shared_ptr<entry> resume_data;
// the error code from the file operation
error_code error;
// this is called when operation completes
boost::function<void(int, disk_io_job const&)> callback;
};
struct cache_status
{
cache_status()
: blocks_written(0)
, writes(0)
, blocks_read(0)
, blocks_read_hit(0)
, reads(0)
, cache_size(0)
, read_cache_size(0)
, total_used_buffers(0)
{}
// the number of 16kB blocks written
size_type blocks_written;
// the number of write operations used
size_type writes;
// (blocks_written - writes) / blocks_written represents the
// "cache hit" ratio in the write cache
// the number of blocks read
// the number of blocks passed back to the bittorrent engine
size_type blocks_read;
// the number of blocks that was just copied from the read cache
size_type blocks_read_hit;
// the number of read operations used
size_type reads;
// the number of blocks in the cache (both read and write)
int cache_size;
// the number of blocks in the cache used for read cache
int read_cache_size;
// the total number of blocks that are currently in use
// this includes send and receive buffers
mutable int total_used_buffers;
};
struct disk_buffer_pool : boost::noncopyable
{
disk_buffer_pool(int block_size);
#ifdef TORRENT_DEBUG
~disk_buffer_pool();
#endif
#ifdef TORRENT_DEBUG
bool is_disk_buffer(char* buffer
, boost::mutex::scoped_lock& l) const;
bool is_disk_buffer(char* buffer) const;
#endif
char* allocate_buffer(char const* category);
void free_buffer(char* buf);
char* allocate_buffers(int blocks, char const* category);
void free_buffers(char* buf, int blocks);
int block_size() const { return m_block_size; }
#ifdef TORRENT_STATS
int disk_allocations() const
{ return m_allocations; }
#endif
void release_memory();
int in_use() const { return m_in_use; }
protected:
// number of bytes per block. The BitTorrent
// protocol defines the block size to 16 KiB.
const int m_block_size;
// number of disk buffers currently allocated
int m_in_use;
session_settings m_settings;
private:
// this only protects the pool allocator
typedef boost::mutex mutex_t;
mutable mutex_t m_pool_mutex;
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
// memory pool for read and write operations
// and disk cache
boost::pool<page_aligned_allocator> m_pool;
#endif
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
int m_allocations;
#endif
#ifdef TORRENT_DISK_STATS
protected:
void disk_buffer_pool::rename_buffer(char* buf, char const* category);
std::map<std::string, int> m_categories;
std::map<char*, std::string> m_buf_to_category;
std::ofstream m_log;
private:
#endif
#ifdef TORRENT_DEBUG
int m_magic;
#endif
};
// this is a singleton consisting of the thread and a queue
// of disk io jobs
struct disk_io_thread : disk_buffer_pool
{
disk_io_thread(io_service& ios, int block_size = 16 * 1024);
~disk_io_thread();
void join();
// aborts read operations
void stop(boost::intrusive_ptr<piece_manager> s);
void add_job(disk_io_job const& j
, boost::function<void(int, disk_io_job const&)> const& f
= boost::function<void(int, disk_io_job const&)>());
// keep track of the number of bytes in the job queue
// at any given time. i.e. the sum of all buffer_size.
// this is used to slow down the download global download
// speed when the queue buffer size is too big.
size_type queue_buffer_size() const
{ return m_queue_buffer_size; }
void get_cache_info(sha1_hash const& ih
, std::vector<cached_piece_info>& ret) const;
cache_status status() const;
void operator()();
#ifdef TORRENT_DEBUG
void check_invariant() const;
#endif
#ifdef TORRENT_DISK_STATS
std::ofstream m_disk_access_log;
#endif
struct cached_piece_entry
{
int piece;
// storage this piece belongs to
boost::intrusive_ptr<piece_manager> storage;
// the last time a block was writting to this piece
ptime last_use;
// the number of blocks in the cache for this piece
int num_blocks;
// the pointers to the block data
boost::shared_array<char*> blocks;
};
typedef boost::recursive_mutex mutex_t;
typedef std::list<cached_piece_entry> cache_t;
private:
bool test_error(disk_io_job& j);
void post_callback(boost::function<void(int, disk_io_job const&)> const& handler
, disk_io_job const& j, int ret);
// cache operations
cache_t::iterator find_cached_piece(
cache_t& cache, disk_io_job const& j
, mutex_t::scoped_lock& l);
int copy_from_piece(cache_t::iterator p, bool& hit
, disk_io_job const& j, mutex_t::scoped_lock& l);
// write cache operations
void flush_cache_blocks(mutex_t::scoped_lock& l, int blocks);
void flush_expired_pieces();
void flush_and_remove(cache_t::iterator i, mutex_t::scoped_lock& l);
int flush_contiguous_blocks(disk_io_thread::cache_t::iterator e
, mutex_t::scoped_lock& l);
void flush_range(cache_t::iterator i, int start, int end, mutex_t::scoped_lock& l);
void cache_block(disk_io_job& j, mutex_t::scoped_lock& l);
// read cache operations
int clear_oldest_read_piece(cache_t::iterator ignore
, mutex_t::scoped_lock& l);
int read_into_piece(cached_piece_entry& p, int start_block
, int options, mutex_t::scoped_lock& l);
int cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l);
int cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l);
int free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l);
bool make_room(int num_blocks
, cache_t::iterator ignore
, bool flush_write_cache
, mutex_t::scoped_lock& l);
int try_read_from_cache(disk_io_job const& j);
int read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h);
// this mutex only protects m_jobs, m_queue_buffer_size
// and m_abort
mutable mutex_t m_queue_mutex;
boost::condition m_signal;
bool m_abort;
bool m_waiting_to_shutdown;
std::list<disk_io_job> m_jobs;
size_type m_queue_buffer_size;
ptime m_last_file_check;
// this protects the piece cache and related members
mutable mutex_t m_piece_mutex;
// write cache
cache_t m_pieces;
// read cache
cache_t m_read_pieces;
// total number of blocks in use by both the read
// and the write cache. This is not supposed to
// exceed m_cache_size
cache_status m_cache_stats;
#ifdef TORRENT_DISK_STATS
std::ofstream m_log;
#endif
io_service& m_ios;
// this keeps the io_service::run() call blocked from
// returning. When shutting down, it's possible that
// the event queue is drained before the disk_io_thread
// has posted its last callback. When this happens, the
// io_service will have a pending callback from the
// disk_io_thread, but the event loop is not running.
// this means that the event is destructed after the
// disk_io_thread. If the event refers to a disk buffer
// it will try to free it, but the buffer pool won't
// exist anymore, and crash. This prevents that.
boost::optional<asio::io_service::work> m_work;
// thread for performing blocking disk io operations
boost::thread m_disk_io_thread;
};
}
#endif
<commit_msg>fixed syntax error<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_DISK_IO_THREAD
#define TORRENT_DISK_IO_THREAD
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
#include <fstream>
#endif
#include "libtorrent/storage.hpp"
#include "libtorrent/allocator.hpp"
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_array.hpp>
#include <list>
#include "libtorrent/config.hpp"
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
#include <boost/pool/pool.hpp>
#endif
#include "libtorrent/session_settings.hpp"
namespace libtorrent
{
struct cached_piece_info
{
int piece;
std::vector<bool> blocks;
ptime last_use;
enum kind_t { read_cache = 0, write_cache = 1 };
kind_t kind;
};
struct disk_io_job
{
disk_io_job()
: action(read)
, buffer(0)
, buffer_size(0)
, piece(0)
, offset(0)
, priority(0)
{}
enum action_t
{
read
, write
, hash
, move_storage
, release_files
, delete_files
, check_fastresume
, check_files
, save_resume_data
, rename_file
, abort_thread
, clear_read_cache
, abort_torrent
, update_settings
, read_and_hash
};
action_t action;
char* buffer;
int buffer_size;
boost::intrusive_ptr<piece_manager> storage;
// arguments used for read and write
int piece, offset;
// used for move_storage and rename_file. On errors, this is set
// to the error message
std::string str;
// on error, this is set to the path of the
// file the disk operation failed on
std::string error_file;
// priority decides whether or not this
// job will skip entries in the queue or
// not. It always skips in front of entries
// with lower priority
int priority;
boost::shared_ptr<entry> resume_data;
// the error code from the file operation
error_code error;
// this is called when operation completes
boost::function<void(int, disk_io_job const&)> callback;
};
struct cache_status
{
cache_status()
: blocks_written(0)
, writes(0)
, blocks_read(0)
, blocks_read_hit(0)
, reads(0)
, cache_size(0)
, read_cache_size(0)
, total_used_buffers(0)
{}
// the number of 16kB blocks written
size_type blocks_written;
// the number of write operations used
size_type writes;
// (blocks_written - writes) / blocks_written represents the
// "cache hit" ratio in the write cache
// the number of blocks read
// the number of blocks passed back to the bittorrent engine
size_type blocks_read;
// the number of blocks that was just copied from the read cache
size_type blocks_read_hit;
// the number of read operations used
size_type reads;
// the number of blocks in the cache (both read and write)
int cache_size;
// the number of blocks in the cache used for read cache
int read_cache_size;
// the total number of blocks that are currently in use
// this includes send and receive buffers
mutable int total_used_buffers;
};
struct disk_buffer_pool : boost::noncopyable
{
disk_buffer_pool(int block_size);
#ifdef TORRENT_DEBUG
~disk_buffer_pool();
#endif
#ifdef TORRENT_DEBUG
bool is_disk_buffer(char* buffer
, boost::mutex::scoped_lock& l) const;
bool is_disk_buffer(char* buffer) const;
#endif
char* allocate_buffer(char const* category);
void free_buffer(char* buf);
char* allocate_buffers(int blocks, char const* category);
void free_buffers(char* buf, int blocks);
int block_size() const { return m_block_size; }
#ifdef TORRENT_STATS
int disk_allocations() const
{ return m_allocations; }
#endif
void release_memory();
int in_use() const { return m_in_use; }
protected:
// number of bytes per block. The BitTorrent
// protocol defines the block size to 16 KiB.
const int m_block_size;
// number of disk buffers currently allocated
int m_in_use;
session_settings m_settings;
private:
// this only protects the pool allocator
typedef boost::mutex mutex_t;
mutable mutex_t m_pool_mutex;
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
// memory pool for read and write operations
// and disk cache
boost::pool<page_aligned_allocator> m_pool;
#endif
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
int m_allocations;
#endif
#ifdef TORRENT_DISK_STATS
protected:
void rename_buffer(char* buf, char const* category);
std::map<std::string, int> m_categories;
std::map<char*, std::string> m_buf_to_category;
std::ofstream m_log;
private:
#endif
#ifdef TORRENT_DEBUG
int m_magic;
#endif
};
// this is a singleton consisting of the thread and a queue
// of disk io jobs
struct disk_io_thread : disk_buffer_pool
{
disk_io_thread(io_service& ios, int block_size = 16 * 1024);
~disk_io_thread();
void join();
// aborts read operations
void stop(boost::intrusive_ptr<piece_manager> s);
void add_job(disk_io_job const& j
, boost::function<void(int, disk_io_job const&)> const& f
= boost::function<void(int, disk_io_job const&)>());
// keep track of the number of bytes in the job queue
// at any given time. i.e. the sum of all buffer_size.
// this is used to slow down the download global download
// speed when the queue buffer size is too big.
size_type queue_buffer_size() const
{ return m_queue_buffer_size; }
void get_cache_info(sha1_hash const& ih
, std::vector<cached_piece_info>& ret) const;
cache_status status() const;
void operator()();
#ifdef TORRENT_DEBUG
void check_invariant() const;
#endif
#ifdef TORRENT_DISK_STATS
std::ofstream m_disk_access_log;
#endif
struct cached_piece_entry
{
int piece;
// storage this piece belongs to
boost::intrusive_ptr<piece_manager> storage;
// the last time a block was writting to this piece
ptime last_use;
// the number of blocks in the cache for this piece
int num_blocks;
// the pointers to the block data
boost::shared_array<char*> blocks;
};
typedef boost::recursive_mutex mutex_t;
typedef std::list<cached_piece_entry> cache_t;
private:
bool test_error(disk_io_job& j);
void post_callback(boost::function<void(int, disk_io_job const&)> const& handler
, disk_io_job const& j, int ret);
// cache operations
cache_t::iterator find_cached_piece(
cache_t& cache, disk_io_job const& j
, mutex_t::scoped_lock& l);
int copy_from_piece(cache_t::iterator p, bool& hit
, disk_io_job const& j, mutex_t::scoped_lock& l);
// write cache operations
void flush_cache_blocks(mutex_t::scoped_lock& l, int blocks);
void flush_expired_pieces();
void flush_and_remove(cache_t::iterator i, mutex_t::scoped_lock& l);
int flush_contiguous_blocks(disk_io_thread::cache_t::iterator e
, mutex_t::scoped_lock& l);
void flush_range(cache_t::iterator i, int start, int end, mutex_t::scoped_lock& l);
void cache_block(disk_io_job& j, mutex_t::scoped_lock& l);
// read cache operations
int clear_oldest_read_piece(cache_t::iterator ignore
, mutex_t::scoped_lock& l);
int read_into_piece(cached_piece_entry& p, int start_block
, int options, mutex_t::scoped_lock& l);
int cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l);
int cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l);
int free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l);
bool make_room(int num_blocks
, cache_t::iterator ignore
, bool flush_write_cache
, mutex_t::scoped_lock& l);
int try_read_from_cache(disk_io_job const& j);
int read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h);
// this mutex only protects m_jobs, m_queue_buffer_size
// and m_abort
mutable mutex_t m_queue_mutex;
boost::condition m_signal;
bool m_abort;
bool m_waiting_to_shutdown;
std::list<disk_io_job> m_jobs;
size_type m_queue_buffer_size;
ptime m_last_file_check;
// this protects the piece cache and related members
mutable mutex_t m_piece_mutex;
// write cache
cache_t m_pieces;
// read cache
cache_t m_read_pieces;
// total number of blocks in use by both the read
// and the write cache. This is not supposed to
// exceed m_cache_size
cache_status m_cache_stats;
#ifdef TORRENT_DISK_STATS
std::ofstream m_log;
#endif
io_service& m_ios;
// this keeps the io_service::run() call blocked from
// returning. When shutting down, it's possible that
// the event queue is drained before the disk_io_thread
// has posted its last callback. When this happens, the
// io_service will have a pending callback from the
// disk_io_thread, but the event loop is not running.
// this means that the event is destructed after the
// disk_io_thread. If the event refers to a disk buffer
// it will try to free it, but the buffer pool won't
// exist anymore, and crash. This prevents that.
boost::optional<asio::io_service::work> m_work;
// thread for performing blocking disk io operations
boost::thread m_disk_io_thread;
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edredln.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:28:59 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#include "redline.hxx"
#include "doc.hxx"
#include "swundo.hxx"
#include "editsh.hxx"
#include "edimp.hxx"
#include "frmtool.hxx"
USHORT SwEditShell::GetRedlineMode() const
{
return GetDoc()->GetRedlineMode();
}
void SwEditShell::SetRedlineMode( USHORT eMode )
{
if( eMode != GetDoc()->GetRedlineMode() )
{
SET_CURR_SHELL( this );
StartAllAction();
GetDoc()->SetRedlineMode( eMode );
EndAllAction();
}
}
BOOL SwEditShell::IsRedlineOn() const
{
return GetDoc()->IsRedlineOn();
}
USHORT SwEditShell::GetRedlineCount() const
{
return GetDoc()->GetRedlineTbl().Count();
}
const SwRedline& SwEditShell::GetRedline( USHORT nPos ) const
{
return *GetDoc()->GetRedlineTbl()[ nPos ];
}
void lcl_InvalidateAll( ViewShell* pSh )
{
ViewShell *pStop = pSh;
do
{
if ( pSh->GetWin() )
pSh->GetWin()->Invalidate();
pSh = (ViewShell*)pSh->GetNext();
} while ( pSh != pStop );
}
BOOL SwEditShell::AcceptRedline( USHORT nPos )
{
SET_CURR_SHELL( this );
StartAllAction();
BOOL bRet = GetDoc()->AcceptRedline( nPos );
if( !nPos && !::IsExtraData( GetDoc() ) )
lcl_InvalidateAll( this );
EndAllAction();
return bRet;
}
BOOL SwEditShell::RejectRedline( USHORT nPos )
{
SET_CURR_SHELL( this );
StartAllAction();
BOOL bRet = GetDoc()->RejectRedline( nPos );
if( !nPos && !::IsExtraData( GetDoc() ) )
lcl_InvalidateAll( this );
EndAllAction();
return bRet;
}
// Kommentar am Redline setzen
BOOL SwEditShell::SetRedlineComment( const String& rS )
{
BOOL bRet = FALSE;
FOREACHPAM_START(this)
bRet = bRet || GetDoc()->SetRedlineComment( *PCURCRSR, rS );
FOREACHPAM_END()
return bRet;
}
const SwRedline* SwEditShell::GetCurrRedline() const
{
return GetDoc()->GetRedline( *GetCrsr()->GetPoint() );
}
void SwEditShell::UpdateRedlineAttr()
{
if( ( REDLINE_SHOW_INSERT | REDLINE_SHOW_DELETE ) ==
( REDLINE_SHOW_MASK & GetDoc()->GetRedlineMode() ))
{
SET_CURR_SHELL( this );
StartAllAction();
GetDoc()->UpdateRedlineAttr();
EndAllAction();
}
}
// suche das Redline zu diesem Data und returne die Pos im Array
// USHRT_MAX wird returnt, falls nicht vorhanden
USHORT SwEditShell::FindRedlineOfData( const SwRedlineData& rData ) const
{
const SwRedlineTbl& rTbl = GetDoc()->GetRedlineTbl();
for( USHORT i = 0, nCnt = rTbl.Count(); i < nCnt; ++i )
if( &rTbl[ i ]->GetRedlineData() == &rData )
return i;
return USHRT_MAX;
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.3.466); FILE MERGED 2005/09/13 13:35:03 tra 1.3.466.2: RESYNC: (1.3-1.4); FILE MERGED 2005/08/31 12:50:52 tra 1.3.466.1: #i50348# Introducing IDocumentRedlineAccess interface<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edredln.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:09:49 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#include "redline.hxx"
#include "doc.hxx"
#include "swundo.hxx"
#include "editsh.hxx"
#include "edimp.hxx"
#include "frmtool.hxx"
USHORT SwEditShell::GetRedlineMode() const
{
return GetDoc()->GetRedlineMode();
}
void SwEditShell::SetRedlineMode( USHORT eMode )
{
if( eMode != GetDoc()->GetRedlineMode() )
{
SET_CURR_SHELL( this );
StartAllAction();
GetDoc()->SetRedlineMode( eMode );
EndAllAction();
}
}
BOOL SwEditShell::IsRedlineOn() const
{
return GetDoc()->IsRedlineOn();
}
USHORT SwEditShell::GetRedlineCount() const
{
return GetDoc()->GetRedlineTbl().Count();
}
const SwRedline& SwEditShell::GetRedline( USHORT nPos ) const
{
return *GetDoc()->GetRedlineTbl()[ nPos ];
}
void lcl_InvalidateAll( ViewShell* pSh )
{
ViewShell *pStop = pSh;
do
{
if ( pSh->GetWin() )
pSh->GetWin()->Invalidate();
pSh = (ViewShell*)pSh->GetNext();
} while ( pSh != pStop );
}
BOOL SwEditShell::AcceptRedline( USHORT nPos )
{
SET_CURR_SHELL( this );
StartAllAction();
BOOL bRet = GetDoc()->AcceptRedline( nPos, true );
if( !nPos && !::IsExtraData( GetDoc() ) )
lcl_InvalidateAll( this );
EndAllAction();
return bRet;
}
BOOL SwEditShell::RejectRedline( USHORT nPos )
{
SET_CURR_SHELL( this );
StartAllAction();
BOOL bRet = GetDoc()->RejectRedline( nPos, true );
if( !nPos && !::IsExtraData( GetDoc() ) )
lcl_InvalidateAll( this );
EndAllAction();
return bRet;
}
// Kommentar am Redline setzen
BOOL SwEditShell::SetRedlineComment( const String& rS )
{
BOOL bRet = FALSE;
FOREACHPAM_START(this)
bRet = bRet || GetDoc()->SetRedlineComment( *PCURCRSR, rS );
FOREACHPAM_END()
return bRet;
}
const SwRedline* SwEditShell::GetCurrRedline() const
{
return GetDoc()->GetRedline( *GetCrsr()->GetPoint(), 0 );
}
void SwEditShell::UpdateRedlineAttr()
{
if( ( IDocumentRedlineAccess::REDLINE_SHOW_INSERT | IDocumentRedlineAccess::REDLINE_SHOW_DELETE ) ==
( IDocumentRedlineAccess::REDLINE_SHOW_MASK & GetDoc()->GetRedlineMode() ))
{
SET_CURR_SHELL( this );
StartAllAction();
GetDoc()->UpdateRedlineAttr();
EndAllAction();
}
}
// suche das Redline zu diesem Data und returne die Pos im Array
// USHRT_MAX wird returnt, falls nicht vorhanden
USHORT SwEditShell::FindRedlineOfData( const SwRedlineData& rData ) const
{
const SwRedlineTbl& rTbl = GetDoc()->GetRedlineTbl();
for( USHORT i = 0, nCnt = rTbl.Count(); i < nCnt; ++i )
if( &rTbl[ i ]->GetRedlineData() == &rData )
return i;
return USHRT_MAX;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#include <vector>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"
namespace libtorrent
{
namespace aux
{
struct session_impl;
struct checker_impl;
}
struct TORRENT_EXPORT duplicate_torrent: std::exception
{
virtual const char* what() const throw()
{ return "torrent already exists in session"; }
};
struct TORRENT_EXPORT invalid_handle: std::exception
{
virtual const char* what() const throw()
{ return "invalid torrent handle used"; }
};
struct TORRENT_EXPORT torrent_status
{
torrent_status()
: state(queued_for_checking)
, paused(false)
, progress(0.f)
, total_download(0)
, total_upload(0)
, total_payload_download(0)
, total_payload_upload(0)
, total_failed_bytes(0)
, total_redundant_bytes(0)
, download_rate(0)
, upload_rate(0)
, download_payload_rate(0)
, upload_payload_rate(0)
, num_peers(0)
, num_complete(-1)
, num_incomplete(-1)
, pieces(0)
, num_pieces(0)
, total_done(0)
, total_wanted_done(0)
, total_wanted(0)
, num_seeds(0)
, distributed_copies(0.f)
, block_size(0)
{}
enum state_t
{
queued_for_checking,
checking_files,
connecting_to_tracker,
downloading_metadata,
downloading,
finished,
seeding,
allocating
};
state_t state;
bool paused;
float progress;
boost::posix_time::time_duration next_announce;
boost::posix_time::time_duration announce_interval;
std::string current_tracker;
// transferred this session!
// total, payload plus protocol
size_type total_download;
size_type total_upload;
// payload only
size_type total_payload_download;
size_type total_payload_upload;
// the amount of payload bytes that
// has failed their hash test
size_type total_failed_bytes;
// the number of payload bytes that
// has been received redundantly.
size_type total_redundant_bytes;
// current transfer rate
// payload plus protocol
float download_rate;
float upload_rate;
// the rate of payload that is
// sent and received
float download_payload_rate;
float upload_payload_rate;
// the number of peers this torrent
// is connected to.
int num_peers;
// if the tracker sends scrape info in its
// announce reply, these fields will be
// set to the total number of peers that
// have the whole file and the total number
// of peers that are still downloading
int num_complete;
int num_incomplete;
const std::vector<bool>* pieces;
// this is the number of pieces the client has
// downloaded. it is equal to:
// std::accumulate(pieces->begin(), pieces->end());
int num_pieces;
// the number of bytes of the file we have
// including pieces that may have been filtered
// after we downloaded them
size_type total_done;
// the number of bytes we have of those that we
// want. i.e. not counting bytes from pieces that
// are filtered as not wanted.
size_type total_wanted_done;
// the total number of bytes we want to download
// this may be smaller than the total torrent size
// in case any pieces are filtered as not wanted
size_type total_wanted;
// the number of peers this torrent is connected to
// that are seeding.
int num_seeds;
// the number of distributed copies of the file.
// note that one copy may be spread out among many peers.
//
// the whole number part tells how many copies
// there are of the rarest piece(s)
//
// the fractional part tells the fraction of pieces that
// have more copies than the rarest piece(s).
float distributed_copies;
// the block size that is used in this torrent. i.e.
// the number of bytes each piece request asks for
// and each bit in the download queue bitfield represents
int block_size;
};
struct TORRENT_EXPORT partial_piece_info
{
enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
int piece_index;
int blocks_in_piece;
std::bitset<max_blocks_per_piece> requested_blocks;
std::bitset<max_blocks_per_piece> finished_blocks;
tcp::endpoint peer[max_blocks_per_piece];
int num_downloads[max_blocks_per_piece];
};
struct TORRENT_EXPORT torrent_handle
{
friend class invariant_access;
friend class aux::session_impl;
friend class torrent;
torrent_handle(): m_ses(0), m_chk(0) {}
void get_peer_info(std::vector<peer_info>& v) const;
bool send_chat_message(tcp::endpoint ip, std::string message) const;
torrent_status status() const;
void get_download_queue(std::vector<partial_piece_info>& queue) const;
// fills the specified vector with the download progress [0, 1]
// of each file in the torrent. The files are ordered as in
// the torrent_info.
void file_progress(std::vector<float>& progress);
std::vector<announce_entry> const& trackers() const;
void replace_trackers(std::vector<announce_entry> const&) const;
void add_url_seed(std::string const& url);
bool has_metadata() const;
const torrent_info& get_torrent_info() const;
bool is_valid() const;
bool is_seed() const;
bool is_paused() const;
void pause() const;
void resume() const;
// marks the piece with the given index as filtered
// it will not be downloaded
void filter_piece(int index, bool filter) const;
void filter_pieces(std::vector<bool> const& pieces) const;
bool is_piece_filtered(int index) const;
std::vector<bool> filtered_pieces() const;
// marks the file with the given index as filtered
// it will not be downloaded
void filter_files(std::vector<bool> const& files) const;
// set the interface to bind outgoing connections
// to.
void use_interface(const char* net_interface) const;
entry write_resume_data() const;
// kind of similar to get_torrent_info() but this
// is lower level, returning the exact info-part of
// the .torrent file. When hashed, this buffer
// will produce the info hash. The reference is valid
// only as long as the torrent is running.
std::vector<char> const& metadata() const;
// forces this torrent to reannounce
// (make a rerequest from the tracker)
void force_reannounce() const;
// forces a reannounce in the specified amount of time.
// This overrides the default announce interval, and no
// announce will take place until the given time has
// timed out.
void force_reannounce(boost::posix_time::time_duration) const;
// TODO: add a feature where the user can tell the torrent
// to finish all pieces currently in the pipeline, and then
// abort the torrent.
void set_upload_limit(int limit) const;
void set_download_limit(int limit) const;
void set_sequenced_download_threshold(int threshold) const;
void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
void set_peer_download_limit(tcp::endpoint ip, int limit) const;
// manually connect a peer
void connect_peer(tcp::endpoint const& adr) const;
// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
// the ratio is uploaded / downloaded. less than 1 is not allowed
void set_ratio(float up_down_ratio) const;
boost::filesystem::path save_path() const;
// -1 means unlimited unchokes
void set_max_uploads(int max_uploads) const;
// -1 means unlimited connections
void set_max_connections(int max_connections) const;
void set_tracker_login(std::string const& name
, std::string const& password) const;
// post condition: save_path() == save_path if true is returned
bool move_storage(boost::filesystem::path const& save_path) const;
const sha1_hash& info_hash() const
{ return m_info_hash; }
bool operator==(const torrent_handle& h) const
{ return m_info_hash == h.m_info_hash; }
bool operator!=(const torrent_handle& h) const
{ return m_info_hash != h.m_info_hash; }
bool operator<(const torrent_handle& h) const
{ return m_info_hash < h.m_info_hash; }
private:
torrent_handle(aux::session_impl* s,
aux::checker_impl* c,
const sha1_hash& h)
: m_ses(s)
, m_chk(c)
, m_info_hash(h)
{
assert(m_ses != 0);
}
#ifndef NDEBUG
void check_invariant() const;
#endif
aux::session_impl* m_ses;
aux::checker_impl* m_chk;
sha1_hash m_info_hash;
};
}
#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<commit_msg>fixed warning on msvc8<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#include <vector>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"
namespace libtorrent
{
namespace aux
{
struct session_impl;
struct checker_impl;
}
struct TORRENT_EXPORT duplicate_torrent: std::exception
{
virtual const char* what() const throw()
{ return "torrent already exists in session"; }
};
struct TORRENT_EXPORT invalid_handle: std::exception
{
virtual const char* what() const throw()
{ return "invalid torrent handle used"; }
};
struct TORRENT_EXPORT torrent_status
{
torrent_status()
: state(queued_for_checking)
, paused(false)
, progress(0.f)
, total_download(0)
, total_upload(0)
, total_payload_download(0)
, total_payload_upload(0)
, total_failed_bytes(0)
, total_redundant_bytes(0)
, download_rate(0)
, upload_rate(0)
, download_payload_rate(0)
, upload_payload_rate(0)
, num_peers(0)
, num_complete(-1)
, num_incomplete(-1)
, pieces(0)
, num_pieces(0)
, total_done(0)
, total_wanted_done(0)
, total_wanted(0)
, num_seeds(0)
, distributed_copies(0.f)
, block_size(0)
{}
enum state_t
{
queued_for_checking,
checking_files,
connecting_to_tracker,
downloading_metadata,
downloading,
finished,
seeding,
allocating
};
state_t state;
bool paused;
float progress;
boost::posix_time::time_duration next_announce;
boost::posix_time::time_duration announce_interval;
std::string current_tracker;
// transferred this session!
// total, payload plus protocol
size_type total_download;
size_type total_upload;
// payload only
size_type total_payload_download;
size_type total_payload_upload;
// the amount of payload bytes that
// has failed their hash test
size_type total_failed_bytes;
// the number of payload bytes that
// has been received redundantly.
size_type total_redundant_bytes;
// current transfer rate
// payload plus protocol
float download_rate;
float upload_rate;
// the rate of payload that is
// sent and received
float download_payload_rate;
float upload_payload_rate;
// the number of peers this torrent
// is connected to.
int num_peers;
// if the tracker sends scrape info in its
// announce reply, these fields will be
// set to the total number of peers that
// have the whole file and the total number
// of peers that are still downloading
int num_complete;
int num_incomplete;
const std::vector<bool>* pieces;
// this is the number of pieces the client has
// downloaded. it is equal to:
// std::accumulate(pieces->begin(), pieces->end());
int num_pieces;
// the number of bytes of the file we have
// including pieces that may have been filtered
// after we downloaded them
size_type total_done;
// the number of bytes we have of those that we
// want. i.e. not counting bytes from pieces that
// are filtered as not wanted.
size_type total_wanted_done;
// the total number of bytes we want to download
// this may be smaller than the total torrent size
// in case any pieces are filtered as not wanted
size_type total_wanted;
// the number of peers this torrent is connected to
// that are seeding.
int num_seeds;
// the number of distributed copies of the file.
// note that one copy may be spread out among many peers.
//
// the whole number part tells how many copies
// there are of the rarest piece(s)
//
// the fractional part tells the fraction of pieces that
// have more copies than the rarest piece(s).
float distributed_copies;
// the block size that is used in this torrent. i.e.
// the number of bytes each piece request asks for
// and each bit in the download queue bitfield represents
int block_size;
};
struct TORRENT_EXPORT partial_piece_info
{
enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
int piece_index;
int blocks_in_piece;
std::bitset<max_blocks_per_piece> requested_blocks;
std::bitset<max_blocks_per_piece> finished_blocks;
tcp::endpoint peer[max_blocks_per_piece];
int num_downloads[max_blocks_per_piece];
};
struct TORRENT_EXPORT torrent_handle
{
friend class invariant_access;
friend struct aux::session_impl;
friend class torrent;
torrent_handle(): m_ses(0), m_chk(0) {}
void get_peer_info(std::vector<peer_info>& v) const;
bool send_chat_message(tcp::endpoint ip, std::string message) const;
torrent_status status() const;
void get_download_queue(std::vector<partial_piece_info>& queue) const;
// fills the specified vector with the download progress [0, 1]
// of each file in the torrent. The files are ordered as in
// the torrent_info.
void file_progress(std::vector<float>& progress);
std::vector<announce_entry> const& trackers() const;
void replace_trackers(std::vector<announce_entry> const&) const;
void add_url_seed(std::string const& url);
bool has_metadata() const;
const torrent_info& get_torrent_info() const;
bool is_valid() const;
bool is_seed() const;
bool is_paused() const;
void pause() const;
void resume() const;
// marks the piece with the given index as filtered
// it will not be downloaded
void filter_piece(int index, bool filter) const;
void filter_pieces(std::vector<bool> const& pieces) const;
bool is_piece_filtered(int index) const;
std::vector<bool> filtered_pieces() const;
// marks the file with the given index as filtered
// it will not be downloaded
void filter_files(std::vector<bool> const& files) const;
// set the interface to bind outgoing connections
// to.
void use_interface(const char* net_interface) const;
entry write_resume_data() const;
// kind of similar to get_torrent_info() but this
// is lower level, returning the exact info-part of
// the .torrent file. When hashed, this buffer
// will produce the info hash. The reference is valid
// only as long as the torrent is running.
std::vector<char> const& metadata() const;
// forces this torrent to reannounce
// (make a rerequest from the tracker)
void force_reannounce() const;
// forces a reannounce in the specified amount of time.
// This overrides the default announce interval, and no
// announce will take place until the given time has
// timed out.
void force_reannounce(boost::posix_time::time_duration) const;
// TODO: add a feature where the user can tell the torrent
// to finish all pieces currently in the pipeline, and then
// abort the torrent.
void set_upload_limit(int limit) const;
void set_download_limit(int limit) const;
void set_sequenced_download_threshold(int threshold) const;
void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
void set_peer_download_limit(tcp::endpoint ip, int limit) const;
// manually connect a peer
void connect_peer(tcp::endpoint const& adr) const;
// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
// the ratio is uploaded / downloaded. less than 1 is not allowed
void set_ratio(float up_down_ratio) const;
boost::filesystem::path save_path() const;
// -1 means unlimited unchokes
void set_max_uploads(int max_uploads) const;
// -1 means unlimited connections
void set_max_connections(int max_connections) const;
void set_tracker_login(std::string const& name
, std::string const& password) const;
// post condition: save_path() == save_path if true is returned
bool move_storage(boost::filesystem::path const& save_path) const;
const sha1_hash& info_hash() const
{ return m_info_hash; }
bool operator==(const torrent_handle& h) const
{ return m_info_hash == h.m_info_hash; }
bool operator!=(const torrent_handle& h) const
{ return m_info_hash != h.m_info_hash; }
bool operator<(const torrent_handle& h) const
{ return m_info_hash < h.m_info_hash; }
private:
torrent_handle(aux::session_impl* s,
aux::checker_impl* c,
const sha1_hash& h)
: m_ses(s)
, m_chk(c)
, m_info_hash(h)
{
assert(m_ses != 0);
}
#ifndef NDEBUG
void check_invariant() const;
#endif
aux::session_impl* m_ses;
aux::checker_impl* m_chk;
sha1_hash m_info_hash;
};
}
#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: swblocks.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2004-08-12 12:28:45 $
*
* 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 _SWBLOCKS_HXX
#define _SWBLOCKS_HXX
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif
#ifndef _PERSIST_HXX //autogen
#include <so3/persist.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class SfxMedium;
class SwPaM;
class SwDoc;
class SvxMacroTableDtor;
class SvXMLTextBlocks;
// Name eines Textblocks:
class SwBlockName
{
friend class SwImpBlocks;
friend class Sw2TextBlocks;
USHORT nHashS, nHashL; // Hash-Codes zum Checken
long nPos; // Dateiposition (SW2-Format)
public:
String aShort; // Short name
String aLong; // Long name
String aPackageName; // Package name
BOOL bIsOnlyTxtFlagInit : 1; // ist das Flag gueltig?
BOOL bIsOnlyTxt : 1; // unformatted text
BOOL bInPutMuchBlocks : 1; // put serveral block entries
SwBlockName( const String& rShort, const String& rLong, long n );
SwBlockName( const String& rShort, const String& rLong, const String& rPackageName );
// fuer das Einsortieren in das Array
int operator==( const SwBlockName& r ) { return aShort == r.aShort; }
int operator< ( const SwBlockName& r ) { return aShort < r.aShort; }
};
SV_DECL_PTRARR_SORT( SwBlockNames, SwBlockName*, 10, 10 );
class SwImpBlocks
{
friend class SwTextBlocks;
protected:
String aFile; // physikalischer Dateiname
String aName; // logischer Name der Datei
String aCur; // aktueller Text
String aShort, aLong; // Kurz- und Langname (PutDoc)
SwBlockNames aNames; // Liste aller Bausteine
Date aDateModified; // fuers abgleichen bei den Aktionen
Time aTimeModified;
SwDoc* pDoc; // Austauschdokument
USHORT nCur; // aktueller Index
BOOL bReadOnly : 1;
BOOL bInPutMuchBlocks : 1; // put serveral block entries
BOOL bInfoChanged : 1; // any Info of TextBlock is changed
SwImpBlocks( const String&, BOOL = FALSE );
virtual ~SwImpBlocks();
static short GetFileType( const String& );
virtual short GetFileType() const = 0;
#define SWBLK_NO_FILE 0 // nicht da
#define SWBLK_NONE 1 // keine TB-Datei
#define SWBLK_SW2 2 // SW2-Datei
#define SWBLK_SW3 3 // SW3-Datei
#define SWBLK_XML 4 // XML Block List
virtual void ClearDoc(); // Doc-Inhalt loeschen
SwPaM* MakePaM(); // PaM ueber Doc aufspannen
virtual void AddName( const String&, const String&, BOOL bOnlyTxt = FALSE );
BOOL IsFileChanged() const;
void Touch();
public:
static USHORT Hash( const String& ); // Hashcode fuer Blocknamen
USHORT GetCount() const; // Anzahl Textbausteine ermitteln
USHORT GetIndex( const String& ) const; // Index fuer Kurznamen ermitteln
USHORT GetLongIndex( const String& ) const; //Index fuer Langnamen ermitteln
const String& GetShortName( USHORT ) const; // Kurzname fuer Index zurueck
const String& GetLongName( USHORT ) const; // Langname fuer Index zurueck
const String& GetPackageName( USHORT ) const; // Langname fuer Index zurueck
const String& GetFileName() const {return aFile;} // phys. Dateinamen liefern
void SetName( const String& rName ) // logic name
{ aName = rName; bInfoChanged = TRUE; }
const String & GetName( void )
{ return aName; }
virtual ULONG Delete( USHORT ) = 0;
virtual ULONG Rename( USHORT, const String&, const String& ) = 0;
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong) = 0;
virtual ULONG GetDoc( USHORT ) = 0;
virtual ULONG GetDocForConversion( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& ) = 0;
virtual ULONG PutDoc() = 0;
virtual ULONG GetText( USHORT, String& ) = 0;
virtual ULONG PutText( const String&, const String&, const String& ) = 0;
virtual ULONG MakeBlockList() = 0;
virtual ULONG OpenFile( BOOL bReadOnly = TRUE ) = 0;
virtual void CloseFile() = 0;
virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
virtual ULONG GetMacroTable( USHORT nIdx, SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual ULONG SetMacroTable( USHORT nIdx,
const SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual BOOL PutMuchEntries( BOOL bOn );
};
class Sw3Persist : public SvPersist
{
virtual void FillClass( SvGlobalName * pClassName,
ULONG * pClipFormat,
String * pAppName,
String * pLongUserName,
String * pUserName,
long nFileFormat=SOFFICE_FILEFORMAT_CURRENT ) const;
virtual BOOL Save();
virtual BOOL SaveCompleted( SvStorage * );
public:
Sw3Persist();
};
class SwSwgReader;
class Sw2TextBlocks : public SwImpBlocks
{
SvPersistRef refPersist; // Fuer OLE-Objekte
SwSwgReader* pRdr; // Lese-Routinen
SfxMedium* pMed; // der logische Input-Stream
String* pText; // String fuer GetText()
long nDocStart; // Beginn des Doc-Records
long nDocSize; // Laenge des Doc-Records
long nStart; // Beginn des CONTENTS-Records
long nSize; // Laenge des CONTENTS-Records
USHORT nNamedFmts; // benannte Formate
USHORT nColls; // Text-Collections
USHORT nBlks; // Anzahl Elemente im CONTENTS-Record
public:
Sw2TextBlocks( const String& );
virtual ~Sw2TextBlocks();
virtual ULONG Delete( USHORT );
virtual ULONG Rename( USHORT, const String&, const String& );
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
virtual ULONG GetDoc( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& );
virtual ULONG PutDoc();
virtual ULONG GetText( USHORT, String& );
virtual ULONG PutText( const String&, const String&, const String& );
virtual ULONG MakeBlockList();
virtual short GetFileType( ) const;
ULONG LoadDoc();
virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
virtual void CloseFile();
void StatLineStartPercent(); // zum Anzeigen des Prozessbars
};
class Sw3Io;
class Sw3IoImp;
class Sw3TextBlocks : public SwImpBlocks
{
Sw3Io* pIo3;
Sw3IoImp* pImp;
BOOL bAutocorrBlock;
public:
Sw3TextBlocks( const String& );
Sw3TextBlocks( SvStorage& );
virtual ~Sw3TextBlocks();
virtual ULONG Delete( USHORT );
virtual ULONG Rename( USHORT, const String&, const String& );
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
virtual ULONG GetDoc( USHORT );
virtual ULONG GetDocForConversion( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& );
virtual ULONG PutDoc();
virtual void SetDoc( SwDoc * pNewDoc);
virtual ULONG GetText( USHORT, String& );
virtual ULONG PutText( const String&, const String&, const String& );
virtual ULONG MakeBlockList();
virtual short GetFileType( ) const;
virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
virtual void CloseFile();
// Methoden fuer die neue Autokorrektur
ULONG GetText( const String& rShort, String& );
SwDoc* GetDoc() const { return pDoc; }
virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
virtual ULONG GetMacroTable( USHORT, SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual ULONG SetMacroTable( USHORT nIdx,
const SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
void ReadInfo();
};
#endif
<commit_msg>INTEGRATION: CWS mav09 (1.9.690); FILE MERGED 2004/09/16 19:47:08 mav 1.9.690.4: RESYNC: (1.9-1.10); FILE MERGED 2004/08/12 17:23:24 mav 1.9.690.3: #i27773# introduce version back 2004/07/15 13:04:40 mba 1.9.690.2: #i27773#: cleaning up todos: scaling in inplace mode, update chart after resizing and some more 2004/05/18 16:48:16 mba 1.9.690.1: RESYNC to m39<commit_after>/*************************************************************************
*
* $RCSfile: swblocks.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2004-10-04 19:08:08 $
*
* 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 _SWBLOCKS_HXX
#define _SWBLOCKS_HXX
#ifndef _DATE_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class SfxMedium;
class SwPaM;
class SwDoc;
class SvxMacroTableDtor;
class SvXMLTextBlocks;
// Name eines Textblocks:
class SwBlockName
{
friend class SwImpBlocks;
friend class Sw2TextBlocks;
USHORT nHashS, nHashL; // Hash-Codes zum Checken
long nPos; // Dateiposition (SW2-Format)
public:
String aShort; // Short name
String aLong; // Long name
String aPackageName; // Package name
BOOL bIsOnlyTxtFlagInit : 1; // ist das Flag gueltig?
BOOL bIsOnlyTxt : 1; // unformatted text
BOOL bInPutMuchBlocks : 1; // put serveral block entries
SwBlockName( const String& rShort, const String& rLong, long n );
SwBlockName( const String& rShort, const String& rLong, const String& rPackageName );
// fuer das Einsortieren in das Array
int operator==( const SwBlockName& r ) { return aShort == r.aShort; }
int operator< ( const SwBlockName& r ) { return aShort < r.aShort; }
};
SV_DECL_PTRARR_SORT( SwBlockNames, SwBlockName*, 10, 10 );
class SwImpBlocks
{
friend class SwTextBlocks;
protected:
String aFile; // physikalischer Dateiname
String aName; // logischer Name der Datei
String aCur; // aktueller Text
String aShort, aLong; // Kurz- und Langname (PutDoc)
SwBlockNames aNames; // Liste aller Bausteine
Date aDateModified; // fuers abgleichen bei den Aktionen
Time aTimeModified;
SwDoc* pDoc; // Austauschdokument
USHORT nCur; // aktueller Index
BOOL bReadOnly : 1;
BOOL bInPutMuchBlocks : 1; // put serveral block entries
BOOL bInfoChanged : 1; // any Info of TextBlock is changed
SwImpBlocks( const String&, BOOL = FALSE );
virtual ~SwImpBlocks();
static short GetFileType( const String& );
virtual short GetFileType() const = 0;
#define SWBLK_NO_FILE 0 // nicht da
#define SWBLK_NONE 1 // keine TB-Datei
#define SWBLK_SW2 2 // SW2-Datei
#define SWBLK_SW3 3 // SW3-Datei
#define SWBLK_XML 4 // XML Block List
virtual void ClearDoc(); // Doc-Inhalt loeschen
SwPaM* MakePaM(); // PaM ueber Doc aufspannen
virtual void AddName( const String&, const String&, BOOL bOnlyTxt = FALSE );
BOOL IsFileChanged() const;
void Touch();
public:
static USHORT Hash( const String& ); // Hashcode fuer Blocknamen
USHORT GetCount() const; // Anzahl Textbausteine ermitteln
USHORT GetIndex( const String& ) const; // Index fuer Kurznamen ermitteln
USHORT GetLongIndex( const String& ) const; //Index fuer Langnamen ermitteln
const String& GetShortName( USHORT ) const; // Kurzname fuer Index zurueck
const String& GetLongName( USHORT ) const; // Langname fuer Index zurueck
const String& GetPackageName( USHORT ) const; // Langname fuer Index zurueck
const String& GetFileName() const {return aFile;} // phys. Dateinamen liefern
void SetName( const String& rName ) // logic name
{ aName = rName; bInfoChanged = TRUE; }
const String & GetName( void )
{ return aName; }
virtual ULONG Delete( USHORT ) = 0;
virtual ULONG Rename( USHORT, const String&, const String& ) = 0;
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong) = 0;
virtual ULONG GetDoc( USHORT ) = 0;
virtual ULONG GetDocForConversion( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& ) = 0;
virtual ULONG PutDoc() = 0;
virtual ULONG GetText( USHORT, String& ) = 0;
virtual ULONG PutText( const String&, const String&, const String& ) = 0;
virtual ULONG MakeBlockList() = 0;
virtual ULONG OpenFile( BOOL bReadOnly = TRUE ) = 0;
virtual void CloseFile() = 0;
virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
virtual ULONG GetMacroTable( USHORT nIdx, SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual ULONG SetMacroTable( USHORT nIdx,
const SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual BOOL PutMuchEntries( BOOL bOn );
};
/*
class Sw3Persist : public SvPersist
{
virtual void FillClass( SvGlobalName * pClassName,
ULONG * pClipFormat,
String * pAppName,
String * pLongUserName,
String * pUserName,
sal_Int32 nFileFormat=SOFFICE_FILEFORMAT_CURRENT ) const;
virtual BOOL Save();
virtual BOOL SaveCompleted( SvStorage * );
public:
Sw3Persist();
};
class SwSwgReader;
class Sw2TextBlocks : public SwImpBlocks
{
SvPersistRef refPersist; // Fuer OLE-Objekte
SwSwgReader* pRdr; // Lese-Routinen
SfxMedium* pMed; // der logische Input-Stream
String* pText; // String fuer GetText()
long nDocStart; // Beginn des Doc-Records
long nDocSize; // Laenge des Doc-Records
long nStart; // Beginn des CONTENTS-Records
long nSize; // Laenge des CONTENTS-Records
USHORT nNamedFmts; // benannte Formate
USHORT nColls; // Text-Collections
USHORT nBlks; // Anzahl Elemente im CONTENTS-Record
public:
Sw2TextBlocks( const String& );
virtual ~Sw2TextBlocks();
virtual ULONG Delete( USHORT );
virtual ULONG Rename( USHORT, const String&, const String& );
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
virtual ULONG GetDoc( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& );
virtual ULONG PutDoc();
virtual ULONG GetText( USHORT, String& );
virtual ULONG PutText( const String&, const String&, const String& );
virtual ULONG MakeBlockList();
virtual short GetFileType( ) const;
ULONG LoadDoc();
virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
virtual void CloseFile();
void StatLineStartPercent(); // zum Anzeigen des Prozessbars
};
class Sw3Io;
class Sw3IoImp;
class Sw3TextBlocks : public SwImpBlocks
{
Sw3Io* pIo3;
Sw3IoImp* pImp;
BOOL bAutocorrBlock;
public:
Sw3TextBlocks( const String& );
Sw3TextBlocks( SvStorage& );
virtual ~Sw3TextBlocks();
virtual ULONG Delete( USHORT );
virtual ULONG Rename( USHORT, const String&, const String& );
virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
virtual ULONG GetDoc( USHORT );
virtual ULONG GetDocForConversion( USHORT );
virtual ULONG BeginPutDoc( const String&, const String& );
virtual ULONG PutDoc();
virtual void SetDoc( SwDoc * pNewDoc);
virtual ULONG GetText( USHORT, String& );
virtual ULONG PutText( const String&, const String&, const String& );
virtual ULONG MakeBlockList();
virtual short GetFileType( ) const;
virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
virtual void CloseFile();
// Methoden fuer die neue Autokorrektur
ULONG GetText( const String& rShort, String& );
SwDoc* GetDoc() const { return pDoc; }
virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
virtual ULONG GetMacroTable( USHORT, SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
virtual ULONG SetMacroTable( USHORT nIdx,
const SvxMacroTableDtor& rMacroTbl,
sal_Bool bFileAlreadyOpen = sal_False );
void ReadInfo();
};
*/
#endif
<|endoftext|> |
<commit_before>/*
Copyright 2011 StormMQ Limited
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 <TestHarness.h>
#include "Transport/Connection/ConnectionTestSupport.h"
#include "debug_helper.h"
SUITE(Connection)
{
class ConnectionFixture : public BrokerUsingFixture
{
public:
ConnectionFixture();
ConnectionFixture(amqp_connection_test_hook_t *test_hooks);
~ConnectionFixture();
void cleanup_connection();
public:
};
ConnectionFixture::ConnectionFixture()
{
connection = amqp_connection_create(context);
setup_stop_hook();
}
ConnectionFixture::ConnectionFixture(amqp_connection_test_hook_t *test_hooks) : BrokerUsingFixture(test_hooks)
{
connection = amqp_connection_create(context);
setup_stop_hook();
}
ConnectionFixture::~ConnectionFixture()
{
amqp_connection_destroy(context, connection);
}
void ConnectionFixture::cleanup_connection()
{
amqp_connection_shutdown(context, connection);
while (amqp_connection_is_running(connection) && run_loop_with_timeout());
CHECK(!amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
}
TEST_FIXTURE(ConnectionFixture, fixture_should_balance_allocations)
{
}
TEST_FIXTURE(ConnectionFixture, limits_should_be_initialized)
{
CHECK_EQUAL(AMQP_DEFAULT_MAX_FRAME_SIZE, connection->amqp.connection.limits.max_frame_size);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_socket_link)
{
CHECK_EQUAL("initialized", connection->state.writer.name);
CHECK_EQUAL("initialized", connection->state.reader.name);
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
CHECK(amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
loop_while_socket_state_is("Connecting");
CHECK(amqp_connection_is(connection, AMQP_CONNECTION_SOCKET_CONNECTED));
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK(!amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
}
class ConnectionHookFixture : public ConnectionFixture
{
public:
ConnectionHookFixture() : ConnectionFixture(ConnectionHookFixture::hooks()) { }
~ConnectionHookFixture() { }
static void post_initialise_hook(amqp_connection_t *connection);
static amqp_connection_test_hook_t *hooks();
public:
};
void ConnectionHookFixture::post_initialise_hook(amqp_connection_t *connection)
{
connection->context->debug.level = 0;
connection->specification_version.required.sasl = AMQP_PROTOCOL_VERSION(AMQP_SASL_PROTOCOL_ID, 2, 0, 0);
connection->specification_version.required.amqp = AMQP_PROTOCOL_VERSION(AMQP_PROTOCOL_ID, 1, 1, 0);
}
amqp_connection_test_hook_t *ConnectionHookFixture::hooks()
{
static amqp_connection_test_hook_t hooks = {
ConnectionHookFixture::post_initialise_hook
};
return &hooks;
}
TEST_FIXTURE(ConnectionHookFixture, connection_should_reject_sasl_version)
{
context->debug.level = 0;
connection->protocols = AMQP_PROTOCOL_SASL | AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
loop_while_connection_state_is("DrainingInput");
CHECK_EQUAL("Stopped", connection->state.connection.name); // TODO - Should it be Failed
loop_while_running();
CHECK(connection->failure_flags & AMQP_CONNECTION_SASL_NEGOTIATION_REJECTED);
}
TEST_FIXTURE(ConnectionHookFixture, connection_should_reject_amqp_version)
{
context->debug.level = 0;
connection->protocols = AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingAmqp");
loop_while_connection_state_is("DrainingInput");
CHECK_EQUAL("Stopped", connection->state.connection.name); // TODO - Should it be Failed
CHECK(connection->failure_flags & AMQP_CONNECTION_AMQP_NEGOTIATION_REJECTED);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_sasl_tunnel)
{
connection->protocols = AMQP_PROTOCOL_SASL | AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
CHECK_EQUAL("ConnectingAmqp", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK_EQUAL("Stopped", connection->state.connection.name);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_amqp_tunnel)
{
connection->protocols = AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingAmqp");
CHECK_EQUAL("AqmpTunnelEstablished", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK_EQUAL("Stopped", connection->state.connection.name);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_sasl_and_amqp_tunnels)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
loop_while_connection_state_is("ConnectingAmqp");
CHECK_EQUAL("AqmpTunnelEstablished", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
}
TEST_FIXTURE(ConnectionFixture, connection_should_open_amqp_connection)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_until_connection_state_is("AqmpTunnelEstablished");
loop_until_connection_amqp_state_is("Opened");
CHECK_EQUAL("Opened", connection->state.amqp.name);
}
/*
TEST_FIXTURE(ConnectionFixture, shutdown_should_close_amqp_connection)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_until_connection_state_is("AqmpTunnelEstablished");
loop_until_connection_amqp_state_is("Opened");
CHECK_EQUAL("Opened", connection->state.amqp.name);
amqp_connection_shutdown(context, connection);
CHECK_EQUAL("CloseSent", connection->state.amqp.name);
loop_while_connection_amqp_state_is("CloseSent");
SOUTS(connection->state.amqp.name);
CHECK(0);
}
*/
}
<commit_msg>Alter ConnectionTest to pass on MacOS.<commit_after>/*
Copyright 2011 StormMQ Limited
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 <TestHarness.h>
#include "Transport/Connection/ConnectionTestSupport.h"
#include "debug_helper.h"
SUITE(Connection)
{
class ConnectionFixture : public BrokerUsingFixture
{
public:
ConnectionFixture();
ConnectionFixture(amqp_connection_test_hook_t *test_hooks);
~ConnectionFixture();
void cleanup_connection();
public:
};
ConnectionFixture::ConnectionFixture()
{
connection = amqp_connection_create(context);
setup_stop_hook();
}
ConnectionFixture::ConnectionFixture(amqp_connection_test_hook_t *test_hooks) : BrokerUsingFixture(test_hooks)
{
connection = amqp_connection_create(context);
setup_stop_hook();
}
ConnectionFixture::~ConnectionFixture()
{
amqp_connection_destroy(context, connection);
}
void ConnectionFixture::cleanup_connection()
{
amqp_connection_shutdown(context, connection);
while (amqp_connection_is_running(connection) && run_loop_with_timeout());
CHECK(!amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
}
TEST_FIXTURE(ConnectionFixture, fixture_should_balance_allocations)
{
}
TEST_FIXTURE(ConnectionFixture, limits_should_be_initialized)
{
CHECK_EQUAL(AMQP_DEFAULT_MAX_FRAME_SIZE, connection->amqp.connection.limits.max_frame_size);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_socket_link)
{
CHECK_EQUAL("initialized", connection->state.writer.name);
CHECK_EQUAL("initialized", connection->state.reader.name);
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
CHECK(amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
loop_while_socket_state_is("Connecting");
CHECK(amqp_connection_is(connection, AMQP_CONNECTION_SOCKET_CONNECTED));
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK(!amqp_connection_is(connection, AMQP_CONNECTION_RUNNING));
}
class ConnectionHookFixture : public ConnectionFixture
{
public:
ConnectionHookFixture() : ConnectionFixture(ConnectionHookFixture::hooks()) { }
~ConnectionHookFixture() { }
static void post_initialise_hook(amqp_connection_t *connection);
static amqp_connection_test_hook_t *hooks();
public:
};
void ConnectionHookFixture::post_initialise_hook(amqp_connection_t *connection)
{
connection->context->debug.level = 0;
connection->specification_version.required.sasl = AMQP_PROTOCOL_VERSION(AMQP_SASL_PROTOCOL_ID, 2, 0, 0);
connection->specification_version.required.amqp = AMQP_PROTOCOL_VERSION(AMQP_PROTOCOL_ID, 1, 1, 0);
}
amqp_connection_test_hook_t *ConnectionHookFixture::hooks()
{
static amqp_connection_test_hook_t hooks = {
ConnectionHookFixture::post_initialise_hook
};
return &hooks;
}
TEST_FIXTURE(ConnectionHookFixture, connection_should_reject_sasl_version)
{
context->debug.level = 0;
connection->protocols = AMQP_PROTOCOL_SASL | AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
// TODO - Ensure that transition to draining input is a by product of number of cores and not a bug
while (amqp_connection_amqp_is_state(connection, "DrainingInput") && run_loop_with_timeout());
CHECK_EQUAL("Stopped", connection->state.connection.name);
loop_while_running();
CHECK(connection->failure_flags & AMQP_CONNECTION_SASL_NEGOTIATION_REJECTED);
}
TEST_FIXTURE(ConnectionHookFixture, connection_should_reject_amqp_version)
{
context->debug.level = 0;
connection->protocols = AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingAmqp");
// TODO - Ensure that transition to draining input is a by product of number of cores and not a bug
while (amqp_connection_amqp_is_state(connection, "DrainingInput") && run_loop_with_timeout());
CHECK_EQUAL("Stopped", connection->state.connection.name);
CHECK(connection->failure_flags & AMQP_CONNECTION_AMQP_NEGOTIATION_REJECTED);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_sasl_tunnel)
{
connection->protocols = AMQP_PROTOCOL_SASL | AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
CHECK_EQUAL("ConnectingAmqp", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK_EQUAL("Stopped", connection->state.connection.name);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_amqp_tunnel)
{
connection->protocols = AMQP_PROTOCOL_AMQP;
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingAmqp");
CHECK_EQUAL("AqmpTunnelEstablished", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
CHECK_EQUAL("Stopped", connection->state.connection.name);
}
TEST_FIXTURE(ConnectionFixture, connection_should_establish_sasl_and_amqp_tunnels)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_while_socket_state_is("Connecting");
loop_while_connection_state_is("ConnectingSasl");
loop_while_connection_state_is("ConnectingAmqp");
CHECK_EQUAL("AqmpTunnelEstablished", connection->state.connection.name);
amqp_connection_shutdown(context, connection);
loop_while_running();
}
TEST_FIXTURE(ConnectionFixture, connection_should_open_amqp_connection)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_until_connection_state_is("AqmpTunnelEstablished");
loop_until_connection_amqp_state_is("Opened");
CHECK_EQUAL("Opened", connection->state.amqp.name);
}
/*
TEST_FIXTURE(ConnectionFixture, shutdown_should_close_amqp_connection)
{
connection->state.connection.mode.client.connect(connection, "localhost", 54321);
loop_until_connection_state_is("AqmpTunnelEstablished");
loop_until_connection_amqp_state_is("Opened");
CHECK_EQUAL("Opened", connection->state.amqp.name);
amqp_connection_shutdown(context, connection);
CHECK_EQUAL("CloseSent", connection->state.amqp.name);
loop_while_connection_amqp_state_is("CloseSent");
SOUTS(connection->state.amqp.name);
CHECK(0);
}
*/
}
<|endoftext|> |
<commit_before>/*
* model.cpp
*
* Created on: Jan 23, 2012
* Author: mpetkova
*/
#include <model.h>
#include <source_models.h>
Model::Model(LensHndl my_lens, SourceHndl my_source, CosmoHndl my_cosmo){
lens = my_lens;
source = my_source;
cosmo = my_cosmo;
setInternal();
}
Model::~Model(){
delete lens;
delete source;
delete cosmo;
}
void Model::setInternal(){
/*Dl = cosmo->angDist(0,lens->zlens);
Ds = cosmo->angDist(0,source->zsource);
Dls = cosmo->angDist(lens->zlens,source->zsource);*/
double zlens = lens->getZlens();
source->DlDs = cosmo->angDist(0,zlens) / cosmo->angDist(0,source->zsource);
lens->setInternalParams(cosmo,source->zsource);
}
<commit_msg>in setInternal(): setInternalParams for the lens is now called before the calculation of Dl/Ds otherwise zlens was not always set, causing problems in the calculation of the coordinate distance<commit_after>/*
* model.cpp
*
* Created on: Jan 23, 2012
* Author: mpetkova
*/
#include <model.h>
#include <source_models.h>
Model::Model(LensHndl my_lens, SourceHndl my_source, CosmoHndl my_cosmo){
lens = my_lens;
source = my_source;
cosmo = my_cosmo;
setInternal();
}
Model::~Model(){
delete lens;
delete source;
delete cosmo;
}
void Model::setInternal(){
lens->setInternalParams(cosmo,source->zsource);
double zlens = lens->getZlens();
source->DlDs = cosmo->angDist(0,zlens) / cosmo->angDist(0,source->zsource);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: selglos.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:51:49 $
*
* 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_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include "swtypes.hxx"
#include "selglos.hxx"
#include "selglos.hrc"
#include "dochdl.hrc"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// STATIC DATA -----------------------------------------------------------
// CTOR / DTOR -----------------------------------------------------------
SwSelGlossaryDlg::SwSelGlossaryDlg(Window * pParent, const String &rShortName)
: ModalDialog(pParent, SW_RES(DLG_SEL_GLOS)),
aGlosBox(this, SW_RES( LB_GLOS)),
aGlosFL(this, SW_RES( FL_GLOS)),
aOKBtn(this, SW_RES( BT_OK)),
aCancelBtn(this, SW_RES( BT_CANCEL)),
aHelpBtn(this, SW_RES(BT_HELP))
{
String sText(aGlosFL.GetText());
sText += rShortName;
aGlosFL.SetText(sText);
FreeResource();
aGlosBox.SetDoubleClickHdl(LINK(this, SwSelGlossaryDlg, DoubleClickHdl));
}
/*-----------------25.02.94 20:50-------------------
dtor ueberladen
--------------------------------------------------*/
SwSelGlossaryDlg::~SwSelGlossaryDlg() {}
/* -----------------25.10.99 08:33-------------------
--------------------------------------------------*/
IMPL_LINK(SwSelGlossaryDlg, DoubleClickHdl, ListBox*, pBox)
{
EndDialog(RET_OK);
return 0;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.7.222); FILE MERGED 2007/03/26 12:08:55 tl 1.7.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: selglos.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:39: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include "swtypes.hxx"
#include "selglos.hxx"
#include "selglos.hrc"
#include "dochdl.hrc"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// STATIC DATA -----------------------------------------------------------
// CTOR / DTOR -----------------------------------------------------------
SwSelGlossaryDlg::SwSelGlossaryDlg(Window * pParent, const String &rShortName)
: ModalDialog(pParent, SW_RES(DLG_SEL_GLOS)),
aGlosBox(this, SW_RES( LB_GLOS)),
aGlosFL(this, SW_RES( FL_GLOS)),
aOKBtn(this, SW_RES( BT_OK)),
aCancelBtn(this, SW_RES( BT_CANCEL)),
aHelpBtn(this, SW_RES(BT_HELP))
{
String sText(aGlosFL.GetText());
sText += rShortName;
aGlosFL.SetText(sText);
FreeResource();
aGlosBox.SetDoubleClickHdl(LINK(this, SwSelGlossaryDlg, DoubleClickHdl));
}
/*-----------------25.02.94 20:50-------------------
dtor ueberladen
--------------------------------------------------*/
SwSelGlossaryDlg::~SwSelGlossaryDlg() {}
/* -----------------25.10.99 08:33-------------------
--------------------------------------------------*/
IMPL_LINK(SwSelGlossaryDlg, DoubleClickHdl, ListBox*, /*pBox*/)
{
EndDialog(RET_OK);
return 0;
}
<|endoftext|> |
<commit_before>#include "job_tracker.hpp"
#include <sys/stat.h>
#include <thread>
#include <chrono>
#include <fstream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
void log(std::ostream& os, const std::string& message)
{
auto now = std::chrono::system_clock::now();
time_t in_time = std::chrono::system_clock::to_time_t(now);
os << std::put_time(std::localtime(&in_time), "%Y-%m-%d %X") << ": " << message << std::endl;
}
class close_mysql_conn
{
public:
void operator()(MYSQL* c)
{
mysql_close(c);
}
};
std::unique_ptr<MYSQL, close_mysql_conn> get_mysql_conn(const std::string& password)
{
MYSQL* ret = nullptr;
MYSQL* my = mysql_init(NULL);
if (my)
{
ret = mysql_real_connect(my, "localhost", "gasp_user", password.c_str(), "gasp", 0, NULL, 0);
if (!ret)
mysql_close(my);
}
return std::unique_ptr<MYSQL, close_mysql_conn>(ret);
}
std::string escape_string(MYSQL* conn, const std::string& input)
{
std::string ret(2 * input.size() + 1, '\0');
std::size_t sz = mysql_real_escape_string(conn, &ret[0], input.data(), input.size());
ret.resize(sz);
return ret;
}
job_status str_to_job_status(std::string input)
{
if (input == "created") return job_status::created;
if (input == "queued") return job_status::queued;
if (input == "started") return job_status::started;
if (input == "succeeded") return job_status::succeeded;
if (input == "failed") return job_status::failed;
if (input == "cancel_requested") return job_status::cancel_requested;
if (input == "cancelled") return job_status::cancelled;
if (input == "quarantined") return job_status::quarantined;
return job_status::invalid;
}
bool job_tracker::query_pending_jobs(MYSQL* conn, std::vector<job>& jobs)
{
bool ret = false;
std::string sql =
"SELECT bin_to_uuid(jobs.id) AS id, statuses.name AS status FROM jobs "
"LEFT JOIN statuses ON statuses.id = jobs.status_id "
"WHERE (statuses.name='created' OR statuses.name='queued' OR statuses.name='started' OR statuses.name='cancel_requested')";
if (mysql_query(conn, sql.c_str()) != 0)
{
}
else
{
MYSQL_RES* res = mysql_store_result(conn);
jobs.reserve(mysql_num_rows(res));
while (MYSQL_ROW row = mysql_fetch_row(res))
jobs.emplace_back(row[0], str_to_job_status(row[1]));
mysql_free_result(res);
ret = true;
}
return ret;
}
void check_for_job_status_update(MYSQL* conn, const std::string& base_path, const job& j)
{
std::string job_directory = base_path + "/" + j.id();
std::string batch_script_path = job_directory + "/batch_script.sh";
std::string stdout_path = job_directory + "/out.log";
std::string stderr_path = job_directory + "/err.log";
std::string exit_status_path = job_directory + "/exit_status.txt";
std::string ped_file = job_directory + "/input.ped";
std::string epacts_output = job_directory + "/output"; //output.epacts.gz
std::ofstream log_ofs(job_directory + "/log.txt", std::ios::app);
if (!log_ofs.good())
{
std::cerr << "Cannot open " << job_directory << "/log.txt" << std::endl;
// Log file cannot be opened. Something is horribly wrong. TODO: Contact admin.
}
else
{
if (j.status() == job_status::created)
{
std::ofstream ofs;
struct stat st{};
bool file_already_exists = !stat(batch_script_path.c_str(), &st);
if (!file_already_exists) // Doesn't already exist.
ofs.open(batch_script_path);
if (file_already_exists || !ofs.good())
{
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='quarantined' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'quarantined' (batch script already exists for job).");
}
}
else
{
std::string ped_header_line;
std::ifstream ped_fs(ped_file.c_str());
if (!ped_fs || !std::getline(ped_fs, ped_header_line, '\n'))
{
log(log_ofs, "Failed to read header from ped file.");
}
else
{
std::vector<std::string> ped_column_names;
std::istringstream is(ped_header_line);
while(is.good())
{
std::string tmp_column_name;
is >> tmp_column_name;
ped_column_names.push_back(std::move(tmp_column_name));
}
std::string analysis_exe;
std::string manhattan_script;
std::string qqplot_script;
const char* analysis_exe_env = getenv("GASP_ANALYSIS_BINARY");
if (!analysis_exe_env)
analysis_exe = analysis_exe_env;
const char* manhattan_script_env = getenv("GASP_MANHATTAN_BINARY");
if (!manhattan_script_env)
manhattan_script = manhattan_script_env;
const char* qqplot_script_env = getenv("GASP_QQPLOT_BINARY");
if (!qqplot_script_env)
qqplot_script = qqplot_script_env;
std::string vcf_file;
const char* vcf_file_env = getenv("GASP_VCF_FILE");
if (vcf_file_env)
vcf_file = vcf_file_env;
std::stringstream analysis_cmd;
analysis_cmd << analysis_exe << " single"
<< " --vcf " << vcf_file
<< " --ped " << ped_file
<< " --min-maf 0.001 --field DS"
<< " --chr 22"
<< " --unit 500000 --test q.linear"
<< " --out " << epacts_output
<< " --run 4";
if (!ped_column_names.size())
{
log(log_ofs, "Failed to parse header from ped file.");
}
else
{
for (std::size_t i = 4; i < ped_column_names.size() - 1; ++i)
analysis_cmd << " --cov " << ped_column_names[i];
analysis_cmd << " --pheno " << ped_column_names.back();
ofs
<< "#!/bin/bash\n"
<< "#SBATCH --job-name=gasp_" << j.id() << "\n"
<< "#SBATCH --ntasks-per-node=4\n"
<< "#SBATCH --workdir=" << job_directory << "\n"
<< "#SBATCH --mem-per-cpu=4000\n"
//<< "#SBATCH --output=" << stdout_path << "\n"
//<< "#SBATCH --error=" << stderr_path << "\n"
//<< "#SBATCH --time=10:00\n"
//<< "#SBATCH --mem-per-cpu=100\n"
<< "\n"
<< analysis_cmd.str() << " 2> " << stderr_path << " 1> " << stdout_path << "\n"
<< "EXIT_STATUS=$?\n"
<< "if [ $EXIT_STATUS == 0 ]; then\n"
<< " " << manhattan_script << " " << epacts_output << ".epacts.gz " << job_directory << "/manhattan.json\n"
<< " " << qqplot_script << " " << epacts_output << ".epacts.gz " << job_directory << "/qq.json\n"
<< "fi\n"
<< "echo $EXIT_STATUS > " << exit_status_path << "\n";
ofs.close();
// TODO: run sbatch batch_script_path
std::string queue_job_exe = "/bin/bash";
const char* queue_job_exe_env = getenv("GASP_QUEUE_JOB_BINARY");
if (queue_job_exe_env)
queue_job_exe = queue_job_exe_env;
queue_job_exe.append(" ");
std::string bash_command = queue_job_exe + batch_script_path;
#ifdef NDEBUG
std::system(bash_command.c_str());
#endif
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='queued' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'queued'.");
}
}
}
}
}
else if (j.status() == job_status::queued)
{
struct stat st{};
if (stat(stdout_path.c_str(), &st) == 0)
{
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='started' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'started'.");
}
}
}
else if (j.status() == job_status::started)
{
std::ifstream ifs(exit_status_path.c_str());
if (ifs.good())
{
int exit_status = 0;
ifs >> exit_status;
std::string new_job_status = exit_status ? "failed" : "succeeded";
std::string error_message_sql = "NULL";
if (exit_status)
{
std::ifstream error_log_ifs(stderr_path);
if (error_log_ifs.good())
{
error_log_ifs.seekg(0, std::ios::end);
std::size_t sz = error_log_ifs.tellg();
error_log_ifs.seekg(0, std::ios::beg);
if (sz > 0)
{
if (sz > 512)
sz = 512;
std::string tmp_error_msg(sz, '\0');
error_log_ifs.read(&tmp_error_msg[0], sz);
error_message_sql = "'" + escape_string(conn, tmp_error_msg) + "'";
}
}
}
std::string sql = "UPDATE jobs SET error_message=" + error_message_sql +", status_id = (SELECT id FROM statuses WHERE name='" + new_job_status + "' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to '" + new_job_status + "'.");
// TODO: send email.
}
}
}
else if (j.status() == job_status::cancel_requested)
{
//TODO: scancel
}
}
}
job_tracker::job_tracker(const std::string& base_path_for_job_folders, const std::string& mysql_pass)
: base_path_(base_path_for_job_folders),
mysql_pass_(mysql_pass),
stopped_(false)
{
}
void job_tracker::operator()()
{
while (!stopped_)
{
auto conn = get_mysql_conn(mysql_pass_);
if (!conn)
{
}
else
{
std::vector<job> jobs;
if (query_pending_jobs(conn.get(), jobs))
{
for (auto it = jobs.begin(); it!=jobs.end(); ++it)
check_for_job_status_update(conn.get(), base_path_, *it);
}
}
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
void job_tracker::stop()
{
this->stopped_.store(true);
}
<commit_msg>Fix negation bug with binary environment variables.<commit_after>#include "job_tracker.hpp"
#include <sys/stat.h>
#include <thread>
#include <chrono>
#include <fstream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
void log(std::ostream& os, const std::string& message)
{
auto now = std::chrono::system_clock::now();
time_t in_time = std::chrono::system_clock::to_time_t(now);
os << std::put_time(std::localtime(&in_time), "%Y-%m-%d %X") << ": " << message << std::endl;
}
class close_mysql_conn
{
public:
void operator()(MYSQL* c)
{
mysql_close(c);
}
};
std::unique_ptr<MYSQL, close_mysql_conn> get_mysql_conn(const std::string& password)
{
MYSQL* ret = nullptr;
MYSQL* my = mysql_init(NULL);
if (my)
{
ret = mysql_real_connect(my, "localhost", "gasp_user", password.c_str(), "gasp", 0, NULL, 0);
if (!ret)
mysql_close(my);
}
return std::unique_ptr<MYSQL, close_mysql_conn>(ret);
}
std::string escape_string(MYSQL* conn, const std::string& input)
{
std::string ret(2 * input.size() + 1, '\0');
std::size_t sz = mysql_real_escape_string(conn, &ret[0], input.data(), input.size());
ret.resize(sz);
return ret;
}
job_status str_to_job_status(std::string input)
{
if (input == "created") return job_status::created;
if (input == "queued") return job_status::queued;
if (input == "started") return job_status::started;
if (input == "succeeded") return job_status::succeeded;
if (input == "failed") return job_status::failed;
if (input == "cancel_requested") return job_status::cancel_requested;
if (input == "cancelled") return job_status::cancelled;
if (input == "quarantined") return job_status::quarantined;
return job_status::invalid;
}
bool job_tracker::query_pending_jobs(MYSQL* conn, std::vector<job>& jobs)
{
bool ret = false;
std::string sql =
"SELECT bin_to_uuid(jobs.id) AS id, statuses.name AS status FROM jobs "
"LEFT JOIN statuses ON statuses.id = jobs.status_id "
"WHERE (statuses.name='created' OR statuses.name='queued' OR statuses.name='started' OR statuses.name='cancel_requested')";
if (mysql_query(conn, sql.c_str()) != 0)
{
}
else
{
MYSQL_RES* res = mysql_store_result(conn);
jobs.reserve(mysql_num_rows(res));
while (MYSQL_ROW row = mysql_fetch_row(res))
jobs.emplace_back(row[0], str_to_job_status(row[1]));
mysql_free_result(res);
ret = true;
}
return ret;
}
void check_for_job_status_update(MYSQL* conn, const std::string& base_path, const job& j)
{
std::string job_directory = base_path + "/" + j.id();
std::string batch_script_path = job_directory + "/batch_script.sh";
std::string stdout_path = job_directory + "/out.log";
std::string stderr_path = job_directory + "/err.log";
std::string exit_status_path = job_directory + "/exit_status.txt";
std::string ped_file = job_directory + "/input.ped";
std::string epacts_output = job_directory + "/output"; //output.epacts.gz
std::ofstream log_ofs(job_directory + "/log.txt", std::ios::app);
if (!log_ofs.good())
{
std::cerr << "Cannot open " << job_directory << "/log.txt" << std::endl;
// Log file cannot be opened. Something is horribly wrong. TODO: Contact admin.
}
else
{
if (j.status() == job_status::created)
{
std::ofstream ofs;
struct stat st{};
bool file_already_exists = !stat(batch_script_path.c_str(), &st);
if (!file_already_exists) // Doesn't already exist.
ofs.open(batch_script_path);
if (file_already_exists || !ofs.good())
{
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='quarantined' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'quarantined' (batch script already exists for job).");
}
}
else
{
std::string ped_header_line;
std::ifstream ped_fs(ped_file.c_str());
if (!ped_fs || !std::getline(ped_fs, ped_header_line, '\n'))
{
log(log_ofs, "Failed to read header from ped file.");
}
else
{
std::vector<std::string> ped_column_names;
std::istringstream is(ped_header_line);
while(is.good())
{
std::string tmp_column_name;
is >> tmp_column_name;
ped_column_names.push_back(std::move(tmp_column_name));
}
std::string analysis_exe;
std::string manhattan_script;
std::string qqplot_script;
const char* analysis_exe_env = getenv("GASP_ANALYSIS_BINARY");
if (analysis_exe_env)
analysis_exe = analysis_exe_env;
const char* manhattan_script_env = getenv("GASP_MANHATTAN_BINARY");
if (manhattan_script_env)
manhattan_script = manhattan_script_env;
const char* qqplot_script_env = getenv("GASP_QQPLOT_BINARY");
if (qqplot_script_env)
qqplot_script = qqplot_script_env;
std::string vcf_file;
const char* vcf_file_env = getenv("GASP_VCF_FILE");
if (vcf_file_env)
vcf_file = vcf_file_env;
std::stringstream analysis_cmd;
analysis_cmd << analysis_exe << " single"
<< " --vcf " << vcf_file
<< " --ped " << ped_file
<< " --min-maf 0.001 --field DS"
<< " --chr 22"
<< " --unit 500000 --test q.linear"
<< " --out " << epacts_output
<< " --run 4";
if (!ped_column_names.size())
{
log(log_ofs, "Failed to parse header from ped file.");
}
else
{
for (std::size_t i = 4; i < ped_column_names.size() - 1; ++i)
analysis_cmd << " --cov " << ped_column_names[i];
analysis_cmd << " --pheno " << ped_column_names.back();
ofs
<< "#!/bin/bash\n"
<< "#SBATCH --job-name=gasp_" << j.id() << "\n"
<< "#SBATCH --ntasks-per-node=4\n"
<< "#SBATCH --workdir=" << job_directory << "\n"
<< "#SBATCH --mem-per-cpu=4000\n"
//<< "#SBATCH --output=" << stdout_path << "\n"
//<< "#SBATCH --error=" << stderr_path << "\n"
//<< "#SBATCH --time=10:00\n"
//<< "#SBATCH --mem-per-cpu=100\n"
<< "\n"
<< analysis_cmd.str() << " 2> " << stderr_path << " 1> " << stdout_path << "\n"
<< "EXIT_STATUS=$?\n"
<< "if [ $EXIT_STATUS == 0 ]; then\n"
<< " " << manhattan_script << " " << epacts_output << ".epacts.gz " << job_directory << "/manhattan.json\n"
<< " " << qqplot_script << " " << epacts_output << ".epacts.gz " << job_directory << "/qq.json\n"
<< "fi\n"
<< "echo $EXIT_STATUS > " << exit_status_path << "\n";
ofs.close();
// TODO: run sbatch batch_script_path
std::string queue_job_exe = "/bin/bash";
const char* queue_job_exe_env = getenv("GASP_QUEUE_JOB_BINARY");
if (queue_job_exe_env)
queue_job_exe = queue_job_exe_env;
queue_job_exe.append(" ");
std::string bash_command = queue_job_exe + batch_script_path;
#ifdef NDEBUG
std::system(bash_command.c_str());
#endif
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='queued' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'queued'.");
}
}
}
}
}
else if (j.status() == job_status::queued)
{
struct stat st{};
if (stat(stdout_path.c_str(), &st) == 0)
{
std::string sql = "UPDATE jobs SET status_id = (SELECT id FROM statuses WHERE name='started' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to 'started'.");
}
}
}
else if (j.status() == job_status::started)
{
std::ifstream ifs(exit_status_path.c_str());
if (ifs.good())
{
int exit_status = 0;
ifs >> exit_status;
std::string new_job_status = exit_status ? "failed" : "succeeded";
std::string error_message_sql = "NULL";
if (exit_status)
{
std::ifstream error_log_ifs(stderr_path);
if (error_log_ifs.good())
{
error_log_ifs.seekg(0, std::ios::end);
std::size_t sz = error_log_ifs.tellg();
error_log_ifs.seekg(0, std::ios::beg);
if (sz > 0)
{
if (sz > 512)
sz = 512;
std::string tmp_error_msg(sz, '\0');
error_log_ifs.read(&tmp_error_msg[0], sz);
error_message_sql = "'" + escape_string(conn, tmp_error_msg) + "'";
}
}
}
std::string sql = "UPDATE jobs SET error_message=" + error_message_sql +", status_id = (SELECT id FROM statuses WHERE name='" + new_job_status + "' LIMIT 1) WHERE id = uuid_to_bin('" + escape_string(conn, j.id()) + "')";
if (mysql_query(conn, sql.c_str()) != 0)
{
log(log_ofs, mysql_error(conn));
}
else
{
log(log_ofs, "Updated status to '" + new_job_status + "'.");
// TODO: send email.
}
}
}
else if (j.status() == job_status::cancel_requested)
{
//TODO: scancel
}
}
}
job_tracker::job_tracker(const std::string& base_path_for_job_folders, const std::string& mysql_pass)
: base_path_(base_path_for_job_folders),
mysql_pass_(mysql_pass),
stopped_(false)
{
}
void job_tracker::operator()()
{
while (!stopped_)
{
auto conn = get_mysql_conn(mysql_pass_);
if (!conn)
{
}
else
{
std::vector<job> jobs;
if (query_pending_jobs(conn.get(), jobs))
{
for (auto it = jobs.begin(); it!=jobs.end(); ++it)
check_for_job_status_update(conn.get(), base_path_, *it);
}
}
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
void job_tracker::stop()
{
this->stopped_.store(true);
}
<|endoftext|> |
<commit_before>//Author: Adam Browne; as well as The Chromium Authors, whom
// were responsible for the module and instance structure,
// I (Adam Browne) wrote all subsequent code which includes;
// Mitie ML usage, message handling logic, and any further code
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cctype>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/var_array.h"
#include "mitie/mitie/text_categorizer.h"
#include "mitie/mitie/text_categorizer_trainer.h"
//we're using MIT's Information Extraction Library / Tool(s)
using namespace mitie;
using namespace dlib;
struct dataClassifier {
//categorizers for sentiment and relevance.
text_categorizer drelevant, sentiment;
bool isTrained = false;
std::string parsedUser;
static bool checkSpaces(char left, char right)
{ return (left == right) && (left == ' '); }
void simplifyString(std::string& input){
//then, reduce multiple spaces into one between each valid character.
if(input.find(' ') != std::string::npos) {
auto badspace = std::unique(input.begin(), input.end(), checkSpaces);
input.erase(badspace, input.end());
}
}
/* In order to categorize a msg, we must first tokenize it.
* this helper function does that by parsing spaces. */
std::vector<std::string> tokenize_msg(std::string& input){
simplifyString(input);
std::vector<std::string> tokens;
tokens.reserve(input.size());
int curSpace = input.find(" "), curPos = 0;
while(curSpace != std::string::npos){
tokens.push_back(input.substr(curPos,curSpace-curPos));
curPos = curSpace+1;
curSpace = input.find(" ",curPos);
}
//if no space, or last region, push it in.
tokens.push_back(input.substr(curPos));
return tokens;
}
void buildBuffer(pp::VarArray& data, std::vector<char>& buffer){
int index = 1, size = data.GetLength();
while(index < size){
char byte = data.Get(index).AsInt();
buffer.push_back(byte);
++index;
}
}
/* We're receiving the entire trained model as binary.
* We parse the binary into it's representation, create a
* vectorstream and decode the stream into the categorizer. */
void buildCategorizer(pp::VarArray& data, std::vector<char>& buf, int inst_id){
auto inst = pp::Instance(inst_id);
int choice = data.Get(0).AsInt();
if(choice == 0){
buildBuffer(data, buf);
decodeStream('r',buf);
} else if(choice == 1){
buildBuffer(data,buf);
inst.PostMessage(pp::Var("f")); //tells them to send second chunk.
} else if(choice == 2){
buildBuffer(data,buf);
decodeStream('s',buf);
isTrained = true;
} else if(choice == 9){
parsedUser = data.Get(1).AsString();
}
}
void decodeStream(char part, std::vector<char>& cont){
dlib::vectorstream trained_model(cont);
deserialize(trained_model,part);
cont.clear();
}
void deserialize(dlib::vectorstream& trained_model, char ch){
if(ch == 'r')
drelevant.decode(drelevant,trained_model);
else
sentiment.decode(sentiment,trained_model);
}
bool isRelevant(std::string& message){
//get our tokens to predict if a msg is relevant.
std::vector<std::string> tokenized = tokenize_msg(message);
std::string tag = drelevant(tokenized);
return tag == "y";
}
//as opposed to relevance, return the tag for the message.
std::string determineFeel(std::string& message) {
std::vector<std::string> tokenized = tokenize_msg(message);
std::string tag = sentiment(tokenized);
return tag;
}
};
/* first, parse the user's name. Then, determine if there is a mention
* with their name. if so, set the flag; also parse that mention out,
* same applies whether or not the user is mentioned. */
struct StreamMessage {
std::string id, time, user, msg, cur_user, cmd;
bool userMentioned = false, cmdMsg = false;
//tolower can crash if not ascii...
void ensureCase(std::string& substring){
for(int i=0; i<substring.size(); ++i){
if((substring[i] & ~0x7F) == 0){ //toascii used to be defined similarly.
substring[i] = std::tolower(substring[i]);
}
}
}
void searchUser(std::string& look_for){
int index = 0;
while(index != msg.size()){
std::string part = msg.substr(index,look_for.size());
ensureCase(part);
if(part == cur_user){
userMentioned = true;
break;
}
++index;
}
}
void parseMention() {
//once we've determined the user's name, we then parse the mention in it...
if(cur_user.size() > 0) {
std::string look_for = '@' + cur_user;
searchUser(look_for);
}
bool in_mention = false;
std::string new_msg = "";
for(auto letter : msg){
if(in_mention == false){
if(letter == '@')
in_mention = true;
else
new_msg += letter;
} else {
if(letter == ' ')
in_mention = false;
}
}
msg = new_msg;
}
/* naive approach to determine if the message was a command:
* If the next character after the '!' isn't a space, it could be one.
* We also extract the command from the message to examine them. */
void determineCommand() {
auto exclamation = msg.find("!");
if(exclamation != std::string::npos && exclamation + 1 < msg.size()){
cmdMsg = msg[exclamation+1] != ' '? true: false;
//extract the command for use in analytics.
if(cmdMsg == true){
int begin = exclamation + 1, end = msg.find(" ",begin);
if(end != std::string::npos){
cmd = "!" + msg.substr(begin,end-begin);
} else {
cmd = "!" + msg.substr(begin);
}
}
}
else
cmdMsg = false;
}
void handleMsg() {
parseMention();
determineCommand();
}
/* A 'StreamMessage' is constructed by parsing the original data,
* where it is subsequently used for computation. */
StreamMessage(std::string& data, std::string sf_usr) {
cur_user = sf_usr;
//data format is id | time | user | message.
int cur_pos = 0, cur_delim = data.find("|", cur_pos);
id = data.substr(0,cur_delim);
cur_pos = cur_delim + 1;
cur_delim = data.find("|", cur_delim+1);
time = data.substr(cur_pos, cur_delim-cur_pos);
cur_pos = cur_delim + 1;
cur_delim = data.find("|", cur_delim+1);
user = data.substr(cur_pos, cur_delim-cur_pos);
cur_pos = cur_delim + 1;
msg = data.substr(cur_pos);
//perform final parsing; parse mentions and determine if !cmd.
handleMsg();
}
};
/* The responseFormatter contains the classifier which makes conclusions about our data.
* it also has a backlog, which as the categorizer is being trained stores the messages.
* once trained, it unloads the backlog and then processes subsequent messages */
struct responseFormatter {
dataClassifier RC;
std::queue<StreamMessage> backlog;
std::string curUser() const {
return RC.parsedUser;
}
bool isReady() const { //ready to shoot messages
return RC.isTrained;
}
void addMessage(StreamMessage& msg){
backlog.push(msg);
}
std::vector<std::string> unload() {
std::vector<std::string> log;
log.reserve(backlog.size());
while(!backlog.empty()) {
StreamMessage msg = backlog.front();
backlog.pop();
std::string response = processMessage(msg);
log.push_back(response);
}
return log;
}
std::string processMessage(StreamMessage& parsed){
std::string response = parsed.id + "|" + parsed.time + "|" + parsed.user + "|";
//if the sfeel user was mentioned here...
if(parsed.userMentioned == true) {
bool relevant = RC.isRelevant(parsed.msg);
response += (relevant == true? "1|": "0|");
if(parsed.cmdMsg == false) {
std::string feeling = RC.determineFeel(parsed.msg);
response += feeling;
}
} else {
if(parsed.cmdMsg == true) { //we assume commands aren't relevant.
response += ("0||" + parsed.cmd);
} else {
bool relevant = RC.isRelevant(parsed.msg);
response += (relevant == true? "1|": "0|");
std::string feeling = RC.determineFeel(parsed.msg);
response += feeling;
}
}
response += ("|" + parsed.msg); //lastly, append the msg.
return response;
}
void processData(pp::VarArray& data, std::vector<char>& buf, int inst_id) {
RC.buildCategorizer(data,buf,inst_id);
}
};
//namespace referenced by the below instance.
namespace {
responseFormatter RF;
std::vector<char> cat_buf;
}
class StreamFeelModInstance : public pp::Instance {
public:
explicit StreamFeelModInstance(PP_Instance instance)
: pp::Instance(instance) {}
virtual ~StreamFeelModInstance() {}
virtual void HandleMessage(const pp::Var& var_message) {
// Ignore the message if it is not a string.
if (!var_message.is_string()){
if(var_message.is_array()){
int inst_id = pp_instance();
auto val = pp::VarArray(var_message);
//loads our containers and trains the classifier.
RF.processData(val,cat_buf,inst_id);
}
return;
}
// ID | Time | From | Rel | Sentiment | Command | Msg <-- Response Format
std::string message = var_message.AsString();
StreamMessage parsed = StreamMessage(message, RF.curUser());
if(RF.isReady() == false){
RF.addMessage(parsed);
} else if(!RF.backlog.empty() && RF.isReady() == true){
RF.addMessage(parsed);
std::vector<std::string> handle = RF.unload();
for(auto message : handle){
PostMessage(pp::Var(message));
}
} else {
std::string response = RF.processMessage(parsed);
PostMessage(pp::Var(response));
}
}
};
class StreamFeelModule : public pp::Module {
public:
StreamFeelModule() : pp::Module() {}
virtual ~StreamFeelModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new StreamFeelModInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new StreamFeelModule();
}
} // namespace pp<commit_msg>clean up some brackets.<commit_after>//Author: Adam Browne; as well as The Chromium Authors, whom
// were responsible for the module and instance structure,
// I (Adam Browne) wrote all subsequent code which includes;
// Mitie ML usage, message handling logic, and any further code
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cctype>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/var_array.h"
#include "mitie/mitie/text_categorizer.h"
#include "mitie/mitie/text_categorizer_trainer.h"
//we're using MIT's Information Extraction Library / Tool(s)
using namespace mitie;
using namespace dlib;
struct dataClassifier {
//categorizers for sentiment and relevance.
text_categorizer drelevant, sentiment;
bool isTrained = false;
std::string parsedUser;
static bool checkSpaces(char left, char right)
{ return (left == right) && (left == ' '); }
void simplifyString(std::string& input){
//then, reduce multiple spaces into one between each valid character.
if(input.find(' ') != std::string::npos) {
auto badspace = std::unique(input.begin(), input.end(), checkSpaces);
input.erase(badspace, input.end());
}
}
/* In order to categorize a msg, we must first tokenize it.
* this helper function does that by parsing spaces. */
std::vector<std::string> tokenize_msg(std::string& input){
simplifyString(input);
std::vector<std::string> tokens;
tokens.reserve(input.size());
int curSpace = input.find(" "), curPos = 0;
while(curSpace != std::string::npos){
tokens.push_back(input.substr(curPos,curSpace-curPos));
curPos = curSpace+1;
curSpace = input.find(" ",curPos);
}
//if no space, or last region, push it in.
tokens.push_back(input.substr(curPos));
return tokens;
}
void buildBuffer(pp::VarArray& data, std::vector<char>& buffer){
int index = 1, size = data.GetLength();
while(index < size){
char byte = data.Get(index).AsInt();
buffer.push_back(byte);
++index;
}
}
/* We're receiving the entire trained model as binary.
* We parse the binary into it's representation, create a
* vectorstream and decode the stream into the categorizer. */
void buildCategorizer(pp::VarArray& data, std::vector<char>& buf, int inst_id){
auto inst = pp::Instance(inst_id);
int choice = data.Get(0).AsInt();
if(choice == 0){
buildBuffer(data, buf);
decodeStream('r',buf);
} else if(choice == 1){
buildBuffer(data,buf);
inst.PostMessage(pp::Var("f")); //tells them to send second chunk.
} else if(choice == 2){
buildBuffer(data,buf);
decodeStream('s',buf);
isTrained = true;
} else if(choice == 9){
parsedUser = data.Get(1).AsString();
}
}
void decodeStream(char part, std::vector<char>& cont){
dlib::vectorstream trained_model(cont);
deserialize(trained_model,part);
cont.clear();
}
void deserialize(dlib::vectorstream& trained_model, char ch){
if(ch == 'r')
drelevant.decode(drelevant,trained_model);
else
sentiment.decode(sentiment,trained_model);
}
bool isRelevant(std::string& message){
//get our tokens to predict if a msg is relevant.
std::vector<std::string> tokenized = tokenize_msg(message);
std::string tag = drelevant(tokenized);
return tag == "y";
}
//as opposed to relevance, return the tag for the message.
std::string determineFeel(std::string& message) {
std::vector<std::string> tokenized = tokenize_msg(message);
std::string tag = sentiment(tokenized);
return tag;
}
};
/* first, parse the user's name. Then, determine if there is a mention
* with their name. if so, set the flag; also parse that mention out,
* same applies whether or not the user is mentioned. */
struct StreamMessage {
std::string id, time, user, msg, cur_user, cmd;
bool userMentioned = false, cmdMsg = false;
//tolower can crash if not ascii...
void ensureCase(std::string& substring){
for(int i=0; i<substring.size(); ++i)
if((substring[i] & ~0x7F) == 0) //toascii used to be defined similarly.
substring[i] = std::tolower(substring[i]);
}
void searchUser(std::string& look_for){
int index = 0;
while(index != msg.size()){
std::string part = msg.substr(index,look_for.size());
ensureCase(part);
if(part == cur_user){
userMentioned = true;
break;
}
++index;
}
}
void parseMention() {
//once we've determined the user's name, we then parse the mention in it...
if(cur_user.size() > 0) {
std::string look_for = '@' + cur_user;
searchUser(look_for);
}
bool in_mention = false;
std::string new_msg = "";
for(auto letter : msg){
if(in_mention == false){
if(letter == '@')
in_mention = true;
else
new_msg += letter;
} else {
if(letter == ' ')
in_mention = false;
}
}
msg = new_msg;
}
/* naive approach to determine if the message was a command:
* If the next character after the '!' isn't a space, it could be one.
* We also extract the command from the message to examine them. */
void determineCommand() {
auto exclamation = msg.find("!");
if(exclamation != std::string::npos && exclamation + 1 < msg.size()){
cmdMsg = msg[exclamation+1] != ' '? true: false;
//extract the command for use in analytics.
if(cmdMsg == true){
int begin = exclamation + 1, end = msg.find(" ",begin);
if(end != std::string::npos){
cmd = "!" + msg.substr(begin,end-begin);
} else {
cmd = "!" + msg.substr(begin);
}
}
}
else
cmdMsg = false;
}
void handleMsg() {
parseMention();
determineCommand();
}
/* A 'StreamMessage' is constructed by parsing the original data,
* where it is subsequently used for computation. */
StreamMessage(std::string& data, std::string sf_usr) {
cur_user = sf_usr;
//data format is id | time | user | message.
int cur_pos = 0, cur_delim = data.find("|", cur_pos);
id = data.substr(0,cur_delim);
cur_pos = cur_delim + 1;
cur_delim = data.find("|", cur_delim+1);
time = data.substr(cur_pos, cur_delim-cur_pos);
cur_pos = cur_delim + 1;
cur_delim = data.find("|", cur_delim+1);
user = data.substr(cur_pos, cur_delim-cur_pos);
cur_pos = cur_delim + 1;
msg = data.substr(cur_pos);
//perform final parsing; parse mentions and determine if !cmd.
handleMsg();
}
};
/* The responseFormatter contains the classifier which makes conclusions about our data.
* it also has a backlog, which as the categorizer is being trained stores the messages.
* once trained, it unloads the backlog and then processes subsequent messages */
struct responseFormatter {
dataClassifier RC;
std::queue<StreamMessage> backlog;
std::string curUser() const {
return RC.parsedUser;
}
bool isReady() const { //ready to shoot messages
return RC.isTrained;
}
void addMessage(StreamMessage& msg){
backlog.push(msg);
}
std::vector<std::string> unload() {
std::vector<std::string> log;
log.reserve(backlog.size());
while(!backlog.empty()) {
StreamMessage msg = backlog.front();
backlog.pop();
std::string response = processMessage(msg);
log.push_back(response);
}
return log;
}
std::string processMessage(StreamMessage& parsed){
std::string response = parsed.id + "|" + parsed.time + "|" + parsed.user + "|";
//if the sfeel user was mentioned here...
if(parsed.userMentioned == true) {
bool relevant = RC.isRelevant(parsed.msg);
response += (relevant == true? "1|": "0|");
if(parsed.cmdMsg == false) {
std::string feeling = RC.determineFeel(parsed.msg);
response += feeling;
}
} else {
if(parsed.cmdMsg == true) { //we assume commands aren't relevant.
response += ("0||" + parsed.cmd);
} else {
bool relevant = RC.isRelevant(parsed.msg);
response += (relevant == true? "1|": "0|");
std::string feeling = RC.determineFeel(parsed.msg);
response += feeling;
}
}
response += ("|" + parsed.msg); //lastly, append the msg.
return response;
}
void processData(pp::VarArray& data, std::vector<char>& buf, int inst_id) {
RC.buildCategorizer(data,buf,inst_id);
}
};
//namespace referenced by the below instance.
namespace {
responseFormatter RF;
std::vector<char> cat_buf;
}
class StreamFeelModInstance : public pp::Instance {
public:
explicit StreamFeelModInstance(PP_Instance instance)
: pp::Instance(instance) {}
virtual ~StreamFeelModInstance() {}
virtual void HandleMessage(const pp::Var& var_message) {
// Ignore the message if it is not a string.
if (!var_message.is_string()){
if(var_message.is_array()){
int inst_id = pp_instance();
auto val = pp::VarArray(var_message);
//loads our containers and trains the classifier.
RF.processData(val,cat_buf,inst_id);
}
return;
}
// ID | Time | From | Rel | Sentiment | Command | Msg <-- Response Format
std::string message = var_message.AsString();
StreamMessage parsed = StreamMessage(message, RF.curUser());
if(RF.isReady() == false){
RF.addMessage(parsed);
} else if(!RF.backlog.empty() && RF.isReady() == true){
RF.addMessage(parsed);
std::vector<std::string> handle = RF.unload();
for(auto message : handle){
PostMessage(pp::Var(message));
}
} else {
std::string response = RF.processMessage(parsed);
PostMessage(pp::Var(response));
}
}
};
class StreamFeelModule : public pp::Module {
public:
StreamFeelModule() : pp::Module() {}
virtual ~StreamFeelModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new StreamFeelModInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new StreamFeelModule();
}
} // namespace pp<|endoftext|> |
<commit_before>/*
This file is part of CanFestival, a library implementing CanOpen Stack.
Copyright (C): Edouard TISSERANT and Francis DUPIN
Copyright (C) Win32 Port Leonid Tochinski
See COPYING file for copyrights details.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
CAN driver interface.
*/
#include <windows.h>
extern "C"
{
#define DLL_CALL(funcname) (*_##funcname)
#define FCT_PTR_INIT =NULL
#include "canfestival.h"
#include "timer.h"
#include "timers_driver.h"
};
typedef UNS8 (*CANRECEIVE_DRIVER_PROC)(void* inst, Message *m);
typedef UNS8 (*CANSEND_DRIVER_PROC)(void* inst, const Message *m);
typedef void* (*CANOPEN_DRIVER_PROC)(s_BOARD *board);
typedef int (*CANCLOSE_DRIVER_PROC)(void* inst);
class driver_procs
{
public:
driver_procs();
~driver_procs();
HMODULE load_canfestival_driver(LPCTSTR driver_name);
bool can_driver_valid() const;
public:
// can driver
CANRECEIVE_DRIVER_PROC m_canReceive;
CANSEND_DRIVER_PROC m_canSend;
CANOPEN_DRIVER_PROC m_canOpen;
CANCLOSE_DRIVER_PROC m_canClose;
// driver module habndle
HMODULE m_driver_handle;
};
driver_procs::driver_procs() : m_canReceive(0),
m_canSend(0),
m_canOpen(0),
m_canClose(0),
m_driver_handle(0)
{}
driver_procs::~driver_procs()
{
if (m_driver_handle)
::FreeLibrary(m_driver_handle);
}
bool driver_procs::can_driver_valid() const
{
return ((m_canReceive != NULL) &&
(m_canSend != NULL) &&
(m_canOpen != NULL) &&
(m_canClose != NULL));
}
// GetProcAddress doesn't have an UNICODE version for NT
#ifdef UNDER_CE
#define myTEXT(str) TEXT(str)
#else
#define myTEXT(str) str
#endif
HMODULE driver_procs::load_canfestival_driver(LPCTSTR driver_name)
{
//LPCTSTR driver1 = "C:\\msys\\1.0\\home\\Ontaide\\can\\CanFestival-3\\drivers\\can_peak_win32\\cygcan_peak_win32.dll";
//LPCTSTR driver2 = "C:\\msys\\1.0\\home\\Ontaide\\can\\CanFestival-3\\drivers\\can_peak_win32\\cygcan_peak_win32.dll";
//printf("can_driver_valid=%d\n",can_driver_valid());
if (can_driver_valid())
return m_driver_handle;
printf("driver_name=%s\n",driver_name);
m_driver_handle = ::LoadLibrary(driver_name);
//printf("m_driver_handle=%d\n",m_driver_handle);
//printf("testerror =%s\n",GetLastError());
if (m_driver_handle == NULL)
return NULL;
m_canReceive = (CANRECEIVE_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canReceive_driver"));
m_canSend = (CANSEND_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canSend_driver"));
m_canOpen = (CANOPEN_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canOpen_driver"));
m_canClose = (CANCLOSE_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canClose_driver"));
return can_driver_valid()?m_driver_handle:NULL;
}
struct driver_data
{
CO_Data * d;
HANDLE receive_thread;
void* inst;
volatile bool continue_receive_thread;
};
driver_procs s_driver_procs;
LIB_HANDLE LoadCanDriver(const char* driver_name)
{
return s_driver_procs.load_canfestival_driver((LPCTSTR)driver_name);
}
UNS8 canReceive(CAN_PORT fd0, Message *m)
{
if (fd0 != NULL && s_driver_procs.m_canReceive != NULL)
{
driver_data* data = (driver_data*)fd0;
return (*s_driver_procs.m_canReceive)(data->inst, m);
}
return 1;
}
void* canReceiveLoop(CAN_PORT fd0)
{
driver_data* data = (driver_data*)fd0;
Message m;
while (data->continue_receive_thread)
{
if (!canReceive(fd0, &m))
{
EnterMutex();
canDispatch(data->d, &m);
LeaveMutex();
}
else
{
break;
::Sleep(1);
}
}
return 0;
}
/***************************************************************************/
UNS8 canSend(CAN_PORT fd0, Message *m)
{
if (fd0 != NULL && s_driver_procs.m_canSend != NULL)
{
UNS8 res;
driver_data* data = (driver_data*)fd0;
res = (*s_driver_procs.m_canSend)(data->inst, m);
if (res)
return 1; // OK
}
return 0; // NOT OK
}
/***************************************************************************/
CAN_HANDLE canOpen(s_BOARD *board, CO_Data * d)
{
if (board != NULL && s_driver_procs.m_canOpen != NULL)
{
void* inst = (*s_driver_procs.m_canOpen)(board);
if (inst != NULL)
{
driver_data* data = new driver_data;
data->d = d;
data->inst = inst;
data->continue_receive_thread = true;
CreateReceiveTask(data, &data->receive_thread, (void*)&canReceiveLoop);
EnterMutex();
d->canHandle = data;
LeaveMutex();
return data;
}
}
return NULL;
}
/***************************************************************************/
int canClose(CO_Data * d)
{
if (s_driver_procs.m_canClose != NULL)
{
driver_data* data;
EnterMutex();
if(d->canHandle != NULL){
data = (driver_data*)d->canHandle;
d->canHandle = NULL;
data->continue_receive_thread = false;}
LeaveMutex();
WaitReceiveTaskEnd(&data->receive_thread);
(*s_driver_procs.m_canClose)(data->inst);
delete data;
return 0;
}
return 0;
}
<commit_msg>fix bug in canclose for win32<commit_after>/*
This file is part of CanFestival, a library implementing CanOpen Stack.
Copyright (C): Edouard TISSERANT and Francis DUPIN
Copyright (C) Win32 Port Leonid Tochinski
See COPYING file for copyrights details.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
CAN driver interface.
*/
#include <windows.h>
extern "C"
{
#define DLL_CALL(funcname) (*_##funcname)
#define FCT_PTR_INIT =NULL
#include "canfestival.h"
#include "timer.h"
#include "timers_driver.h"
};
typedef UNS8 (*CANRECEIVE_DRIVER_PROC)(void* inst, Message *m);
typedef UNS8 (*CANSEND_DRIVER_PROC)(void* inst, const Message *m);
typedef void* (*CANOPEN_DRIVER_PROC)(s_BOARD *board);
typedef int (*CANCLOSE_DRIVER_PROC)(void* inst);
class driver_procs
{
public:
driver_procs();
~driver_procs();
HMODULE load_canfestival_driver(LPCTSTR driver_name);
bool can_driver_valid() const;
public:
// can driver
CANRECEIVE_DRIVER_PROC m_canReceive;
CANSEND_DRIVER_PROC m_canSend;
CANOPEN_DRIVER_PROC m_canOpen;
CANCLOSE_DRIVER_PROC m_canClose;
// driver module habndle
HMODULE m_driver_handle;
};
driver_procs::driver_procs() : m_canReceive(0),
m_canSend(0),
m_canOpen(0),
m_canClose(0),
m_driver_handle(0)
{}
driver_procs::~driver_procs()
{
if (m_driver_handle)
::FreeLibrary(m_driver_handle);
}
bool driver_procs::can_driver_valid() const
{
return ((m_canReceive != NULL) &&
(m_canSend != NULL) &&
(m_canOpen != NULL) &&
(m_canClose != NULL));
}
// GetProcAddress doesn't have an UNICODE version for NT
#ifdef UNDER_CE
#define myTEXT(str) TEXT(str)
#else
#define myTEXT(str) str
#endif
HMODULE driver_procs::load_canfestival_driver(LPCTSTR driver_name)
{
//LPCTSTR driver1 = "C:\\msys\\1.0\\home\\Ontaide\\can\\CanFestival-3\\drivers\\can_peak_win32\\cygcan_peak_win32.dll";
//LPCTSTR driver2 = "C:\\msys\\1.0\\home\\Ontaide\\can\\CanFestival-3\\drivers\\can_peak_win32\\cygcan_peak_win32.dll";
//printf("can_driver_valid=%d\n",can_driver_valid());
if (can_driver_valid())
return m_driver_handle;
printf("driver_name=%s\n",driver_name);
m_driver_handle = ::LoadLibrary(driver_name);
//printf("m_driver_handle=%d\n",m_driver_handle);
//printf("testerror =%s\n",GetLastError());
if (m_driver_handle == NULL)
return NULL;
m_canReceive = (CANRECEIVE_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canReceive_driver"));
m_canSend = (CANSEND_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canSend_driver"));
m_canOpen = (CANOPEN_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canOpen_driver"));
m_canClose = (CANCLOSE_DRIVER_PROC)::GetProcAddress(m_driver_handle, myTEXT("canClose_driver"));
return can_driver_valid()?m_driver_handle:NULL;
}
struct driver_data
{
CO_Data * d;
HANDLE receive_thread;
void* inst;
volatile bool continue_receive_thread;
};
driver_procs s_driver_procs;
LIB_HANDLE LoadCanDriver(const char* driver_name)
{
return s_driver_procs.load_canfestival_driver((LPCTSTR)driver_name);
}
UNS8 canReceive(CAN_PORT fd0, Message *m)
{
if (fd0 != NULL && s_driver_procs.m_canReceive != NULL)
{
driver_data* data = (driver_data*)fd0;
return (*s_driver_procs.m_canReceive)(data->inst, m);
}
return 1;
}
void* canReceiveLoop(CAN_PORT fd0)
{
driver_data* data = (driver_data*)fd0;
Message m;
while (data->continue_receive_thread)
{
if (!canReceive(fd0, &m))
{
EnterMutex();
canDispatch(data->d, &m);
LeaveMutex();
}
else
{
break;
::Sleep(1);
}
}
return 0;
}
/***************************************************************************/
UNS8 canSend(CAN_PORT fd0, Message *m)
{
if (fd0 != NULL && s_driver_procs.m_canSend != NULL)
{
UNS8 res;
driver_data* data = (driver_data*)fd0;
res = (*s_driver_procs.m_canSend)(data->inst, m);
if (res)
return 1; // OK
}
return 0; // NOT OK
}
/***************************************************************************/
CAN_HANDLE canOpen(s_BOARD *board, CO_Data * d)
{
if (board != NULL && s_driver_procs.m_canOpen != NULL)
{
void* inst = (*s_driver_procs.m_canOpen)(board);
if (inst != NULL)
{
driver_data* data = new driver_data;
data->d = d;
data->inst = inst;
data->continue_receive_thread = true;
CreateReceiveTask(data, &data->receive_thread, (void*)&canReceiveLoop);
EnterMutex();
d->canHandle = data;
LeaveMutex();
return data;
}
}
return NULL;
}
/***************************************************************************/
int canClose(CO_Data * d)
{
if (s_driver_procs.m_canClose != NULL)
{
driver_data* data;
EnterMutex();
if(d->canHandle != NULL){
data = (driver_data*)d->canHandle;
d->canHandle = NULL;
data->continue_receive_thread = false;}
LeaveMutex();
(*s_driver_procs.m_canClose)(data->inst);
WaitReceiveTaskEnd(&data->receive_thread);
delete data;
return 0;
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "FlareCreditsMenu.h"
#include "../../Flare.h"
#include "../Components/FlareButton.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareCreditsMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCreditsMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
int32 Width = 1.75 * Theme.ContentWidth;
int32 TextWidth = Width - 2 * Theme.ContentPadding.Left - 2 * Theme.ContentPadding.Right;
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(FFlareStyleSet::GetImage("HeliumRain"))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Title", "HELIUM RAIN"))
.TextStyle(&Theme.SpecialTitleFont)
]
]
// Main
+ SVerticalBox::Slot()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SBox)
.WidthOverride(Width)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Scroll container
+ SVerticalBox::Slot()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
// Team 1
+ SScrollBox::Slot()
[
SNew(SHorizontalBox)
// Company
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Center)
.VAlign(VAlign_Top)
[
SNew(SImage).Image(FFlareStyleSet::GetImage("DeimosGames"))
]
// Team
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SVerticalBox)
// Part 1
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 0, 0, 20))
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-DeimosGames", "Deimos Games"))
.TextStyle(&Theme.TitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger", "Gwenna\u00EBl 'Stranger' ARBONA"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger-Info", "Art \u2022 UI \u2022 Game design"))
.TextStyle(&Theme.NameFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok", "Fr\u00E9d\u00E9ric 'Niavok' BERTOLUS"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok-Info", "Gameplay \u2022 Game design"))
.TextStyle(&Theme.NameFont)
]
// Part 2
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 50, 0, 20))
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Others", "Other awesome people"))
.TextStyle(&Theme.TitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy", "Music by Daisy HERBAULT"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom", "Game logo by J\u00E9r\u00F4me MILLION-ROUSSEAU"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Special-Thanks", "Special thanks to Johanna and all our nerd friends ! This game took us more than three years to create. We hope you'll have as much fun playing it as we did creating it !"))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth / 2)
]
]
]
// Separator
+ SScrollBox::Slot()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info", "Helium Rain uses the Unreal\u00AE Engine. Unreal\u00AE is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info2", "Unreal\u00AE Engine, Copyright 1998 - 2017, Epic Games, Inc. All rights reserved."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Sound-Info", "Some sound resources were provided by FreeSFX (http://www.freesfx.co.uk)."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Assets-Info", "Some art assets were provided by CGMontreal, Poleshift Games, W3 Studios and 'Gargore'."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
]
]
]
// Back
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.AutoHeight()
[
SNew(SFlareButton)
.Transparent(true)
.Width(3)
.Text(LOCTEXT("Back", "Back"))
.OnClicked(this, &SFlareCreditsMenu::OnMainMenu)
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareCreditsMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareCreditsMenu::Enter()
{
FLOG("SFlareCreditsMenu::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
}
void SFlareCreditsMenu::Exit()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCreditsMenu::OnMainMenu()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Main);
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Fix typo<commit_after>
#include "FlareCreditsMenu.h"
#include "../../Flare.h"
#include "../Components/FlareButton.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareCreditsMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCreditsMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
int32 Width = 1.75 * Theme.ContentWidth;
int32 TextWidth = Width - 2 * Theme.ContentPadding.Left - 2 * Theme.ContentPadding.Right;
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(FFlareStyleSet::GetImage("HeliumRain"))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Title", "HELIUM RAIN"))
.TextStyle(&Theme.SpecialTitleFont)
]
]
// Main
+ SVerticalBox::Slot()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SBox)
.WidthOverride(Width)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Scroll container
+ SVerticalBox::Slot()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
// Team 1
+ SScrollBox::Slot()
[
SNew(SHorizontalBox)
// Company
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Center)
.VAlign(VAlign_Top)
[
SNew(SImage).Image(FFlareStyleSet::GetImage("DeimosGames"))
]
// Team
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SVerticalBox)
// Part 1
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 0, 0, 20))
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-DeimosGames", "Deimos Games"))
.TextStyle(&Theme.TitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger", "Gwenna\u00EBl 'Stranger' ARBONA"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger-Info", "Art \u2022 UI \u2022 Game design"))
.TextStyle(&Theme.NameFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok", "Fr\u00E9d\u00E9ric 'Niavok' BERTOLUS"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok-Info", "Gameplay \u2022 Game design"))
.TextStyle(&Theme.NameFont)
]
// Part 2
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 50, 0, 20))
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Others", "Other awesome people"))
.TextStyle(&Theme.TitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy", "Music by Daisy HERBAUT"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom", "Game logo by J\u00E9r\u00F4me MILLION-ROUSSEAU"))
.TextStyle(&Theme.SubTitleFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Special-Thanks", "Special thanks to Johanna and all our nerd friends ! This game took us more than three years to create. We hope you'll have as much fun playing it as we did creating it !"))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth / 2)
]
]
]
// Separator
+ SScrollBox::Slot()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info", "Helium Rain uses the Unreal\u00AE Engine. Unreal\u00AE is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info2", "Unreal\u00AE Engine, Copyright 1998 - 2017, Epic Games, Inc. All rights reserved."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Sound-Info", "Some sound resources were provided by FreeSFX (http://www.freesfx.co.uk)."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
+ SScrollBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Assets-Info", "Some art assets were provided by CGMontreal, Poleshift Games, W3 Studios and 'Gargore'."))
.TextStyle(&Theme.NameFont)
.WrapTextAt(TextWidth)
]
]
]
]
// Back
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.AutoHeight()
[
SNew(SFlareButton)
.Transparent(true)
.Width(3)
.Text(LOCTEXT("Back", "Back"))
.OnClicked(this, &SFlareCreditsMenu::OnMainMenu)
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareCreditsMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareCreditsMenu::Enter()
{
FLOG("SFlareCreditsMenu::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
}
void SFlareCreditsMenu::Exit()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCreditsMenu::OnMainMenu()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Main);
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>#ifndef GCL_TMP_H_
# define GCL_TMP_H_
#include <array>
namespace gcl::mp
{ // C++17
template <typename ... ts>
struct super : ts...
{};
template <template <typename...> class trait_type, typename ... ts>
struct partial_template
{
template <typename ... us>
using type = trait_type<ts..., us...>;
template <typename ... us>
static constexpr bool value = trait_type<ts..., us...>::value;
};
template <template <typename> class ... constraint_type>
struct require
{ // todo : std::conjunction ?
template <typename T>
static constexpr void on()
{
(check_constraint<constraint_type, T>(), ...);
}
template <typename T>
static inline constexpr
std::array<bool, sizeof...(constraint_type)>
values_on{ std::move(constraint_type<T>::value)... };
private:
template <template <typename> class constraint_type, typename T>
static constexpr void check_constraint()
{
static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos");
}
};
template <typename T, typename ... ts>
static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value;
template <typename to_find, typename ... ts>
/*constexpr */auto get_index()
{ // [C++20] constexpr => std::count, std::find
static_assert(contains<to_find, ts...>);
constexpr auto result = gcl::mp::require
<
gcl::mp::partial_template<std::is_same, ts>::type
...
>::values_on<to_find>;
auto count = std::count(std::cbegin(result), std::cend(result), true);
if (count > 1)
throw std::runtime_error("get_index : duplicate type");
if (count == 0)
throw std::out_of_range("get_index : no match");
return std::distance
(
std::cbegin(result),
std::find(std::cbegin(result), std::cend(result), true)
);
}
}
namespace gcl::deprecated::mp
{ // C++98
template <class T, class ... T_Classes>
struct super
{
struct Type : T, super<T_Classes...>::Type
{};
};
template <class T>
struct super<T>
{
using Type = T;
};
// constexpr if
template <bool condition, typename _THEN, typename _ELSE> struct IF
{};
template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE>
{
using _Type = _THEN;
};
template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE>
{
using _Type = _ELSE;
};
struct out_of_range {};
template <size_t N_id = 0>
struct list
{
static constexpr size_t id = N_id;
using type_t = list<id>;
using next = list<id + 1>;
using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >;
constexpr static const bool is_head = mp::IF<(id == 0), true, false>;
};
template <template <typename> class T_trait>
struct apply_trait
{
template <typename T>
static constexpr bool value = T_trait<T>::value;
};
template <template <typename> class T_Constraint>
struct require
{
template <typename T>
static constexpr void on()
{
static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched");
}
};
template <typename ... T> struct for_each;
template <typename T0, typename ... T> struct for_each<T0, T...>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{
T_Constraint<T0> _check; // Check by generation, not value
typename for_each<T...>::template require<T_Constraint> _next;
};
template <template <typename> class T_Functor>
static void call(void)
{
T_Functor<T0>::call();
for_each<T...>::call<T_Functor>();
}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
if (N == pos) T_Functor<T0>::call();
else for_each<T...>::call_at<T_Functor, (N + 1)>(pos);
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos)
{
if (N == pos) return T_Functor<T0>::call();
else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos);
}
};
template <> struct for_each<>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{};
template <template <typename> class T_Functor>
static void call(void)
{}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at");
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value");
}
};
}
#endif // GCL_TMP_H_
<commit_msg>gcl::mp::get_index<needle, haystack...> : add constexpr implementation. Comment previous implementation, waiting for C++20 (constexpr implementation of std::count and std::find)<commit_after>#ifndef GCL_TMP_H_
# define GCL_TMP_H_
#include <array>
namespace gcl::mp
{ // C++17
template <typename ... ts>
struct super : ts...
{};
template <template <typename...> class trait_type, typename ... ts>
struct partial_template
{
template <typename ... us>
using type = trait_type<ts..., us...>;
template <typename ... us>
static constexpr bool value = trait_type<ts..., us...>::value;
};
template <template <typename> class ... constraint_type>
struct require
{ // todo : std::conjunction ?
template <typename T>
static constexpr void on()
{
(check_constraint<constraint_type, T>(), ...);
}
template <typename T>
static inline constexpr
std::array<bool, sizeof...(constraint_type)>
values_on{ std::move(constraint_type<T>::value)... };
private:
template <template <typename> class constraint_type, typename T>
static constexpr void check_constraint()
{
static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos");
}
};
template <typename T, typename ... ts>
static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value;
template <typename to_find, typename ... ts>
constexpr auto get_index()
{
return index_of<to_find, ts...>;
// [C++20] constexpr => std::count, std::find
/*static_assert(contains<to_find, ts...>);
constexpr auto result = gcl::mp::require
<
gcl::mp::partial_template<std::is_same, ts>::type
...
>::values_on<to_find>;
auto count = std::count(std::cbegin(result), std::cend(result), true);
if (count > 1)
throw std::runtime_error("get_index : duplicate type");
if (count == 0)
throw std::out_of_range("get_index : no match");
return std::distance
(
std::cbegin(result),
std::find(std::cbegin(result), std::cend(result), true)
);*/
}
// C++17 constexpr index_of. Use recursion. remove when C++20 is ready. see get_index comments for more infos.
template <typename T, typename ...ts>
static constexpr inline auto index_of = index_of_impl<T, ts...>();
template <typename T, typename T_it = void, typename... ts>
static constexpr std::size_t index_of_impl()
{
if constexpr (std::is_same_v<T, T_it>)
return 0;
if constexpr (sizeof...(ts) == 0)
throw 0; // "index_of : no match found";
return 1 + index_of_impl<T, ts...>();
}
}
namespace gcl::deprecated::mp
{ // C++98
template <class T, class ... T_Classes>
struct super
{
struct Type : T, super<T_Classes...>::Type
{};
};
template <class T>
struct super<T>
{
using Type = T;
};
// constexpr if
template <bool condition, typename _THEN, typename _ELSE> struct IF
{};
template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE>
{
using _Type = _THEN;
};
template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE>
{
using _Type = _ELSE;
};
struct out_of_range {};
template <size_t N_id = 0>
struct list
{
static constexpr size_t id = N_id;
using type_t = list<id>;
using next = list<id + 1>;
using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >;
constexpr static const bool is_head = mp::IF<(id == 0), true, false>;
};
template <template <typename> class T_trait>
struct apply_trait
{
template <typename T>
static constexpr bool value = T_trait<T>::value;
};
template <template <typename> class T_Constraint>
struct require
{
template <typename T>
static constexpr void on()
{
static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched");
}
};
template <typename ... T> struct for_each;
template <typename T0, typename ... T> struct for_each<T0, T...>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{
T_Constraint<T0> _check; // Check by generation, not value
typename for_each<T...>::template require<T_Constraint> _next;
};
template <template <typename> class T_Functor>
static void call(void)
{
T_Functor<T0>::call();
for_each<T...>::call<T_Functor>();
}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
if (N == pos) T_Functor<T0>::call();
else for_each<T...>::call_at<T_Functor, (N + 1)>(pos);
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos)
{
if (N == pos) return T_Functor<T0>::call();
else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos);
}
};
template <> struct for_each<>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{};
template <template <typename> class T_Functor>
static void call(void)
{}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at");
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value");
}
};
}
#endif // GCL_TMP_H_
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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 <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/RenderPath.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Slider.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Text.h>
#ifdef URHO3D_ANGELSCRIPT
#include <Urho3D/AngelScript/Script.h>
#endif
#include "PBRMaterials.h"
#include <Urho3D/DebugNew.h>
URHO3D_DEFINE_APPLICATION_MAIN(PBRMaterials)
PBRMaterials::PBRMaterials(Context* context) :
Sample(context),
dynamicMaterial_(0),
roughnessLabel_(0),
metallicLabel_(0),
ambientLabel_(0)
{
}
void PBRMaterials::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateUI();
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Subscribe to global events for camera movement
SubscribeToEvents();
}
void PBRMaterials::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use sliders to change Roughness and Metallic\n"
"Hold RMB and use WASD keys and mouse to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
instructionText->SetTextAlignment(HA_CENTER);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void PBRMaterials::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
#ifdef URHO3D_ANGELSCRIPT
// The scene uses an AngelScript component for animation. Instantiate the subsystem if possible
context_->RegisterSubsystem(new Script(context_));
#endif
scene_ = new Scene(context_);
// Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system
// which scene.LoadXML() will read
SharedPtr<File> file = cache->GetFile("Scenes/PBRExample.xml");
scene_->LoadXML(*file);
Node* sphereWithDynamicMatNode = scene_->GetChild("SphereWithDynamicMat");
StaticModel* staticModel = sphereWithDynamicMatNode->GetComponent<StaticModel>();
dynamicMaterial_ = staticModel->GetMaterial(0);
Node* zoneNode = scene_->GetChild("Zone");
zone_ = zoneNode->GetComponent<Zone>();
// Create the camera (not included in the scene file)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
cameraNode_->SetPosition(sphereWithDynamicMatNode->GetPosition() + Vector3(2.0f, 2.0f, 2.0f));
cameraNode_->LookAt(sphereWithDynamicMatNode->GetPosition());
yaw_ = cameraNode_->GetRotation().YawAngle();
pitch_ = cameraNode_->GetRotation().PitchAngle();
}
void PBRMaterials::CreateUI()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Set up global UI style into the root UI element
XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
ui->GetRoot()->SetDefaultStyle(style);
// Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
// control the camera, and when visible, it will interact with the UI
SharedPtr<Cursor> cursor(new Cursor(context_));
cursor->SetStyleAuto();
ui->SetCursor(cursor);
// Set starting position of the cursor at the rendering window center
Graphics* graphics = GetSubsystem<Graphics>();
cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
roughnessLabel_ = ui->GetRoot()->CreateChild<Text>();
roughnessLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
roughnessLabel_->SetPosition(370, 50);
roughnessLabel_->SetTextEffect(TE_SHADOW);
metallicLabel_ = ui->GetRoot()->CreateChild<Text>();
metallicLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
metallicLabel_->SetPosition(370, 100);
metallicLabel_->SetTextEffect(TE_SHADOW);
ambientLabel_ = ui->GetRoot()->CreateChild<Text>();
ambientLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
ambientLabel_->SetPosition(370, 150);
ambientLabel_->SetTextEffect(TE_SHADOW);
Slider* roughnessSlider = ui->GetRoot()->CreateChild<Slider>();
roughnessSlider->SetStyleAuto();
roughnessSlider->SetPosition(50, 50);
roughnessSlider->SetSize(300, 20);
roughnessSlider->SetRange(1.0f); // 0 - 1 range
SubscribeToEvent(roughnessSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleRoughnessSliderChanged));
roughnessSlider->SetValue(0.5f);
Slider* metallicSlider = ui->GetRoot()->CreateChild<Slider>();
metallicSlider->SetStyleAuto();
metallicSlider->SetPosition(50, 100);
metallicSlider->SetSize(300, 20);
metallicSlider->SetRange(1.0f); // 0 - 1 range
SubscribeToEvent(metallicSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleMetallicSliderChanged));
metallicSlider->SetValue(0.5f);
Slider* ambientSlider = ui->GetRoot()->CreateChild<Slider>();
ambientSlider->SetStyleAuto();
ambientSlider->SetPosition(50, 150);
ambientSlider->SetSize(300, 20);
ambientSlider->SetRange(10.0f); // 0 - 10 range
SubscribeToEvent(ambientSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleAmbientSliderChanged));
ambientSlider->SetValue(zone_->GetAmbientColor().a_);
}
void PBRMaterials::HandleRoughnessSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
dynamicMaterial_->SetShaderParameter("Roughness", newValue);
roughnessLabel_->SetText("Roughness: " + String(newValue));
}
void PBRMaterials::HandleMetallicSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
dynamicMaterial_->SetShaderParameter("Metallic", newValue);
metallicLabel_->SetText("Metallic: " + String(newValue));
}
void PBRMaterials::HandleAmbientSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
Color col = Color(0.0, 0.0, 0.0, newValue);
zone_->SetAmbientColor(col);
ambientLabel_->SetText("Ambient HDR Scale: " + String(zone_->GetAmbientColor().a_));
}
void PBRMaterials::SetupViewport()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
Renderer* renderer = GetSubsystem<Renderer>();
renderer->SetHDRRendering(true);
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
// Add post-processing effects appropriate with the example scene
SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/GammaCorrection.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Tonemap.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml"));
viewport->SetRenderPath(effectRenderPath);
}
void PBRMaterials::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for camera motion
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(PBRMaterials, HandleUpdate));
}
void PBRMaterials::MoveCamera(float timeStep)
{
// Right mouse button controls mouse cursor visibility: hide when pressed
UI* ui = GetSubsystem<UI>();
Input* input = GetSubsystem<Input>();
ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
// Do not move if the UI has a focused element
if (ui->GetFocusElement())
return;
// Movement speed as world units per second
const float MOVE_SPEED = 10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
// Only move the camera when the cursor is hidden
if (!ui->GetCursor()->IsVisible())
{
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
}
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown(KEY_W))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_S))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_A))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_D))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void PBRMaterials::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<commit_msg>Tabs to spaces.<commit_after>//
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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 <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/RenderPath.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Slider.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Text.h>
#ifdef URHO3D_ANGELSCRIPT
#include <Urho3D/AngelScript/Script.h>
#endif
#include "PBRMaterials.h"
#include <Urho3D/DebugNew.h>
URHO3D_DEFINE_APPLICATION_MAIN(PBRMaterials)
PBRMaterials::PBRMaterials(Context* context) :
Sample(context),
dynamicMaterial_(0),
roughnessLabel_(0),
metallicLabel_(0),
ambientLabel_(0)
{
}
void PBRMaterials::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateUI();
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Subscribe to global events for camera movement
SubscribeToEvents();
}
void PBRMaterials::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use sliders to change Roughness and Metallic\n"
"Hold RMB and use WASD keys and mouse to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
instructionText->SetTextAlignment(HA_CENTER);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void PBRMaterials::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
#ifdef URHO3D_ANGELSCRIPT
// The scene uses an AngelScript component for animation. Instantiate the subsystem if possible
context_->RegisterSubsystem(new Script(context_));
#endif
scene_ = new Scene(context_);
// Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system
// which scene.LoadXML() will read
SharedPtr<File> file = cache->GetFile("Scenes/PBRExample.xml");
scene_->LoadXML(*file);
Node* sphereWithDynamicMatNode = scene_->GetChild("SphereWithDynamicMat");
StaticModel* staticModel = sphereWithDynamicMatNode->GetComponent<StaticModel>();
dynamicMaterial_ = staticModel->GetMaterial(0);
Node* zoneNode = scene_->GetChild("Zone");
zone_ = zoneNode->GetComponent<Zone>();
// Create the camera (not included in the scene file)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
cameraNode_->SetPosition(sphereWithDynamicMatNode->GetPosition() + Vector3(2.0f, 2.0f, 2.0f));
cameraNode_->LookAt(sphereWithDynamicMatNode->GetPosition());
yaw_ = cameraNode_->GetRotation().YawAngle();
pitch_ = cameraNode_->GetRotation().PitchAngle();
}
void PBRMaterials::CreateUI()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Set up global UI style into the root UI element
XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
ui->GetRoot()->SetDefaultStyle(style);
// Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
// control the camera, and when visible, it will interact with the UI
SharedPtr<Cursor> cursor(new Cursor(context_));
cursor->SetStyleAuto();
ui->SetCursor(cursor);
// Set starting position of the cursor at the rendering window center
Graphics* graphics = GetSubsystem<Graphics>();
cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
roughnessLabel_ = ui->GetRoot()->CreateChild<Text>();
roughnessLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
roughnessLabel_->SetPosition(370, 50);
roughnessLabel_->SetTextEffect(TE_SHADOW);
metallicLabel_ = ui->GetRoot()->CreateChild<Text>();
metallicLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
metallicLabel_->SetPosition(370, 100);
metallicLabel_->SetTextEffect(TE_SHADOW);
ambientLabel_ = ui->GetRoot()->CreateChild<Text>();
ambientLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
ambientLabel_->SetPosition(370, 150);
ambientLabel_->SetTextEffect(TE_SHADOW);
Slider* roughnessSlider = ui->GetRoot()->CreateChild<Slider>();
roughnessSlider->SetStyleAuto();
roughnessSlider->SetPosition(50, 50);
roughnessSlider->SetSize(300, 20);
roughnessSlider->SetRange(1.0f); // 0 - 1 range
SubscribeToEvent(roughnessSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleRoughnessSliderChanged));
roughnessSlider->SetValue(0.5f);
Slider* metallicSlider = ui->GetRoot()->CreateChild<Slider>();
metallicSlider->SetStyleAuto();
metallicSlider->SetPosition(50, 100);
metallicSlider->SetSize(300, 20);
metallicSlider->SetRange(1.0f); // 0 - 1 range
SubscribeToEvent(metallicSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleMetallicSliderChanged));
metallicSlider->SetValue(0.5f);
Slider* ambientSlider = ui->GetRoot()->CreateChild<Slider>();
ambientSlider->SetStyleAuto();
ambientSlider->SetPosition(50, 150);
ambientSlider->SetSize(300, 20);
ambientSlider->SetRange(10.0f); // 0 - 10 range
SubscribeToEvent(ambientSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleAmbientSliderChanged));
ambientSlider->SetValue(zone_->GetAmbientColor().a_);
}
void PBRMaterials::HandleRoughnessSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
dynamicMaterial_->SetShaderParameter("Roughness", newValue);
roughnessLabel_->SetText("Roughness: " + String(newValue));
}
void PBRMaterials::HandleMetallicSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
dynamicMaterial_->SetShaderParameter("Metallic", newValue);
metallicLabel_->SetText("Metallic: " + String(newValue));
}
void PBRMaterials::HandleAmbientSliderChanged(StringHash eventType, VariantMap& eventData)
{
float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
Color col = Color(0.0, 0.0, 0.0, newValue);
zone_->SetAmbientColor(col);
ambientLabel_->SetText("Ambient HDR Scale: " + String(zone_->GetAmbientColor().a_));
}
void PBRMaterials::SetupViewport()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
Renderer* renderer = GetSubsystem<Renderer>();
renderer->SetHDRRendering(true);
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
// Add post-processing effects appropriate with the example scene
SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/GammaCorrection.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Tonemap.xml"));
effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml"));
viewport->SetRenderPath(effectRenderPath);
}
void PBRMaterials::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for camera motion
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(PBRMaterials, HandleUpdate));
}
void PBRMaterials::MoveCamera(float timeStep)
{
// Right mouse button controls mouse cursor visibility: hide when pressed
UI* ui = GetSubsystem<UI>();
Input* input = GetSubsystem<Input>();
ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
// Do not move if the UI has a focused element
if (ui->GetFocusElement())
return;
// Movement speed as world units per second
const float MOVE_SPEED = 10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
// Only move the camera when the cursor is hidden
if (!ui->GetCursor()->IsVisible())
{
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
}
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown(KEY_W))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_S))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_A))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_D))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void PBRMaterials::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<|endoftext|> |
<commit_before>// Time: ctor: O(n),
// update: O(logn),
// query: O(logn)
// Space: O(n)
// Segment Tree solution.
class NumArray {
public:
NumArray(vector<int> &nums) : nums_(nums) {
root_ = buildHelper(nums, 0, nums.size() - 1);
}
void update(int i, int val) {
if (nums_[i] != val) {
nums_[i] = val;
updateHelper(root_, i, val);
}
}
int sumRange(int i, int j) {
return sumRangeHelper(root_, i, j);
}
private:
vector<int>& nums_;
class SegmentTreeNode {
public:
int start, end;
int sum;
SegmentTreeNode *left, *right;
SegmentTreeNode(int i, int j, int s) :
start(i), end(j), sum(s),
left(nullptr), right(nullptr) {
}
};
SegmentTreeNode *root_;
// Build segment tree.
SegmentTreeNode *buildHelper(const vector<int>& nums, int start, int end) {
if (start > end) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeNode *root = new SegmentTreeNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = nums[start];
return root;
}
// Left child: start=numsleft, end=(numsleft + numsright) / 2.
root->left = buildHelper(nums, start, (start + end) / 2);
// Right child: start=(numsleft + numsright) / 2 + 1, end=numsright.
root->right = buildHelper(nums, (start + end) / 2 + 1, end);
// Update sum.
root->sum = (root->left != nullptr ? root->left->sum : 0) +
(root->right != nullptr ? root->right->sum : 0);
return root;
}
void updateHelper(SegmentTreeNode *root, int i, int val) {
// Out of range.
if (root == nullptr || root->start > i || root->end < i) {
return;
}
// Change the node's value with [i] to the new given value.
if (root->start == i && root->end == i) {
root->sum = val;
return;
}
updateHelper(root->left, i, val);
updateHelper(root->right, i, val);
// Update sum.
root->sum = (root->left != nullptr ? root->left->sum : 0) +
(root->right != nullptr ? root->right->sum : 0);
}
int sumRangeHelper(SegmentTreeNode *root, int start, int end) {
// Out of range.
if (root == nullptr || root->start > end || root->end < start) {
return 0;
}
// Current segment is totally within range [start, end]
if (root->start >= start && root->end <= end) {
return root->sum;
}
return sumRangeHelper(root->left, start, end) +
sumRangeHelper(root->right, start, end);
}
};
// Time: ctor: O(nlogn),
// update: O(logn),
// query: O(logn)
// Space: O(n)
// Binary Indexed Tree (BIT) solution.
class NumArray2 {
public:
NumArray(vector<int> &nums) :
nums_(nums), n_(nums.size()) {
bit_ = vector<int>(n_ + 1);
for (int i = 0; i < n_; ++i) {
add(i, nums_[i]);
}
}
void update(int i, int val) {
if (val - nums_[i]) {
add(i, val - nums_[i]);
nums_[i] = val;
}
}
int sumRange(int i, int j) {
int sum = sumRegion_bit(j);
if (i > 0) {
sum -= sumRegion_bit(i - 1);
}
return sum;
}
private:
vector<int> &nums_;
vector<int> bit_;
int n_;
int sumRegion_bit(int i) {
++i;
int sum = 0;
for (; i > 0; i -= lower_bit(i)) {
sum += bit_[i];
}
return sum;
}
void add(int i, int val) {
++i;
for (; i <= n_; i += lower_bit(i)) {
bit_[i] += val;
}
}
int lower_bit(int i) {
return i & -i;
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);
<commit_msg>Update range-sum-query-mutable.cpp<commit_after>// Time: ctor: O(n),
// update: O(logn),
// query: O(logn)
// Space: O(n)
// Segment Tree solution.
class NumArray {
public:
NumArray(vector<int> &nums) : nums_(nums) {
root_ = buildHelper(nums, 0, nums.size() - 1);
}
void update(int i, int val) {
if (nums_[i] != val) {
nums_[i] = val;
updateHelper(root_, i, val);
}
}
int sumRange(int i, int j) {
return sumRangeHelper(root_, i, j);
}
private:
vector<int>& nums_;
class SegmentTreeNode {
public:
int start, end;
int sum;
SegmentTreeNode *left, *right;
SegmentTreeNode(int i, int j, int s) :
start(i), end(j), sum(s),
left(nullptr), right(nullptr) {
}
};
SegmentTreeNode *root_;
// Build segment tree.
SegmentTreeNode *buildHelper(const vector<int>& nums, int start, int end) {
if (start > end) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeNode *root = new SegmentTreeNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = nums[start];
return root;
}
// Left child: start=numsleft, end=(numsleft + numsright) / 2.
root->left = buildHelper(nums, start, (start + end) / 2);
// Right child: start=(numsleft + numsright) / 2 + 1, end=numsright.
root->right = buildHelper(nums, (start + end) / 2 + 1, end);
// Update sum.
root->sum = (root->left != nullptr ? root->left->sum : 0) +
(root->right != nullptr ? root->right->sum : 0);
return root;
}
void updateHelper(SegmentTreeNode *root, int i, int val) {
// Out of range.
if (root == nullptr || root->start > i || root->end < i) {
return;
}
// Change the node's value with [i] to the new given value.
if (root->start == i && root->end == i) {
root->sum = val;
return;
}
updateHelper(root->left, i, val);
updateHelper(root->right, i, val);
// Update sum.
root->sum = (root->left != nullptr ? root->left->sum : 0) +
(root->right != nullptr ? root->right->sum : 0);
}
int sumRangeHelper(SegmentTreeNode *root, int start, int end) {
// Out of range.
if (root == nullptr || root->start > end || root->end < start) {
return 0;
}
// Current segment is totally within range [start, end]
if (root->start >= start && root->end <= end) {
return root->sum;
}
return sumRangeHelper(root->left, start, end) +
sumRangeHelper(root->right, start, end);
}
};
// Time: ctor: O(nlogn),
// update: O(logn),
// query: O(logn)
// Space: O(n)
// Binary Indexed Tree (BIT) solution.
class NumArray2 {
public:
NumArray(vector<int> &nums) : nums_(nums) {
bit_ = vector<int>(nums_.size() + 1);
for (int i = 0; i < nums_.size(); ++i) {
add(i, nums_[i]);
}
}
void update(int i, int val) {
if (val - nums_[i]) {
add(i, val - nums_[i]);
nums_[i] = val;
}
}
int sumRange(int i, int j) {
int sum = sumRegion_bit(j);
if (i > 0) {
sum -= sumRegion_bit(i - 1);
}
return sum;
}
private:
vector<int> &nums_;
vector<int> bit_;
int sumRegion_bit(int i) {
++i;
int sum = 0;
for (; i > 0; i -= lower_bit(i)) {
sum += bit_[i];
}
return sum;
}
void add(int i, int val) {
++i;
for (; i <= nums_.size(); i += lower_bit(i)) {
bit_[i] += val;
}
}
int lower_bit(int i) {
return i & -i;
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);
<|endoftext|> |
<commit_before>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - OpenGL Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLLoader.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.hpp>
#ifdef NAZARA_PLATFORM_LINUX
#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextX11.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextWayland.hpp>
#endif
#ifdef NAZARA_PLATFORM_WINDOWS
#include <Nazara/OpenGLRenderer/Wrapper/Win32/EGLContextWin32.hpp>
#endif
#include <Nazara/OpenGLRenderer/Debug.hpp>
namespace Nz::GL
{
EGLLoader::EGLLoader()
{
if (!m_eglLib.Load("libEGL"))
throw std::runtime_error("failed to load gdi32.dll: " + m_eglLib.GetLastError());
auto LoadSymbol = [](DynLib& lib, auto& func, const char* funcName)
{
func = reinterpret_cast<std::decay_t<decltype(func)>>(lib.GetSymbol(funcName));
if (!func)
throw std::runtime_error("failed to load core function " + std::string(funcName));
};
// Load gdi32 functions
#define NAZARA_OPENGLRENDERER_EXT_BEGIN(ext)
#define NAZARA_OPENGLRENDERER_EXT_END()
#define NAZARA_OPENGLRENDERER_EXT_FUNC(name, sig) //< Ignore extensions
// Load base WGL functions
#define NAZARA_OPENGLRENDERER_FUNC(name, sig) LoadSymbol(m_eglLib, name, #name);
NAZARA_OPENGLRENDERER_FOREACH_EGL_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_EXT_BEGIN, NAZARA_OPENGLRENDERER_EXT_END, NAZARA_OPENGLRENDERER_EXT_FUNC)
#undef NAZARA_OPENGLRENDERER_FUNC
#undef NAZARA_OPENGLRENDERER_EXT_BEGIN
#undef NAZARA_OPENGLRENDERER_EXT_END
#undef NAZARA_OPENGLRENDERER_EXT_FUNC
// Try to create a dummy context in order to check EGL support (FIXME: is this really necessary?)
ContextParams params;
EGLContextBase baseContext(nullptr, *this);
if (!baseContext.Create(params))
throw std::runtime_error("failed to create load context");
if (!baseContext.Initialize(params))
throw std::runtime_error("failed to load OpenGL functions");
}
std::unique_ptr<Context> EGLLoader::CreateContext(const OpenGLDevice* device, const ContextParams& params, Context* shareContext) const
{
std::unique_ptr<EGLContextBase> context;
#ifdef NAZARA_PLATFORM_WINDOWS
// On Windows context sharing seems to work only with window contexts
context = std::make_unique<EGLContextWin32>(device, *this);
#else
context = std::make_unique<EGLContextBase>(device, *this);
#endif
if (!context->Create(params, static_cast<EGLContextBase*>(shareContext)))
{
NazaraError("failed to create context");
return {};
}
if (!context->Initialize(params))
{
NazaraError("failed to initialize context");
return {};
}
return context;
}
std::unique_ptr<Context> EGLLoader::CreateContext(const OpenGLDevice* device, const ContextParams& params, WindowHandle handle, Context* shareContext) const
{
std::unique_ptr<EGLContextBase> context;
switch (handle.type)
{
case WindowManager::Invalid:
break;
case WindowManager::X11:
#ifdef NAZARA_PLATFORM_LINUX
context = std::make_unique<EGLContextX11>(device, *this);
#endif
break;
case WindowManager::Windows:
#ifdef NAZARA_PLATFORM_WINDOWS
context = std::make_unique<EGLContextWin32>(device, *this);
#endif
break;
case WindowManager::Wayland:
#ifdef NAZARA_PLATFORM_LINUX
context = std::make_unique<EGLContextWayland>(device, *this);
#endif
break;
}
if (!context)
{
NazaraError("unsupported window type");
return {};
}
if (!context->Create(params, handle, /*static_cast<EGLContextBase*>(shareContext)*/nullptr))
{
NazaraError("failed to create context");
return {};
}
if (!context->Initialize(params))
{
NazaraError("failed to initialize context");
return {};
}
return context;
}
GLFunction EGLLoader::LoadFunction(const char* name) const
{
return eglGetProcAddress(name);
}
const char* EGLLoader::TranslateError(EGLint errorId)
{
switch (errorId)
{
case EGL_SUCCESS: return "The last function succeeded without error.";
case EGL_NOT_INITIALIZED: return "EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
case EGL_BAD_ACCESS: return "EGL cannot access a requested resource.";
case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation.";
case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list.";
case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context.";
case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration.";
case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection.";
case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
case EGL_BAD_MATCH: return "Arguments are inconsistent.";
case EGL_BAD_PARAMETER: return "One or more argument values are invalid.";
case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap.";
case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window.";
case EGL_CONTEXT_LOST: return "A power management event has occurred.";
default: return "Invalid or unknown error.";
}
}
}
<commit_msg>Fix context sharing<commit_after>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - OpenGL Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLLoader.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.hpp>
#ifdef NAZARA_PLATFORM_LINUX
#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextX11.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextWayland.hpp>
#endif
#ifdef NAZARA_PLATFORM_WINDOWS
#include <Nazara/OpenGLRenderer/Wrapper/Win32/EGLContextWin32.hpp>
#endif
#include <Nazara/OpenGLRenderer/Debug.hpp>
namespace Nz::GL
{
EGLLoader::EGLLoader()
{
if (!m_eglLib.Load("libEGL"))
throw std::runtime_error("failed to load gdi32.dll: " + m_eglLib.GetLastError());
auto LoadSymbol = [](DynLib& lib, auto& func, const char* funcName)
{
func = reinterpret_cast<std::decay_t<decltype(func)>>(lib.GetSymbol(funcName));
if (!func)
throw std::runtime_error("failed to load core function " + std::string(funcName));
};
// Load gdi32 functions
#define NAZARA_OPENGLRENDERER_EXT_BEGIN(ext)
#define NAZARA_OPENGLRENDERER_EXT_END()
#define NAZARA_OPENGLRENDERER_EXT_FUNC(name, sig) //< Ignore extensions
// Load base WGL functions
#define NAZARA_OPENGLRENDERER_FUNC(name, sig) LoadSymbol(m_eglLib, name, #name);
NAZARA_OPENGLRENDERER_FOREACH_EGL_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_EXT_BEGIN, NAZARA_OPENGLRENDERER_EXT_END, NAZARA_OPENGLRENDERER_EXT_FUNC)
#undef NAZARA_OPENGLRENDERER_FUNC
#undef NAZARA_OPENGLRENDERER_EXT_BEGIN
#undef NAZARA_OPENGLRENDERER_EXT_END
#undef NAZARA_OPENGLRENDERER_EXT_FUNC
// Try to create a dummy context in order to check EGL support (FIXME: is this really necessary?)
ContextParams params;
EGLContextBase baseContext(nullptr, *this);
if (!baseContext.Create(params))
throw std::runtime_error("failed to create load context");
if (!baseContext.Initialize(params))
throw std::runtime_error("failed to load OpenGL functions");
}
std::unique_ptr<Context> EGLLoader::CreateContext(const OpenGLDevice* device, const ContextParams& params, Context* shareContext) const
{
std::unique_ptr<EGLContextBase> context;
#ifdef NAZARA_PLATFORM_WINDOWS
// On Windows context sharing seems to work only with window contexts
context = std::make_unique<EGLContextWin32>(device, *this);
#else
context = std::make_unique<EGLContextBase>(device, *this);
#endif
if (!context->Create(params, static_cast<EGLContextBase*>(shareContext)))
{
NazaraError("failed to create context");
return {};
}
if (!context->Initialize(params))
{
NazaraError("failed to initialize context");
return {};
}
return context;
}
std::unique_ptr<Context> EGLLoader::CreateContext(const OpenGLDevice* device, const ContextParams& params, WindowHandle handle, Context* shareContext) const
{
std::unique_ptr<EGLContextBase> context;
switch (handle.type)
{
case WindowManager::Invalid:
break;
case WindowManager::X11:
#ifdef NAZARA_PLATFORM_LINUX
context = std::make_unique<EGLContextX11>(device, *this);
#endif
break;
case WindowManager::Windows:
#ifdef NAZARA_PLATFORM_WINDOWS
context = std::make_unique<EGLContextWin32>(device, *this);
#endif
break;
case WindowManager::Wayland:
#ifdef NAZARA_PLATFORM_LINUX
context = std::make_unique<EGLContextWayland>(device, *this);
#endif
break;
}
if (!context)
{
NazaraError("unsupported window type");
return {};
}
if (!context->Create(params, handle, static_cast<EGLContextBase*>(shareContext)))
{
NazaraError("failed to create context");
return {};
}
if (!context->Initialize(params))
{
NazaraError("failed to initialize context");
return {};
}
return context;
}
GLFunction EGLLoader::LoadFunction(const char* name) const
{
return eglGetProcAddress(name);
}
const char* EGLLoader::TranslateError(EGLint errorId)
{
switch (errorId)
{
case EGL_SUCCESS: return "The last function succeeded without error.";
case EGL_NOT_INITIALIZED: return "EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
case EGL_BAD_ACCESS: return "EGL cannot access a requested resource.";
case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation.";
case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list.";
case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context.";
case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration.";
case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection.";
case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
case EGL_BAD_MATCH: return "Arguments are inconsistent.";
case EGL_BAD_PARAMETER: return "One or more argument values are invalid.";
case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap.";
case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window.";
case EGL_CONTEXT_LOST: return "A power management event has occurred.";
default: return "Invalid or unknown error.";
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Google Inc. 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 Google Inc. 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 "config.h"
#include "modules/filesystem/DOMFileSystemSync.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileError.h"
#include "modules/filesystem/DOMFilePath.h"
#include "modules/filesystem/DirectoryEntrySync.h"
#include "modules/filesystem/ErrorCallback.h"
#include "modules/filesystem/FileEntrySync.h"
#include "modules/filesystem/FileSystemCallbacks.h"
#include "modules/filesystem/FileWriterBaseCallback.h"
#include "modules/filesystem/FileWriterSync.h"
#include "platform/FileMetadata.h"
#include "public/platform/WebFileSystem.h"
#include "public/platform/WebFileSystemCallbacks.h"
namespace WebCore {
class FileWriterBase;
PassRefPtr<DOMFileSystemSync> DOMFileSystemSync::create(DOMFileSystemBase* fileSystem)
{
return adoptRef(new DOMFileSystemSync(fileSystem->m_context, fileSystem->name(), fileSystem->type(), fileSystem->rootURL()));
}
DOMFileSystemSync::DOMFileSystemSync(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL)
: DOMFileSystemBase(context, name, type, rootURL)
{
ScriptWrappable::init(this);
}
DOMFileSystemSync::~DOMFileSystemSync()
{
}
void DOMFileSystemSync::reportError(PassOwnPtr<ErrorCallback> errorCallback, PassRefPtr<FileError> fileError)
{
errorCallback->handleEvent(fileError.get());
}
PassRefPtr<DirectoryEntrySync> DOMFileSystemSync::root()
{
return DirectoryEntrySync::create(this, DOMFilePath::root);
}
namespace {
class CreateFileHelper FINAL : public AsyncFileSystemCallbacks {
public:
class CreateFileResult : public RefCounted<CreateFileResult> {
public:
static PassRefPtr<CreateFileResult> create()
{
return adoptRef(new CreateFileResult());
}
bool m_failed;
int m_code;
RefPtr<File> m_file;
private:
CreateFileResult()
: m_failed(false)
, m_code(0)
{
}
~CreateFileResult()
{
}
friend class WTF::RefCounted<CreateFileResult>;
};
static PassOwnPtr<AsyncFileSystemCallbacks> create(PassRefPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
{
return adoptPtr(static_cast<AsyncFileSystemCallbacks*>(new CreateFileHelper(result, name, url, type)));
}
virtual void didFail(int code) OVERRIDE
{
m_result->m_failed = true;
m_result->m_code = code;
}
virtual ~CreateFileHelper()
{
}
virtual void didCreateSnapshotFile(const FileMetadata& metadata, PassRefPtr<BlobDataHandle> snapshot) OVERRIDE
{
// We can't directly use the snapshot blob data handle because the content type on it hasn't been set.
// The |snapshot| param is here to provide a a chain of custody thru thread bridging that is held onto until
// *after* we've coined a File with a new handle that has the correct type set on it. This allows the
// blob storage system to track when a temp file can and can't be safely deleted.
// For regular filesystem types (temporary or persistent), we should not cache file metadata as it could change File semantics.
// For other filesystem types (which could be platform-specific ones), there's a chance that the files are on remote filesystem.
// If the port has returned metadata just pass it to File constructor (so we may cache the metadata).
// FIXME: We should use the snapshot metadata for all files.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=17746
if (m_type == FileSystemTypeTemporary || m_type == FileSystemTypePersistent) {
m_result->m_file = File::createWithName(metadata.platformPath, m_name);
} else if (!metadata.platformPath.isEmpty()) {
// If the platformPath in the returned metadata is given, we create a File object for the path.
m_result->m_file = File::createForFileSystemFile(m_name, metadata).get();
} else {
// Otherwise create a File from the FileSystem URL.
m_result->m_file = File::createForFileSystemFile(m_url, metadata).get();
}
}
virtual bool shouldBlockUntilCompletion() const OVERRIDE
{
return true;
}
private:
CreateFileHelper(PassRefPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
RefPtr<CreateFileResult> m_result;
String m_name;
KURL m_url;
FileSystemType m_type;
};
} // namespace
PassRefPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
KURL fileSystemURL = createFileSystemURL(fileEntry);
RefPtr<CreateFileHelper::CreateFileResult> result(CreateFileHelper::CreateFileResult::create());
fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type()));
if (result->m_failed) {
exceptionState.throwUninformativeAndGenericDOMException(result->m_code);
return 0;
}
return result->m_file;
}
namespace {
class ReceiveFileWriterCallback FINAL : public FileWriterBaseCallback {
public:
static PassOwnPtr<ReceiveFileWriterCallback> create()
{
return adoptPtr(new ReceiveFileWriterCallback());
}
virtual void handleEvent(FileWriterBase*) OVERRIDE
{
}
private:
ReceiveFileWriterCallback()
{
}
};
class LocalErrorCallback FINAL : public ErrorCallback {
public:
static PassOwnPtr<LocalErrorCallback> create(FileError::ErrorCode& errorCode)
{
return adoptPtr(new LocalErrorCallback(errorCode));
}
virtual void handleEvent(FileError* error) OVERRIDE
{
ASSERT(error->code() != FileError::OK);
m_errorCode = error->code();
}
private:
explicit LocalErrorCallback(FileError::ErrorCode& errorCode)
: m_errorCode(errorCode)
{
}
FileError::ErrorCode& m_errorCode;
};
}
PassRefPtr<FileWriterSync> DOMFileSystemSync::createWriter(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
ASSERT(fileEntry);
RefPtr<FileWriterSync> fileWriter = FileWriterSync::create();
OwnPtr<ReceiveFileWriterCallback> successCallback = ReceiveFileWriterCallback::create();
FileError::ErrorCode errorCode = FileError::OK;
OwnPtr<LocalErrorCallback> errorCallback = LocalErrorCallback::create(errorCode);
OwnPtr<AsyncFileSystemCallbacks> callbacks = FileWriterBaseCallbacks::create(fileWriter, successCallback.release(), errorCallback.release());
callbacks->setShouldBlockUntilCompletion(true);
fileSystem()->createFileWriter(createFileSystemURL(fileEntry), fileWriter.get(), callbacks.release());
if (errorCode != FileError::OK) {
FileError::throwDOMException(exceptionState, errorCode);
return 0;
}
return fileWriter.release();
}
}
<commit_msg>Improve exception message in Source/modules/filesystem/DOMFileSystemSync.cpp.<commit_after>/*
* Copyright (C) 2010 Google Inc. 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 Google Inc. 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 "config.h"
#include "modules/filesystem/DOMFileSystemSync.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileError.h"
#include "modules/filesystem/DOMFilePath.h"
#include "modules/filesystem/DirectoryEntrySync.h"
#include "modules/filesystem/ErrorCallback.h"
#include "modules/filesystem/FileEntrySync.h"
#include "modules/filesystem/FileSystemCallbacks.h"
#include "modules/filesystem/FileWriterBaseCallback.h"
#include "modules/filesystem/FileWriterSync.h"
#include "platform/FileMetadata.h"
#include "public/platform/WebFileSystem.h"
#include "public/platform/WebFileSystemCallbacks.h"
namespace WebCore {
class FileWriterBase;
PassRefPtr<DOMFileSystemSync> DOMFileSystemSync::create(DOMFileSystemBase* fileSystem)
{
return adoptRef(new DOMFileSystemSync(fileSystem->m_context, fileSystem->name(), fileSystem->type(), fileSystem->rootURL()));
}
DOMFileSystemSync::DOMFileSystemSync(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL)
: DOMFileSystemBase(context, name, type, rootURL)
{
ScriptWrappable::init(this);
}
DOMFileSystemSync::~DOMFileSystemSync()
{
}
void DOMFileSystemSync::reportError(PassOwnPtr<ErrorCallback> errorCallback, PassRefPtr<FileError> fileError)
{
errorCallback->handleEvent(fileError.get());
}
PassRefPtr<DirectoryEntrySync> DOMFileSystemSync::root()
{
return DirectoryEntrySync::create(this, DOMFilePath::root);
}
namespace {
class CreateFileHelper FINAL : public AsyncFileSystemCallbacks {
public:
class CreateFileResult : public RefCounted<CreateFileResult> {
public:
static PassRefPtr<CreateFileResult> create()
{
return adoptRef(new CreateFileResult());
}
bool m_failed;
int m_code;
RefPtr<File> m_file;
private:
CreateFileResult()
: m_failed(false)
, m_code(0)
{
}
~CreateFileResult()
{
}
friend class WTF::RefCounted<CreateFileResult>;
};
static PassOwnPtr<AsyncFileSystemCallbacks> create(PassRefPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
{
return adoptPtr(static_cast<AsyncFileSystemCallbacks*>(new CreateFileHelper(result, name, url, type)));
}
virtual void didFail(int code) OVERRIDE
{
m_result->m_failed = true;
m_result->m_code = code;
}
virtual ~CreateFileHelper()
{
}
virtual void didCreateSnapshotFile(const FileMetadata& metadata, PassRefPtr<BlobDataHandle> snapshot) OVERRIDE
{
// We can't directly use the snapshot blob data handle because the content type on it hasn't been set.
// The |snapshot| param is here to provide a a chain of custody thru thread bridging that is held onto until
// *after* we've coined a File with a new handle that has the correct type set on it. This allows the
// blob storage system to track when a temp file can and can't be safely deleted.
// For regular filesystem types (temporary or persistent), we should not cache file metadata as it could change File semantics.
// For other filesystem types (which could be platform-specific ones), there's a chance that the files are on remote filesystem.
// If the port has returned metadata just pass it to File constructor (so we may cache the metadata).
// FIXME: We should use the snapshot metadata for all files.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=17746
if (m_type == FileSystemTypeTemporary || m_type == FileSystemTypePersistent) {
m_result->m_file = File::createWithName(metadata.platformPath, m_name);
} else if (!metadata.platformPath.isEmpty()) {
// If the platformPath in the returned metadata is given, we create a File object for the path.
m_result->m_file = File::createForFileSystemFile(m_name, metadata).get();
} else {
// Otherwise create a File from the FileSystem URL.
m_result->m_file = File::createForFileSystemFile(m_url, metadata).get();
}
}
virtual bool shouldBlockUntilCompletion() const OVERRIDE
{
return true;
}
private:
CreateFileHelper(PassRefPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
RefPtr<CreateFileResult> m_result;
String m_name;
KURL m_url;
FileSystemType m_type;
};
} // namespace
PassRefPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
KURL fileSystemURL = createFileSystemURL(fileEntry);
RefPtr<CreateFileHelper::CreateFileResult> result(CreateFileHelper::CreateFileResult::create());
fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type()));
if (result->m_failed) {
exceptionState.throwDOMException(result->m_code, "Could not create '" + fileEntry->name() + "'.");
return 0;
}
return result->m_file;
}
namespace {
class ReceiveFileWriterCallback FINAL : public FileWriterBaseCallback {
public:
static PassOwnPtr<ReceiveFileWriterCallback> create()
{
return adoptPtr(new ReceiveFileWriterCallback());
}
virtual void handleEvent(FileWriterBase*) OVERRIDE
{
}
private:
ReceiveFileWriterCallback()
{
}
};
class LocalErrorCallback FINAL : public ErrorCallback {
public:
static PassOwnPtr<LocalErrorCallback> create(FileError::ErrorCode& errorCode)
{
return adoptPtr(new LocalErrorCallback(errorCode));
}
virtual void handleEvent(FileError* error) OVERRIDE
{
ASSERT(error->code() != FileError::OK);
m_errorCode = error->code();
}
private:
explicit LocalErrorCallback(FileError::ErrorCode& errorCode)
: m_errorCode(errorCode)
{
}
FileError::ErrorCode& m_errorCode;
};
}
PassRefPtr<FileWriterSync> DOMFileSystemSync::createWriter(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
ASSERT(fileEntry);
RefPtr<FileWriterSync> fileWriter = FileWriterSync::create();
OwnPtr<ReceiveFileWriterCallback> successCallback = ReceiveFileWriterCallback::create();
FileError::ErrorCode errorCode = FileError::OK;
OwnPtr<LocalErrorCallback> errorCallback = LocalErrorCallback::create(errorCode);
OwnPtr<AsyncFileSystemCallbacks> callbacks = FileWriterBaseCallbacks::create(fileWriter, successCallback.release(), errorCallback.release());
callbacks->setShouldBlockUntilCompletion(true);
fileSystem()->createFileWriter(createFileSystemURL(fileEntry), fileWriter.get(), callbacks.release());
if (errorCode != FileError::OK) {
FileError::throwDOMException(exceptionState, errorCode);
return 0;
}
return fileWriter.release();
}
}
<|endoftext|> |
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pymor/dune-pymor
// Copyright holders: Stephan Rave, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONS_HH
#define DUNE_PYMOR_FUNCTIONS_HH
#include <string>
#include <vector>
#include <dune/common/parametertree.hh>
#include <dune/stuff/functions.hh>
#include "functions/interfaces.hh"
#include "functions/default.hh"
#include "functions/checkerboard.hh"
namespace Dune {
namespace Pymor {
template< class E, class D, int d, class R, int r, int rC = 1 >
class AffinelyDecomposableFunctions
{
public:
static std::vector< std::string > available()
{
auto availableFunctions = Stuff::Functions< E, D, d, R, r, rC >::available();
for (const auto& id : { Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id()
, Function::Checkerboard< E, D, d, R, r, rC >::static_id()})
availableFunctions.push_back(id);
return availableFunctions;
} // ... available(...)
static Dune::ParameterTree defaultSettings(const std::string type = available()[0])
{
auto dune_stuff_functions = Stuff::Functions< E, D, d, R, r, rC >::available();
for (auto dune_stuff_function : dune_stuff_functions)
if (type.compare(dune_stuff_function) == 0)
return Stuff::Functions< E, D, d, R, r, rC >::defaultSettings(type);
if (type.compare(Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id()) == 0)
return Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::defaultSettings();
else if (type.compare(Function::Checkerboard< E, D, d, R, r, rC >::static_id()) == 0)
return Function::Checkerboard< E, D, d, R, r, rC >::defaultSettings();
else
DUNE_PYMOR_THROW(Exception::wrong_input, "unknown function '" << type << "' requested!");
} // ... defaultSettings(...)
static AffinelyDecomposableFunctionInterface< E, D, d, R, r, rC >*
create(const std::string type = available()[0], const ParameterTree settings = defaultSettings())
{
typedef Function::NonparametricDefault< E, D, d, R, r, rC > NonparametricType;
auto dune_stuff_functions = Stuff::Functions< E, D, d, R, r, rC >::available();
for (auto dune_stuff_function : dune_stuff_functions)
if (type.compare(dune_stuff_function))
return new NonparametricType(Stuff::Functions< E, D, d, R, r, rC >::create(type, settings));
if (type.compare(Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id()))
return Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::create(settings);
else if (type.compare(Function::Checkerboard< E, D, d, R, r, rC >::static_id()))
return Function::Checkerboard< E, D, d, R, r, rC >::create(settings);
else
DUNE_PYMOR_THROW(Exception::wrong_input, "unknown function '" << type << "' requested!");
} // ... create(...)
}; // class AffinelyDecomposableFunctions
} // namespace Pymor
} // namespace Dune
#ifdef DUNE_PYMOR_FUNCTIONS_TO_LIB
# define DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(etype, ddim) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 1) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 2) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 3)
# define DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, rdim) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)
# define DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Pymor::AffinelyDecomposableFunctions< etype, dftype, ddim, rftype, rdim, rcdim >;
# include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DunePymorFunctionsInterfacesFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DunePymorFunctionsInterfacesFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DunePymorFunctionsInterfacesFake3dEntityType;
# ifdef HAVE_DUNE_GRID
# include <dune/grid/sgrid.hh>
typedef Dune::SGrid< 1, 1 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid1dEntityType;
typedef Dune::SGrid< 2, 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid2dEntityType;
typedef Dune::SGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid3dEntityType, 3)
# include <dune/grid/yaspgrid.hh>
typedef Dune::YaspGrid< 1 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid1dEntityType;
typedef Dune::YaspGrid< 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid2dEntityType;
typedef Dune::YaspGrid< 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid3dEntityType, 3)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# ifdef ALUGRID_CONFORM
# define DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# else
# define ALUGRID_CONFORM 1
# endif
# ifdef ENABLE_ALUGRID
# define DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# else
# define ENABLE_ALUGRID 1
# endif
# include <dune/grid/alugrid.hh>
typedef Dune::ALUSimplexGrid< 2, 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluSimplexGrid2dEntityType;
typedef Dune::ALUSimplexGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluSimplexGrid3dEntityType;
typedef Dune::ALUCubeGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluCubeGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluCubeGrid3dEntityType, 3)
# ifdef DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# undef DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# else
# undef ALUGRID_CONFORM
# endif
# ifdef DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# undef DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# else
# undef ENABLE_ALUGRID
# endif
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION
# undef DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES
# undef DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES
# undef DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE
#endif // DUNE_PYMOR_FUNCTIONS_TO_LIB
#endif // DUNE_PYMOR_FUNCTIONS_HH
<commit_msg>[functions] * return unique_ptr * fix string compare<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pymor/dune-pymor
// Copyright holders: Stephan Rave, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONS_HH
#define DUNE_PYMOR_FUNCTIONS_HH
#include <string>
#include <vector>
#include <dune/common/parametertree.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions.hh>
#include "functions/interfaces.hh"
#include "functions/default.hh"
#include "functions/checkerboard.hh"
namespace Dune {
namespace Pymor {
template< class E, class D, int d, class R, int r, int rC = 1 >
class AffinelyDecomposableFunctions
{
public:
static std::vector< std::string > available()
{
auto availableFunctions = Stuff::Functions< E, D, d, R, r, rC >::available();
for (const auto& id : { Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id()
, Function::Checkerboard< E, D, d, R, r, rC >::static_id()})
availableFunctions.push_back(id);
return availableFunctions;
} // ... available(...)
static Dune::ParameterTree defaultSettings(const std::string type = available()[0])
{
auto dune_stuff_functions = Stuff::Functions< E, D, d, R, r, rC >::available();
for (auto dune_stuff_function : dune_stuff_functions)
if (type.compare(dune_stuff_function) == 0)
return Stuff::Functions< E, D, d, R, r, rC >::defaultSettings(type);
if (type.compare(Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id()) == 0)
return Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::defaultSettings();
else if (type.compare(Function::Checkerboard< E, D, d, R, r, rC >::static_id()) == 0)
return Function::Checkerboard< E, D, d, R, r, rC >::defaultSettings();
else
DUNE_PYMOR_THROW(Exception::wrong_input, "unknown function '" << type << "' requested!");
} // ... defaultSettings(...)
static std::unique_ptr< AffinelyDecomposableFunctionInterface< E, D, d, R, r, rC > >
create(const std::string type = available()[0], const Stuff::Common::ConfigTree settings = defaultSettings())
{
if (type == Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::static_id())
return std::unique_ptr< Function::AffinelyDecomposableDefault< E, D, d, R, r, rC > >(Function::AffinelyDecomposableDefault< E, D, d, R, r, rC >::create(settings));
else if (type == Function::Checkerboard< E, D, d, R, r, rC >::static_id())
return std::unique_ptr< Function::Checkerboard< E, D, d, R, r, rC > >(Function::Checkerboard< E, D, d, R, r, rC >::create(settings));
else {
typedef Function::NonparametricDefault< E, D, d, R, r, rC > NonparametricType;
return Stuff::Common::make_unique< NonparametricType >(Stuff::Functions< E, D, d, R, r, rC >::create(type,
settings));
}
} // ... create(...)
}; // class AffinelyDecomposableFunctions
} // namespace Pymor
} // namespace Dune
#ifdef DUNE_PYMOR_FUNCTIONS_TO_LIB
# define DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(etype, ddim) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 1) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 2) \
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, 3)
# define DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGECOLS(etype, ddim, rdim) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)
# define DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Pymor::AffinelyDecomposableFunctions< etype, dftype, ddim, rftype, rdim, rcdim >;
# include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DunePymorFunctionsInterfacesFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DunePymorFunctionsInterfacesFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DunePymorFunctionsInterfacesFake3dEntityType;
# ifdef HAVE_DUNE_GRID
# include <dune/grid/sgrid.hh>
typedef Dune::SGrid< 1, 1 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid1dEntityType;
typedef Dune::SGrid< 2, 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid2dEntityType;
typedef Dune::SGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesSGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesSGrid3dEntityType, 3)
# include <dune/grid/yaspgrid.hh>
typedef Dune::YaspGrid< 1 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid1dEntityType;
typedef Dune::YaspGrid< 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid2dEntityType;
typedef Dune::YaspGrid< 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesYaspGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesYaspGrid3dEntityType, 3)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# ifdef ALUGRID_CONFORM
# define DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# else
# define ALUGRID_CONFORM 1
# endif
# ifdef ENABLE_ALUGRID
# define DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# else
# define ENABLE_ALUGRID 1
# endif
# include <dune/grid/alugrid.hh>
typedef Dune::ALUSimplexGrid< 2, 2 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluSimplexGrid2dEntityType;
typedef Dune::ALUSimplexGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluSimplexGrid3dEntityType;
typedef Dune::ALUCubeGrid< 3, 3 >::Codim< 0 >::Entity DunePymorFunctionsInterfacesAluCubeGrid3dEntityType;
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE(DunePymorFunctionsInterfacesAluCubeGrid3dEntityType, 3)
# ifdef DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# undef DUNE_PYMOR_FUNCTIONS_ALUGRID_CONFORM_WAS_DEFINED_BEFORE
# else
# undef ALUGRID_CONFORM
# endif
# ifdef DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# undef DUNE_PYMOR_FUNCTIONS_ENABLE_ALUGRID_WAS_DEFINED_BEFORE
# else
# undef ENABLE_ALUGRID
# endif
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_PYMOR_FUNCTIONS_LAST_EXPANSION
# undef DUNE_PYMOR_FUNCTIONS_LIST_RANGEFIELDTYPES
# undef DUNE_PYMOR_FUNCTIONS_LIST_DOMAINFIELDTYPES
# undef DUNE_PYMOR_FUNCTIONS_LIST_DIMRANGE
#endif // DUNE_PYMOR_FUNCTIONS_TO_LIB
#endif // DUNE_PYMOR_FUNCTIONS_HH
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bse/processor.hh"
#include "bse/bseieee754.hh"
#include "bse/internal.hh"
#include "revmodel.hpp"
#include "revmodel.cpp"
#include "allpass.cpp"
#include "comb.cpp"
namespace {
using namespace Bse;
using namespace AudioSignal;
class Freeverb : public AudioSignal::Processor {
IBusId stereoin;
OBusId stereout;
revmodel model;
void
query_info (ProcessorInfo &info) override
{
info.uri = "Bse.VST2.JzR3.Freeverb3";
info.version = "0";
info.label = "Freeverb3";
info.category = "Reverb";
info.website_url = "https://beast.testbit.eu";
info.creator_name = "Jezar at Dreampoint";
}
enum ParamIds { DRY = 1, WET, ROOMSIZE, WIDTH, DAMPING, MODE };
void
initialize () override
{
ChoiceEntries centries;
ParamId tag;
start_param_group ("Reverb Settings");
tag = add_param ("Dry level", "Dry", 0, scaledry, scaledry * initialdry, "dB");
assert_return (ParamIds (tag) == DRY);
tag = add_param ("Wet level", "Wet", 0, scalewet, scalewet * initialwet, "dB");
assert_return (ParamIds (tag) == WET);
start_param_group ("Room Settings");
tag = add_param ("Room size", "RS", offsetroom, offsetroom + scaleroom, offsetroom + scaleroom * initialroom, "size");
assert_return (ParamIds (tag) == ROOMSIZE);
tag = add_param ("Width", "W", 0, 100, 100 * initialwidth, "%");
assert_return (ParamIds (tag) == WIDTH);
tag = add_param ("Damping", "D", 0, 100, 100 * initialdamp, "%");
assert_return (ParamIds (tag) == DAMPING);
centries += { "Normal Damping", "Damping with sign correction as implemented in STK Freeverb" };
centries += { "VLC Damping", "The VLC Freeverb version disables one damping feedback chain" };
centries += { "Signflip 2000", "Preserve May 2000 Freeverb damping sign flip" };
tag = add_param ("Mode", "M", std::move (centries), -1, "", "Damping mode found in different Freeverb variants");
assert_return (ParamIds (tag) == MODE);
}
void
configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override
{
remove_all_buses();
stereoin = add_input_bus ("Stereo In", SpeakerArrangement::STEREO);
stereout = add_output_bus ("Stereo Out", SpeakerArrangement::STEREO);
}
void
adjust_param (ParamId tag) override
{
switch (ParamIds (tag))
{
case WET: return model.setwet (get_param (tag) / scalewet);
case DRY: return model.setdry (get_param (tag) / scaledry);
case ROOMSIZE: return model.setroomsize ((get_param (tag) - offsetroom) / scaleroom);
case WIDTH: return model.setwidth (0.01 * get_param (tag));
case MODE:
case DAMPING: return model.setdamp (0.01 * get_param (ParamId (DAMPING)),
bse_ftoi (get_param (ParamId (MODE))));
}
}
void
reset() override
{
model.setmode (0); // no-freeze, allow mute
model.mute(); // silence internal buffers
adjust_params (true);
}
void
render (uint n_frames) override
{
adjust_params (false);
float *input0 = const_cast<float*> (ifloats (stereoin, 0));
float *input1 = const_cast<float*> (ifloats (stereoin, 1));
float *output0 = oblock (stereout, 0);
float *output1 = oblock (stereout, 1);
model.processreplace (input0, input1, output0, output1, n_frames, 1);
}
};
static auto freeverb = Bse::enroll_asp<Freeverb>();
} // Anon
<commit_msg>DEVICES: freeverb/freeverb.cc: call add_param() with explicit enum IDs<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bse/processor.hh"
#include "bse/bseieee754.hh"
#include "bse/internal.hh"
#include "revmodel.hpp"
#include "revmodel.cpp"
#include "allpass.cpp"
#include "comb.cpp"
namespace {
using namespace Bse;
using namespace AudioSignal;
class Freeverb : public AudioSignal::Processor {
IBusId stereoin;
OBusId stereout;
revmodel model;
void
query_info (ProcessorInfo &info) override
{
info.uri = "Bse.VST2.JzR3.Freeverb3";
info.version = "0";
info.label = "Freeverb3";
info.category = "Reverb";
info.website_url = "https://beast.testbit.eu";
info.creator_name = "Jezar at Dreampoint";
}
enum Params { MODE = 1, DRY, WET, ROOMSIZE, DAMPING, WIDTH };
void
initialize () override
{
ChoiceEntries centries;
start_param_group ("Reverb Settings");
add_param (DRY, "Dry level", "Dry", 0, scaledry, scaledry * initialdry, "dB");
add_param (WET, "Wet level", "Wet", 0, scalewet, scalewet * initialwet, "dB");
start_param_group ("Room Settings");
add_param (ROOMSIZE, "Room size", "RS", offsetroom, offsetroom + scaleroom, offsetroom + scaleroom * initialroom, "size");
add_param (WIDTH, "Width", "W", 0, 100, 100 * initialwidth, "%");
add_param (DAMPING, "Damping", "D", 0, 100, 100 * initialdamp, "%");
centries += { "Normal Damping", "Damping with sign correction as implemented in STK Freeverb" };
centries += { "VLC Damping", "The VLC Freeverb version disables one damping feedback chain" };
centries += { "Signflip 2000", "Preserve May 2000 Freeverb damping sign flip" };
add_param (MODE, "Mode", "M", std::move (centries), -1, "", "Damping mode found in different Freeverb variants");
}
void
configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override
{
remove_all_buses();
stereoin = add_input_bus ("Stereo In", SpeakerArrangement::STEREO);
stereout = add_output_bus ("Stereo Out", SpeakerArrangement::STEREO);
}
void
adjust_param (Id32 tag) override
{
switch (Params (tag.id))
{
case WET: return model.setwet (get_param (tag) / scalewet);
case DRY: return model.setdry (get_param (tag) / scaledry);
case ROOMSIZE: return model.setroomsize ((get_param (tag) - offsetroom) / scaleroom);
case WIDTH: return model.setwidth (0.01 * get_param (tag));
case MODE:
case DAMPING: return model.setdamp (0.01 * get_param (ParamId (DAMPING)),
bse_ftoi (get_param (ParamId (MODE))));
}
}
void
reset() override
{
model.setmode (0); // no-freeze, allow mute
model.mute(); // silence internal buffers
adjust_params (true);
}
void
render (uint n_frames) override
{
adjust_params (false);
float *input0 = const_cast<float*> (ifloats (stereoin, 0));
float *input1 = const_cast<float*> (ifloats (stereoin, 1));
float *output0 = oblock (stereout, 0);
float *output1 = oblock (stereout, 1);
model.processreplace (input0, input1, output0, output1, n_frames, 1);
}
};
static auto freeverb = Bse::enroll_asp<Freeverb>();
} // Anon
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
//
// Copyright (C) Streamlet. All rights reserved.
//
// File Name: ZLibWrapLib.cpp
// Author: Streamlet
// Create Time: 2010-09-16
// Description:
//
// Version history:
//
//
//
//------------------------------------------------------------------------------
#include "stdafx.h"
#include "ZLibWrapLib.h"
#include "Encoding.h"
#include "Loki/ScopeGuard.h"
#include "ZLib/zip.h"
#include "ZLib/unzip.h"
#include <atlstr.h>
#define ZIP_GPBF_LANGUAGE_ENCODING_FLAG 0x800
BOOL ZipAddFile(zipFile zf, LPCTSTR lpszFileNameInZip, LPCTSTR lpszFilePath, bool bUtf8 = false)
{
DWORD dwFileAttr = GetFileAttributes(lpszFilePath);
if (dwFileAttr == INVALID_FILE_ATTRIBUTES)
{
return false;
}
DWORD dwOpenAttr = (dwFileAttr & FILE_ATTRIBUTE_DIRECTORY) != 0 ? FILE_FLAG_BACKUP_SEMANTICS : 0;
HANDLE hFile = CreateFile(lpszFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, dwOpenAttr, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(CloseHandle, hFile);
FILETIME ftUTC, ftLocal;
GetFileTime(hFile, NULL, NULL, &ftUTC);
FileTimeToLocalFileTime(&ftUTC, &ftLocal);
WORD wDate, wTime;
FileTimeToDosDateTime(&ftLocal, &wDate, &wTime);
zip_fileinfo FileInfo;
ZeroMemory(&FileInfo, sizeof(FileInfo));
FileInfo.dosDate = ((((DWORD)wDate) << 16) | (DWORD)wTime);
FileInfo.external_fa |= dwFileAttr;
if (bUtf8)
{
CStringA strFileNameInZipA = UCS2ToANSI(lpszFileNameInZip, CP_UTF8);
if (zipOpenNewFileInZip4(zf, strFileNameInZipA, &FileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 9,
0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0, 0, ZIP_GPBF_LANGUAGE_ENCODING_FLAG) != ZIP_OK)
{
return FALSE;
}
}
else
{
CStringA strFileNameInZipA = UCS2ToANSI(lpszFileNameInZip);
if (zipOpenNewFileInZip(zf, strFileNameInZipA, &FileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 9) != ZIP_OK)
{
return FALSE;
}
}
LOKI_ON_BLOCK_EXIT(zipCloseFileInZip, zf);
const DWORD BUFFER_SIZE = 4096;
BYTE byBuffer[BUFFER_SIZE];
LARGE_INTEGER li = {};
if (!GetFileSizeEx(hFile, &li))
{
return FALSE;
}
while (li.QuadPart > 0)
{
DWORD dwSizeToRead = li.QuadPart > (LONGLONG)BUFFER_SIZE ? BUFFER_SIZE : (DWORD)li.LowPart;
DWORD dwRead = 0;
if (!ReadFile(hFile, byBuffer, dwSizeToRead, &dwRead, NULL))
{
return FALSE;
}
if (zipWriteInFileInZip(zf, byBuffer, dwRead) < 0)
{
return FALSE;
}
li.QuadPart -= (LONGLONG)dwRead;
}
return TRUE;
}
BOOL ZipAddFiles(zipFile zf, LPCTSTR lpszFileNameInZip, LPCTSTR lpszFiles, bool bUtf8 = false)
{
WIN32_FIND_DATA wfd;
ZeroMemory(&wfd, sizeof(wfd));
HANDLE hFind = FindFirstFile(lpszFiles, &wfd);
if (hFind == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(FindClose, hFind);
CString strFilePath = lpszFiles;
int nPos = strFilePath.ReverseFind('\\');
if (nPos != -1)
{
strFilePath = strFilePath.Left(nPos + 1);
}
else
{
strFilePath.Empty();
}
CString strFileNameInZip = lpszFileNameInZip;
do
{
CString strFileName = wfd.cFileName;
if (strFileName == _T(".") || strFileName == _T(".."))
{
continue;
}
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
if (!ZipAddFile(zf, strFileNameInZip + strFileName + _T("/"), strFilePath + strFileName, bUtf8))
{
return FALSE;
}
if (!ZipAddFiles(zf, strFileNameInZip + strFileName + _T("/"), strFilePath + strFileName + _T("\\*"), bUtf8))
{
return FALSE;
}
}
else
{
if (!ZipAddFile(zf, strFileNameInZip + strFileName, strFilePath + strFileName, bUtf8))
{
return FALSE;
}
}
} while (FindNextFile(hFind, &wfd));
return TRUE;
}
BOOL ZipCompress(LPCTSTR lpszSourceFiles, LPCTSTR lpszDestFile, bool bUtf8 /*= false*/)
{
CStringA strDestFile = UCS2ToANSI(lpszDestFile);
zipFile zf = zipOpen64(strDestFile, 0);
if (zf == NULL)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
if (!ZipAddFiles(zf, _T(""), lpszSourceFiles, bUtf8))
{
return FALSE;
}
return TRUE;
}
BOOL ZipExtractCurrentFile(unzFile uf, LPCTSTR lpszDestFolder)
{
char szFilePathA[MAX_PATH];
unz_file_info64 FileInfo;
if (unzGetCurrentFileInfo64(uf, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0) != UNZ_OK)
{
return FALSE;
}
if (unzOpenCurrentFile(uf) != UNZ_OK)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(unzCloseCurrentFile, uf);
CString strDestPath = lpszDestFolder;
CString strFileName;
if ((FileInfo.flag & ZIP_GPBF_LANGUAGE_ENCODING_FLAG) != 0)
{
strFileName = ANSIToUCS2(szFilePathA, CP_UTF8);
}
else
{
strFileName = ANSIToUCS2(szFilePathA);
}
int nLength = strFileName.GetLength();
LPTSTR lpszFileName = strFileName.GetBuffer();
LPTSTR lpszCurrentFile = lpszFileName;
LOKI_ON_BLOCK_EXIT_OBJ(strFileName, &CString::ReleaseBuffer, -1);
for (int i = 0; i <= nLength; ++i)
{
if (lpszFileName[i] == _T('\0'))
{
strDestPath += lpszCurrentFile;
break;
}
if (lpszFileName[i] == '\\' || lpszFileName[i] == '/')
{
lpszFileName[i] = '\0';
strDestPath += lpszCurrentFile;
strDestPath += _T("\\");
CreateDirectory(strDestPath, NULL);
lpszCurrentFile = lpszFileName + i + 1;
}
}
if (lpszCurrentFile[0] == _T('\0'))
{
return TRUE;
}
HANDLE hFile = CreateFile(strDestPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(CloseHandle, hFile);
const DWORD BUFFER_SIZE = 4096;
BYTE byBuffer[BUFFER_SIZE];
while (true)
{
int nSize = unzReadCurrentFile(uf, byBuffer, BUFFER_SIZE);
if (nSize < 0)
{
return FALSE;
}
else if (nSize == 0)
{
break;
}
else
{
DWORD dwWritten = 0;
if (!WriteFile(hFile, byBuffer, (DWORD)nSize, &dwWritten, NULL) || dwWritten != (DWORD)nSize)
{
return FALSE;
}
}
}
FILETIME ftLocal, ftUTC;
DosDateTimeToFileTime((WORD)(FileInfo.dosDate>>16), (WORD)FileInfo.dosDate, &ftLocal);
LocalFileTimeToFileTime(&ftLocal, &ftUTC);
SetFileTime(hFile, &ftUTC, &ftUTC, &ftUTC);
return TRUE;
}
BOOL ZipExtract(LPCTSTR lpszSourceFile, LPCTSTR lpszDestFolder)
{
CStringA strSourceFileA = UCS2ToANSI(lpszSourceFile);
unzFile uf = unzOpen64(strSourceFileA);
if (uf == NULL)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(unzClose, uf);
unz_global_info64 gi;
if (unzGetGlobalInfo64(uf, &gi) != UNZ_OK)
{
return FALSE;
}
CString strDestFolder = lpszDestFolder;
CreateDirectory(lpszDestFolder, NULL);
if (!strDestFolder.IsEmpty() && strDestFolder[strDestFolder.GetLength() - 1] != _T('\\'))
{
strDestFolder += _T("\\");
}
for (int i = 0; i < gi.number_entry; ++i)
{
if (!ZipExtractCurrentFile(uf, strDestFolder))
{
return FALSE;
}
if (i < gi.number_entry - 1)
{
if (unzGoToNextFile(uf) != UNZ_OK)
{
return FALSE;
}
}
}
return TRUE;
}
<commit_msg>fix bug<commit_after>//------------------------------------------------------------------------------
//
// Copyright (C) Streamlet. All rights reserved.
//
// File Name: ZLibWrapLib.cpp
// Author: Streamlet
// Create Time: 2010-09-16
// Description:
//
// Version history:
//
//
//
//------------------------------------------------------------------------------
#include "stdafx.h"
#include "ZLibWrapLib.h"
#include "Encoding.h"
#include "Loki/ScopeGuard.h"
#include "ZLib/zip.h"
#include "ZLib/unzip.h"
#include <atlstr.h>
#define ZIP_GPBF_LANGUAGE_ENCODING_FLAG 0x800
BOOL ZipAddFile(zipFile zf, LPCTSTR lpszFileNameInZip, LPCTSTR lpszFilePath, bool bUtf8 = false)
{
DWORD dwFileAttr = GetFileAttributes(lpszFilePath);
if (dwFileAttr == INVALID_FILE_ATTRIBUTES)
{
return false;
}
DWORD dwOpenAttr = (dwFileAttr & FILE_ATTRIBUTE_DIRECTORY) != 0 ? FILE_FLAG_BACKUP_SEMANTICS : 0;
HANDLE hFile = CreateFile(lpszFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, dwOpenAttr, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(CloseHandle, hFile);
FILETIME ftUTC, ftLocal;
GetFileTime(hFile, NULL, NULL, &ftUTC);
FileTimeToLocalFileTime(&ftUTC, &ftLocal);
WORD wDate, wTime;
FileTimeToDosDateTime(&ftLocal, &wDate, &wTime);
zip_fileinfo FileInfo;
ZeroMemory(&FileInfo, sizeof(FileInfo));
FileInfo.dosDate = ((((DWORD)wDate) << 16) | (DWORD)wTime);
FileInfo.external_fa |= dwFileAttr;
if (bUtf8)
{
CStringA strFileNameInZipA = UCS2ToANSI(lpszFileNameInZip, CP_UTF8);
if (zipOpenNewFileInZip4(zf, strFileNameInZipA, &FileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 9,
0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0, 0, ZIP_GPBF_LANGUAGE_ENCODING_FLAG) != ZIP_OK)
{
return FALSE;
}
}
else
{
CStringA strFileNameInZipA = UCS2ToANSI(lpszFileNameInZip);
if (zipOpenNewFileInZip(zf, strFileNameInZipA, &FileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 9) != ZIP_OK)
{
return FALSE;
}
}
LOKI_ON_BLOCK_EXIT(zipCloseFileInZip, zf);
if ((dwFileAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
return TRUE;
}
const DWORD BUFFER_SIZE = 4096;
BYTE byBuffer[BUFFER_SIZE];
LARGE_INTEGER li = {};
if (!GetFileSizeEx(hFile, &li))
{
return FALSE;
}
while (li.QuadPart > 0)
{
DWORD dwSizeToRead = li.QuadPart > (LONGLONG)BUFFER_SIZE ? BUFFER_SIZE : (DWORD)li.LowPart;
DWORD dwRead = 0;
if (!ReadFile(hFile, byBuffer, dwSizeToRead, &dwRead, NULL))
{
return FALSE;
}
if (zipWriteInFileInZip(zf, byBuffer, dwRead) < 0)
{
return FALSE;
}
li.QuadPart -= (LONGLONG)dwRead;
}
return TRUE;
}
BOOL ZipAddFiles(zipFile zf, LPCTSTR lpszFileNameInZip, LPCTSTR lpszFiles, bool bUtf8 = false)
{
WIN32_FIND_DATA wfd;
ZeroMemory(&wfd, sizeof(wfd));
HANDLE hFind = FindFirstFile(lpszFiles, &wfd);
if (hFind == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(FindClose, hFind);
CString strFilePath = lpszFiles;
int nPos = strFilePath.ReverseFind('\\');
if (nPos != -1)
{
strFilePath = strFilePath.Left(nPos + 1);
}
else
{
strFilePath.Empty();
}
CString strFileNameInZip = lpszFileNameInZip;
do
{
CString strFileName = wfd.cFileName;
if (strFileName == _T(".") || strFileName == _T(".."))
{
continue;
}
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
if (!ZipAddFile(zf, strFileNameInZip + strFileName + _T("/"), strFilePath + strFileName, bUtf8))
{
return FALSE;
}
if (!ZipAddFiles(zf, strFileNameInZip + strFileName + _T("/"), strFilePath + strFileName + _T("\\*"), bUtf8))
{
return FALSE;
}
}
else
{
if (!ZipAddFile(zf, strFileNameInZip + strFileName, strFilePath + strFileName, bUtf8))
{
return FALSE;
}
}
} while (FindNextFile(hFind, &wfd));
return TRUE;
}
BOOL ZipCompress(LPCTSTR lpszSourceFiles, LPCTSTR lpszDestFile, bool bUtf8 /*= false*/)
{
CStringA strDestFile = UCS2ToANSI(lpszDestFile);
zipFile zf = zipOpen64(strDestFile, 0);
if (zf == NULL)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
if (!ZipAddFiles(zf, _T(""), lpszSourceFiles, bUtf8))
{
return FALSE;
}
return TRUE;
}
BOOL ZipExtractCurrentFile(unzFile uf, LPCTSTR lpszDestFolder)
{
char szFilePathA[MAX_PATH];
unz_file_info64 FileInfo;
if (unzGetCurrentFileInfo64(uf, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0) != UNZ_OK)
{
return FALSE;
}
if (unzOpenCurrentFile(uf) != UNZ_OK)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(unzCloseCurrentFile, uf);
CString strDestPath = lpszDestFolder;
CString strFileName;
if ((FileInfo.flag & ZIP_GPBF_LANGUAGE_ENCODING_FLAG) != 0)
{
strFileName = ANSIToUCS2(szFilePathA, CP_UTF8);
}
else
{
strFileName = ANSIToUCS2(szFilePathA);
}
int nLength = strFileName.GetLength();
LPTSTR lpszFileName = strFileName.GetBuffer();
LPTSTR lpszCurrentFile = lpszFileName;
LOKI_ON_BLOCK_EXIT_OBJ(strFileName, &CString::ReleaseBuffer, -1);
for (int i = 0; i <= nLength; ++i)
{
if (lpszFileName[i] == _T('\0'))
{
strDestPath += lpszCurrentFile;
break;
}
if (lpszFileName[i] == '\\' || lpszFileName[i] == '/')
{
lpszFileName[i] = '\0';
strDestPath += lpszCurrentFile;
strDestPath += _T("\\");
CreateDirectory(strDestPath, NULL);
lpszCurrentFile = lpszFileName + i + 1;
}
}
if (lpszCurrentFile[0] == _T('\0'))
{
return TRUE;
}
HANDLE hFile = CreateFile(strDestPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(CloseHandle, hFile);
const DWORD BUFFER_SIZE = 4096;
BYTE byBuffer[BUFFER_SIZE];
while (true)
{
int nSize = unzReadCurrentFile(uf, byBuffer, BUFFER_SIZE);
if (nSize < 0)
{
return FALSE;
}
else if (nSize == 0)
{
break;
}
else
{
DWORD dwWritten = 0;
if (!WriteFile(hFile, byBuffer, (DWORD)nSize, &dwWritten, NULL) || dwWritten != (DWORD)nSize)
{
return FALSE;
}
}
}
FILETIME ftLocal, ftUTC;
DosDateTimeToFileTime((WORD)(FileInfo.dosDate>>16), (WORD)FileInfo.dosDate, &ftLocal);
LocalFileTimeToFileTime(&ftLocal, &ftUTC);
SetFileTime(hFile, &ftUTC, &ftUTC, &ftUTC);
return TRUE;
}
BOOL ZipExtract(LPCTSTR lpszSourceFile, LPCTSTR lpszDestFolder)
{
CStringA strSourceFileA = UCS2ToANSI(lpszSourceFile);
unzFile uf = unzOpen64(strSourceFileA);
if (uf == NULL)
{
return FALSE;
}
LOKI_ON_BLOCK_EXIT(unzClose, uf);
unz_global_info64 gi;
if (unzGetGlobalInfo64(uf, &gi) != UNZ_OK)
{
return FALSE;
}
CString strDestFolder = lpszDestFolder;
CreateDirectory(lpszDestFolder, NULL);
if (!strDestFolder.IsEmpty() && strDestFolder[strDestFolder.GetLength() - 1] != _T('\\'))
{
strDestFolder += _T("\\");
}
for (int i = 0; i < gi.number_entry; ++i)
{
if (!ZipExtractCurrentFile(uf, strDestFolder))
{
return FALSE;
}
if (i < gi.number_entry - 1)
{
if (unzGoToNextFile(uf) != UNZ_OK)
{
return FALSE;
}
}
}
return TRUE;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
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.
*/
#ifndef ELFIO_STRINGS_HPP
#define ELFIO_STRINGS_HPP
#include <cstdlib>
#include <cstring>
#include <string>
namespace ELFIO {
//------------------------------------------------------------------------------
class string_section_accessor
{
public:
//------------------------------------------------------------------------------
string_section_accessor( section* section_ ) :
string_section( section_ )
{
}
//------------------------------------------------------------------------------
const char*
get_string( Elf_Word index ) const
{
if ( index < string_section->get_size() ) {
const char* data = string_section->get_data();
if ( 0 != data ) {
return data + index;
}
}
return 0;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const char* str )
{
// Strings are addeded to the end of the current section data
Elf_Word current_position = (Elf_Word)string_section->get_size();
if ( current_position == 0 ) {
char empty_string[1] = {'\0'};
string_section->append_data( empty_string, 1 );
current_position++;
}
string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 );
return current_position;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const std::string& str )
{
// Strings are addeded to the end of the current section data
Elf_Word current_position = (Elf_Word)string_section->get_size();
char empty_string[1] = {'\0'};
if ( current_position == 0 ) {
string_section->append_data( empty_string, 1 );
current_position++;
}
string_section->append_data( str );
string_section->append_data( empty_string, 1 );
return current_position;
}
//------------------------------------------------------------------------------
private:
section* string_section;
};
} // namespace ELFIO
#endif // ELFIO_STRINGS_HPP
<commit_msg>String section accessor refactoring<commit_after>/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
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.
*/
#ifndef ELFIO_STRINGS_HPP
#define ELFIO_STRINGS_HPP
#include <cstdlib>
#include <cstring>
#include <string>
namespace ELFIO {
//------------------------------------------------------------------------------
class string_section_accessor
{
public:
//------------------------------------------------------------------------------
string_section_accessor( section* section_ ) :
string_section( section_ )
{
}
//------------------------------------------------------------------------------
const char*
get_string( Elf_Word index ) const
{
if ( index < string_section->get_size() ) {
const char* data = string_section->get_data();
if ( 0 != data ) {
return data + index;
}
}
return 0;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const char* str )
{
// Strings are addeded to the end of the current section data
Elf_Word current_position = (Elf_Word)string_section->get_size();
if ( current_position == 0 ) {
char empty_string = '\0';
string_section->append_data( &empty_string, 1 );
current_position++;
}
string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 );
return current_position;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const std::string& str )
{
return add_string( str.c_str() );
}
//------------------------------------------------------------------------------
private:
section* string_section;
};
} // namespace ELFIO
#endif // ELFIO_STRINGS_HPP
<|endoftext|> |
<commit_before>#include "msfem_solver.hh"
#include <unordered_set>
#include <dune/multiscale/common/righthandside_assembler.hh>
#include <dune/multiscale/msfem/localproblems/subgrid-list.hh>
#include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh>
#include <dune/multiscale/tools/misc/linear-lagrange-interpolation.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
#include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/fem/fem_traits.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace)
: discreteFunctionSpace_(discreteFunctionSpace)
{}
void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType &host_func) const {
host_func.clear();
const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space();
const SubGridType& subGrid = subDiscreteFunctionSpace.grid();
typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator;
typedef typename SubgridIterator::Entity SubgridEntity;
typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction;
const SubgridIterator sub_endit = subDiscreteFunctionSpace.end();
for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it)
{
const SubgridEntity& sub_entity = *sub_it;
const HostEntityPointer host_entity_pointer = subGrid.getHostEntity< 0 >(*sub_it);
const HostEntity& host_entity = *host_entity_pointer;
const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity);
LocalFunction host_loc_value = host_func.localFunction(host_entity);
const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size();
for (unsigned int i = 0; i < numBaseFunctions; ++i)
{
host_loc_value[i] = sub_loc_value[i];
}
}
} // subgrid_to_hostrid_projection
void Elliptic_MsFEM_Solver::projectCoarseToFineScale( MacroMicroGridSpecifier& /*specifier*/,
const DiscreteFunctionType& coarse_msfem_solution,
DiscreteFunctionType& coarse_scale_part ) const
{
DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... ";
coarse_scale_part.clear();
Dune::Stuff::HeterogenousProjection<> projection;
projection.project(coarse_msfem_solution, coarse_scale_part);
DSC_LOG_INFO << " done." << std::endl;
}
void Elliptic_MsFEM_Solver::identify_fine_scale_part( MacroMicroGridSpecifier& specifier,
MsFEMTraits::SubGridListType& subgrid_list,
const DiscreteFunctionType& coarse_msfem_solution,
DiscreteFunctionType& fine_scale_part ) const {
fine_scale_part.clear();
const HostGrid& grid = discreteFunctionSpace_.gridPart().grid();
const GridPart& gridPart = discreteFunctionSpace_.gridPart();
DiscreteFunctionSpace& coarse_space = specifier.coarseSpace();
const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet();
const int number_of_nodes = grid.size(2 /*codim*/);
std::vector< std::vector< HostEntityPointer > > entities_sharing_same_node(number_of_nodes);
DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... ";
// traverse coarse space
for (auto& coarseCell : coarse_space) {
const int coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell);
LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier);
localSolManager.loadLocalSolutions();
auto& localSolutions = localSolManager.getLocalSolutions();
LocalFunction coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell);
if ((specifier.getOversamplingStrategy()==3) || specifier.simplexCoarseGrid()) {
assert(localSolutions.size()==Dune::GridSelector::dimgrid
&& "We should have dim local solutions per coarse element on triangular meshes!");
JacobianRangeType grad_coarse_msfem_on_entity;
// We only need the gradient of the coarse scale part on the element, which is a constant.
coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity);
// get the coarse gradient on T, multiply it with the local correctors and sum it up.
for (int spaceDimension=0; spaceDimension<Dune::GridSelector::dimgrid; ++spaceDimension) {
*localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension];
if (spaceDimension>0)
*localSolutions[0] += *localSolutions[spaceDimension];
}
} else {
//! @warning At this point, we assume to have the same types of elements in the coarse and fine grid!
assert(localSolutions.size()-localSolManager.numBoundaryCorrectors()
== coarseSolutionLF.numDofs() && "The current implementation relies on having the \
same types of elements on coarse and fine level!");
for (int dof=0; dof< coarseSolutionLF.numDofs(); ++dof) {
*localSolutions[dof] *= coarseSolutionLF[dof];
if (dof>0)
*localSolutions[0] += *localSolutions[dof];
}
// add dirichlet corrector
DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_);
boundaryCorrector.clear();
subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()+1], boundaryCorrector);
fine_scale_part += boundaryCorrector;
// substract neumann corrector
// boundaryCorrector.clear();
// subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector);
// fine_scale_part -= boundaryCorrector;
}
// oversampling strategy 3: just sum up the local correctors:
if ( (specifier.getOversamplingStrategy() == 3) ) {
DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_);
subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T);
fine_scale_part += correction_on_U_T;
}
// oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming projection:
if ( ( specifier.getOversamplingStrategy() == 1 ) || ( specifier.getOversamplingStrategy() == 2 ) ) {
assert(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel()
== discreteFunctionSpace_.gridPart().grid().maxLevel() &&
"Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid.");
const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap();
typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator;
typedef typename SubgridIterator::Entity SubgridEntity;
typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction;
for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) {
//! MARK actual subgrid usage
const HostEntityPointer fine_host_entity_pointer
= localSolManager.getSubGridPart().grid().getHostEntity< 0 >(subgridEntity);
const HostEntity& fine_host_entity = *fine_host_entity_pointer;
const int hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer);
if (hostFatherIndex== coarseCellIndex) {
const SubgridLocalFunction sub_loc_value = localSolutions[0]->localFunction(subgridEntity);
assert(localSolutions.size()==coarseSolutionLF.numDofs()+localSolManager.numBoundaryCorrectors());
const SubgridLocalFunction dirichletLF = localSolutions[coarseSolutionLF.numDofs()+1]->localFunction(subgridEntity);
LocalFunction host_loc_value = fine_scale_part.localFunction(fine_host_entity);
int number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>();
for (int i = 0; i < number_of_nodes_entity; ++i)
{
const typename HostEntity::Codim< HostGrid::dimension >::EntityPointer node = fine_host_entity.subEntity< HostGrid::dimension >(i);
const int global_index_node = gridPart.grid().leafIndexSet().index(*node);
// count the number of different coarse-grid-entities that share the above node
std::unordered_set< SubGridListType::IdType > coarse_entities;
const int numEntitiesSharingNode = nodeToEntityMap[global_index_node].size();
for (size_t j = 0; j < numEntitiesSharingNode; ++j) {
// get the id of the macro element enclosing the current element
const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]);
// the following will only add the entity index if it is not yet present
coarse_entities.insert(innerId);
}
host_loc_value[i] += ( sub_loc_value[i] / coarse_entities.size() );
}
}
}
}
}
DSC_LOG_INFO << " done." << std::endl;
}
void Elliptic_MsFEM_Solver::solve_dirichlet_zero(const CommonTraits::DiffusionType& diffusion_op,
const CommonTraits::FirstSourceType& f,
// number of layers per coarse grid entity T: U(T) is created by enrichting T with
// n(T)-layers.
MacroMicroGridSpecifier& specifier,
MsFEMTraits::SubGridListType& subgrid_list,
DiscreteFunctionType& coarse_scale_part,
DiscreteFunctionType& fine_scale_part,
DiscreteFunctionType& solution) const
{
DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero");
DiscreteFunctionSpace& coarse_space = specifier.coarseSpace();
DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space);
coarse_msfem_solution.clear();
//! define the right hand side assembler tool
// (for linear and non-linear elliptic and parabolic problems, for sources f and/or G )
typedef RightHandSideAssembler< DiscreteFunctionType > RhsAssembler;
//! define the discrete (elliptic) operator that describes our problem
// discrete elliptic MsFEM operator (corresponds with MsFEM Matrix)
// ( effect of the discretized differential operator on a certain discrete function )
// This will assemble and solve the local problems
const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op);
// discrete elliptic operator (corresponds with FEM Matrix)
//! (stiffness) matrix
MsFEMMatrixType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space);
//! right hand side vector
// right hand side for the finite element method:
DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space);
msfem_rhs.clear();
DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl
<< "Solving linear problem with MsFEM and maximum coarse grid level "
<< coarse_space.gridPart().grid().maxLevel() << "." << std::endl
<< "------------------------------------------------------------------------------" << std::endl;
// to assemble the computational time
Dune::Timer assembleTimer;
// assemble the MsFEM stiffness matrix
elliptic_msfem_op.assemble_matrix(msfem_matrix);
DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl;
// assemble right hand side
if ( DSC_CONFIG_GET("msfem.petrov_galerkin", 1 ) ) {
RhsAssembler::assemble< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, msfem_rhs);
} else {
RhsAssembler::assemble_for_MsFEM_symmetric< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f,
specifier,
subgrid_list,
msfem_rhs);
}
msfem_rhs.communicate();
assert(msfem_rhs.dofsValid() && "Coarse scale RHS DOFs need to be valid!");
const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor")));
msfem_biCGStab(msfem_rhs, coarse_msfem_solution);
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
if (!coarse_msfem_solution.dofsValid())
DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
// get the dirichlet values
solution.clear();
Dune::Multiscale::projectDirichletValues(coarse_space, solution);
//! copy coarse scale part of MsFEM solution into a function defined on the fine grid
projectCoarseToFineScale( specifier, coarse_msfem_solution, coarse_scale_part );
//! identify fine scale part of MsFEM solution (including the projection!)
identify_fine_scale_part( specifier, subgrid_list, coarse_msfem_solution, fine_scale_part );
{
DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part");
fine_scale_part.communicate();
}
assert(coarse_scale_part.dofsValid() && "Coarse scale part DOFs need to be valid!");
assert(fine_scale_part.dofsValid() && "Fine scale part DOFs need to be valid!");
// add coarse and fine scale part to solution
solution += coarse_scale_part;
solution += fine_scale_part;
} // solve_dirichlet_zero
} //namespace MsFEM {
} //namespace Multiscale {
} //namespace Dune {
<commit_msg>Minor simplification<commit_after>#include "msfem_solver.hh"
#include <unordered_set>
#include <dune/multiscale/common/righthandside_assembler.hh>
#include <dune/multiscale/msfem/localproblems/subgrid-list.hh>
#include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh>
#include <dune/multiscale/tools/misc/linear-lagrange-interpolation.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
#include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/fem/fem_traits.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace)
: discreteFunctionSpace_(discreteFunctionSpace)
{}
void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType &host_func) const {
host_func.clear();
const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space();
const SubGridType& subGrid = subDiscreteFunctionSpace.grid();
typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator;
typedef typename SubgridIterator::Entity SubgridEntity;
typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction;
const SubgridIterator sub_endit = subDiscreteFunctionSpace.end();
for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it)
{
const SubgridEntity& sub_entity = *sub_it;
const HostEntityPointer host_entity_pointer = subGrid.getHostEntity< 0 >(*sub_it);
const HostEntity& host_entity = *host_entity_pointer;
const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity);
LocalFunction host_loc_value = host_func.localFunction(host_entity);
const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size();
for (unsigned int i = 0; i < numBaseFunctions; ++i)
{
host_loc_value[i] = sub_loc_value[i];
}
}
} // subgrid_to_hostrid_projection
void Elliptic_MsFEM_Solver::projectCoarseToFineScale( MacroMicroGridSpecifier& /*specifier*/,
const DiscreteFunctionType& coarse_msfem_solution,
DiscreteFunctionType& coarse_scale_part ) const
{
DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... ";
coarse_scale_part.clear();
Dune::Stuff::HeterogenousProjection<> projection;
projection.project(coarse_msfem_solution, coarse_scale_part);
DSC_LOG_INFO << " done." << std::endl;
}
void Elliptic_MsFEM_Solver::identify_fine_scale_part( MacroMicroGridSpecifier& specifier,
MsFEMTraits::SubGridListType& subgrid_list,
const DiscreteFunctionType& coarse_msfem_solution,
DiscreteFunctionType& fine_scale_part ) const {
fine_scale_part.clear();
const GridPart& gridPart = discreteFunctionSpace_.gridPart();
const HostGrid& grid = gridPart.grid();
DiscreteFunctionSpace& coarse_space = specifier.coarseSpace();
const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet();
const int number_of_nodes = grid.size(2 /*codim*/);
std::vector< std::vector< HostEntityPointer > > entities_sharing_same_node(number_of_nodes);
DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... ";
// traverse coarse space
for (auto& coarseCell : coarse_space) {
const int coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell);
LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier);
localSolManager.loadLocalSolutions();
auto& localSolutions = localSolManager.getLocalSolutions();
LocalFunction coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell);
if ((specifier.getOversamplingStrategy()==3) || specifier.simplexCoarseGrid()) {
assert(localSolutions.size()==Dune::GridSelector::dimgrid
&& "We should have dim local solutions per coarse element on triangular meshes!");
JacobianRangeType grad_coarse_msfem_on_entity;
// We only need the gradient of the coarse scale part on the element, which is a constant.
coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity);
// get the coarse gradient on T, multiply it with the local correctors and sum it up.
for (int spaceDimension=0; spaceDimension<Dune::GridSelector::dimgrid; ++spaceDimension) {
*localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension];
if (spaceDimension>0)
*localSolutions[0] += *localSolutions[spaceDimension];
}
} else {
//! @warning At this point, we assume to have the same types of elements in the coarse and fine grid!
assert(localSolutions.size()-localSolManager.numBoundaryCorrectors()
== coarseSolutionLF.numDofs() && "The current implementation relies on having the \
same types of elements on coarse and fine level!");
for (int dof=0; dof< coarseSolutionLF.numDofs(); ++dof) {
*localSolutions[dof] *= coarseSolutionLF[dof];
if (dof>0)
*localSolutions[0] += *localSolutions[dof];
}
// add dirichlet corrector
DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_);
boundaryCorrector.clear();
subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()+1], boundaryCorrector);
fine_scale_part += boundaryCorrector;
// substract neumann corrector
// boundaryCorrector.clear();
// subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector);
// fine_scale_part -= boundaryCorrector;
}
// oversampling strategy 3: just sum up the local correctors:
if ( (specifier.getOversamplingStrategy() == 3) ) {
DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_);
subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T);
fine_scale_part += correction_on_U_T;
}
// oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming projection:
if ( ( specifier.getOversamplingStrategy() == 1 ) || ( specifier.getOversamplingStrategy() == 2 ) ) {
assert(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel()
== discreteFunctionSpace_.gridPart().grid().maxLevel() &&
"Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid.");
const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap();
typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator;
typedef typename SubgridIterator::Entity SubgridEntity;
typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction;
for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) {
//! MARK actual subgrid usage
const HostEntityPointer fine_host_entity_pointer
= localSolManager.getSubGridPart().grid().getHostEntity< 0 >(subgridEntity);
const HostEntity& fine_host_entity = *fine_host_entity_pointer;
const int hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer);
if (hostFatherIndex== coarseCellIndex) {
const SubgridLocalFunction sub_loc_value = localSolutions[0]->localFunction(subgridEntity);
assert(localSolutions.size()==coarseSolutionLF.numDofs()+localSolManager.numBoundaryCorrectors());
const SubgridLocalFunction dirichletLF = localSolutions[coarseSolutionLF.numDofs()+1]->localFunction(subgridEntity);
LocalFunction host_loc_value = fine_scale_part.localFunction(fine_host_entity);
int number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>();
for (int i = 0; i < number_of_nodes_entity; ++i)
{
const typename HostEntity::Codim< HostGrid::dimension >::EntityPointer node = fine_host_entity.subEntity< HostGrid::dimension >(i);
const int global_index_node = gridPart.grid().leafIndexSet().index(*node);
// count the number of different coarse-grid-entities that share the above node
std::unordered_set< SubGridListType::IdType > coarse_entities;
const int numEntitiesSharingNode = nodeToEntityMap[global_index_node].size();
for (size_t j = 0; j < numEntitiesSharingNode; ++j) {
// get the id of the macro element enclosing the current element
const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]);
// the following will only add the entity index if it is not yet present
coarse_entities.insert(innerId);
}
host_loc_value[i] += ( sub_loc_value[i] / coarse_entities.size() );
}
}
}
}
}
DSC_LOG_INFO << " done." << std::endl;
}
void Elliptic_MsFEM_Solver::solve_dirichlet_zero(const CommonTraits::DiffusionType& diffusion_op,
const CommonTraits::FirstSourceType& f,
// number of layers per coarse grid entity T: U(T) is created by enrichting T with
// n(T)-layers.
MacroMicroGridSpecifier& specifier,
MsFEMTraits::SubGridListType& subgrid_list,
DiscreteFunctionType& coarse_scale_part,
DiscreteFunctionType& fine_scale_part,
DiscreteFunctionType& solution) const
{
DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero");
DiscreteFunctionSpace& coarse_space = specifier.coarseSpace();
DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space);
coarse_msfem_solution.clear();
//! define the right hand side assembler tool
// (for linear and non-linear elliptic and parabolic problems, for sources f and/or G )
typedef RightHandSideAssembler< DiscreteFunctionType > RhsAssembler;
//! define the discrete (elliptic) operator that describes our problem
// discrete elliptic MsFEM operator (corresponds with MsFEM Matrix)
// ( effect of the discretized differential operator on a certain discrete function )
// This will assemble and solve the local problems
const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op);
// discrete elliptic operator (corresponds with FEM Matrix)
//! (stiffness) matrix
MsFEMMatrixType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space);
//! right hand side vector
// right hand side for the finite element method:
DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space);
msfem_rhs.clear();
DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl
<< "Solving linear problem with MsFEM and maximum coarse grid level "
<< coarse_space.gridPart().grid().maxLevel() << "." << std::endl
<< "------------------------------------------------------------------------------" << std::endl;
// to assemble the computational time
Dune::Timer assembleTimer;
// assemble the MsFEM stiffness matrix
elliptic_msfem_op.assemble_matrix(msfem_matrix);
DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl;
// assemble right hand side
if ( DSC_CONFIG_GET("msfem.petrov_galerkin", 1 ) ) {
RhsAssembler::assemble< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, msfem_rhs);
} else {
RhsAssembler::assemble_for_MsFEM_symmetric< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f,
specifier,
subgrid_list,
msfem_rhs);
}
msfem_rhs.communicate();
assert(msfem_rhs.dofsValid() && "Coarse scale RHS DOFs need to be valid!");
const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor")));
msfem_biCGStab(msfem_rhs, coarse_msfem_solution);
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
if (!coarse_msfem_solution.dofsValid())
DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
// get the dirichlet values
solution.clear();
Dune::Multiscale::projectDirichletValues(coarse_space, solution);
//! copy coarse scale part of MsFEM solution into a function defined on the fine grid
projectCoarseToFineScale( specifier, coarse_msfem_solution, coarse_scale_part );
//! identify fine scale part of MsFEM solution (including the projection!)
identify_fine_scale_part( specifier, subgrid_list, coarse_msfem_solution, fine_scale_part );
{
DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part");
fine_scale_part.communicate();
}
assert(coarse_scale_part.dofsValid() && "Coarse scale part DOFs need to be valid!");
assert(fine_scale_part.dofsValid() && "Fine scale part DOFs need to be valid!");
// add coarse and fine scale part to solution
solution += coarse_scale_part;
solution += fine_scale_part;
} // solve_dirichlet_zero
} //namespace MsFEM {
} //namespace Multiscale {
} //namespace Dune {
<|endoftext|> |
<commit_before>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "actions/transformations/remove_comments_char.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include "modsecurity/transaction.h"
#include "actions/transformations/transformation.h"
namespace modsecurity {
namespace actions {
namespace transformations {
RemoveCommentsChar::RemoveCommentsChar(std::string action)
: Transformation(action) {
this->action_kind = 1;
}
std::string RemoveCommentsChar::evaluate(std::string value,
Transaction *transaction) {
int64_t i;
i = 0;
while (i < value.size()) {
if (value.at(i) == '/' && (i+1 < value.size()) && value.at(i+1) == '*') {
value.erase(i, 2);
} else if (value.at(i) == '*' && (i+1 < value.size()) && value.at(i+1) == '/') {
value.erase(i, 2);
} else if (value.at(i) == '<' && (i+1 < value.size()) && value.at(i+1) == '!' &&
(i+2 < value.size()) && value.at(i+2) == '-' && (i+3 < value.size()) &&
value.at(i+3) == '-') {
value.erase(i, 4);
} else if (value.at(i) == '-' && (i+1 < value.size()) && value.at(i+1) == '-' &&
(i+2 < value.size()) && value.at(i+2) == '>') {
value.erase(i, 3);
} else if (value.at(i) == '-' && (i+1 < value.size()) && value.at(i+1) == '-') {
value.erase(i, 2);
} else if (value.at(i) == '#') {
value.erase(i, 1);
} else {
i++;
}
}
return value;
}
} // namespace transformations
} // namespace actions
} // namespace modsecurity
<commit_msg>Reduces the amount of warnings<commit_after>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "actions/transformations/remove_comments_char.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include "modsecurity/transaction.h"
#include "actions/transformations/transformation.h"
namespace modsecurity {
namespace actions {
namespace transformations {
RemoveCommentsChar::RemoveCommentsChar(std::string action)
: Transformation(action) {
this->action_kind = 1;
}
std::string RemoveCommentsChar::evaluate(std::string value,
Transaction *transaction) {
int64_t i;
i = 0;
while (i < value.size()) {
if (value.at(i) == '/'
&& (i+1 < value.size()) && value.at(i+1) == '*') {
value.erase(i, 2);
} else if (value.at(i) == '*'
&& (i+1 < value.size()) && value.at(i+1) == '/') {
value.erase(i, 2);
} else if (value.at(i) == '<'
&& (i+1 < value.size())
&& value.at(i+1) == '!'
&& (i+2 < value.size())
&& value.at(i+2) == '-'
&& (i+3 < value.size())
&& value.at(i+3) == '-') {
value.erase(i, 4);
} else if (value.at(i) == '-' && (i+1 < value.size()) && value.at(i+1) == '-' &&
(i+2 < value.size()) && value.at(i+2) == '>') {
value.erase(i, 3);
} else if (value.at(i) == '-' && (i+1 < value.size()) && value.at(i+1) == '-') {
value.erase(i, 2);
} else if (value.at(i) == '#') {
value.erase(i, 1);
} else {
i++;
}
}
return value;
}
} // namespace transformations
} // namespace actions
} // namespace modsecurity
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/platform_popup.hpp>
#include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <GG/DropDownList.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
GG::Y RowHeight()
{
static GG::Y retval = GG::Y0;
if (!retval) {
const GG::Y DEFAULT_MARGIN(8); // DEFAULT_ROW_HEIGHT from ListBox.cpp, minus the default font's lineskip of 14
retval = adobe::implementation::DefaultFont()->Lineskip() + DEFAULT_MARGIN;
}
return retval;
}
/****************************************************************************************************/
GG::Y DropHeight(unsigned int lines)
{ return RowHeight() * static_cast<int>(lines) + static_cast<int>(2 * GG::ListBox::BORDER_THICK); }
/****************************************************************************************************/
enum metrics {
gap = 4 // Measured as space from popup to label.
};
/****************************************************************************************************/
void clear_menu_items(adobe::popup_t& control)
{
assert(control.control_m);
control.menu_items_m.clear();
control.control_m->Clear();
}
/****************************************************************************************************/
void sel_changed_slot(adobe::popup_t& popup, GG::DropDownList::iterator it)
{
assert(popup.control_m);
if (!popup.value_proc_m.empty() || !popup.extended_value_proc_m.empty())
{
std::size_t new_index(popup.control_m->CurrentItemIndex());
if (popup.custom_m)
--new_index;
if (popup.value_proc_m)
popup.value_proc_m(popup.menu_items_m.at(new_index).second);
if (popup.extended_value_proc_m)
popup.extended_value_proc_m(popup.menu_items_m.at(new_index).second, adobe::modifier_state());
}
}
/****************************************************************************************************/
void set_menu_item_set(adobe::popup_t& p, const adobe::popup_t::menu_item_t* first, const adobe::popup_t::menu_item_t* last)
{
p.custom_m = false;
unsigned int lines = 0;
for (; first != last; ++first, ++lines)
{
// MM: Revisit. Is there a way to have disabled separators in combo boxes?
// Since I don't know a way I intercept -'s here. (Dashes inidcate separators
// on the macintosh and also in eve at the moment).
if (first->first != "-" && first->first != "__separator")
p.menu_items_m.push_back(*first);
}
if (p.control_m)
p.control_m->SetDropHeight(DropHeight(lines));
}
/****************************************************************************************************/
void message_menu_item_set(adobe::popup_t& popup)
{
assert(popup.control_m);
for (adobe::popup_t::menu_item_set_t::const_iterator
first = popup.menu_items_m.begin(), last = popup.menu_items_m.end();
first != last;
++first) {
GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), "");
row->push_back(adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, first->first,
adobe::implementation::DefaultFont(),
GG::CLR_BLACK, GG::FORMAT_LEFT));
popup.control_m->Insert(row);
}
popup.enable(!popup.menu_items_m.empty());
if (popup.menu_items_m.empty())
return;
popup.display(popup.last_m);
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
popup_t::popup_t(const std::string& name,
const std::string& alt_text,
const std::string& custom_item_name,
const menu_item_t* first,
const menu_item_t* last,
theme_t theme) :
control_m(0),
theme_m(theme),
name_m(name, alt_text, 0, GG::FORMAT_NONE, theme),
alt_text_m(alt_text),
using_label_m(!name.empty()),
custom_m(false),
custom_item_name_m(custom_item_name)
{
::set_menu_item_set(*this, first, last);
}
/****************************************************************************************************/
void popup_t::measure(extents_t& result)
{
assert(control_m);
//
// The popup_t has multiple text items. We need to find the one with
// the widest extents (when drawn). Then we can make sure that we get
// enough space to draw our largest text item.
//
const boost::shared_ptr<GG::Font>& font = implementation::DefaultFont();
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
GG::Pt largest_extent;
bool have_extents = false;
for (; first != last; ++first)
{
GG::Pt extent = font->TextExtent(first->first) + GG::Pt(2 * implementation::CharWidth(), GG::Y0);
if (largest_extent.x < extent.x)
largest_extent = extent;
have_extents = true;
}
GG::Pt non_client_size = implementation::NonClientSize(*control_m);
result.width() = Value(largest_extent.x + non_client_size.x);
result.height() = original_height_m;
GG::Y baseline =
(static_cast<int>(result.height()) - implementation::CharHeight()) / 2 +
implementation::DefaultFont()->Ascent();
result.vertical().guide_set_m.push_back(Value(baseline));
//
// If we have a label (always on our left side?) then we
// need to add the size of the label to our result. We try
// to align the label with the popup by baseline. Which is
// kind of what Eve does, so it's bad that we do this
// ourselves, really...
//
if (!using_label_m)
return;
//
// We store the height of the label, from this we can
// figure out how much to offset it when positioning
// the widgets in set_bounds.
//
extents_t label_bounds(measure_text(name_m.name_m, font));
label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));
//
// Now we can align the label within the vertical
// slice of the result. This doesn't do anything if
// the label is shorter than the popup.
//
align_slices(result.vertical(), label_bounds.vertical());
//
// Add the width of the label (plus a gap) to the
// resulting width.
//
result.width() += gap + label_bounds.width();
//
// Don't let the width of the popup go too crazy now...
//
result.width() = std::min(result.width(), 300L); // REVISIT (fbrereto) : fixed width
//
// Add a point-of-interest where the label ends.
// We put the label to the left of the popup.
//
result.horizontal().guide_set_m.push_back(label_bounds.width());
}
/****************************************************************************************************/
void popup_t::place(const place_data_t& place_data)
{
using adobe::place;
assert(control_m);
place_data_t local_place_data(place_data);
if (using_label_m)
{
//
// The vertical offset of the label is the geometry's
// baseline - the label's baseline.
//
assert(place_data.vertical().guide_set_m.empty() == false);
place_data_t label_place_data;
label_place_data.horizontal().position_m = left(place_data);
label_place_data.vertical().position_m = top(place_data);
//
// The width of the label is the first horizontal
// point of interest.
//
assert(place_data.horizontal().guide_set_m.empty() == false);
width(label_place_data) = place_data.horizontal().guide_set_m[0];
height(label_place_data) = height(place_data);
//
// Set the label dimensions.
//
place(name_m, label_place_data);
//
// Now we need to adjust the position of the popup
// widget.
//
long width = gap + adobe::width(label_place_data);
local_place_data.horizontal().position_m += width;
adobe::width(local_place_data) -= width;
}
implementation::set_control_bounds(control_m, local_place_data);
}
/****************************************************************************************************/
void popup_t::enable(bool make_enabled)
{
assert(control_m);
control_m->Disable(!make_enabled);
}
/****************************************************************************************************/
void popup_t::reset_menu_item_set(const menu_item_t* first, const menu_item_t* last)
{
assert(control_m);
clear_menu_items(*this);
::set_menu_item_set(*this, first, last);
::message_menu_item_set(*this);
}
/****************************************************************************************************/
void popup_t::display(const model_type& value)
{
assert(control_m);
last_m = value;
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
for (; first != last; ++first) {
if ((*first).second == value) {
if (custom_m) {
custom_m = false;
control_m->Erase(control_m->begin());
}
std::ptrdiff_t index(first - menu_items_m.begin());
control_m->Select(index);
return;
}
}
display_custom();
}
/****************************************************************************************************/
void popup_t::display_custom()
{
if (custom_m)
return;
custom_m = true;
GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), "");
row->push_back(adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, custom_item_name_m,
adobe::implementation::DefaultFont(),
GG::CLR_BLACK, GG::FORMAT_LEFT));
control_m->Insert(row, control_m->begin());
control_m->Select(0);
}
/****************************************************************************************************/
void popup_t::select_with_text(const std::string& text)
{
assert(control_m);
std::size_t old_index(control_m->CurrentItemIndex());
std::size_t new_index = std::numeric_limits<std::size_t>::max();
for (std::size_t i = 0; i < menu_items_m.size(); ++i) {
if (menu_items_m[i].first == text) {
new_index = i;
break;
}
}
if (new_index < menu_items_m.size())
control_m->Select(new_index);
if (value_proc_m.empty())
return;
if (new_index != old_index)
value_proc_m(menu_items_m.at(new_index).second);
}
/****************************************************************************************************/
void popup_t::monitor(const setter_type& proc)
{
assert(control_m);
value_proc_m = proc;
}
/****************************************************************************************************/
void popup_t::monitor_extended(const extended_setter_type& proc)
{
assert(control_m);
extended_value_proc_m = proc;
}
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/container idiom for event and drawing system.
template <> platform_display_type insert<popup_t>(display_t& display,
platform_display_type& parent,
popup_t& element)
{
if (element.using_label_m)
insert(display, parent, element.name_m);
assert(!element.control_m);
int lines = std::min(element.menu_items_m.size(), std::size_t(20u));
element.control_m =
implementation::Factory().NewDropDownList(GG::X0, GG::Y0, GG::X1, implementation::StandardHeight(),
DropHeight(lines), GG::CLR_GRAY);
element.control_m->SetStyle(GG::LIST_NOSORT);
element.original_height_m = Value(element.control_m->Height());
GG::Connect(element.control_m->SelChangedSignal,
boost::bind(&sel_changed_slot, boost::ref(element), _1));
if (!element.alt_text_m.empty())
adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);
::message_menu_item_set(element);
return display.insert(parent, element.control_m);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Adjusted spacing inside popups in Eve layout tests.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/platform_popup.hpp>
#include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <GG/DropDownList.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
GG::Y RowHeight()
{
static GG::Y retval = GG::Y0;
if (!retval) {
const GG::Y DEFAULT_MARGIN(8); // DEFAULT_ROW_HEIGHT from ListBox.cpp, minus the default font's lineskip of 14
retval = adobe::implementation::DefaultFont()->Lineskip() + DEFAULT_MARGIN;
}
return retval;
}
/****************************************************************************************************/
GG::Y DropHeight(unsigned int lines)
{ return RowHeight() * static_cast<int>(lines) + static_cast<int>(2 * GG::ListBox::BORDER_THICK); }
/****************************************************************************************************/
enum metrics {
gap = 4 // Measured as space from popup to label.
};
/****************************************************************************************************/
void clear_menu_items(adobe::popup_t& control)
{
assert(control.control_m);
control.menu_items_m.clear();
control.control_m->Clear();
}
/****************************************************************************************************/
void sel_changed_slot(adobe::popup_t& popup, GG::DropDownList::iterator it)
{
assert(popup.control_m);
if (!popup.value_proc_m.empty() || !popup.extended_value_proc_m.empty())
{
std::size_t new_index(popup.control_m->CurrentItemIndex());
if (popup.custom_m)
--new_index;
if (popup.value_proc_m)
popup.value_proc_m(popup.menu_items_m.at(new_index).second);
if (popup.extended_value_proc_m)
popup.extended_value_proc_m(popup.menu_items_m.at(new_index).second, adobe::modifier_state());
}
}
/****************************************************************************************************/
void set_menu_item_set(adobe::popup_t& p, const adobe::popup_t::menu_item_t* first, const adobe::popup_t::menu_item_t* last)
{
p.custom_m = false;
unsigned int lines = 0;
for (; first != last; ++first, ++lines)
{
// MM: Revisit. Is there a way to have disabled separators in combo boxes?
// Since I don't know a way I intercept -'s here. (Dashes inidcate separators
// on the macintosh and also in eve at the moment).
if (first->first != "-" && first->first != "__separator")
p.menu_items_m.push_back(*first);
}
if (p.control_m)
p.control_m->SetDropHeight(DropHeight(lines));
}
/****************************************************************************************************/
void message_menu_item_set(adobe::popup_t& popup)
{
assert(popup.control_m);
for (adobe::popup_t::menu_item_set_t::const_iterator
first = popup.menu_items_m.begin(), last = popup.menu_items_m.end();
first != last;
++first) {
GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), "");
row->push_back(adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, first->first,
adobe::implementation::DefaultFont(),
GG::CLR_BLACK, GG::FORMAT_LEFT));
popup.control_m->Insert(row);
}
popup.enable(!popup.menu_items_m.empty());
if (popup.menu_items_m.empty())
return;
popup.display(popup.last_m);
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
popup_t::popup_t(const std::string& name,
const std::string& alt_text,
const std::string& custom_item_name,
const menu_item_t* first,
const menu_item_t* last,
theme_t theme) :
control_m(0),
theme_m(theme),
name_m(name, alt_text, 0, GG::FORMAT_NONE, theme),
alt_text_m(alt_text),
using_label_m(!name.empty()),
custom_m(false),
custom_item_name_m(custom_item_name)
{
::set_menu_item_set(*this, first, last);
}
/****************************************************************************************************/
void popup_t::measure(extents_t& result)
{
assert(control_m);
//
// The popup_t has multiple text items. We need to find the one with
// the widest extents (when drawn). Then we can make sure that we get
// enough space to draw our largest text item.
//
const boost::shared_ptr<GG::Font>& font = implementation::DefaultFont();
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
GG::Pt largest_extent;
bool have_extents = false;
for (; first != last; ++first)
{
GG::Pt extent = font->TextExtent(first->first) + GG::Pt(implementation::CharWidth(), GG::Y0);
if (largest_extent.x < extent.x)
largest_extent = extent;
have_extents = true;
}
GG::Pt non_client_size = implementation::NonClientSize(*control_m);
result.width() = Value(largest_extent.x + non_client_size.x);
result.height() = original_height_m;
GG::Y baseline =
(static_cast<int>(result.height()) - implementation::CharHeight()) / 2 +
implementation::DefaultFont()->Ascent();
result.vertical().guide_set_m.push_back(Value(baseline));
//
// If we have a label (always on our left side?) then we
// need to add the size of the label to our result. We try
// to align the label with the popup by baseline. Which is
// kind of what Eve does, so it's bad that we do this
// ourselves, really...
//
if (!using_label_m)
return;
//
// We store the height of the label, from this we can
// figure out how much to offset it when positioning
// the widgets in set_bounds.
//
extents_t label_bounds(measure_text(name_m.name_m, font));
label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));
//
// Now we can align the label within the vertical
// slice of the result. This doesn't do anything if
// the label is shorter than the popup.
//
align_slices(result.vertical(), label_bounds.vertical());
//
// Add the width of the label (plus a gap) to the
// resulting width.
//
result.width() += gap + label_bounds.width();
//
// Don't let the width of the popup go too crazy now...
//
result.width() = std::min(result.width(), 300L); // REVISIT (fbrereto) : fixed width
//
// Add a point-of-interest where the label ends.
// We put the label to the left of the popup.
//
result.horizontal().guide_set_m.push_back(label_bounds.width());
}
/****************************************************************************************************/
void popup_t::place(const place_data_t& place_data)
{
using adobe::place;
assert(control_m);
place_data_t local_place_data(place_data);
if (using_label_m)
{
//
// The vertical offset of the label is the geometry's
// baseline - the label's baseline.
//
assert(place_data.vertical().guide_set_m.empty() == false);
place_data_t label_place_data;
label_place_data.horizontal().position_m = left(place_data);
label_place_data.vertical().position_m = top(place_data);
//
// The width of the label is the first horizontal
// point of interest.
//
assert(place_data.horizontal().guide_set_m.empty() == false);
width(label_place_data) = place_data.horizontal().guide_set_m[0];
height(label_place_data) = height(place_data);
//
// Set the label dimensions.
//
place(name_m, label_place_data);
//
// Now we need to adjust the position of the popup
// widget.
//
long width = gap + adobe::width(label_place_data);
local_place_data.horizontal().position_m += width;
adobe::width(local_place_data) -= width;
}
implementation::set_control_bounds(control_m, local_place_data);
}
/****************************************************************************************************/
void popup_t::enable(bool make_enabled)
{
assert(control_m);
control_m->Disable(!make_enabled);
}
/****************************************************************************************************/
void popup_t::reset_menu_item_set(const menu_item_t* first, const menu_item_t* last)
{
assert(control_m);
clear_menu_items(*this);
::set_menu_item_set(*this, first, last);
::message_menu_item_set(*this);
}
/****************************************************************************************************/
void popup_t::display(const model_type& value)
{
assert(control_m);
last_m = value;
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
for (; first != last; ++first) {
if ((*first).second == value) {
if (custom_m) {
custom_m = false;
control_m->Erase(control_m->begin());
}
std::ptrdiff_t index(first - menu_items_m.begin());
control_m->Select(index);
return;
}
}
display_custom();
}
/****************************************************************************************************/
void popup_t::display_custom()
{
if (custom_m)
return;
custom_m = true;
GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), "");
row->push_back(adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, custom_item_name_m,
adobe::implementation::DefaultFont(),
GG::CLR_BLACK, GG::FORMAT_LEFT));
control_m->Insert(row, control_m->begin());
control_m->Select(0);
}
/****************************************************************************************************/
void popup_t::select_with_text(const std::string& text)
{
assert(control_m);
std::size_t old_index(control_m->CurrentItemIndex());
std::size_t new_index = std::numeric_limits<std::size_t>::max();
for (std::size_t i = 0; i < menu_items_m.size(); ++i) {
if (menu_items_m[i].first == text) {
new_index = i;
break;
}
}
if (new_index < menu_items_m.size())
control_m->Select(new_index);
if (value_proc_m.empty())
return;
if (new_index != old_index)
value_proc_m(menu_items_m.at(new_index).second);
}
/****************************************************************************************************/
void popup_t::monitor(const setter_type& proc)
{
assert(control_m);
value_proc_m = proc;
}
/****************************************************************************************************/
void popup_t::monitor_extended(const extended_setter_type& proc)
{
assert(control_m);
extended_value_proc_m = proc;
}
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/container idiom for event and drawing system.
template <> platform_display_type insert<popup_t>(display_t& display,
platform_display_type& parent,
popup_t& element)
{
if (element.using_label_m)
insert(display, parent, element.name_m);
assert(!element.control_m);
int lines = std::min(element.menu_items_m.size(), std::size_t(20u));
element.control_m =
implementation::Factory().NewDropDownList(GG::X0, GG::Y0, GG::X1, implementation::StandardHeight(),
DropHeight(lines), GG::CLR_GRAY);
element.control_m->SetStyle(GG::LIST_NOSORT);
element.original_height_m = Value(element.control_m->Height());
GG::Connect(element.control_m->SelChangedSignal,
boost::bind(&sel_changed_slot, boost::ref(element), _1));
if (!element.alt_text_m.empty())
adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);
::message_menu_item_set(element);
return display.insert(parent, element.control_m);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <QtGui/QImage>
#include <QtGui/QFrame>
#include <QtCore/QtDebug>
#include <algorithm>
#include "SensitivitiesWidget.h"
#include "DataModelGUI.h"
#include "qtUtilities.h"
#include "CQTaskBtnWidget.h"
#include "CQTaskHeaderWidget.h"
#include "CQTaskMethodWidget.h"
#include "CCopasiSelectionDialog.h"
#include "resourcesUI/CQIconResource.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "sensitivities/CSensTask.h"
#include "sensitivities/CSensProblem.h"
#include "sensitivities/CSensMethod.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "report/CKeyFactory.h"
#include "CQSensResultWidget.h"
/**
* Constructs a SensitivitiesWidget which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
SensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)
: TaskWidget(parent, name, fl),
mpSingleFunction(NULL),
mpSingleVariable(NULL),
mpSingleVariable2(NULL)
{
setupUi(this);
init();
retranslateUi(this);
}
/*
* Destroys the object and frees any allocated resources
*/
SensitivitiesWidget::~SensitivitiesWidget()
{}
void SensitivitiesWidget::init()
{
mpHeaderWidget->setTaskName("Sensitivities");
verticalLayout->insertWidget(0, mpHeaderWidget); // header
// verticalLayout->insertSpacing(1, 14); // space between header and body
mpMethodWidget->showMethodParameters(true);
verticalLayout->addWidget(mpMethodWidget);
verticalLayout->addWidget(mpBtnWidget); // 'footer'
// icons
SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
// initialization
initCombos();
}
bool SensitivitiesWidget::saveTask()
{
saveCommon();
saveMethod();
CSensTask* sensTask =
dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
if (sensTask == NULL)
return false;
CSensProblem* problem =
dynamic_cast<CSensProblem *>(sensTask->getProblem());
if (problem == NULL)
return false;
CSensMethod* method =
dynamic_cast<CSensMethod *>(sensTask->getMethod());
if (method == NULL)
return false;
// subtask
problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());
CSensItem tmp;
// target function
if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleFunction)
tmp.setSingleObjectCN(mpSingleFunction->getCN());
}
else
tmp.setListType(FunctionChooser->getCurrentObjectList());
problem->changeTargetFunctions(tmp);
// variables 1
if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleVariable)
tmp.setSingleObjectCN(mpSingleVariable->getCN());
}
else
tmp.setListType(VariableChooser->getCurrentObjectList());
problem->removeVariables();
if (tmp.getListType() != CObjectLists::EMPTY_LIST)
problem->addVariables(tmp);
else
return true;
//variables 2
CSensItem tmp2;
if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleVariable2)
tmp2.setSingleObjectCN(mpSingleVariable2->getCN());
}
else
tmp2.setListType(Variable2Chooser->getCurrentObjectList());
// write variables to problem
problem->removeVariables();
if (tmp.getListType() != CObjectLists::EMPTY_LIST)
{
problem->addVariables(tmp);
if (tmp2.getListType() != CObjectLists::EMPTY_LIST)
problem->addVariables(tmp2);
}
// :TODO Bug 322: This should only be called when actual changes have been saved.
// However we do not track the changes for the variables we just delete them and add them again.
if (true)
{
if (mpDataModel != NULL)
{
mpDataModel->changed();
}
mChanged = false;
}
return true;
}
CCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)
{return CSensMethod::createMethod(type);}
bool SensitivitiesWidget::runTask()
{
if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)
FunctionLineEdit->setText(QApplication::translate("SensitivitiesWidget", "[Please Choose Object.] --->", 0, QApplication::UnicodeUTF8));
if (!commonBeforeRunTask()) return false;
bool success = true;
if (!commonRunTask()) success = false;
return success;
}
bool SensitivitiesWidget::taskFinishedEvent()
{
bool success = true;
//setup the result widget
CQSensResultWidget *pResult =
dynamic_cast<CQSensResultWidget*>(mpListView->findWidgetFromId(341));
if (pResult) pResult->newResult();
if (success && isVisible()) mpListView->switchToOtherWidget(341, ""); //change to the results window
return success;
}
bool SensitivitiesWidget::loadTask()
{
loadCommon();
loadMethod();
CSensTask* sensTask =
dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
assert(sensTask);
CSensProblem* problem =
dynamic_cast<CSensProblem *>(sensTask->getProblem());
assert(problem);
//CSensMethod* method =
// dynamic_cast<CSensMethod *>(sensTask->getMethod());
//assert(method);
//mSubTaskType = problem->getSubTaskType();
SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());
updateComboBoxes(problem->getSubTaskType());
CSensItem tmp = problem->getTargetFunctions();
//target function
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
assert(pDataModel != NULL);
if (tmp.isSingleObject())
{
FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleFunction)
FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));
}
else
{
mpSingleFunction = NULL;
FunctionChooser->setCurrentObjectList(tmp.getListType());
}
//variables 1
if (problem->getNumberOfVariables() > 0)
{
tmp = problem->getVariables(0);
if (tmp.isSingleObject())
{
VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleVariable)
VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));
}
else
VariableChooser->setCurrentObjectList(tmp.getListType());
}
else
{
VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
mpSingleVariable = NULL;
}
//variables 2
if (problem->getNumberOfVariables() > 1)
{
tmp = problem->getVariables(1);
if (tmp.isSingleObject())
{
Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleVariable2)
Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));
}
else
Variable2Chooser->setCurrentObjectList(tmp.getListType());
}
else
{
Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
mpSingleVariable2 = NULL;
}
// initCombos(problem);
mChanged = false;
updateAllLineditEnable();
return true;
}
//**************************************************************************
void SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)
{
if (!box) return;
bool enable = false;
if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
enable = true;
if (w1) w1->setVisible(enable);
if (w2) w2->setVisible(enable);
}
void SensitivitiesWidget::updateAllLineditEnable()
{
/*
updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);
updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);
updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);
*/
updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);
updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);
updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);
}
void
SensitivitiesWidget::initCombos()
{
QStringList StringList;
//std::vector<int> mFunctionIndexTable, mVariableIndexTable;
// SubTaskChooser combo
int i = 0;
while (CSensProblem::SubTaskName[i].length() > 0)
{
StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));
++i;
}
SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);
SubTaskChooser->setCurrentIndex(0);
updateComboBoxes((CSensProblem::SubTaskType)0);
}
void SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)
{
FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));
VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));
Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));
}
// ******************* SLOTs *******************************+
void
//SensitivitiesWidget::on_SubTaskChooser_activated(int)
SensitivitiesWidget::slotChooseSubTask(int)
{
CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();
updateComboBoxes(subTaskType);
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_FunctionChooser_activated(int a)
SensitivitiesWidget::slotChooseFunction(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_VariableChooser_activated(int)
SensitivitiesWidget::slotChooseVariable(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_Variable2Chooser_activated(int)
SensitivitiesWidget::slotChooseVariable2(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_SingleFunctionChooser_clicked()
SensitivitiesWidget::slotChooseSingleFunction()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::Variables |
CQSimpleSelectionTree::ObservedValues |
CQSimpleSelectionTree::ObservedConstants);
if (pObject)
{
FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleFunction = pObject;
FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
void
//SensitivitiesWidget::on_SingleVariableChooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::InitialTime |
CQSimpleSelectionTree::Parameters);
if (pObject)
{
VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleVariable = pObject;
VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
void
//SensitivitiesWidget::on_SingleVariable2Chooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable2()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::InitialTime |
CQSimpleSelectionTree::Parameters);
if (pObject)
{
Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleVariable2 = pObject;
Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
<commit_msg>Fixed Bug 2097. The constant are no longer shown in the object browser.<commit_after>// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <QtGui/QImage>
#include <QtGui/QFrame>
#include <QtCore/QtDebug>
#include <algorithm>
#include "SensitivitiesWidget.h"
#include "DataModelGUI.h"
#include "qtUtilities.h"
#include "CQTaskBtnWidget.h"
#include "CQTaskHeaderWidget.h"
#include "CQTaskMethodWidget.h"
#include "CCopasiSelectionDialog.h"
#include "resourcesUI/CQIconResource.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "sensitivities/CSensTask.h"
#include "sensitivities/CSensProblem.h"
#include "sensitivities/CSensMethod.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "report/CKeyFactory.h"
#include "CQSensResultWidget.h"
/**
* Constructs a SensitivitiesWidget which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
SensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)
: TaskWidget(parent, name, fl),
mpSingleFunction(NULL),
mpSingleVariable(NULL),
mpSingleVariable2(NULL)
{
setupUi(this);
init();
retranslateUi(this);
}
/*
* Destroys the object and frees any allocated resources
*/
SensitivitiesWidget::~SensitivitiesWidget()
{}
void SensitivitiesWidget::init()
{
mpHeaderWidget->setTaskName("Sensitivities");
verticalLayout->insertWidget(0, mpHeaderWidget); // header
// verticalLayout->insertSpacing(1, 14); // space between header and body
mpMethodWidget->showMethodParameters(true);
verticalLayout->addWidget(mpMethodWidget);
verticalLayout->addWidget(mpBtnWidget); // 'footer'
// icons
SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
// initialization
initCombos();
}
bool SensitivitiesWidget::saveTask()
{
saveCommon();
saveMethod();
CSensTask* sensTask =
dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
if (sensTask == NULL)
return false;
CSensProblem* problem =
dynamic_cast<CSensProblem *>(sensTask->getProblem());
if (problem == NULL)
return false;
CSensMethod* method =
dynamic_cast<CSensMethod *>(sensTask->getMethod());
if (method == NULL)
return false;
// subtask
problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());
CSensItem tmp;
// target function
if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleFunction)
tmp.setSingleObjectCN(mpSingleFunction->getCN());
}
else
tmp.setListType(FunctionChooser->getCurrentObjectList());
problem->changeTargetFunctions(tmp);
// variables 1
if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleVariable)
tmp.setSingleObjectCN(mpSingleVariable->getCN());
}
else
tmp.setListType(VariableChooser->getCurrentObjectList());
problem->removeVariables();
if (tmp.getListType() != CObjectLists::EMPTY_LIST)
problem->addVariables(tmp);
else
return true;
//variables 2
CSensItem tmp2;
if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
{
if (mpSingleVariable2)
tmp2.setSingleObjectCN(mpSingleVariable2->getCN());
}
else
tmp2.setListType(Variable2Chooser->getCurrentObjectList());
// write variables to problem
problem->removeVariables();
if (tmp.getListType() != CObjectLists::EMPTY_LIST)
{
problem->addVariables(tmp);
if (tmp2.getListType() != CObjectLists::EMPTY_LIST)
problem->addVariables(tmp2);
}
// :TODO Bug 322: This should only be called when actual changes have been saved.
// However we do not track the changes for the variables we just delete them and add them again.
if (true)
{
if (mpDataModel != NULL)
{
mpDataModel->changed();
}
mChanged = false;
}
return true;
}
CCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)
{return CSensMethod::createMethod(type);}
bool SensitivitiesWidget::runTask()
{
if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)
FunctionLineEdit->setText(QApplication::translate("SensitivitiesWidget", "[Please Choose Object.] --->", 0, QApplication::UnicodeUTF8));
if (!commonBeforeRunTask()) return false;
bool success = true;
if (!commonRunTask()) success = false;
return success;
}
bool SensitivitiesWidget::taskFinishedEvent()
{
bool success = true;
//setup the result widget
CQSensResultWidget *pResult =
dynamic_cast<CQSensResultWidget*>(mpListView->findWidgetFromId(341));
if (pResult) pResult->newResult();
if (success && isVisible()) mpListView->switchToOtherWidget(341, ""); //change to the results window
return success;
}
bool SensitivitiesWidget::loadTask()
{
loadCommon();
loadMethod();
CSensTask* sensTask =
dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
assert(sensTask);
CSensProblem* problem =
dynamic_cast<CSensProblem *>(sensTask->getProblem());
assert(problem);
//CSensMethod* method =
// dynamic_cast<CSensMethod *>(sensTask->getMethod());
//assert(method);
//mSubTaskType = problem->getSubTaskType();
SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());
updateComboBoxes(problem->getSubTaskType());
CSensItem tmp = problem->getTargetFunctions();
//target function
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
assert(pDataModel != NULL);
if (tmp.isSingleObject())
{
FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleFunction)
FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));
}
else
{
mpSingleFunction = NULL;
FunctionChooser->setCurrentObjectList(tmp.getListType());
}
//variables 1
if (problem->getNumberOfVariables() > 0)
{
tmp = problem->getVariables(0);
if (tmp.isSingleObject())
{
VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleVariable)
VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));
}
else
VariableChooser->setCurrentObjectList(tmp.getListType());
}
else
{
VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
mpSingleVariable = NULL;
}
//variables 2
if (problem->getNumberOfVariables() > 1)
{
tmp = problem->getVariables(1);
if (tmp.isSingleObject())
{
Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());
if (mpSingleVariable2)
Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));
}
else
Variable2Chooser->setCurrentObjectList(tmp.getListType());
}
else
{
Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
mpSingleVariable2 = NULL;
}
// initCombos(problem);
mChanged = false;
updateAllLineditEnable();
return true;
}
//**************************************************************************
void SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)
{
if (!box) return;
bool enable = false;
if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
enable = true;
if (w1) w1->setVisible(enable);
if (w2) w2->setVisible(enable);
}
void SensitivitiesWidget::updateAllLineditEnable()
{
/*
updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);
updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);
updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);
*/
updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);
updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);
updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);
}
void
SensitivitiesWidget::initCombos()
{
QStringList StringList;
//std::vector<int> mFunctionIndexTable, mVariableIndexTable;
// SubTaskChooser combo
int i = 0;
while (CSensProblem::SubTaskName[i].length() > 0)
{
StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));
++i;
}
SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);
SubTaskChooser->setCurrentIndex(0);
updateComboBoxes((CSensProblem::SubTaskType)0);
}
void SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)
{
FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));
VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));
Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));
}
// ******************* SLOTs *******************************+
void
//SensitivitiesWidget::on_SubTaskChooser_activated(int)
SensitivitiesWidget::slotChooseSubTask(int)
{
CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();
updateComboBoxes(subTaskType);
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_FunctionChooser_activated(int a)
SensitivitiesWidget::slotChooseFunction(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_VariableChooser_activated(int)
SensitivitiesWidget::slotChooseVariable(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_Variable2Chooser_activated(int)
SensitivitiesWidget::slotChooseVariable2(int)
{
updateAllLineditEnable();
}
void
//SensitivitiesWidget::on_SingleFunctionChooser_clicked()
SensitivitiesWidget::slotChooseSingleFunction()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::Variables |
CQSimpleSelectionTree::ObservedValues);
if (pObject)
{
FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleFunction = pObject;
FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
void
//SensitivitiesWidget::on_SingleVariableChooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::InitialTime |
CQSimpleSelectionTree::Parameters);
if (pObject)
{
VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleVariable = pObject;
VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
void
//SensitivitiesWidget::on_SingleVariable2Chooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable2()
{
const CCopasiObject * pObject =
CCopasiSelectionDialog::getObjectSingle(this,
CQSimpleSelectionTree::InitialTime |
CQSimpleSelectionTree::Parameters);
if (pObject)
{
Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
mpSingleVariable2 = pObject;
Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
}
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* @file application.cpp
* @authors Sam Decrock
*
* Detect sound over a sliding window
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "application.h"
/* Function prototypes -------------------------------------------------------*/
void updateState(int state);
void sendStateOverTcp(int state);
void postState(int state);
void readIncommingHttpData();
/* Variables -----------------------------------------------------------------*/
bool useTCP = false;
bool useHTTP = true;
int ledPin = D0;
int ledPin2 = D1;
int soundPin = A0;
int currentSoundValue;
int buttonPin = D2;
bool buttonState = 0;
bool buttonPressed = false;
int threshold = 2200; //in mV
int capacity = 0;
int thresholdCapacity = 0;
int currentSoundState = 0;
// TCP:
TCPClient tcpclient;
IPAddress tcpServer(10,100,11,7);
int tcpPort = 8000;
// HTTP:
TCPClient httpclient;
IPAddress httpServer(10,100,11,7);
int httpPort = 3000;
uint8_t *responseBuffer;
const char *actionSound = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 12\r\n\r\naction=sound\r\n";
const char *actionNoSound = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 14\r\n\r\naction=nosound\r\n";
const char *actionStartup = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 14\r\n\r\naction=startup\r\n";
bool debug = false;
/* This function is called once at start up ----------------------------------*/
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(soundPin, INPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
responseBuffer = new uint8_t[1024];
updateState(-1);
digitalWrite(ledPin2, 1);
}
/* This function loops forever (every 5ms) ------------------------------------*/
void loop()
{
// SIMULATE SOUND USING BUTTON:
buttonState = digitalRead(buttonPin);
if(buttonState == 1 && buttonPressed == false)
{
buttonPressed = true;
updateState(1);
}
if(buttonPressed == true && buttonState == 0)
{
buttonPressed = false;
updateState(0);
}
// LISTEN FOR SOUND:
if(!buttonPressed) // dont interfere with the testbutton
{
currentSoundValue = analogRead(soundPin);
if(currentSoundValue > threshold)
{
thresholdCapacity++;
if(thresholdCapacity >= 3)
{
capacity = 200; //2 seconds
thresholdCapacity = 0;
updateState(1);
}
}
else
{
capacity--;
if(capacity <= 0 ){
// happens after capacity*(delay+5 ms):
capacity = 0; //cap
updateState(0);
}
thresholdCapacity--;
if(thresholdCapacity <= 0)
{
thresholdCapacity = 0;
}
}
}
if( useHTTP )
{
readIncommingHttpData();
}
delay(5); // wait an extra 5ms, that's 10ms between loops
// indicates machine has bootet:
digitalWrite(ledPin2, 0);
}
void updateState(int state)
{
digitalWrite(ledPin, state); // turn LED on/off
// only send state if different from previous:
if(currentSoundState != state)
{
currentSoundState = state;
if( useTCP == true)
{
sendStateOverTcp(state);
}
if( useHTTP == true )
{
postState(state);
}
}
}
void sendStateOverTcp(int state)
{
if(debug) Serial.println("Sending state over TCP");
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP was not connected. Connecting...");
tcpclient.connect(tcpServer, tcpPort);
}
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP still not connected. Trying a second time...");
tcpclient.connect(tcpServer, tcpPort);
}
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP could not connect.");
return;
}
if(debug) Serial.println("TCP connected. Sending state.");
if(state == 1)
{
tcpclient.print("sound");
}
if(state == 0)
{
tcpclient.print("nosound");
}
if(state == -1)
{
tcpclient.print("startup");
}
tcpclient.flush();
if(debug) Serial.println("TCP flushed.");
}
void postState(int state) {
if(debug) Serial.println("Sending state over HTTP POST");
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP was not connected. Connecting...");
httpclient.connect(httpServer, httpPort);
}
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP still not connected. Trying a second time...");
httpclient.connect(httpServer, httpPort);
}
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP could not connect.");
return;
}
if(debug) Serial.println("HTTP connected. Sending state.");
if(state == 1)
{
httpclient.print(actionSound);
}
if(state == 0)
{
httpclient.print(actionNoSound);
}
if(state == -1)
{
httpclient.print(actionStartup);
}
// flush, so the buffer is clear to read response:
httpclient.flush();
if(debug) Serial.println("> HTTP request sent:");
// httpclient.stop(); //break connection (not necessary, server will break connection depending on 'Connection' header)
}
void readIncommingHttpData()
{
// READ RESPONSE
if( httpclient.available() )
{
// 1. fill the buffer with zeros
memset(responseBuffer, 0x00, 1024);
// 2. read the first 1023 bytes
httpclient.read(responseBuffer, 1023);
// 3. read the rest of the socket buffer so that it's empty
while(httpclient.available())
{
httpclient.read();
}
if(responseBuffer[0] != 0x00)
{
if(debug) Serial.println("> incomming HTTP response:");
if(debug) Serial.println();
if(debug) Serial.println((char*)responseBuffer);
if(debug) Serial.println();
}
}
}
<commit_msg>changed ip<commit_after>/**
******************************************************************************
* @file application.cpp
* @authors Sam Decrock
*
* Detect sound over a sliding window
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "application.h"
/* Function prototypes -------------------------------------------------------*/
void updateState(int state);
void sendStateOverTcp(int state);
void postState(int state);
void readIncommingHttpData();
/* Variables -----------------------------------------------------------------*/
bool useTCP = false;
bool useHTTP = true;
int ledPin = D0;
int ledPin2 = D1;
int soundPin = A0;
int currentSoundValue;
int buttonPin = D2;
bool buttonState = 0;
bool buttonPressed = false;
int threshold = 2200; //in mV
int capacity = 0;
int thresholdCapacity = 0;
int currentSoundState = 0;
// TCP:
TCPClient tcpclient;
IPAddress tcpServer(10,100,11,60);
int tcpPort = 8000;
// HTTP:
TCPClient httpclient;
IPAddress httpServer(10,100,11,60);
int httpPort = 3000;
uint8_t *responseBuffer;
const char *actionSound = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 12\r\n\r\naction=sound\r\n";
const char *actionNoSound = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 14\r\n\r\naction=nosound\r\n";
const char *actionStartup = "POST /rest/soundstate HTTP/1.1\r\nHost: somehost\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 14\r\n\r\naction=startup\r\n";
bool debug = false;
/* This function is called once at start up ----------------------------------*/
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(soundPin, INPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
responseBuffer = new uint8_t[1024];
updateState(-1);
digitalWrite(ledPin2, 1);
}
/* This function loops forever (every 5ms) ------------------------------------*/
void loop()
{
// SIMULATE SOUND USING BUTTON:
buttonState = digitalRead(buttonPin);
if(buttonState == 1 && buttonPressed == false)
{
buttonPressed = true;
updateState(1);
}
if(buttonPressed == true && buttonState == 0)
{
buttonPressed = false;
updateState(0);
}
// LISTEN FOR SOUND:
if(!buttonPressed) // dont interfere with the testbutton
{
currentSoundValue = analogRead(soundPin);
if(currentSoundValue > threshold)
{
thresholdCapacity++;
if(thresholdCapacity >= 3)
{
capacity = 200; //2 seconds
thresholdCapacity = 0;
updateState(1);
}
}
else
{
capacity--;
if(capacity <= 0 ){
// happens after capacity*(delay+5 ms):
capacity = 0; //cap
updateState(0);
}
thresholdCapacity--;
if(thresholdCapacity <= 0)
{
thresholdCapacity = 0;
}
}
}
if( useHTTP )
{
readIncommingHttpData();
}
delay(5); // wait an extra 5ms, that's 10ms between loops
// indicates machine has bootet:
digitalWrite(ledPin2, 0);
}
void updateState(int state)
{
digitalWrite(ledPin, state); // turn LED on/off
// only send state if different from previous:
if(currentSoundState != state)
{
currentSoundState = state;
if( useTCP == true)
{
sendStateOverTcp(state);
}
if( useHTTP == true )
{
postState(state);
}
}
}
void sendStateOverTcp(int state)
{
if(debug) Serial.println("Sending state over TCP");
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP was not connected. Connecting...");
tcpclient.connect(tcpServer, tcpPort);
}
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP still not connected. Trying a second time...");
tcpclient.connect(tcpServer, tcpPort);
}
if( !tcpclient.connected() )
{
if(debug) Serial.println("TCP could not connect.");
return;
}
if(debug) Serial.println("TCP connected. Sending state.");
if(state == 1)
{
tcpclient.print("sound");
}
if(state == 0)
{
tcpclient.print("nosound");
}
if(state == -1)
{
tcpclient.print("startup");
}
tcpclient.flush();
if(debug) Serial.println("TCP flushed.");
}
void postState(int state) {
if(debug) Serial.println("Sending state over HTTP POST");
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP was not connected. Connecting...");
httpclient.connect(httpServer, httpPort);
}
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP still not connected. Trying a second time...");
httpclient.connect(httpServer, httpPort);
}
if( !httpclient.connected() )
{
if(debug) Serial.println("HTTP could not connect.");
return;
}
if(debug) Serial.println("HTTP connected. Sending state.");
if(state == 1)
{
httpclient.print(actionSound);
}
if(state == 0)
{
httpclient.print(actionNoSound);
}
if(state == -1)
{
httpclient.print(actionStartup);
}
// flush, so the buffer is clear to read response:
httpclient.flush();
if(debug) Serial.println("> HTTP request sent:");
// httpclient.stop(); //break connection (not necessary, server will break connection depending on 'Connection' header)
}
void readIncommingHttpData()
{
// READ RESPONSE
if( httpclient.available() )
{
// 1. fill the buffer with zeros
memset(responseBuffer, 0x00, 1024);
// 2. read the first 1023 bytes
httpclient.read(responseBuffer, 1023);
// 3. read the rest of the socket buffer so that it's empty
while(httpclient.available())
{
httpclient.read();
}
if(responseBuffer[0] != 0x00)
{
if(debug) Serial.println("> incomming HTTP response:");
if(debug) Serial.println();
if(debug) Serial.println((char*)responseBuffer);
if(debug) Serial.println();
}
}
}
<|endoftext|> |
<commit_before>/**
* \file EQ.cpp
*/
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <ATK/EQ/ChamberlinFilter.h>
#include <ATK/EQ/CustomIIRFilter.h>
#include <ATK/EQ/PedalToneStackFilter.h>
#include <ATK/EQ/RIAAFilter.h>
#include <ATK/EQ/FourthOrderFilter.h>
#include <ATK/EQ/LinkwitzRileyFilter.h>
#include <ATK/EQ/RobertBristowJohnsonFilter.h>
#include <ATK/EQ/ToneStackFilter.h>
#include <ATK/EQ/CustomFIRFilter.h>
#include <ATK/EQ/FIRFilter.h>
#include "ChebyshevFilter.h"
#include "MainFilter.h"
#include "RobertBristowJohnsonFilter.h"
#include "SecondOrderFilter.h"
#include "SecondOrderSVFFilter.h"
#include "StandardFilters.h"
#include "TimeVaryingIIRFilter.h"
#include "TimeVaryingSVFFilter.h"
namespace py = pybind11;
using namespace ATK;
using namespace py::literals;
namespace
{
template<typename DataType, typename T>
void populate_ChamberlinFilter(py::module& m, const char* type, T& parent)
{
py::class_<ChamberlinFilter<DataType>>(m, type, parent)
.def(py::init<>())
.def_property("cut_frequency", &ChamberlinFilter<DataType>::get_cut_frequency, &ChamberlinFilter<DataType>::set_cut_frequency)
.def_property("attenuation", &ChamberlinFilter<DataType>::get_attenuation, &ChamberlinFilter<DataType>::set_attenuation)
.def_property("selected", &ChamberlinFilter<DataType>::get_selected, &ChamberlinFilter<DataType>::select);
}
template<typename Coefficients>
void populate_FIRFilter(py::module& m, const char* type)
{
typedef typename Coefficients::DataType DataType;
py::class_<FIRFilter<Coefficients>, Coefficients>(m, type)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property_readonly("coefficients_in", [](const FIRFilter<Coefficients>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
});
}
template<typename DataType, typename T>
void populate_CustomFIR(py::module& m, const char* type, T& parent)
{
py::class_<FIRFilter<CustomFIRCoefficients<DataType>>>(m, type, parent)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property("coefficients_in", [](const FIRFilter<CustomFIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
},
[](FIRFilter<CustomFIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_in(std::vector<DataType>(array.data(), array.data() + array.size()));
});
}
template<typename DataType, typename T>
void populate_CustomIIR(py::module& m, const char* type, T& parent)
{
py::class_<IIRFilter<CustomIIRCoefficients<DataType>>>(m, type, parent)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property("coefficients_in", [](const IIRFilter<CustomIIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
},
[](IIRFilter<CustomIIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_in(std::vector<DataType>(array.data(), array.data() + array.size()));
})
.def_property("coefficients_out", [](const IIRFilter<CustomIIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_out().size(), instance.get_coefficients_out().data());
},
[](IIRFilter<CustomIIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_out(std::vector<DataType>(array.data(), array.data() + array.size()));
});
}
template<typename Coefficients, typename T>
void populate_EmptyCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent);
}
template<typename Coefficients, typename T>
void populate_PedalCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent)
.def_property("tone", &Coefficients::get_tone, &Coefficients::set_tone);
}
template<typename Coefficients, typename T>
void populate_StackCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent)
.def_property("low", &Coefficients::get_low, &Coefficients::set_low)
.def_property("middle", &Coefficients::get_middle, &Coefficients::set_middle)
.def_property("high", &Coefficients::get_high, &Coefficients::set_high);
}
template<typename Coefficients>
void populate_StackFilter(py::module& m, const char* type)
{
py::class_<IIRFilter<Coefficients>, Coefficients>(m, type)
.def_property_readonly("coefficients_in", &IIRFilter<Coefficients>::get_coefficients_in)
.def_property_readonly("coefficients_out", &IIRFilter<Coefficients>::get_coefficients_out)
.def_static("build_Bassman_stack", &Coefficients::buildBassmanStack)
.def_static("build_JCM800_stack", &Coefficients::buildJCM800Stack);
}
}
PYBIND11_MODULE(PythonEQ, m)
{
m.doc() = "Audio ToolKit EQ module";
py::object f1 = (py::object) py::module::import("ATK.Core").attr("FloatTypedBaseFilter");
py::object f2 = (py::object) py::module::import("ATK.Core").attr("DoubleTypedBaseFilter");
populate_ChamberlinFilter<float>(m, "FloatChamberlinFilter", f1);
populate_ChamberlinFilter<double>(m, "DoubleChamberlinFilter", f1);
populate_CustomFIR<float>(m, "FloatCustomFIRFilter", f1);
populate_CustomFIR<double>(m, "DoubleCustomFIRFilter", f2);
populate_CustomIIR<float>(m, "FloatCustomIIRFilter", f1);
populate_CustomIIR<double>(m, "DoubleCustomIIRFilter", f2);
populate_StandardFilters(m, f1, f2);
populate_ChebyshevFilter(m, f1, f2);
populate_SecondOrderFilter(m, f1, f2);
populate_RobertBristowJohnsonFilter(m, f1, f2);
populate_SecondOrderSVFFilter(m, f1, f2);
populate_ndOrderCoefficients<FourthOrderBaseCoefficients<float>>(m, "FloatFourthOrderBaseCoefficients", f1);
populate_ndOrderCoefficients<FourthOrderBaseCoefficients<double>>(m, "DoubleFourthOrderBaseCoefficients", f2);
populate_DirectCoefficients<LinkwitzRileyLowPassCoefficients<float>>(m, "FloatLinkwitzRileyLowPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyLowPassCoefficients<double>>(m, "DoubleLinkwitzRileyLowPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyHighPassCoefficients<float>>(m, "FloatLinkwitzRileyHighPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyHighPassCoefficients<double>>(m, "DoubleLinkwitzRileyHighPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4LowPassCoefficients<float>>(m, "FloatLinkwitzRiley4LowPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4LowPassCoefficients<double>>(m, "DoubleLinkwitzRiley4LowPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4HighPassCoefficients<float>>(m, "FloatLinkwitzRiley4HighPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4HighPassCoefficients<double>>(m, "DoubleLinkwitzRiley4HighPassCoefficients");
populate_IIRFilter<LinkwitzRileyLowPassCoefficients<float>>(m, "FloatLinkwitzRileyLowPassFilter");
populate_IIRFilter<LinkwitzRileyLowPassCoefficients<double>>(m, "DoubleLinkwitzRileyLowPassFilter");
populate_IIRFilter<LinkwitzRileyHighPassCoefficients<float>>(m, "FloatLinkwitzRileyHighPasssFilter");
populate_IIRFilter<LinkwitzRileyHighPassCoefficients<double>>(m, "DoubleLinkwitzRileyHighPassFilter");
populate_IIRFilter<LinkwitzRiley4LowPassCoefficients<float>>(m, "FloatLinkwitzRiley4LowPassFilter");
populate_IIRFilter<LinkwitzRiley4LowPassCoefficients<double>>(m, "DoubleLinkwitzRiley4LowPassFilter");
populate_IIRFilter<LinkwitzRiley4HighPassCoefficients<float>>(m, "FloatLinkwitzRiley4HighPassFilter");
populate_IIRFilter<LinkwitzRiley4HighPassCoefficients<double>>(m, "DoubleLinkwitzRiley4HighPassFilter");
populate_EmptyCoefficients<RIAACoefficients<float>>(m, "FloatRIAACoefficients", f1);
populate_EmptyCoefficients<RIAACoefficients<double>>(m, "DoubleRIAACoefficients", f2);
populate_EmptyCoefficients<InverseRIAACoefficients<float>>(m, "FloatInverseRIAACoefficients", f1);
populate_EmptyCoefficients<InverseRIAACoefficients<double>>(m, "DoubleInverseRIAACoefficients", f2);
populate_IIRFilter<RIAACoefficients<float>>(m, "FloatRIAAFilter");
populate_IIRFilter<RIAACoefficients<double>>(m, "DoubleRIAAFilter");
populate_IIRFilter<InverseRIAACoefficients<float>>(m, "FloatInverseRIAAFilter");
populate_IIRFilter<InverseRIAACoefficients<double>>(m, "DoubleInverseRIAAFilter");
populate_PedalCoefficients<SD1ToneCoefficients<float>>(m, "FloatSD1ToneCoefficients", f1);
populate_PedalCoefficients<SD1ToneCoefficients<double>>(m, "DoubleSD1ToneCoefficients", f2);
populate_PedalCoefficients<TS9ToneCoefficients<float>>(m, "FloatTS9ToneCoefficients", f1);
populate_PedalCoefficients<TS9ToneCoefficients<double>>(m, "DoubleTS9ToneCoefficients", f2);
populate_IIRFilter<SD1ToneCoefficients<float>>(m, "FloatSD1ToneFilter");
populate_IIRFilter<SD1ToneCoefficients<double>>(m, "DoubleSD1ToneFilter");
populate_IIRFilter<TS9ToneCoefficients<float>>(m, "FloatTS9ToneFilter");
populate_IIRFilter<TS9ToneCoefficients<double>>(m, "DoubleTS9ToneFilter");
populate_StackCoefficients<ToneStackCoefficients<float>>(m, "FloatStackToneCoefficients", f1);
populate_StackCoefficients<ToneStackCoefficients<double>>(m, "DoubleStackToneCoefficients", f2);
populate_StackFilter<ToneStackCoefficients<float>>(m, "FloatStackToneFilter");
populate_StackFilter<ToneStackCoefficients<double>>(m, "DoubleStackToneFilter");
populate_TimeVaryingIIRFilters(m, f1, f2);
populate_TimeVaryingSVFFilters(m, f1, f2);
}
<commit_msg>Trial to fix crash on BeagleBoard<commit_after>/**
* \file EQ.cpp
*/
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <ATK/EQ/ChamberlinFilter.h>
#include <ATK/EQ/CustomIIRFilter.h>
#include <ATK/EQ/PedalToneStackFilter.h>
#include <ATK/EQ/RIAAFilter.h>
#include <ATK/EQ/FourthOrderFilter.h>
#include <ATK/EQ/LinkwitzRileyFilter.h>
#include <ATK/EQ/RobertBristowJohnsonFilter.h>
#include <ATK/EQ/ToneStackFilter.h>
#include <ATK/EQ/CustomFIRFilter.h>
#include <ATK/EQ/FIRFilter.h>
#include "ChebyshevFilter.h"
#include "MainFilter.h"
#include "RobertBristowJohnsonFilter.h"
#include "SecondOrderFilter.h"
#include "SecondOrderSVFFilter.h"
#include "StandardFilters.h"
#include "TimeVaryingIIRFilter.h"
#include "TimeVaryingSVFFilter.h"
namespace py = pybind11;
using namespace ATK;
using namespace py::literals;
namespace
{
template<typename DataType, typename T>
void populate_ChamberlinFilter(py::module& m, const char* type, T& parent)
{
py::class_<ChamberlinFilter<DataType>>(m, type, parent)
.def(py::init<>())
.def_property("cut_frequency", &ChamberlinFilter<DataType>::get_cut_frequency, &ChamberlinFilter<DataType>::set_cut_frequency)
.def_property("attenuation", &ChamberlinFilter<DataType>::get_attenuation, &ChamberlinFilter<DataType>::set_attenuation)
.def_property("selected", &ChamberlinFilter<DataType>::get_selected, &ChamberlinFilter<DataType>::select);
}
template<typename Coefficients>
void populate_FIRFilter(py::module& m, const char* type)
{
typedef typename Coefficients::DataType DataType;
py::class_<FIRFilter<Coefficients>, Coefficients>(m, type)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property_readonly("coefficients_in", [](const FIRFilter<Coefficients>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
});
}
template<typename DataType, typename T>
void populate_CustomFIR(py::module& m, const char* type, T& parent)
{
py::class_<FIRFilter<CustomFIRCoefficients<DataType>>>(m, type, parent)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property("coefficients_in", [](const FIRFilter<CustomFIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
},
[](FIRFilter<CustomFIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_in(std::vector<DataType>(array.data(), array.data() + array.shape()[0]));
});
}
template<typename DataType, typename T>
void populate_CustomIIR(py::module& m, const char* type, T& parent)
{
py::class_<IIRFilter<CustomIIRCoefficients<DataType>>>(m, type, parent)
.def(py::init<std::size_t>(), "nb_channels"_a = 1)
.def_property("coefficients_in", [](const IIRFilter<CustomIIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_in().size(), instance.get_coefficients_in().data());
},
[](IIRFilter<CustomIIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_in(std::vector<DataType>(array.data(), array.data() + array.shape()[0]));
})
.def_property("coefficients_out", [](const IIRFilter<CustomIIRCoefficients<DataType>>& instance)
{
return py::array_t<DataType>(instance.get_coefficients_out().size(), instance.get_coefficients_out().data());
},
[](IIRFilter<CustomIIRCoefficients<DataType>>& instance, const py::array_t<DataType>& array)
{
if(array.ndim() != 1 || array.shape()[0] == 0)
{
throw std::length_error("Wrong size for input coefficients, must be of dimension 1 and not empty");
}
instance.set_coefficients_out(std::vector<DataType>(array.data(), array.data() + array.shape()[0]));
});
}
template<typename Coefficients, typename T>
void populate_EmptyCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent);
}
template<typename Coefficients, typename T>
void populate_PedalCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent)
.def_property("tone", &Coefficients::get_tone, &Coefficients::set_tone);
}
template<typename Coefficients, typename T>
void populate_StackCoefficients(py::module& m, const char* type, T& parent)
{
py::class_<Coefficients>(m, type, parent)
.def_property("low", &Coefficients::get_low, &Coefficients::set_low)
.def_property("middle", &Coefficients::get_middle, &Coefficients::set_middle)
.def_property("high", &Coefficients::get_high, &Coefficients::set_high);
}
template<typename Coefficients>
void populate_StackFilter(py::module& m, const char* type)
{
py::class_<IIRFilter<Coefficients>, Coefficients>(m, type)
.def_property_readonly("coefficients_in", &IIRFilter<Coefficients>::get_coefficients_in)
.def_property_readonly("coefficients_out", &IIRFilter<Coefficients>::get_coefficients_out)
.def_static("build_Bassman_stack", &Coefficients::buildBassmanStack)
.def_static("build_JCM800_stack", &Coefficients::buildJCM800Stack);
}
}
PYBIND11_MODULE(PythonEQ, m)
{
m.doc() = "Audio ToolKit EQ module";
py::object f1 = (py::object) py::module::import("ATK.Core").attr("FloatTypedBaseFilter");
py::object f2 = (py::object) py::module::import("ATK.Core").attr("DoubleTypedBaseFilter");
populate_ChamberlinFilter<float>(m, "FloatChamberlinFilter", f1);
populate_ChamberlinFilter<double>(m, "DoubleChamberlinFilter", f1);
populate_CustomFIR<float>(m, "FloatCustomFIRFilter", f1);
populate_CustomFIR<double>(m, "DoubleCustomFIRFilter", f2);
populate_CustomIIR<float>(m, "FloatCustomIIRFilter", f1);
populate_CustomIIR<double>(m, "DoubleCustomIIRFilter", f2);
populate_StandardFilters(m, f1, f2);
populate_ChebyshevFilter(m, f1, f2);
populate_SecondOrderFilter(m, f1, f2);
populate_RobertBristowJohnsonFilter(m, f1, f2);
populate_SecondOrderSVFFilter(m, f1, f2);
populate_ndOrderCoefficients<FourthOrderBaseCoefficients<float>>(m, "FloatFourthOrderBaseCoefficients", f1);
populate_ndOrderCoefficients<FourthOrderBaseCoefficients<double>>(m, "DoubleFourthOrderBaseCoefficients", f2);
populate_DirectCoefficients<LinkwitzRileyLowPassCoefficients<float>>(m, "FloatLinkwitzRileyLowPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyLowPassCoefficients<double>>(m, "DoubleLinkwitzRileyLowPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyHighPassCoefficients<float>>(m, "FloatLinkwitzRileyHighPassCoefficients");
populate_DirectCoefficients<LinkwitzRileyHighPassCoefficients<double>>(m, "DoubleLinkwitzRileyHighPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4LowPassCoefficients<float>>(m, "FloatLinkwitzRiley4LowPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4LowPassCoefficients<double>>(m, "DoubleLinkwitzRiley4LowPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4HighPassCoefficients<float>>(m, "FloatLinkwitzRiley4HighPassCoefficients");
populate_DirectCoefficients<LinkwitzRiley4HighPassCoefficients<double>>(m, "DoubleLinkwitzRiley4HighPassCoefficients");
populate_IIRFilter<LinkwitzRileyLowPassCoefficients<float>>(m, "FloatLinkwitzRileyLowPassFilter");
populate_IIRFilter<LinkwitzRileyLowPassCoefficients<double>>(m, "DoubleLinkwitzRileyLowPassFilter");
populate_IIRFilter<LinkwitzRileyHighPassCoefficients<float>>(m, "FloatLinkwitzRileyHighPasssFilter");
populate_IIRFilter<LinkwitzRileyHighPassCoefficients<double>>(m, "DoubleLinkwitzRileyHighPassFilter");
populate_IIRFilter<LinkwitzRiley4LowPassCoefficients<float>>(m, "FloatLinkwitzRiley4LowPassFilter");
populate_IIRFilter<LinkwitzRiley4LowPassCoefficients<double>>(m, "DoubleLinkwitzRiley4LowPassFilter");
populate_IIRFilter<LinkwitzRiley4HighPassCoefficients<float>>(m, "FloatLinkwitzRiley4HighPassFilter");
populate_IIRFilter<LinkwitzRiley4HighPassCoefficients<double>>(m, "DoubleLinkwitzRiley4HighPassFilter");
populate_EmptyCoefficients<RIAACoefficients<float>>(m, "FloatRIAACoefficients", f1);
populate_EmptyCoefficients<RIAACoefficients<double>>(m, "DoubleRIAACoefficients", f2);
populate_EmptyCoefficients<InverseRIAACoefficients<float>>(m, "FloatInverseRIAACoefficients", f1);
populate_EmptyCoefficients<InverseRIAACoefficients<double>>(m, "DoubleInverseRIAACoefficients", f2);
populate_IIRFilter<RIAACoefficients<float>>(m, "FloatRIAAFilter");
populate_IIRFilter<RIAACoefficients<double>>(m, "DoubleRIAAFilter");
populate_IIRFilter<InverseRIAACoefficients<float>>(m, "FloatInverseRIAAFilter");
populate_IIRFilter<InverseRIAACoefficients<double>>(m, "DoubleInverseRIAAFilter");
populate_PedalCoefficients<SD1ToneCoefficients<float>>(m, "FloatSD1ToneCoefficients", f1);
populate_PedalCoefficients<SD1ToneCoefficients<double>>(m, "DoubleSD1ToneCoefficients", f2);
populate_PedalCoefficients<TS9ToneCoefficients<float>>(m, "FloatTS9ToneCoefficients", f1);
populate_PedalCoefficients<TS9ToneCoefficients<double>>(m, "DoubleTS9ToneCoefficients", f2);
populate_IIRFilter<SD1ToneCoefficients<float>>(m, "FloatSD1ToneFilter");
populate_IIRFilter<SD1ToneCoefficients<double>>(m, "DoubleSD1ToneFilter");
populate_IIRFilter<TS9ToneCoefficients<float>>(m, "FloatTS9ToneFilter");
populate_IIRFilter<TS9ToneCoefficients<double>>(m, "DoubleTS9ToneFilter");
populate_StackCoefficients<ToneStackCoefficients<float>>(m, "FloatStackToneCoefficients", f1);
populate_StackCoefficients<ToneStackCoefficients<double>>(m, "DoubleStackToneCoefficients", f2);
populate_StackFilter<ToneStackCoefficients<float>>(m, "FloatStackToneFilter");
populate_StackFilter<ToneStackCoefficients<double>>(m, "DoubleStackToneFilter");
populate_TimeVaryingIIRFilters(m, f1, f2);
populate_TimeVaryingSVFFilters(m, f1, f2);
}
<|endoftext|> |
<commit_before>// @(#)root/core/meta:$Id$
// Author: Vassil Vassilev 7/10/2012
/*************************************************************************
* Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TClingCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
using namespace clang;
using namespace cling;
class TObject;
// Functions used to forward calls from code compiled with no-rtti to code
// compiled with rtti.
extern "C" {
void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);
void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&);
TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);
Decl* TCintWithCling__GetObjectDecl(TObject *obj);
int TCintWithCling__AutoLoadCallback(const char* className);
}
TClingCallbacks::TClingCallbacks(cling::Interpreter* interp)
: InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),
fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {
const Decl* D = 0;
m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &D);
fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));
}
//pin the vtable here
TClingCallbacks::~TClingCallbacks() {}
// If cling cannot find a name it should ask ROOT before it issues an error.
// If ROOT knows the name then it has to create a new variable with that name
// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
// For example if the interpreter is looking for h in h-Draw(), this routine
// will create
// namespace __ROOT_SpecialObjects {
// THist* h = (THist*) the_address;
// }
//
// Later if h is called again it again won't be found by the standart lookup
// because it is in our hidden namespace (nobody should do using namespace
// __ROOT_SpecialObjects). It caches the variable declarations and their
// last address. If the newly found decl with the same name (h) has different
// address than the cached one it goes directly at the address and updates it.
//
// returns true when declaration is found and no error should be emitted.
bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {
if (tryAutoloadInternal(R, S))
return true; // happiness.
// If the autoload wasn't successful try ROOT specials.
return tryFindROOTSpecialInternal(R, S);
}
bool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {
Sema &SemaR = m_Interpreter->getSema();
ASTContext& C = SemaR.getASTContext();
Preprocessor &PP = SemaR.getPreprocessor();
DeclarationName Name = R.getLookupName();
// Try to autoload first if autoloading is enabled
if (IsAutoloadingEnabled()) {
// Avoid tail chasing.
if (fIsAutoloadingRecursively)
return false;
fIsAutoloadingRecursively = true;
// Save state of the PP
Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
Parser::ParserCurTokRestoreRAII savedCurToken(P);
bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();
SemaR.getDiagnostics().setSuppressAllDiagnostics();
// We can't PushDeclContext, because we go up and the routine that pops
// the DeclContext assumes that we drill down always.
// We have to be on the global context. At that point we are in a
// wrapper function so the parent context must be the global.
Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(),
SemaR.TUScope);
bool lookupSuccess = false;
if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {
pushedSAndDC.pop();
cleanupRAII.pop();
lookupSuccess = SemaR.LookupName(R, S);
}
SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);
fIsAutoloadingRecursively = false;
if (lookupSuccess)
return true;
}
}
// If cling cannot find a name it should ask ROOT before it issues an error.
// If ROOT knows the name then it has to create a new variable with that name
// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
// For example if the interpreter is looking for h in h-Draw(), this routine
// will create
// namespace __ROOT_SpecialObjects {
// THist* h = (THist*) the_address;
// }
//
// Later if h is called again it again won't be found by the standart lookup
// because it is in our hidden namespace (nobody should do using namespace
// __ROOT_SpecialObjects). It caches the variable declarations and their
// last address. If the newly found decl with the same name (h) has different
// address than the cached one it goes directly at the address and updates it.
//
// returns true when declaration is found and no error should be emitted.
//
bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {
Sema &SemaR = m_Interpreter->getSema();
ASTContext& C = SemaR.getASTContext();
Preprocessor &PP = SemaR.getPreprocessor();
DeclContext *CurDC = SemaR.CurContext;
DeclarationName Name = R.getLookupName();
// Make sure that the failed lookup comes from the prompt.
if(!CurDC || !CurDC->isFunctionOrMethod())
return false;
if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))
if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))
return false;
TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(),
fLastLookupCtx);
if (obj) {
VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR,
Name,
fROOTSpecialNamespace));
if (VD) {
//TODO: Check for same types.
TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);
// Since code was generated already we cannot rely on the initializer
// of the decl in the AST, however we will update that init so that it
// will be easier while debugging.
CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
CStyleCast->setSubExpr(newInit);
// The actual update happens here, directly in memory.
*address = obj;
}
else {
// Save state of the PP
Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
const Decl *TD = TCintWithCling__GetObjectDecl(obj);
// We will declare the variable as pointer.
QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
SourceLocation(), Name.getAsIdentifierInfo(), QT,
/*TypeSourceInfo*/0, SC_None, SC_None
);
// Build an initializer
Expr* Init
= utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
// Register the decl in our hidden special namespace
VD->setInit(Init);
fROOTSpecialNamespace->addDecl(VD);
cling::CompilationOptions CO;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = CompilationOptions::VPDisabled;
CO.ResultEvaluation = 0;
CO.DynamicScoping = 0;
CO.Debug = 0;
CO.CodeGeneration = 1;
cling::Transaction T(CO, /*llvm::Module=*/0);
T.appendUnique(VD);
T.setCompleted();
Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);
assert(Result == Interpreter::kSuccess
&& "Compilation should never fail!");
}
assert(VD && "Cannot be null!");
R.addDecl(VD);
return true;
}
return false;
}
// The callback is used to update the list of globals in ROOT.
//
void TClingCallbacks::TransactionCommitted(const Transaction &T) {
if (!T.size())
return;
if (fFirstRun) {
// Before setting up the callbacks register what cling have seen during init.
const cling::Transaction* T = m_Interpreter->getFirstTransaction();
while (T) {
if (T->getState() == cling::Transaction::kCommitted)
TCintWithCling__UpdateListsOnCommitted(*T);
T = T->getNext();
}
fFirstRun = false;
}
TCintWithCling__UpdateListsOnCommitted(T);
}
// The callback is used to update the list of globals in ROOT.
//
void TClingCallbacks::TransactionUnloaded(const Transaction &T) {
if (!T.size())
return;
TCintWithCling__UpdateListsOnUnloaded(T);
}
<commit_msg>Silence a warning.<commit_after>// @(#)root/core/meta:$Id$
// Author: Vassil Vassilev 7/10/2012
/*************************************************************************
* Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TClingCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
using namespace clang;
using namespace cling;
class TObject;
// Functions used to forward calls from code compiled with no-rtti to code
// compiled with rtti.
extern "C" {
void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);
void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&);
TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);
Decl* TCintWithCling__GetObjectDecl(TObject *obj);
int TCintWithCling__AutoLoadCallback(const char* className);
}
TClingCallbacks::TClingCallbacks(cling::Interpreter* interp)
: InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),
fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {
const Decl* D = 0;
m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &D);
fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));
}
//pin the vtable here
TClingCallbacks::~TClingCallbacks() {}
// If cling cannot find a name it should ask ROOT before it issues an error.
// If ROOT knows the name then it has to create a new variable with that name
// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
// For example if the interpreter is looking for h in h-Draw(), this routine
// will create
// namespace __ROOT_SpecialObjects {
// THist* h = (THist*) the_address;
// }
//
// Later if h is called again it again won't be found by the standart lookup
// because it is in our hidden namespace (nobody should do using namespace
// __ROOT_SpecialObjects). It caches the variable declarations and their
// last address. If the newly found decl with the same name (h) has different
// address than the cached one it goes directly at the address and updates it.
//
// returns true when declaration is found and no error should be emitted.
bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {
if (tryAutoloadInternal(R, S))
return true; // happiness.
// If the autoload wasn't successful try ROOT specials.
return tryFindROOTSpecialInternal(R, S);
}
bool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {
Sema &SemaR = m_Interpreter->getSema();
ASTContext& C = SemaR.getASTContext();
Preprocessor &PP = SemaR.getPreprocessor();
DeclarationName Name = R.getLookupName();
// Try to autoload first if autoloading is enabled
if (IsAutoloadingEnabled()) {
// Avoid tail chasing.
if (fIsAutoloadingRecursively)
return false;
fIsAutoloadingRecursively = true;
// Save state of the PP
Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
Parser::ParserCurTokRestoreRAII savedCurToken(P);
bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();
SemaR.getDiagnostics().setSuppressAllDiagnostics();
// We can't PushDeclContext, because we go up and the routine that pops
// the DeclContext assumes that we drill down always.
// We have to be on the global context. At that point we are in a
// wrapper function so the parent context must be the global.
Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(),
SemaR.TUScope);
bool lookupSuccess = false;
if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {
pushedSAndDC.pop();
cleanupRAII.pop();
lookupSuccess = SemaR.LookupName(R, S);
}
SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);
fIsAutoloadingRecursively = false;
if (lookupSuccess)
return true;
}
return false;
}
// If cling cannot find a name it should ask ROOT before it issues an error.
// If ROOT knows the name then it has to create a new variable with that name
// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
// For example if the interpreter is looking for h in h-Draw(), this routine
// will create
// namespace __ROOT_SpecialObjects {
// THist* h = (THist*) the_address;
// }
//
// Later if h is called again it again won't be found by the standart lookup
// because it is in our hidden namespace (nobody should do using namespace
// __ROOT_SpecialObjects). It caches the variable declarations and their
// last address. If the newly found decl with the same name (h) has different
// address than the cached one it goes directly at the address and updates it.
//
// returns true when declaration is found and no error should be emitted.
//
bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {
Sema &SemaR = m_Interpreter->getSema();
ASTContext& C = SemaR.getASTContext();
Preprocessor &PP = SemaR.getPreprocessor();
DeclContext *CurDC = SemaR.CurContext;
DeclarationName Name = R.getLookupName();
// Make sure that the failed lookup comes from the prompt.
if(!CurDC || !CurDC->isFunctionOrMethod())
return false;
if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))
if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))
return false;
TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(),
fLastLookupCtx);
if (obj) {
VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR,
Name,
fROOTSpecialNamespace));
if (VD) {
//TODO: Check for same types.
TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);
// Since code was generated already we cannot rely on the initializer
// of the decl in the AST, however we will update that init so that it
// will be easier while debugging.
CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
CStyleCast->setSubExpr(newInit);
// The actual update happens here, directly in memory.
*address = obj;
}
else {
// Save state of the PP
Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
const Decl *TD = TCintWithCling__GetObjectDecl(obj);
// We will declare the variable as pointer.
QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
SourceLocation(), Name.getAsIdentifierInfo(), QT,
/*TypeSourceInfo*/0, SC_None, SC_None
);
// Build an initializer
Expr* Init
= utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
// Register the decl in our hidden special namespace
VD->setInit(Init);
fROOTSpecialNamespace->addDecl(VD);
cling::CompilationOptions CO;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = CompilationOptions::VPDisabled;
CO.ResultEvaluation = 0;
CO.DynamicScoping = 0;
CO.Debug = 0;
CO.CodeGeneration = 1;
cling::Transaction T(CO, /*llvm::Module=*/0);
T.appendUnique(VD);
T.setCompleted();
Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);
assert(Result == Interpreter::kSuccess
&& "Compilation should never fail!");
}
assert(VD && "Cannot be null!");
R.addDecl(VD);
return true;
}
return false;
}
// The callback is used to update the list of globals in ROOT.
//
void TClingCallbacks::TransactionCommitted(const Transaction &T) {
if (!T.size())
return;
if (fFirstRun) {
// Before setting up the callbacks register what cling have seen during init.
const cling::Transaction* T = m_Interpreter->getFirstTransaction();
while (T) {
if (T->getState() == cling::Transaction::kCommitted)
TCintWithCling__UpdateListsOnCommitted(*T);
T = T->getNext();
}
fFirstRun = false;
}
TCintWithCling__UpdateListsOnCommitted(T);
}
// The callback is used to update the list of globals in ROOT.
//
void TClingCallbacks::TransactionUnloaded(const Transaction &T) {
if (!T.size())
return;
TCintWithCling__UpdateListsOnUnloaded(T);
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "display.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/modeling/project/project.h"
#include "renderer/utility/plugin.h"
// appleseed.foundation headers.
#include "foundation/platform/sharedlibrary.h"
#include "foundation/utility/searchpaths.h"
// Standard headers.
#include <memory>
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// Display class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID Display::get_class_uid()
{
return g_class_uid;
}
struct Display::Impl
{
Impl(
const char* plugin_path,
const ParamArray& params)
: m_plugin(PluginCache::load(plugin_path))
{
typedef ITileCallbackFactory*(*CreateFnType)(const ParamArray*);
CreateFnType create_fn =
reinterpret_cast<CreateFnType>(m_plugin->get_symbol("create_tile_callback_factory", false));
m_tile_callback_factory.reset(create_fn(¶ms));
}
auto_release_ptr<Plugin> m_plugin;
auto_release_ptr<ITileCallbackFactory> m_tile_callback_factory;
};
Display::Display(
const char* name,
const ParamArray& params)
: Entity(g_class_uid, params)
, impl(0)
{
set_name(name);
}
Display::~Display()
{
close();
}
void Display::release()
{
delete this;
}
bool Display::open(const Project& project)
{
string plugin;
try
{
plugin = get_parameters().get("plugin_name");
plugin += Plugin::get_default_file_extension();
plugin = project.search_paths().qualify(plugin);
}
catch (const ExceptionDictionaryKeyNotFound&)
{
RENDERER_LOG_ERROR("%s", "cannot open display: missing plugin_name parameter.");
return false;
}
try
{
impl = new Impl(plugin.c_str(), get_parameters());
}
catch (const ExceptionCannotLoadSharedLib& e)
{
RENDERER_LOG_ERROR("cannot open display: %s", e.what());
return false;
}
catch (const ExceptionPluginInitializationFailed&)
{
RENDERER_LOG_ERROR("initialization of display plugin %s failed", plugin.c_str());
return false;
}
catch (const ExceptionSharedLibCannotGetSymbol& e)
{
RENDERER_LOG_ERROR("cannot load symbol %s from display plugin", e.what());
return false;
}
return true;
}
void Display::close()
{
delete impl;
impl = 0;
}
ITileCallbackFactory* Display::get_tile_callback_factory() const
{
if (impl)
return impl->m_tile_callback_factory.get();
return 0;
}
//
// DisplayFactory class implementation.
//
auto_release_ptr<Display> DisplayFactory::create(
const char* name,
const ParamArray& params)
{
return auto_release_ptr<Display>(new Display(name, params));
}
} // namespace renderer
<commit_msg>Code tweak<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "display.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/modeling/project/project.h"
#include "renderer/utility/plugin.h"
// appleseed.foundation headers.
#include "foundation/platform/sharedlibrary.h"
#include "foundation/utility/searchpaths.h"
// Standard headers.
#include <memory>
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// Display class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID Display::get_class_uid()
{
return g_class_uid;
}
struct Display::Impl
{
Impl(
const char* plugin_path,
const ParamArray& params)
: m_plugin(PluginCache::load(plugin_path))
{
typedef ITileCallbackFactory*(*CreateFnType)(const ParamArray*);
CreateFnType create_fn =
reinterpret_cast<CreateFnType>(m_plugin->get_symbol("create_tile_callback_factory", false));
m_tile_callback_factory.reset(create_fn(¶ms));
}
auto_release_ptr<Plugin> m_plugin;
auto_release_ptr<ITileCallbackFactory> m_tile_callback_factory;
};
Display::Display(
const char* name,
const ParamArray& params)
: Entity(g_class_uid, params)
, impl(0)
{
set_name(name);
}
Display::~Display()
{
close();
}
void Display::release()
{
delete this;
}
bool Display::open(const Project& project)
{
string plugin;
try
{
plugin = get_parameters().get("plugin_name");
plugin += Plugin::get_default_file_extension();
plugin = project.search_paths().qualify(plugin);
}
catch (const ExceptionDictionaryKeyNotFound&)
{
RENDERER_LOG_ERROR("cannot open display: missing \"plugin_name\" parameter.");
return false;
}
try
{
impl = new Impl(plugin.c_str(), get_parameters());
}
catch (const ExceptionCannotLoadSharedLib& e)
{
RENDERER_LOG_ERROR("cannot open display: %s", e.what());
return false;
}
catch (const ExceptionPluginInitializationFailed&)
{
RENDERER_LOG_ERROR("initialization of display plugin %s failed", plugin.c_str());
return false;
}
catch (const ExceptionSharedLibCannotGetSymbol& e)
{
RENDERER_LOG_ERROR("cannot load symbol %s from display plugin", e.what());
return false;
}
return true;
}
void Display::close()
{
delete impl;
impl = 0;
}
ITileCallbackFactory* Display::get_tile_callback_factory() const
{
if (impl)
return impl->m_tile_callback_factory.get();
return 0;
}
//
// DisplayFactory class implementation.
//
auto_release_ptr<Display> DisplayFactory::create(
const char* name,
const ParamArray& params)
{
return auto_release_ptr<Display>(new Display(name, params));
}
} // namespace renderer
<|endoftext|> |
<commit_before>/*
* SSBOStreamer.cpp
*
* Copyright (C) 2018 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/utility/SSBOStreamer.h"
#include <algorithm>
#include "vislib/assert.h"
#include <iostream>
#include <sstream>
using namespace megamol::core::utility;
SSBOStreamer::SSBOStreamer(const std::string& debugLabel)
: theSSBO(0), bufferSize(0), numBuffers(0), srcStride(0), dstStride(0), theData(nullptr),
mappedMem(nullptr), numItems(0), numChunks(0), currIdx(0), numThr(omp_get_max_threads()), debugLabel(debugLabel) {
}
SSBOStreamer::~SSBOStreamer() {
if (this->mappedMem != nullptr && this->theSSBO != 0) {
glUnmapNamedBuffer(this->theSSBO);
}
if (this->theSSBO != 0) {
glDeleteBuffers(1, &this->theSSBO);
}
for (auto &x : fences) {
if (x) {
glDeleteSync(x);
}
}
}
GLuint SSBOStreamer::SetDataWithSize(const void *data, GLuint srcStride, GLuint dstStride,
size_t numItems, GLuint numBuffers, GLuint bufferSize) {
if (data == nullptr || srcStride == 0 || dstStride == 0 || numItems == 0 ||
numBuffers == 0 || bufferSize == 0) {
theData = nullptr;
return 0;
}
genBufferAndMap(numBuffers, bufferSize);
this->dstStride = dstStride;
this->srcStride = dstStride;
this->numItems = numItems;
this->theData = data;
this->numItemsPerChunk = GetNumItemsPerChunkAligned(bufferSize / dstStride);
this->numChunks = (numItems + numItemsPerChunk - 1) / numItemsPerChunk; // round up int division!
this->fences.resize(numBuffers, nullptr);
return numChunks;
}
GLuint SSBOStreamer::GetNumItemsPerChunkAligned(GLuint numItemsPerChunk, bool up) {
// Rounding the number of items per chunk is important for alignment and thus performance.
// That means, if we synchronize with another buffer that has tiny items, we have to make
// sure that we do not get non-aligned chunks with due to the number of items.
// For modern GPUs, 32bytes seems like a safe bet, i.e., we upload in multiples of eight
// to get 8 * 4 = 32.
const GLuint multiRound = 8;
return (((numItemsPerChunk) / multiRound) + (up ? 1 : 0)) * multiRound;
}
void SSBOStreamer::genBufferAndMap(GLuint numBuffers, GLuint bufferSize) {
if (this->theSSBO == 0) {
glGenBuffers(1, &this->theSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, this->theSSBO);
#if _DEBUG
glObjectLabel(GL_BUFFER, this->theSSBO, debugLabel.length(), debugLabel.c_str());
#endif
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
if (bufferSize != this->bufferSize || numBuffers != this->numBuffers) {
if (this->mappedMem != nullptr && this->theSSBO != 0) {
glUnmapNamedBuffer(this->theSSBO);
}
const size_t mapSize = bufferSize * numBuffers;
glNamedBufferStorage(this->theSSBO, mapSize, nullptr,
GL_MAP_PERSISTENT_BIT | GL_MAP_WRITE_BIT);
this->mappedMem = glMapNamedBufferRange(this->theSSBO, 0,
mapSize,
GL_MAP_PERSISTENT_BIT | GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);
if (this->mappedMem == nullptr) {
std::stringstream err;
err << std::string("SSBOStreamer: could not map memory (") << mapSize << std::string(" bytes)") << std::endl;
throw std::runtime_error(err.str());
}
this->bufferSize = bufferSize;
this->numBuffers = numBuffers;
}
}
GLuint SSBOStreamer::SetDataWithItems(const void *data, GLuint srcStride, GLuint dstStride, size_t numItems,
GLuint numBuffers, GLuint numItemsPerChunk) {
if (data == nullptr || srcStride == 0 || dstStride == 0 || numItems == 0 ||
numBuffers == 0 || numItemsPerChunk == 0) {
theData = nullptr;
return 0;
}
const GLuint bufferSize = numItemsPerChunk * dstStride;
genBufferAndMap(numBuffers, bufferSize);
this->dstStride = dstStride;
this->srcStride = dstStride;
this->numItems = numItems;
this->theData = data;
this->numItemsPerChunk = numItemsPerChunk;
this->numChunks = (numItems + numItemsPerChunk - 1) / numItemsPerChunk; // round up int division!
this->fences.resize(numBuffers, nullptr);
return this->bufferSize;
}
void SSBOStreamer::UploadChunk(unsigned int idx, GLuint& numItems, unsigned int& sync,
GLsizeiptr& dstOffset, GLsizeiptr& dstLength) {
if (theData == nullptr || idx > this->numChunks - 1) return;
// we did not succeed doing anything yet
numItems = sync = 0;
dstOffset = this->bufferSize * this->currIdx;
GLsizeiptr srcOffset = this->numItemsPerChunk * this->srcStride * idx;
void *dst = static_cast<char*>(this->mappedMem) + dstOffset;
const void *src = static_cast<const char*>(this->theData) + srcOffset;
const size_t itemsThisTime = std::min<unsigned int>(
this->numItems - idx * this->numItemsPerChunk, this->numItemsPerChunk);
dstLength = itemsThisTime * this->dstStride;
//printf("going to upload %llu x %u bytes to offset %lld from %lld\n", itemsThisTime,
// this->dstStride, dstOffset, srcOffset);
waitSignal(this->fences[currIdx]);
ASSERT(this->srcStride == this->dstStride);
memcpy(dst, src, itemsThisTime * this->srcStride);
glFlushMappedNamedBufferRange(this->theSSBO,
this->bufferSize * this->currIdx, itemsThisTime * this->dstStride);
numItems = itemsThisTime;
sync = currIdx;
currIdx = (currIdx + 1) % this->numBuffers;
}
void SSBOStreamer::SignalCompletion(unsigned int sync) {
queueSignal(this->fences[sync]);
}
void SSBOStreamer::queueSignal(GLsync& syncObj) {
if (syncObj) {
glDeleteSync(syncObj);
}
syncObj = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
void SSBOStreamer::waitSignal(GLsync& syncObj) {
if (syncObj) {
//XXX: Spinlocks in user code are a really bad idea.
while (true) {
const GLenum wait = glClientWaitSync(syncObj, GL_SYNC_FLUSH_COMMANDS_BIT, 1);
if (wait == GL_ALREADY_SIGNALED || wait == GL_CONDITION_SATISFIED) {
return;
}
}
}
}
<commit_msg>Tabs to spaces<commit_after>/*
* SSBOStreamer.cpp
*
* Copyright (C) 2018 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/utility/SSBOStreamer.h"
#include <algorithm>
#include "vislib/assert.h"
#include <iostream>
#include <sstream>
using namespace megamol::core::utility;
SSBOStreamer::SSBOStreamer(const std::string& debugLabel)
: theSSBO(0), bufferSize(0), numBuffers(0), srcStride(0), dstStride(0), theData(nullptr),
mappedMem(nullptr), numItems(0), numChunks(0), currIdx(0), numThr(omp_get_max_threads()), debugLabel(debugLabel) {
}
SSBOStreamer::~SSBOStreamer() {
if (this->mappedMem != nullptr && this->theSSBO != 0) {
glUnmapNamedBuffer(this->theSSBO);
}
if (this->theSSBO != 0) {
glDeleteBuffers(1, &this->theSSBO);
}
for (auto &x : fences) {
if (x) {
glDeleteSync(x);
}
}
}
GLuint SSBOStreamer::SetDataWithSize(const void *data, GLuint srcStride, GLuint dstStride,
size_t numItems, GLuint numBuffers, GLuint bufferSize) {
if (data == nullptr || srcStride == 0 || dstStride == 0 || numItems == 0 ||
numBuffers == 0 || bufferSize == 0) {
theData = nullptr;
return 0;
}
genBufferAndMap(numBuffers, bufferSize);
this->dstStride = dstStride;
this->srcStride = dstStride;
this->numItems = numItems;
this->theData = data;
this->numItemsPerChunk = GetNumItemsPerChunkAligned(bufferSize / dstStride);
this->numChunks = (numItems + numItemsPerChunk - 1) / numItemsPerChunk; // round up int division!
this->fences.resize(numBuffers, nullptr);
return numChunks;
}
GLuint SSBOStreamer::GetNumItemsPerChunkAligned(GLuint numItemsPerChunk, bool up) {
// Rounding the number of items per chunk is important for alignment and thus performance.
// That means, if we synchronize with another buffer that has tiny items, we have to make
// sure that we do not get non-aligned chunks with due to the number of items.
// For modern GPUs, 32bytes seems like a safe bet, i.e., we upload in multiples of eight
// to get 8 * 4 = 32.
const GLuint multiRound = 8;
return (((numItemsPerChunk) / multiRound) + (up ? 1 : 0)) * multiRound;
}
void SSBOStreamer::genBufferAndMap(GLuint numBuffers, GLuint bufferSize) {
if (this->theSSBO == 0) {
glGenBuffers(1, &this->theSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, this->theSSBO);
#if _DEBUG
glObjectLabel(GL_BUFFER, this->theSSBO, debugLabel.length(), debugLabel.c_str());
#endif
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
if (bufferSize != this->bufferSize || numBuffers != this->numBuffers) {
if (this->mappedMem != nullptr && this->theSSBO != 0) {
glUnmapNamedBuffer(this->theSSBO);
}
const size_t mapSize = bufferSize * numBuffers;
glNamedBufferStorage(this->theSSBO, mapSize, nullptr,
GL_MAP_PERSISTENT_BIT | GL_MAP_WRITE_BIT);
this->mappedMem = glMapNamedBufferRange(this->theSSBO, 0,
mapSize,
GL_MAP_PERSISTENT_BIT | GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);
if (this->mappedMem == nullptr) {
std::stringstream err;
err << std::string("SSBOStreamer: could not map memory (") << mapSize << std::string(" bytes)") << std::endl;
throw std::runtime_error(err.str());
}
this->bufferSize = bufferSize;
this->numBuffers = numBuffers;
}
}
GLuint SSBOStreamer::SetDataWithItems(const void *data, GLuint srcStride, GLuint dstStride, size_t numItems,
GLuint numBuffers, GLuint numItemsPerChunk) {
if (data == nullptr || srcStride == 0 || dstStride == 0 || numItems == 0 ||
numBuffers == 0 || numItemsPerChunk == 0) {
theData = nullptr;
return 0;
}
const GLuint bufferSize = numItemsPerChunk * dstStride;
genBufferAndMap(numBuffers, bufferSize);
this->dstStride = dstStride;
this->srcStride = dstStride;
this->numItems = numItems;
this->theData = data;
this->numItemsPerChunk = numItemsPerChunk;
this->numChunks = (numItems + numItemsPerChunk - 1) / numItemsPerChunk; // round up int division!
this->fences.resize(numBuffers, nullptr);
return this->bufferSize;
}
void SSBOStreamer::UploadChunk(unsigned int idx, GLuint& numItems, unsigned int& sync,
GLsizeiptr& dstOffset, GLsizeiptr& dstLength) {
if (theData == nullptr || idx > this->numChunks - 1) return;
// we did not succeed doing anything yet
numItems = sync = 0;
dstOffset = this->bufferSize * this->currIdx;
GLsizeiptr srcOffset = this->numItemsPerChunk * this->srcStride * idx;
void *dst = static_cast<char*>(this->mappedMem) + dstOffset;
const void *src = static_cast<const char*>(this->theData) + srcOffset;
const size_t itemsThisTime = std::min<unsigned int>(
this->numItems - idx * this->numItemsPerChunk, this->numItemsPerChunk);
dstLength = itemsThisTime * this->dstStride;
//printf("going to upload %llu x %u bytes to offset %lld from %lld\n", itemsThisTime,
// this->dstStride, dstOffset, srcOffset);
waitSignal(this->fences[currIdx]);
ASSERT(this->srcStride == this->dstStride);
memcpy(dst, src, itemsThisTime * this->srcStride);
glFlushMappedNamedBufferRange(this->theSSBO,
this->bufferSize * this->currIdx, itemsThisTime * this->dstStride);
numItems = itemsThisTime;
sync = currIdx;
currIdx = (currIdx + 1) % this->numBuffers;
}
void SSBOStreamer::SignalCompletion(unsigned int sync) {
queueSignal(this->fences[sync]);
}
void SSBOStreamer::queueSignal(GLsync& syncObj) {
if (syncObj) {
glDeleteSync(syncObj);
}
syncObj = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
void SSBOStreamer::waitSignal(GLsync& syncObj) {
if (syncObj) {
//XXX: Spinlocks in user code are a really bad idea.
while (true) {
const GLenum wait = glClientWaitSync(syncObj, GL_SYNC_FLUSH_COMMANDS_BIT, 1);
if (wait == GL_ALREADY_SIGNALED || wait == GL_CONDITION_SATISFIED) {
return;
}
}
}
}
<|endoftext|> |
<commit_before>#include "umundo/core.h"
#include <iostream>
using namespace umundo;
bool testRecursiveMutex() {
Mutex mutex;
UMUNDO_LOCK(mutex);
if(!mutex.tryLock()) {
LOG_ERR("tryLock should be possible from within the same thread");
assert(false);
}
UMUNDO_LOCK(mutex);
// can we unlock it as well?
UMUNDO_UNLOCK(mutex);
UMUNDO_UNLOCK(mutex);
return true;
}
static Mutex testMutex;
bool testThreads() {
class Thread1 : public Thread {
void run() {
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // blocks
Thread::sleepMs(50);
UMUNDO_UNLOCK(testMutex);
Thread::sleepMs(100);
}
};
/**
* tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)
* thread1: start tl l l s50 u
* main: start l s50 u s20 tl l join
* t-> 0 50 70 100
*/
UMUNDO_LOCK(testMutex);
Thread1 thread1;
thread1.start();
Thread::sleepMs(50); // thread1 will trylock and block on lock
UMUNDO_UNLOCK(testMutex); // unlock
Thread::sleepMs(20); // yield cpu and sleep
// thread1 sleeps with lock on mutex
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // thread1 will unlock and sleep
thread1.join(); // join with thread1
if(thread1.isStarted()) {
LOG_ERR("thread still running after join");
assert(false);
}
return true;
}
static Monitor testMonitor;
static int passedMonitor = 0;
bool testMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testMonitor.wait();
Thread::sleepMs(10); // avoid clash with other threads
passedMonitor++;
}
};
TestThread thread1(0);
TestThread thread2(5);
TestThread thread3(10);
for (int i = 0; i < 10; i++) {
passedMonitor = 0;
// all will block on monitor
thread1.start();
thread2.start();
thread3.start();
Thread::sleepMs(5); // give threads a chance to run into wait
if(passedMonitor != 0) {
LOG_ERR("%d threads already passed the monitor", passedMonitor);
assert(false);
}
UMUNDO_SIGNAL(testMonitor); // signal a single thread
Thread::sleepMs(15); // thread will increase passedMonitor
if(passedMonitor != 1) {
LOG_ERR("Expected 1 threads to pass the monitor, but %d did", passedMonitor);
assert(false);
}
UMUNDO_BROADCAST(testMonitor); // signal all other threads
Thread::sleepMs(15);
if (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {
LOG_ERR("Threads ran to completion but still insist on being started");
assert(false);
}
}
return true;
}
static Monitor testTimedMonitor;
static int passedTimedMonitor = 0;
bool testTimedMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testTimedMonitor.wait(_ms);
passedTimedMonitor++;
}
};
TestThread thread1(15);
TestThread thread2(0); // waits forever
TestThread thread3(0); // waits forever
TestThread thread4(0); // waits forever
TestThread thread5(0); // waits forever
for (int i = 0; i < 50; i++) {
// test waiting for a given time
passedTimedMonitor = 0;
thread1.start(); // wait for 15ms at mutex before resuming
Thread::sleepMs(5);
assert(passedTimedMonitor == 0); // thread1 should not have passed
Thread::sleepMs(15);
assert(passedTimedMonitor == 1); // thread1 should have passed
assert(!thread1.isStarted());
// test signalling a set of threads
passedTimedMonitor = 0;
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Thread::sleepMs(5);
testTimedMonitor.signal(2); // signal 2 threads
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
testTimedMonitor.signal(1); // signal another thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
testTimedMonitor.broadcast(); // signal last thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 4);
assert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());
// test timed and unlimited waiting
passedTimedMonitor = 0;
thread1.start();
thread2.start(); // with another thread
thread3.start(); // with another thread
Thread::sleepMs(5);
testTimedMonitor.signal(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
// wo do not know which thread passed
assert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());
if (thread1.isStarted()) {
// thread1 is still running, just wait
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
}
testTimedMonitor.broadcast(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
assert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());
// test signalling prior to waiting
passedTimedMonitor = 0;
testTimedMonitor.signal();
thread1.start();
Thread::sleepMs(5);
thread2.start();
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
assert(!thread1.isStarted());
assert(thread2.isStarted());
testTimedMonitor.signal();
Thread::sleepMs(5);
assert(passedTimedMonitor == 2);
assert(!thread1.isStarted());
assert(!thread2.isStarted());
assert(!thread3.isStarted());
}
return true;
}
class FooTracer : public Traceable, public Thread {
void run() {
while(isStarted()) {
trace("This is foo");
Thread::sleepMs(20);
}
}
};
bool testTracing() {
FooTracer* tr1 = new FooTracer();
FooTracer* tr2 = new FooTracer();
FooTracer* tr3 = new FooTracer();
tr1->setTraceFile("trace.txt");
tr2->setTraceFile("trace.txt");
tr3->setTraceFile("trace.txt");
tr1->start();
tr2->start();
tr3->start();
Thread::sleepMs(100);
delete tr1;
delete tr2;
delete tr3;
return true;
}
int main(int argc, char** argv) {
if(!testTracing())
return EXIT_FAILURE;
if(!testRecursiveMutex())
return EXIT_FAILURE;
if(!testThreads())
return EXIT_FAILURE;
if(!testMonitors())
return EXIT_FAILURE;
if(!testTimedMonitors())
return EXIT_FAILURE;
}
<commit_msg>increased timeout somewhat<commit_after>#include "umundo/core.h"
#include <iostream>
using namespace umundo;
bool testRecursiveMutex() {
Mutex mutex;
UMUNDO_LOCK(mutex);
if(!mutex.tryLock()) {
LOG_ERR("tryLock should be possible from within the same thread");
assert(false);
}
UMUNDO_LOCK(mutex);
// can we unlock it as well?
UMUNDO_UNLOCK(mutex);
UMUNDO_UNLOCK(mutex);
return true;
}
static Mutex testMutex;
bool testThreads() {
class Thread1 : public Thread {
void run() {
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // blocks
Thread::sleepMs(50);
UMUNDO_UNLOCK(testMutex);
Thread::sleepMs(100);
}
};
/**
* tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)
* thread1: start tl l l s50 u
* main: start l s50 u s20 tl l join
* t-> 0 50 70 100
*/
UMUNDO_LOCK(testMutex);
Thread1 thread1;
thread1.start();
Thread::sleepMs(50); // thread1 will trylock and block on lock
UMUNDO_UNLOCK(testMutex); // unlock
Thread::sleepMs(20); // yield cpu and sleep
// thread1 sleeps with lock on mutex
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // thread1 will unlock and sleep
thread1.join(); // join with thread1
if(thread1.isStarted()) {
LOG_ERR("thread still running after join");
assert(false);
}
return true;
}
static Monitor testMonitor;
static int passedMonitor = 0;
bool testMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testMonitor.wait();
Thread::sleepMs(10); // avoid clash with other threads
passedMonitor++;
}
};
TestThread thread1(0);
TestThread thread2(5);
TestThread thread3(10);
for (int i = 0; i < 10; i++) {
passedMonitor = 0;
// all will block on monitor
thread1.start();
thread2.start();
thread3.start();
Thread::sleepMs(5); // give threads a chance to run into wait
if(passedMonitor != 0) {
LOG_ERR("%d threads already passed the monitor", passedMonitor);
assert(false);
}
UMUNDO_SIGNAL(testMonitor); // signal a single thread
Thread::sleepMs(15); // thread will increase passedMonitor
if(passedMonitor != 1) {
LOG_ERR("Expected 1 threads to pass the monitor, but %d did", passedMonitor);
assert(false);
}
UMUNDO_BROADCAST(testMonitor); // signal all other threads
Thread::sleepMs(15);
if (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {
LOG_ERR("Threads ran to completion but still insist on being started");
assert(false);
}
}
return true;
}
static Monitor testTimedMonitor;
static int passedTimedMonitor = 0;
bool testTimedMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testTimedMonitor.wait(_ms);
passedTimedMonitor++;
}
};
TestThread thread1(15);
TestThread thread2(0); // waits forever
TestThread thread3(0); // waits forever
TestThread thread4(0); // waits forever
TestThread thread5(0); // waits forever
for (int i = 0; i < 50; i++) {
// test waiting for a given time
passedTimedMonitor = 0;
thread1.start(); // wait for 15ms at mutex before resuming
Thread::sleepMs(5);
assert(passedTimedMonitor == 0); // thread1 should not have passed
Thread::sleepMs(25);
assert(passedTimedMonitor == 1); // thread1 should have passed
assert(!thread1.isStarted());
// test signalling a set of threads
passedTimedMonitor = 0;
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Thread::sleepMs(5);
testTimedMonitor.signal(2); // signal 2 threads
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
testTimedMonitor.signal(1); // signal another thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
testTimedMonitor.broadcast(); // signal last thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 4);
assert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());
// test timed and unlimited waiting
passedTimedMonitor = 0;
thread1.start();
thread2.start(); // with another thread
thread3.start(); // with another thread
Thread::sleepMs(5);
testTimedMonitor.signal(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
// wo do not know which thread passed
assert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());
if (thread1.isStarted()) {
// thread1 is still running, just wait
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
}
testTimedMonitor.broadcast(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
assert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());
// test signalling prior to waiting
passedTimedMonitor = 0;
testTimedMonitor.signal();
thread1.start();
Thread::sleepMs(5);
thread2.start();
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
assert(!thread1.isStarted());
assert(thread2.isStarted());
testTimedMonitor.signal();
Thread::sleepMs(5);
assert(passedTimedMonitor == 2);
assert(!thread1.isStarted());
assert(!thread2.isStarted());
assert(!thread3.isStarted());
}
return true;
}
class FooTracer : public Traceable, public Thread {
void run() {
while(isStarted()) {
trace("This is foo");
Thread::sleepMs(20);
}
}
};
bool testTracing() {
FooTracer* tr1 = new FooTracer();
FooTracer* tr2 = new FooTracer();
FooTracer* tr3 = new FooTracer();
tr1->setTraceFile("trace.txt");
tr2->setTraceFile("trace.txt");
tr3->setTraceFile("trace.txt");
tr1->start();
tr2->start();
tr3->start();
Thread::sleepMs(100);
delete tr1;
delete tr2;
delete tr3;
return true;
}
int main(int argc, char** argv) {
if(!testTracing())
return EXIT_FAILURE;
if(!testRecursiveMutex())
return EXIT_FAILURE;
if(!testThreads())
return EXIT_FAILURE;
if(!testMonitors())
return EXIT_FAILURE;
if(!testTimedMonitors())
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "umundo/core.h"
#include <iostream>
using namespace umundo;
bool testRecursiveMutex() {
Mutex mutex;
UMUNDO_LOCK(mutex);
if(!mutex.tryLock()) {
LOG_ERR("tryLock should be possible from within the same thread");
assert(false);
}
UMUNDO_LOCK(mutex);
// can we unlock it as well?
UMUNDO_UNLOCK(mutex);
UMUNDO_UNLOCK(mutex);
return true;
}
static Mutex testMutex;
bool testThreads() {
class Thread1 : public Thread {
void run() {
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // blocks
Thread::sleepMs(50);
UMUNDO_UNLOCK(testMutex);
Thread::sleepMs(100);
}
};
/**
* tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)
* thread1: start tl l l s50 u
* main: start l s50 u s20 tl l join
* t-> 0 50 70 100
*/
UMUNDO_LOCK(testMutex);
Thread1 thread1;
thread1.start();
Thread::sleepMs(50); // thread1 will trylock and block on lock
UMUNDO_UNLOCK(testMutex); // unlock
Thread::sleepMs(20); // yield cpu and sleep
// thread1 sleeps with lock on mutex
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // thread1 will unlock and sleep
thread1.join(); // join with thread1
if(thread1.isStarted()) {
LOG_ERR("thread still running after join");
assert(false);
}
return true;
}
static Monitor testMonitor;
static int passedMonitor = 0;
bool testMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testMonitor.wait();
Thread::sleepMs(10); // avoid clash with other threads
passedMonitor++;
}
};
TestThread thread1(0);
TestThread thread2(5);
TestThread thread3(10);
for (int i = 0; i < 10; i++) {
passedMonitor = 0;
// all will block on monitor
thread1.start();
thread2.start();
thread3.start();
Thread::sleepMs(5); // give threads a chance to run into wait
if(passedMonitor != 0) {
LOG_ERR("%d threads already passed the monitor", passedMonitor);
assert(false);
}
UMUNDO_SIGNAL(testMonitor); // signal a single thread
Thread::sleepMs(15); // thread will increase passedMonitor
if(passedMonitor != 1) {
LOG_ERR("Expected 1 threads to pass the monitor, but %d did", passedMonitor);
assert(false);
}
UMUNDO_BROADCAST(testMonitor); // signal all other threads
Thread::sleepMs(15);
if (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {
LOG_ERR("Threads ran to completion but still insist on being started");
assert(false);
}
}
return true;
}
static Monitor testTimedMonitor;
static int passedTimedMonitor = 0;
bool testTimedMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testTimedMonitor.wait(_ms);
passedTimedMonitor++;
}
};
TestThread thread1(15);
TestThread thread2(0); // waits forever
TestThread thread3(0); // waits forever
TestThread thread4(0); // waits forever
TestThread thread5(0); // waits forever
for (int i = 0; i < 50; i++) {
// test waiting for a given time
passedTimedMonitor = 0;
thread1.start(); // wait for 15ms at mutex before resuming
Thread::sleepMs(5);
assert(passedTimedMonitor == 0); // thread1 should not have passed
Thread::sleepMs(15);
assert(passedTimedMonitor == 1); // thread1 should have passed
assert(!thread1.isStarted());
// test signalling a set of threads
passedTimedMonitor = 0;
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Thread::sleepMs(5);
testTimedMonitor.signal(2); // signal 2 threads
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
testTimedMonitor.signal(1); // signal another thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
testTimedMonitor.broadcast(); // signal last thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 4);
assert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());
// test timed and unlimited waiting
passedTimedMonitor = 0;
thread1.start();
thread2.start(); // with another thread
thread3.start(); // with another thread
Thread::sleepMs(5);
testTimedMonitor.signal(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
// wo do not know which thread passed
assert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());
if (thread1.isStarted()) {
// thread1 is still running, just wait
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
}
testTimedMonitor.broadcast(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
assert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());
// test signalling prior to waiting
passedTimedMonitor = 0;
testTimedMonitor.signal();
thread1.start();
Thread::sleepMs(5);
thread2.start();
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
assert(!thread1.isStarted());
assert(thread2.isStarted());
testTimedMonitor.signal();
Thread::sleepMs(5);
assert(passedTimedMonitor == 2);
assert(!thread1.isStarted());
assert(!thread2.isStarted());
assert(!thread3.isStarted());
}
return true;
}
class FooTracer : public Traceable, public Thread {
void run() {
while(isStarted()) {
trace("This is foo");
Thread::sleepMs(20);
}
}
};
bool testTracing() {
FooTracer* tr1 = new FooTracer();
FooTracer* tr2 = new FooTracer();
FooTracer* tr3 = new FooTracer();
tr1->setTraceFile("trace.txt");
tr2->setTraceFile("trace.txt");
tr3->setTraceFile("trace.txt");
tr1->start();
tr2->start();
tr3->start();
Thread::sleepMs(100);
delete tr1;
delete tr2;
delete tr3;
return true;
}
int main(int argc, char** argv) {
if(!testTracing())
return EXIT_FAILURE;
if(!testRecursiveMutex())
return EXIT_FAILURE;
if(!testThreads())
return EXIT_FAILURE;
if(!testMonitors())
return EXIT_FAILURE;
if(!testTimedMonitors())
return EXIT_FAILURE;
}
<commit_msg>increased timeout somewhat<commit_after>#include "umundo/core.h"
#include <iostream>
using namespace umundo;
bool testRecursiveMutex() {
Mutex mutex;
UMUNDO_LOCK(mutex);
if(!mutex.tryLock()) {
LOG_ERR("tryLock should be possible from within the same thread");
assert(false);
}
UMUNDO_LOCK(mutex);
// can we unlock it as well?
UMUNDO_UNLOCK(mutex);
UMUNDO_UNLOCK(mutex);
return true;
}
static Mutex testMutex;
bool testThreads() {
class Thread1 : public Thread {
void run() {
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // blocks
Thread::sleepMs(50);
UMUNDO_UNLOCK(testMutex);
Thread::sleepMs(100);
}
};
/**
* tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)
* thread1: start tl l l s50 u
* main: start l s50 u s20 tl l join
* t-> 0 50 70 100
*/
UMUNDO_LOCK(testMutex);
Thread1 thread1;
thread1.start();
Thread::sleepMs(50); // thread1 will trylock and block on lock
UMUNDO_UNLOCK(testMutex); // unlock
Thread::sleepMs(20); // yield cpu and sleep
// thread1 sleeps with lock on mutex
if(testMutex.tryLock()) {
LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // thread1 will unlock and sleep
thread1.join(); // join with thread1
if(thread1.isStarted()) {
LOG_ERR("thread still running after join");
assert(false);
}
return true;
}
static Monitor testMonitor;
static int passedMonitor = 0;
bool testMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testMonitor.wait();
Thread::sleepMs(10); // avoid clash with other threads
passedMonitor++;
}
};
TestThread thread1(0);
TestThread thread2(5);
TestThread thread3(10);
for (int i = 0; i < 10; i++) {
passedMonitor = 0;
// all will block on monitor
thread1.start();
thread2.start();
thread3.start();
Thread::sleepMs(5); // give threads a chance to run into wait
if(passedMonitor != 0) {
LOG_ERR("%d threads already passed the monitor", passedMonitor);
assert(false);
}
UMUNDO_SIGNAL(testMonitor); // signal a single thread
Thread::sleepMs(15); // thread will increase passedMonitor
if(passedMonitor != 1) {
LOG_ERR("Expected 1 threads to pass the monitor, but %d did", passedMonitor);
assert(false);
}
UMUNDO_BROADCAST(testMonitor); // signal all other threads
Thread::sleepMs(15);
if (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {
LOG_ERR("Threads ran to completion but still insist on being started");
assert(false);
}
}
return true;
}
static Monitor testTimedMonitor;
static int passedTimedMonitor = 0;
bool testTimedMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
testTimedMonitor.wait(_ms);
passedTimedMonitor++;
}
};
TestThread thread1(15);
TestThread thread2(0); // waits forever
TestThread thread3(0); // waits forever
TestThread thread4(0); // waits forever
TestThread thread5(0); // waits forever
for (int i = 0; i < 50; i++) {
// test waiting for a given time
passedTimedMonitor = 0;
thread1.start(); // wait for 15ms at mutex before resuming
Thread::sleepMs(5);
assert(passedTimedMonitor == 0); // thread1 should not have passed
Thread::sleepMs(25);
assert(passedTimedMonitor == 1); // thread1 should have passed
assert(!thread1.isStarted());
// test signalling a set of threads
passedTimedMonitor = 0;
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Thread::sleepMs(5);
testTimedMonitor.signal(2); // signal 2 threads
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
testTimedMonitor.signal(1); // signal another thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
testTimedMonitor.broadcast(); // signal last thread
Thread::sleepMs(5);
assert(passedTimedMonitor == 4);
assert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());
// test timed and unlimited waiting
passedTimedMonitor = 0;
thread1.start();
thread2.start(); // with another thread
thread3.start(); // with another thread
Thread::sleepMs(5);
testTimedMonitor.signal(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
// wo do not know which thread passed
assert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());
if (thread1.isStarted()) {
// thread1 is still running, just wait
Thread::sleepMs(10);
assert(passedTimedMonitor == 2);
}
testTimedMonitor.broadcast(); // explicit signal
Thread::sleepMs(5);
assert(passedTimedMonitor == 3);
assert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());
// test signalling prior to waiting
passedTimedMonitor = 0;
testTimedMonitor.signal();
thread1.start();
Thread::sleepMs(5);
thread2.start();
Thread::sleepMs(5);
assert(passedTimedMonitor == 1);
assert(!thread1.isStarted());
assert(thread2.isStarted());
testTimedMonitor.signal();
Thread::sleepMs(5);
assert(passedTimedMonitor == 2);
assert(!thread1.isStarted());
assert(!thread2.isStarted());
assert(!thread3.isStarted());
}
return true;
}
class FooTracer : public Traceable, public Thread {
void run() {
while(isStarted()) {
trace("This is foo");
Thread::sleepMs(20);
}
}
};
bool testTracing() {
FooTracer* tr1 = new FooTracer();
FooTracer* tr2 = new FooTracer();
FooTracer* tr3 = new FooTracer();
tr1->setTraceFile("trace.txt");
tr2->setTraceFile("trace.txt");
tr3->setTraceFile("trace.txt");
tr1->start();
tr2->start();
tr3->start();
Thread::sleepMs(100);
delete tr1;
delete tr2;
delete tr3;
return true;
}
int main(int argc, char** argv) {
if(!testTracing())
return EXIT_FAILURE;
if(!testRecursiveMutex())
return EXIT_FAILURE;
if(!testThreads())
return EXIT_FAILURE;
if(!testMonitors())
return EXIT_FAILURE;
if(!testTimedMonitors())
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*
Q Light Controller Plus
audiorenderer_qt.cpp
Copyright (c) Massimo Callegari
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.
*/
#include <QSettings>
#include <QString>
#include <QDebug>
#include "audiodecoder.h"
#include "audiorenderer_qt.h"
AudioRendererQt::AudioRendererQt(QString device, QObject * parent)
: AudioRenderer(parent)
, m_audioOutput(NULL)
, m_output(NULL)
{
m_device = device;
}
AudioRendererQt::~AudioRendererQt()
{
if (m_audioOutput == NULL)
return;
m_audioOutput->stop();
delete m_audioOutput;
m_audioOutput = NULL;
}
bool AudioRendererQt::initialize(quint32 freq, int chan, AudioFormat format)
{
QSettings settings;
QString devName = "";
m_deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
QVariant var;
if (m_device.isEmpty())
var = settings.value(SETTINGS_AUDIO_OUTPUT_DEVICE);
else
var = QVariant(m_device);
if (var.isValid() == true)
{
devName = var.toString();
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
{
if (deviceInfo.deviceName() == devName)
{
m_deviceInfo = deviceInfo;
break;
}
}
}
m_format.setChannelCount(chan);
m_format.setSampleRate(freq);
m_format.setCodec("audio/pcm");
switch (format)
{
case PCM_S8:
m_format.setSampleSize(8);
m_format.setSampleType(QAudioFormat::SignedInt);
break;
case PCM_S16LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
case PCM_S24LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
case PCM_S32LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
default:
qWarning("AudioRendererQt: unsupported format detected");
return false;
}
if (!m_deviceInfo.isFormatSupported(m_format))
{
m_format = m_deviceInfo.nearestFormat(m_format);
qWarning() << "Default format not supported - trying to use nearest" << m_format.sampleRate();
}
return true;
}
qint64 AudioRendererQt::latency()
{
return 0;
}
QList<AudioDeviceInfo> AudioRendererQt::getDevicesInfo()
{
QList<AudioDeviceInfo> devList;
int i = 0;
QStringList outDevs, inDevs;
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
inDevs.append(deviceInfo.deviceName());
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
{
outDevs.append(deviceInfo.deviceName());
AudioDeviceInfo info;
info.deviceName = deviceInfo.deviceName();
info.privateName = deviceInfo.deviceName(); //QString::number(i);
info.capabilities = 0;
info.capabilities |= AUDIO_CAP_OUTPUT;
if (inDevs.contains(deviceInfo.deviceName()))
{
info.capabilities |= AUDIO_CAP_INPUT;
inDevs.removeOne(deviceInfo.deviceName());
}
devList.append(info);
i++;
}
foreach(QString dev, inDevs)
{
AudioDeviceInfo info;
info.deviceName = dev;
info.privateName = QString::number(i);
info.capabilities = 0;
info.capabilities |= AUDIO_CAP_INPUT;
devList.append(info);
i++;
}
return devList;
}
qint64 AudioRendererQt::writeAudio(unsigned char *data, qint64 maxSize)
{
if (m_audioOutput == NULL || m_audioOutput->bytesFree() < maxSize)
return 0;
//qDebug() << "writeAudio called !! - " << maxSize;
qint64 written = m_output->write((const char *)data, maxSize);
if (written != maxSize)
qDebug() << "[writeAudio] expexcted to write" << maxSize << "but wrote" << written;
return written;
}
void AudioRendererQt::drain()
{
m_audioOutput->reset();
}
void AudioRendererQt::reset()
{
m_audioOutput->reset();
}
void AudioRendererQt::suspend()
{
m_audioOutput->suspend();
}
void AudioRendererQt::resume()
{
m_audioOutput->resume();
}
void AudioRendererQt::run()
{
if (m_audioOutput == NULL)
{
m_audioOutput = new QAudioOutput(m_deviceInfo, m_format);
if(m_audioOutput == NULL)
{
qWarning() << "Cannot open audio output stream from device" << m_deviceInfo.deviceName();
return;
}
m_audioOutput->setBufferSize(8192 * 8);
m_output = m_audioOutput->start();
if(m_audioOutput->error() != QAudio::NoError)
{
qWarning() << "Cannot start audio output stream. Error:" << m_audioOutput->error();
return;
}
}
AudioRenderer::run();
}
<commit_msg>engine/audio: stop the Qt renderer on thread closing<commit_after>/*
Q Light Controller Plus
audiorenderer_qt.cpp
Copyright (c) Massimo Callegari
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.
*/
#include <QSettings>
#include <QString>
#include <QDebug>
#include "audiodecoder.h"
#include "audiorenderer_qt.h"
AudioRendererQt::AudioRendererQt(QString device, QObject * parent)
: AudioRenderer(parent)
, m_audioOutput(NULL)
, m_output(NULL)
{
m_device = device;
}
AudioRendererQt::~AudioRendererQt()
{
if (m_audioOutput == NULL)
return;
m_audioOutput->stop();
delete m_audioOutput;
m_audioOutput = NULL;
}
bool AudioRendererQt::initialize(quint32 freq, int chan, AudioFormat format)
{
QSettings settings;
QString devName = "";
m_deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
QVariant var;
if (m_device.isEmpty())
var = settings.value(SETTINGS_AUDIO_OUTPUT_DEVICE);
else
var = QVariant(m_device);
if (var.isValid() == true)
{
devName = var.toString();
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
{
if (deviceInfo.deviceName() == devName)
{
m_deviceInfo = deviceInfo;
break;
}
}
}
m_format.setChannelCount(chan);
m_format.setSampleRate(freq);
m_format.setCodec("audio/pcm");
switch (format)
{
case PCM_S8:
m_format.setSampleSize(8);
m_format.setSampleType(QAudioFormat::SignedInt);
break;
case PCM_S16LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
case PCM_S24LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
case PCM_S32LE:
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::SignedInt);
m_format.setByteOrder(QAudioFormat::LittleEndian);
break;
default:
qWarning("AudioRendererQt: unsupported format detected");
return false;
}
if (!m_deviceInfo.isFormatSupported(m_format))
{
m_format = m_deviceInfo.nearestFormat(m_format);
qWarning() << "Default format not supported - trying to use nearest" << m_format.sampleRate();
}
return true;
}
qint64 AudioRendererQt::latency()
{
return 0;
}
QList<AudioDeviceInfo> AudioRendererQt::getDevicesInfo()
{
QList<AudioDeviceInfo> devList;
int i = 0;
QStringList outDevs, inDevs;
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
inDevs.append(deviceInfo.deviceName());
foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
{
outDevs.append(deviceInfo.deviceName());
AudioDeviceInfo info;
info.deviceName = deviceInfo.deviceName();
info.privateName = deviceInfo.deviceName(); //QString::number(i);
info.capabilities = 0;
info.capabilities |= AUDIO_CAP_OUTPUT;
if (inDevs.contains(deviceInfo.deviceName()))
{
info.capabilities |= AUDIO_CAP_INPUT;
inDevs.removeOne(deviceInfo.deviceName());
}
devList.append(info);
i++;
}
foreach(QString dev, inDevs)
{
AudioDeviceInfo info;
info.deviceName = dev;
info.privateName = QString::number(i);
info.capabilities = 0;
info.capabilities |= AUDIO_CAP_INPUT;
devList.append(info);
i++;
}
return devList;
}
qint64 AudioRendererQt::writeAudio(unsigned char *data, qint64 maxSize)
{
if (m_audioOutput == NULL || m_audioOutput->bytesFree() < maxSize)
return 0;
//qDebug() << "writeAudio called !! - " << maxSize;
qint64 written = m_output->write((const char *)data, maxSize);
if (written != maxSize)
qDebug() << "[writeAudio] expexcted to write" << maxSize << "but wrote" << written;
return written;
}
void AudioRendererQt::drain()
{
m_audioOutput->reset();
}
void AudioRendererQt::reset()
{
m_audioOutput->reset();
}
void AudioRendererQt::suspend()
{
m_audioOutput->suspend();
}
void AudioRendererQt::resume()
{
m_audioOutput->resume();
}
void AudioRendererQt::run()
{
if (m_audioOutput == NULL)
{
m_audioOutput = new QAudioOutput(m_deviceInfo, m_format);
if(m_audioOutput == NULL)
{
qWarning() << "Cannot open audio output stream from device" << m_deviceInfo.deviceName();
return;
}
m_audioOutput->setBufferSize(8192 * 8);
m_output = m_audioOutput->start();
if(m_audioOutput->error() != QAudio::NoError)
{
qWarning() << "Cannot start audio output stream. Error:" << m_audioOutput->error();
return;
}
}
AudioRenderer::run();
m_audioOutput->stop();
}
<|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 "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>
#include <sofia-sip/msg_addr.h>
using namespace ::std;
void MsgSip::defineMsg(msg_t *msg) {
mMsg = msg_copy(msg);
msg_addr_copy(mMsg, msg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
mOriginal = false;
}
MsgSip::MsgSip(msg_t *msg) {
// LOGD("New MsgSip %p with reference to msg %p", this, msg);
mOriginalMsg = msg_ref_create(msg);
defineMsg(mOriginalMsg);
mOriginal = true;
}
MsgSip::MsgSip(const MsgSip &msgSip) {
// LOGD("New MsgSip %p with swallow copy %p of msg %p", this, mMsg, msgSip.mMsg);
msgSip.serialize();
defineMsg(msgSip.mMsg);
mOriginalMsg = msg_ref_create(msgSip.mOriginalMsg);
}
MsgSip::MsgSip(const MsgSip &msgSip, msg_t *msg) {
defineMsg(msg);
mOriginalMsg = msg_ref_create(msgSip.mOriginalMsg);
}
void MsgSip::log(const char *fmt, ...) {
if (IS_LOGD) {
size_t msg_size;
char *header = NULL;
char *buf = NULL;
if (fmt) {
va_list args;
va_start(args, fmt);
header = su_vsprintf(mHome, fmt, args);
va_end(args);
}
msg_serialize(mMsg,(msg_pub_t*)mSip); //make sure the message is serialized before showing it; it can be very confusing.
buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
LOGD("%s%s%s\nendmsg", (header) ? header : "", (header) ? "\n" : "", buf);
}
}
MsgSip::~MsgSip() {
//LOGD("Destroy MsgSip %p", this);
msg_destroy(mMsg);
msg_destroy(mOriginalMsg);
}
SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
LOGD("New SipEvent %p", this);
}
SipEvent::SipEvent(const SipEvent &sipEvent) :
mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
LOGD("New SipEvent %p with state %s", this, stateStr(mState).c_str());
}
SipEvent::~SipEvent() {
//LOGD("Destroy SipEvent %p", this);
}
void SipEvent::flushLog(){
if (mEventLog){
Agent *agent=NULL;
if (mIncomingAgent) agent=mIncomingAgent->getAgent();
else if (mOutgoingAgent) agent=mOutgoingAgent->getAgent();
else LOGA("Event has no incoming nor outgoing agent.");
agent->logEvent(shared_from_this());
mEventLog=NULL;
}
}
void SipEvent::setEventLog(const std::shared_ptr<EventLog> & log){
mEventLog=log;
if (mState==TERMINATED){
flushLog();
}
}
void SipEvent::terminateProcessing() {
LOGD("Terminate SipEvent %p", this);
if (mState == STARTED || mState == SUSPENDED) {
mState = TERMINATED;
flushLog();
} else {
LOGA("Can't terminateProcessing: wrong state %s", stateStr(mState).c_str());
}
}
void SipEvent::suspendProcessing() {
LOGD("Suspend SipEvent %p", this);
if (mState == STARTED) {
mState = SUSPENDED;
} else {
LOGA("Can't suspendProcessing: wrong state %s", stateStr(mState).c_str());
}
}
void SipEvent::restartProcessing() {
LOGD("Restart SipEvent %p", this);
if (mState == SUSPENDED) {
mState = STARTED;
} else {
LOGA("Can't restartProcessing: wrong state %s", stateStr(mState).c_str());
}
}
RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip), mRecordRouteAdded(false) {
mIncomingAgent = incomingAgent;
mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}
RequestSipEvent::RequestSipEvent(const shared_ptr<RequestSipEvent> &sipEvent) :
SipEvent(*sipEvent), mRecordRouteAdded(sipEvent->mRecordRouteAdded) {
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mOutgoingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message:");
}
mOutgoingAgent->send(msg);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::reply(int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->reply(getMsgSip(), status, phrase, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not reply");
}
terminateProcessing();
}
void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
LOGA("Can't change incoming agent in request sip event");
}
shared_ptr<IncomingTransaction> RequestSipEvent::createIncomingTransaction() {
shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
if (transaction == NULL) {
if (!mMsgSip->mOriginal) LOGA("It is too late to create an incoming transaction");
transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
mIncomingAgent = transaction;
transaction->handle(mMsgSip);
}
return transaction;
}
shared_ptr<OutgoingTransaction> RequestSipEvent::createOutgoingTransaction() {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
if (transaction == NULL) {
transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
mOutgoingAgent = transaction;
}
return transaction;
}
void RequestSipEvent::suspendProcessing() {
SipEvent::suspendProcessing();
// Become stateful if not already the case.
createIncomingTransaction();
}
RequestSipEvent::~RequestSipEvent() {
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mOutgoingAgent = outgoingAgent;
mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Response SIP message is not sent");
}
terminateProcessing();
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message:");
}
mIncomingAgent->send(msg);
} else {
LOGD("The Response SIP message is not sent");
}
terminateProcessing();
}
void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
LOGA("Can't change outgoing agent in response sip event");
}
ResponseSipEvent::~ResponseSipEvent() {
}
<commit_msg>fix compile issue with some versions of gcc<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 "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>
#include <sofia-sip/msg_addr.h>
using namespace ::std;
void MsgSip::defineMsg(msg_t *msg) {
mMsg = msg_copy(msg);
msg_addr_copy(mMsg, msg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
mOriginal = false;
}
MsgSip::MsgSip(msg_t *msg) {
// LOGD("New MsgSip %p with reference to msg %p", this, msg);
mOriginalMsg = msg_ref_create(msg);
defineMsg(mOriginalMsg);
mOriginal = true;
}
MsgSip::MsgSip(const MsgSip &msgSip) {
// LOGD("New MsgSip %p with swallow copy %p of msg %p", this, mMsg, msgSip.mMsg);
msgSip.serialize();
defineMsg(msgSip.mMsg);
mOriginalMsg = msg_ref_create(msgSip.mOriginalMsg);
}
MsgSip::MsgSip(const MsgSip &msgSip, msg_t *msg) {
defineMsg(msg);
mOriginalMsg = msg_ref_create(msgSip.mOriginalMsg);
}
void MsgSip::log(const char *fmt, ...) {
if (IS_LOGD) {
size_t msg_size;
char *header = NULL;
char *buf = NULL;
if (fmt) {
va_list args;
va_start(args, fmt);
header = su_vsprintf(mHome, fmt, args);
va_end(args);
}
msg_serialize(mMsg,(msg_pub_t*)mSip); //make sure the message is serialized before showing it; it can be very confusing.
buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
LOGD("%s%s%s\nendmsg", (header) ? header : "", (header) ? "\n" : "", buf);
}
}
MsgSip::~MsgSip() {
//LOGD("Destroy MsgSip %p", this);
msg_destroy(mMsg);
msg_destroy(mOriginalMsg);
}
SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
LOGD("New SipEvent %p", this);
}
SipEvent::SipEvent(const SipEvent &sipEvent) :
mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
LOGD("New SipEvent %p with state %s", this, stateStr(mState).c_str());
}
SipEvent::~SipEvent() {
//LOGD("Destroy SipEvent %p", this);
}
void SipEvent::flushLog(){
if (mEventLog){
Agent *agent=NULL;
if (mIncomingAgent) agent=mIncomingAgent->getAgent();
else if (mOutgoingAgent) agent=mOutgoingAgent->getAgent();
else LOGA("Event has no incoming nor outgoing agent.");
agent->logEvent(shared_from_this());
mEventLog.reset();
}
}
void SipEvent::setEventLog(const std::shared_ptr<EventLog> & log){
mEventLog=log;
if (mState==TERMINATED){
flushLog();
}
}
void SipEvent::terminateProcessing() {
LOGD("Terminate SipEvent %p", this);
if (mState == STARTED || mState == SUSPENDED) {
mState = TERMINATED;
flushLog();
} else {
LOGA("Can't terminateProcessing: wrong state %s", stateStr(mState).c_str());
}
}
void SipEvent::suspendProcessing() {
LOGD("Suspend SipEvent %p", this);
if (mState == STARTED) {
mState = SUSPENDED;
} else {
LOGA("Can't suspendProcessing: wrong state %s", stateStr(mState).c_str());
}
}
void SipEvent::restartProcessing() {
LOGD("Restart SipEvent %p", this);
if (mState == SUSPENDED) {
mState = STARTED;
} else {
LOGA("Can't restartProcessing: wrong state %s", stateStr(mState).c_str());
}
}
RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip), mRecordRouteAdded(false) {
mIncomingAgent = incomingAgent;
mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}
RequestSipEvent::RequestSipEvent(const shared_ptr<RequestSipEvent> &sipEvent) :
SipEvent(*sipEvent), mRecordRouteAdded(sipEvent->mRecordRouteAdded) {
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mOutgoingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message:");
}
mOutgoingAgent->send(msg);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::reply(int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->reply(getMsgSip(), status, phrase, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not reply");
}
terminateProcessing();
}
void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
LOGA("Can't change incoming agent in request sip event");
}
shared_ptr<IncomingTransaction> RequestSipEvent::createIncomingTransaction() {
shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
if (transaction == NULL) {
if (!mMsgSip->mOriginal) LOGA("It is too late to create an incoming transaction");
transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
mIncomingAgent = transaction;
transaction->handle(mMsgSip);
}
return transaction;
}
shared_ptr<OutgoingTransaction> RequestSipEvent::createOutgoingTransaction() {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
if (transaction == NULL) {
transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
mOutgoingAgent = transaction;
}
return transaction;
}
void RequestSipEvent::suspendProcessing() {
SipEvent::suspendProcessing();
// Become stateful if not already the case.
createIncomingTransaction();
}
RequestSipEvent::~RequestSipEvent() {
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mOutgoingAgent = outgoingAgent;
mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Response SIP message is not sent");
}
terminateProcessing();
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message:");
}
mIncomingAgent->send(msg);
} else {
LOGD("The Response SIP message is not sent");
}
terminateProcessing();
}
void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
LOGA("Can't change outgoing agent in response sip event");
}
ResponseSipEvent::~ResponseSipEvent() {
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
commands/detailscommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "detailscommand.h"
#include "command_p.h"
#include "../certificateinfowidgetimpl.h"
#include <QAbstractItemView>
using namespace Kleo;
class DetailsCommand::Private : public Command::Private {
friend class ::Kleo::DetailsCommand;
public:
Private( DetailsCommand * qq );
~Private();
private:
QPointer<CertificateInfoWidgetImpl> dialog;
};
DetailsCommand::Private * DetailsCommand::d_func() { return static_cast<Private*>( d.get() ); }
const DetailsCommand::Private * DetailsCommand::d_func() const { return static_cast<const Private*>( d.get() ); }
DetailsCommand::Private::Private( DetailsCommand * qq )
: Command::Private( qq ), dialog()
{
}
DetailsCommand::Private::~Private() {}
DetailsCommand::DetailsCommand( KeyListController * p )
: Command( p, new Private( this ) )
{
}
#define d d_func()
DetailsCommand::~DetailsCommand() {
if ( d->dialog )
d->dialog->close();
}
void DetailsCommand::doStart() {
if ( d->indexes().count() != 1 ) {
qWarning( "DetailsCommand::doStart: can only work with one certificate at a time" );
return;
}
if ( !d->dialog ) {
d->dialog = new CertificateInfoWidgetImpl( d->key(), false, d->view() );
d->dialog->setAttribute( Qt::WA_DeleteOnClose );
}
if ( d->dialog->isVisible() )
d->dialog->raise();
else
d->dialog->show();
}
void DetailsCommand::doCancel() {
if ( d->dialog )
d->dialog->close();
}
#undef d
#include "moc_detailscommand.cpp"
<commit_msg>show details as dialog, not widget<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
commands/detailscommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "detailscommand.h"
#include "command_p.h"
#include "../certificateinfowidgetimpl.h"
#include <KDialog>
#include <QAbstractItemView>
using namespace Kleo;
class DetailsCommand::Private : public Command::Private {
friend class ::Kleo::DetailsCommand;
public:
Private( DetailsCommand * qq, KeyListController * controller );
~Private();
private:
QPointer<KDialog> dialog;
};
DetailsCommand::Private * DetailsCommand::d_func() { return static_cast<Private*>( d.get() ); }
const DetailsCommand::Private * DetailsCommand::d_func() const { return static_cast<const Private*>( d.get() ); }
DetailsCommand::Private::Private( DetailsCommand * qq, KeyListController* controller )
: Command::Private( qq, controller ), dialog()
{
}
DetailsCommand::Private::~Private() {}
DetailsCommand::DetailsCommand( KeyListController * p )
: Command( p, new Private( this, p ) )
{
}
#define d d_func()
DetailsCommand::~DetailsCommand() {
if ( d->dialog )
d->dialog->close();
}
void DetailsCommand::doStart() {
if ( d->indexes().count() != 1 ) {
qWarning( "DetailsCommand::doStart: can only work with one certificate at a time" );
return;
}
if ( !d->dialog ) {
d->dialog = new KDialog( d->view() );
d->dialog->setButtons( KDialog::Ok );
d->dialog->setMainWidget( new CertificateInfoWidgetImpl( d->key(), false, d->dialog ) );
d->dialog->setAttribute( Qt::WA_DeleteOnClose );
}
if ( d->dialog->isVisible() )
d->dialog->raise();
else
d->dialog->show();
}
void DetailsCommand::doCancel() {
if ( d->dialog )
d->dialog->close();
}
#undef d
#include "moc_detailscommand.cpp"
<|endoftext|> |
<commit_before>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>
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; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kolabbase.h"
#include <kabc/addressee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <qfile.h>
using namespace Kolab;
KolabBase::KolabBase()
: mCreationDate( QDateTime::currentDateTime() ),
mLastModified( QDateTime::currentDateTime() ),
mSensitivity( Public )
{
}
KolabBase::~KolabBase()
{
}
void KolabBase::setFields( const KCal::Incidence* incidence )
{
// So far unhandled KCal::IncidenceBase fields:
// mPilotID, mSyncStatus, mFloats
setUid( incidence->uid() );
setBody( incidence->description() );
setCategories( incidence->categoriesStr() );
setCreationDate( incidence->created() );
setLastModified( incidence->lastModified() );
setSensitivity( static_cast<Sensitivity>( incidence->secrecy() ) );
// TODO: Attachments
}
void KolabBase::saveTo( KCal::Incidence* incidence ) const
{
incidence->setUid( uid() );
incidence->setDescription( body() );
incidence->setCategories( categories() );
incidence->setCreated( creationDate() );
incidence->setLastModified( lastModified() );
incidence->setSecrecy( sensitivity() );
// TODO: Attachments
}
void KolabBase::setFields( const KABC::Addressee* addressee )
{
// An addressee does not have a creation date, so somehow we should
// make one, if this is a new entry
setUid( addressee->uid() );
setBody( addressee->note() );
setCategories( addressee->categories().join( "," ) );
setLastModified( addressee->revision() );
switch( addressee->secrecy().type() ) {
case KABC::Secrecy::Private:
setSensitivity( Private );
break;
case KABC::Secrecy::Confidential:
setSensitivity( Confidential );
break;
default:
setSensitivity( Public );
}
// TODO: Attachments
}
void KolabBase::saveTo( KABC::Addressee* addressee ) const
{
addressee->setUid( uid() );
addressee->setNote( body() );
addressee->setCategories( QStringList::split( ',', categories() ) );
addressee->setRevision( lastModified() );
switch( sensitivity() ) {
case Private:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Private ) );
break;
case Confidential:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Confidential ) );
break;
default:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Public ) );
break;
}
// TODO: Attachments
}
void KolabBase::setUid( const QString& uid )
{
mUid = uid;
}
QString KolabBase::uid() const
{
return mUid;
}
void KolabBase::setBody( const QString& body )
{
mBody = body;
}
QString KolabBase::body() const
{
return mBody;
}
void KolabBase::setCategories( const QString& categories )
{
mCategories = categories;
}
QString KolabBase::categories() const
{
return mCategories;
}
void KolabBase::setCreationDate( const QDateTime& date )
{
mCreationDate = date;
}
QDateTime KolabBase::creationDate() const
{
return mCreationDate;
}
void KolabBase::setLastModified( const QDateTime& date )
{
mLastModified = date;
}
QDateTime KolabBase::lastModified() const
{
return mLastModified;
}
void KolabBase::setSensitivity( Sensitivity sensitivity )
{
mSensitivity = sensitivity;
}
KolabBase::Sensitivity KolabBase::sensitivity() const
{
return mSensitivity;
}
bool KolabBase::loadEmailAttribute( QDomElement& element, Email& email )
{
for ( QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
QString tagName = e.tagName();
if ( tagName == "display-name" )
email.displayName = e.text();
else if ( tagName == "smtp-address" )
email.smtpAddress = e.text();
else
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
void KolabBase::saveEmailAttribute( QDomElement& element, const Email& email,
const QString& tagName ) const
{
QDomElement e = element.ownerDocument().createElement( tagName );
element.appendChild( e );
writeString( e, "display-name", email.displayName );
writeString( e, "smtp-address", email.smtpAddress );
}
bool KolabBase::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "uid" )
setUid( element.text() );
else if ( tagName == "body" )
setBody( element.text() );
else if ( tagName == "categories" )
setCategories( element.text() );
else if ( tagName == "creation-date" )
setCreationDate( stringToDateTime( element.text() ) );
else if ( tagName == "last-modification-date" )
setLastModified( stringToDateTime( element.text() ) );
else if ( tagName == "sensitivity" )
setSensitivity( stringToSensitivity( element.text() ) );
else
return false;
// Handled here
return true;
}
bool KolabBase::saveAttributes( QDomElement& element ) const
{
writeString( element, "uid", uid() );
writeString( element, "body", body() );
writeString( element, "categories", categories() );
writeString( element, "creation-date", dateTimeToString( creationDate() ) );
writeString( element, "last-modification-date",
dateTimeToString( lastModified() ) );
writeString( element, "sensitivity", sensitivityToString( sensitivity() ) );
return true;
}
bool KolabBase::load( const QString& xml )
{
QString errorMsg;
int errorLine, errorColumn;
QDomDocument document;
bool ok = document.setContent( xml, &errorMsg, &errorLine, &errorColumn );
if ( !ok ) {
qWarning( "Error loading document: %s, line %d, column %d",
errorMsg.latin1(), errorLine, errorColumn );
return false;
}
// XML file loaded into tree. Now parse it
return loadXML( document );
}
bool KolabBase::load( QFile& xml )
{
QString errorMsg;
int errorLine, errorColumn;
QDomDocument document;
bool ok = document.setContent( &xml, &errorMsg, &errorLine, &errorColumn );
if ( !ok ) {
qWarning( "Error loading document: %s, line %d, column %d",
errorMsg.latin1(), errorLine, errorColumn );
return false;
}
// XML file loaded into tree. Now parse it
return loadXML( document );
}
QDomDocument KolabBase::domTree()
{
QDomDocument document;
QString p = "version=\"1.0\" encoding=\"UTF-8\"";
document.appendChild(document.createProcessingInstruction( "xml", p ) );
return document;
}
QString KolabBase::dateTimeToString( const QDateTime& time )
{
return time.toString( Qt::ISODate );
}
QString KolabBase::dateToString( const QDate& date )
{
return date.toString( Qt::ISODate );
}
QDateTime KolabBase::stringToDateTime( const QString& date )
{
return QDateTime::fromString( date, Qt::ISODate );
}
QDate KolabBase::stringToDate( const QString& date )
{
return QDate::fromString( date, Qt::ISODate );
}
QString KolabBase::sensitivityToString( Sensitivity s )
{
switch( s ) {
case Private: return "private";
case Confidential: return "confidential";
case Public: return "public";
}
return "What what what???";
}
KolabBase::Sensitivity KolabBase::stringToSensitivity( const QString& s )
{
if ( s == "private" )
return Private;
if ( s == "confidential" )
return Confidential;
return Public;
}
QString KolabBase::colorToString( const QColor& color )
{
// Color is in the format "#RRGGBB"
return color.name();
}
QColor KolabBase::stringToColor( const QString& s )
{
return QColor( s );
}
void KolabBase::writeString( QDomElement& element, const QString& tag,
const QString& tagString )
{
QDomElement e = element.ownerDocument().createElement( tag );
QDomText t = element.ownerDocument().createTextNode( tagString );
e.appendChild( t );
element.appendChild( e );
}
<commit_msg>Per the spec, use trailing 'Z'<commit_after>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>
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; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kolabbase.h"
#include <kabc/addressee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <qfile.h>
using namespace Kolab;
KolabBase::KolabBase()
: mCreationDate( QDateTime::currentDateTime() ),
mLastModified( QDateTime::currentDateTime() ),
mSensitivity( Public )
{
}
KolabBase::~KolabBase()
{
}
void KolabBase::setFields( const KCal::Incidence* incidence )
{
// So far unhandled KCal::IncidenceBase fields:
// mPilotID, mSyncStatus, mFloats
setUid( incidence->uid() );
setBody( incidence->description() );
setCategories( incidence->categoriesStr() );
setCreationDate( incidence->created() );
setLastModified( incidence->lastModified() );
setSensitivity( static_cast<Sensitivity>( incidence->secrecy() ) );
// TODO: Attachments
}
void KolabBase::saveTo( KCal::Incidence* incidence ) const
{
incidence->setUid( uid() );
incidence->setDescription( body() );
incidence->setCategories( categories() );
incidence->setCreated( creationDate() );
incidence->setLastModified( lastModified() );
incidence->setSecrecy( sensitivity() );
// TODO: Attachments
}
void KolabBase::setFields( const KABC::Addressee* addressee )
{
// An addressee does not have a creation date, so somehow we should
// make one, if this is a new entry
setUid( addressee->uid() );
setBody( addressee->note() );
setCategories( addressee->categories().join( "," ) );
setLastModified( addressee->revision() );
switch( addressee->secrecy().type() ) {
case KABC::Secrecy::Private:
setSensitivity( Private );
break;
case KABC::Secrecy::Confidential:
setSensitivity( Confidential );
break;
default:
setSensitivity( Public );
}
// TODO: Attachments
}
void KolabBase::saveTo( KABC::Addressee* addressee ) const
{
addressee->setUid( uid() );
addressee->setNote( body() );
addressee->setCategories( QStringList::split( ',', categories() ) );
addressee->setRevision( lastModified() );
switch( sensitivity() ) {
case Private:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Private ) );
break;
case Confidential:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Confidential ) );
break;
default:
addressee->setSecrecy( KABC::Secrecy( KABC::Secrecy::Public ) );
break;
}
// TODO: Attachments
}
void KolabBase::setUid( const QString& uid )
{
mUid = uid;
}
QString KolabBase::uid() const
{
return mUid;
}
void KolabBase::setBody( const QString& body )
{
mBody = body;
}
QString KolabBase::body() const
{
return mBody;
}
void KolabBase::setCategories( const QString& categories )
{
mCategories = categories;
}
QString KolabBase::categories() const
{
return mCategories;
}
void KolabBase::setCreationDate( const QDateTime& date )
{
mCreationDate = date;
}
QDateTime KolabBase::creationDate() const
{
return mCreationDate;
}
void KolabBase::setLastModified( const QDateTime& date )
{
mLastModified = date;
}
QDateTime KolabBase::lastModified() const
{
return mLastModified;
}
void KolabBase::setSensitivity( Sensitivity sensitivity )
{
mSensitivity = sensitivity;
}
KolabBase::Sensitivity KolabBase::sensitivity() const
{
return mSensitivity;
}
bool KolabBase::loadEmailAttribute( QDomElement& element, Email& email )
{
for ( QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
QString tagName = e.tagName();
if ( tagName == "display-name" )
email.displayName = e.text();
else if ( tagName == "smtp-address" )
email.smtpAddress = e.text();
else
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
void KolabBase::saveEmailAttribute( QDomElement& element, const Email& email,
const QString& tagName ) const
{
QDomElement e = element.ownerDocument().createElement( tagName );
element.appendChild( e );
writeString( e, "display-name", email.displayName );
writeString( e, "smtp-address", email.smtpAddress );
}
bool KolabBase::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "uid" )
setUid( element.text() );
else if ( tagName == "body" )
setBody( element.text() );
else if ( tagName == "categories" )
setCategories( element.text() );
else if ( tagName == "creation-date" )
setCreationDate( stringToDateTime( element.text() ) );
else if ( tagName == "last-modification-date" )
setLastModified( stringToDateTime( element.text() ) );
else if ( tagName == "sensitivity" )
setSensitivity( stringToSensitivity( element.text() ) );
else
return false;
// Handled here
return true;
}
bool KolabBase::saveAttributes( QDomElement& element ) const
{
writeString( element, "uid", uid() );
writeString( element, "body", body() );
writeString( element, "categories", categories() );
writeString( element, "creation-date", dateTimeToString( creationDate() ) );
writeString( element, "last-modification-date",
dateTimeToString( lastModified() ) );
writeString( element, "sensitivity", sensitivityToString( sensitivity() ) );
return true;
}
bool KolabBase::load( const QString& xml )
{
QString errorMsg;
int errorLine, errorColumn;
QDomDocument document;
bool ok = document.setContent( xml, &errorMsg, &errorLine, &errorColumn );
if ( !ok ) {
qWarning( "Error loading document: %s, line %d, column %d",
errorMsg.latin1(), errorLine, errorColumn );
return false;
}
// XML file loaded into tree. Now parse it
return loadXML( document );
}
bool KolabBase::load( QFile& xml )
{
QString errorMsg;
int errorLine, errorColumn;
QDomDocument document;
bool ok = document.setContent( &xml, &errorMsg, &errorLine, &errorColumn );
if ( !ok ) {
qWarning( "Error loading document: %s, line %d, column %d",
errorMsg.latin1(), errorLine, errorColumn );
return false;
}
// XML file loaded into tree. Now parse it
return loadXML( document );
}
QDomDocument KolabBase::domTree()
{
QDomDocument document;
QString p = "version=\"1.0\" encoding=\"UTF-8\"";
document.appendChild(document.createProcessingInstruction( "xml", p ) );
return document;
}
QString KolabBase::dateTimeToString( const QDateTime& time )
{
return time.toString( Qt::ISODate ) + 'Z';
}
QString KolabBase::dateToString( const QDate& date )
{
return date.toString( Qt::ISODate );
}
QDateTime KolabBase::stringToDateTime( const QString& _date )
{
QString date( _date );
if ( date.endsWith( "Z" ) )
date.truncate( date.length() - 1 );
return QDateTime::fromString( date, Qt::ISODate );
}
QDate KolabBase::stringToDate( const QString& date )
{
return QDate::fromString( date, Qt::ISODate );
}
QString KolabBase::sensitivityToString( Sensitivity s )
{
switch( s ) {
case Private: return "private";
case Confidential: return "confidential";
case Public: return "public";
}
return "What what what???";
}
KolabBase::Sensitivity KolabBase::stringToSensitivity( const QString& s )
{
if ( s == "private" )
return Private;
if ( s == "confidential" )
return Confidential;
return Public;
}
QString KolabBase::colorToString( const QColor& color )
{
// Color is in the format "#RRGGBB"
return color.name();
}
QColor KolabBase::stringToColor( const QString& s )
{
return QColor( s );
}
void KolabBase::writeString( QDomElement& element, const QString& tag,
const QString& tagString )
{
QDomElement e = element.ownerDocument().createElement( tag );
QDomText t = element.ownerDocument().createTextNode( tagString );
e.appendChild( t );
element.appendChild( e );
}
<|endoftext|> |
<commit_before>//===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CallGraphSCCPass class, which is used for passes
// which are implemented as bottom-up traversals on the call graph. Because
// there may be cycles in the call graph, passes of this type operate on the
// call-graph in SCC order: that is, they process function bottom-up, except for
// recursive functions, which they process all at once.
//
//===----------------------------------------------------------------------===//
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/PassManagers.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// CGPassManager
//
/// CGPassManager manages FPPassManagers and CalLGraphSCCPasses.
class CGPassManager : public ModulePass, public PMDataManager {
public:
CGPassManager(int Depth) : PMDataManager(Depth) { }
/// run - Execute all of the passes scheduled for execution. Keep track of
/// whether any of the passes modifies the module, and if so, return true.
bool runOnModule(Module &M);
bool doInitialization(CallGraph &CG);
bool doFinalization(CallGraph &CG);
/// Pass Manager itself does not invalidate any analysis info.
void getAnalysisUsage(AnalysisUsage &Info) const {
// CGPassManager walks SCC and it needs CallGraph.
Info.addRequired<CallGraph>();
Info.setPreservesAll();
}
// Print passes managed by this manager
void dumpPassStructure(unsigned Offset) {
llvm::cerr << std::string(Offset*2, ' ') << "Call Graph SCC Pass Manager\n";
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
P->dumpPassStructure(Offset + 1);
dumpLastUses(P, Offset+1);
}
}
Pass *getContainedPass(unsigned N) {
assert ( N < PassVector.size() && "Pass number out of range!");
Pass *FP = static_cast<Pass *>(PassVector[N]);
return FP;
}
virtual PassManagerType getPassManagerType() {
return PMT_CallGraphPassManager;
}
};
/// run - Execute all of the passes scheduled for execution. Keep track of
/// whether any of the passes modifies the module, and if so, return true.
bool CGPassManager::runOnModule(Module &M) {
CallGraph &CG = getAnalysis<CallGraph>();
bool Changed = doInitialization(CG);
std::string Msg1 = "Executing Pass '";
std::string Msg3 = "' Made Modification '";
// Walk SCC
for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG);
I != E; ++I) {
// Run all passes on current SCC
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
AnalysisUsage AnUsage;
P->getAnalysisUsage(AnUsage);
std::string Msg2 = "' on Call Graph ...\n'";
dumpPassInfo(P, Msg1, Msg2);
dumpAnalysisSetInfo("Required", P, AnUsage.getRequiredSet());
initializeAnalysisImpl(P);
TimingInfo *TheTimeInfo = llvm::getTheTimeInfo();
if (TheTimeInfo) TheTimeInfo->passStarted(P);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->runOnSCC(*I); // TODO : What if CG is changed ?
else {
FPPassManager *FPP = dynamic_cast<FPPassManager *>(P);
assert (FPP && "Invalid CGPassManager member");
// Run pass P on all functions current SCC
std::vector<CallGraphNode*> &SCC = *I;
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F)
Changed |= FPP->runOnFunction(*F);
}
}
if (TheTimeInfo) TheTimeInfo->passEnded(P);
if (Changed)
dumpPassInfo(P, Msg3, Msg2);
dumpAnalysisSetInfo("Preserved", P, AnUsage.getPreservedSet());
removeNotPreservedAnalysis(P);
recordAvailableAnalysis(P);
removeDeadPasses(P, Msg2);
}
}
Changed |= doFinalization(CG);
return Changed;
}
/// Initialize CG
bool CGPassManager::doInitialization(CallGraph &CG) {
bool Changed = false;
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->doInitialization(CG);
}
return Changed;
}
/// Finalize CG
bool CGPassManager::doFinalization(CallGraph &CG) {
bool Changed = false;
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->doFinalization(CG);
}
return Changed;
}
/// Assign pass manager to manage this pass.
void CallGraphSCCPass::assignPassManager(PMStack &PMS,
PassManagerType PreferredType) {
// Find CGPassManager
while (!PMS.empty()) {
if (PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
PMS.pop();
else;
break;
}
CGPassManager *CGP = dynamic_cast<CGPassManager *>(PMS.top());
// Create new Call Graph SCC Pass Manager if it does not exist.
if (!CGP) {
assert (!PMS.empty() && "Unable to create Call Graph Pass Manager");
PMDataManager *PMD = PMS.top();
// [1] Create new Call Graph Pass Manager
CGP = new CGPassManager(PMD->getDepth() + 1);
// [2] Set up new manager's top level manager
PMTopLevelManager *TPM = PMD->getTopLevelManager();
TPM->addIndirectPassManager(CGP);
// [3] Assign manager to manage this new manager. This may create
// and push new managers into PMS
Pass *P = dynamic_cast<Pass *>(CGP);
P->assignPassManager(PMS);
// [4] Push new manager into PMS
PMS.push(CGP);
}
CGP->add(this);
}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
AU.addPreserved<CallGraph>();
}
<commit_msg>Use StartPassTimer() and StopPassManager()<commit_after>//===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CallGraphSCCPass class, which is used for passes
// which are implemented as bottom-up traversals on the call graph. Because
// there may be cycles in the call graph, passes of this type operate on the
// call-graph in SCC order: that is, they process function bottom-up, except for
// recursive functions, which they process all at once.
//
//===----------------------------------------------------------------------===//
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/PassManagers.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// CGPassManager
//
/// CGPassManager manages FPPassManagers and CalLGraphSCCPasses.
class CGPassManager : public ModulePass, public PMDataManager {
public:
CGPassManager(int Depth) : PMDataManager(Depth) { }
/// run - Execute all of the passes scheduled for execution. Keep track of
/// whether any of the passes modifies the module, and if so, return true.
bool runOnModule(Module &M);
bool doInitialization(CallGraph &CG);
bool doFinalization(CallGraph &CG);
/// Pass Manager itself does not invalidate any analysis info.
void getAnalysisUsage(AnalysisUsage &Info) const {
// CGPassManager walks SCC and it needs CallGraph.
Info.addRequired<CallGraph>();
Info.setPreservesAll();
}
// Print passes managed by this manager
void dumpPassStructure(unsigned Offset) {
llvm::cerr << std::string(Offset*2, ' ') << "Call Graph SCC Pass Manager\n";
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
P->dumpPassStructure(Offset + 1);
dumpLastUses(P, Offset+1);
}
}
Pass *getContainedPass(unsigned N) {
assert ( N < PassVector.size() && "Pass number out of range!");
Pass *FP = static_cast<Pass *>(PassVector[N]);
return FP;
}
virtual PassManagerType getPassManagerType() {
return PMT_CallGraphPassManager;
}
};
/// run - Execute all of the passes scheduled for execution. Keep track of
/// whether any of the passes modifies the module, and if so, return true.
bool CGPassManager::runOnModule(Module &M) {
CallGraph &CG = getAnalysis<CallGraph>();
bool Changed = doInitialization(CG);
std::string Msg1 = "Executing Pass '";
std::string Msg3 = "' Made Modification '";
// Walk SCC
for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG);
I != E; ++I) {
// Run all passes on current SCC
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
AnalysisUsage AnUsage;
P->getAnalysisUsage(AnUsage);
std::string Msg2 = "' on Call Graph ...\n'";
dumpPassInfo(P, Msg1, Msg2);
dumpAnalysisSetInfo("Required", P, AnUsage.getRequiredSet());
initializeAnalysisImpl(P);
StartPassTimer(P);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->runOnSCC(*I); // TODO : What if CG is changed ?
else {
FPPassManager *FPP = dynamic_cast<FPPassManager *>(P);
assert (FPP && "Invalid CGPassManager member");
// Run pass P on all functions current SCC
std::vector<CallGraphNode*> &SCC = *I;
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F)
Changed |= FPP->runOnFunction(*F);
}
}
StopPassTimer(P);
if (Changed)
dumpPassInfo(P, Msg3, Msg2);
dumpAnalysisSetInfo("Preserved", P, AnUsage.getPreservedSet());
removeNotPreservedAnalysis(P);
recordAvailableAnalysis(P);
removeDeadPasses(P, Msg2);
}
}
Changed |= doFinalization(CG);
return Changed;
}
/// Initialize CG
bool CGPassManager::doInitialization(CallGraph &CG) {
bool Changed = false;
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->doInitialization(CG);
}
return Changed;
}
/// Finalize CG
bool CGPassManager::doFinalization(CallGraph &CG) {
bool Changed = false;
for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
Pass *P = getContainedPass(Index);
if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P))
Changed |= CGSP->doFinalization(CG);
}
return Changed;
}
/// Assign pass manager to manage this pass.
void CallGraphSCCPass::assignPassManager(PMStack &PMS,
PassManagerType PreferredType) {
// Find CGPassManager
while (!PMS.empty()) {
if (PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
PMS.pop();
else;
break;
}
CGPassManager *CGP = dynamic_cast<CGPassManager *>(PMS.top());
// Create new Call Graph SCC Pass Manager if it does not exist.
if (!CGP) {
assert (!PMS.empty() && "Unable to create Call Graph Pass Manager");
PMDataManager *PMD = PMS.top();
// [1] Create new Call Graph Pass Manager
CGP = new CGPassManager(PMD->getDepth() + 1);
// [2] Set up new manager's top level manager
PMTopLevelManager *TPM = PMD->getTopLevelManager();
TPM->addIndirectPassManager(CGP);
// [3] Assign manager to manage this new manager. This may create
// and push new managers into PMS
Pass *P = dynamic_cast<Pass *>(CGP);
P->assignPassManager(PMS);
// [4] Push new manager into PMS
PMS.push(CGP);
}
CGP->add(this);
}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
AU.addPreserved<CallGraph>();
}
<|endoftext|> |
<commit_before>
// This program was created by the Equelle compiler from SINTEF.
#include <opm/core/utility/parameters/ParameterGroup.hpp>
#include <opm/core/linalg/LinearSolverFactory.hpp>
#include <opm/core/utility/ErrorMacros.hpp>
#include <opm/autodiff/AutoDiffBlock.hpp>
#include <opm/autodiff/AutoDiffHelpers.hpp>
#include <opm/core/grid.h>
#include <opm/core/grid/GridManager.hpp>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cmath>
#include <array>
#include "EquelleRuntimeCPU.hpp"
void ensureRequirements(const EquelleRuntimeCPU& er);
int main(int argc, char** argv)
{
// Get user parameters.
Opm::parameter::ParameterGroup param(argc, argv, false);
// Create the Equelle runtime.
EquelleRuntimeCPU er(param);
ensureRequirements(er);
// ============= Generated code starts here ================
const Scalar k = er.inputScalarWithDefault("k", double(0.3));
const CollOfScalar u_initial = er.inputCollectionOfScalar("u_initial", er.allCells());
const CollOfFace dirichlet_boundary = er.inputDomainSubsetOf("dirichlet_boundary", er.boundaryFaces());
const CollOfScalar dirichlet_val = er.inputCollectionOfScalar("dirichlet_val", dirichlet_boundary);
const CollOfScalar vol = er.norm(er.allCells());
const CollOfFace interior_faces = er.interiorFaces();
const CollOfCell first = er.firstCell(interior_faces);
const CollOfCell second = er.secondCell(interior_faces);
const CollOfScalar itrans = (k * (er.norm(interior_faces) / er.norm((er.centroid(first) - er.centroid(second)))));
const CollOfFace bf = er.boundaryFaces();
const CollOfCell bf_cells = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.secondCell(bf), er.firstCell(bf));
const CollOfScalar bf_sign = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.operatorExtend(-double(1), bf), er.operatorExtend(double(1), bf));
const CollOfScalar btrans = (k * (er.norm(bf) / er.norm((er.centroid(bf) - er.centroid(bf_cells)))));
const CollOfScalar dir_sign = er.operatorOn(bf_sign, er.boundaryFaces(), dirichlet_boundary);
auto computeInteriorFlux = [&](const CollOfScalar& u) -> CollOfScalar {
return (-itrans * er.gradient(u));
};
auto computeBoundaryFlux = [&](const CollOfScalar& u) -> CollOfScalar {
const CollOfScalar u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, er.boundaryFaces(), dirichlet_boundary));
const CollOfScalar dir_fluxes = ((er.operatorOn(btrans, er.boundaryFaces(), dirichlet_boundary) * dir_sign) * (u_dirbdycells - dirichlet_val));
return er.operatorExtend(dir_fluxes, dirichlet_boundary, er.boundaryFaces());
};
auto computeResidual = [&](const CollOfScalar& u, const CollOfScalar& u0, const Scalar& dt) -> CollOfScalar {
const CollOfScalar ifluxes = computeInteriorFlux(u);
const CollOfScalar bfluxes = computeBoundaryFlux(u);
const CollOfScalar fluxes = (er.operatorExtend(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorExtend(bfluxes, er.boundaryFaces(), er.allFaces()));
const CollOfScalar residual = ((u - u0) + ((dt / vol) * er.divergence(fluxes)));
return residual;
};
const SeqOfScalar timesteps = er.inputSequenceOfScalar("timesteps");
CollOfScalar u0;
u0 = u_initial;
for (const Scalar& dt : timesteps) {
auto computeResidualLocal = [&](const CollOfScalar& u) -> CollOfScalar {
return computeResidual(u, u0, dt);
};
const CollOfScalar u_guess = u0;
const CollOfScalar u = er.newtonSolve(computeResidualLocal, u_guess);
er.output("u", u);
u0 = u;
}
// ============= Generated code ends here ================
return 0;
}
void ensureRequirements(const EquelleRuntimeCPU& er)
{
}
<commit_msg>Example: update heateq_timesteps to current compiler output.<commit_after>
// This program was created by the Equelle compiler from SINTEF.
#include <opm/core/utility/parameters/ParameterGroup.hpp>
#include <opm/core/linalg/LinearSolverFactory.hpp>
#include <opm/core/utility/ErrorMacros.hpp>
#include <opm/autodiff/AutoDiffBlock.hpp>
#include <opm/autodiff/AutoDiffHelpers.hpp>
#include <opm/core/grid.h>
#include <opm/core/grid/GridManager.hpp>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cmath>
#include <array>
#include "EquelleRuntimeCPU.hpp"
void ensureRequirements(const EquelleRuntimeCPU& er);
int main(int argc, char** argv)
{
// Get user parameters.
Opm::parameter::ParameterGroup param(argc, argv, false);
// Create the Equelle runtime.
EquelleRuntimeCPU er(param);
ensureRequirements(er);
// ============= Generated code starts here ================
const Scalar k = er.inputScalarWithDefault("k", double(0.3));
const CollOfScalar u_initial = er.inputCollectionOfScalar("u_initial", er.allCells());
const CollOfFace dirichlet_boundary = er.inputDomainSubsetOf("dirichlet_boundary", er.boundaryFaces());
const CollOfScalar dirichlet_val = er.inputCollectionOfScalar("dirichlet_val", dirichlet_boundary);
const CollOfScalar vol = er.norm(er.allCells());
const CollOfFace interior_faces = er.interiorFaces();
const CollOfCell first = er.firstCell(interior_faces);
const CollOfCell second = er.secondCell(interior_faces);
const CollOfScalar itrans = (k * (er.norm(interior_faces) / er.norm((er.centroid(first) - er.centroid(second)))));
const CollOfFace bf = er.boundaryFaces();
const CollOfCell bf_cells = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.secondCell(bf), er.firstCell(bf));
const CollOfScalar bf_sign = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.operatorExtend(-double(1), bf), er.operatorExtend(double(1), bf));
const CollOfScalar btrans = (k * (er.norm(bf) / er.norm((er.centroid(bf) - er.centroid(bf_cells)))));
const CollOfScalar dir_sign = er.operatorOn(bf_sign, er.boundaryFaces(), dirichlet_boundary);
std::function<CollOfScalar(const CollOfScalar&)> computeInteriorFlux = [&](const CollOfScalar& u) -> CollOfScalar {
return (-itrans * er.gradient(u));
};
std::function<CollOfScalar(const CollOfScalar&)> computeBoundaryFlux = [&](const CollOfScalar& u) -> CollOfScalar {
const CollOfScalar u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, er.boundaryFaces(), dirichlet_boundary));
const CollOfScalar dir_fluxes = ((er.operatorOn(btrans, er.boundaryFaces(), dirichlet_boundary) * dir_sign) * (u_dirbdycells - dirichlet_val));
return er.operatorExtend(dir_fluxes, dirichlet_boundary, er.boundaryFaces());
};
std::function<CollOfScalar(const CollOfScalar&, const CollOfScalar&, const Scalar&)> computeResidual = [&](const CollOfScalar& u, const CollOfScalar& u0, const Scalar& dt) -> CollOfScalar {
const CollOfScalar ifluxes = computeInteriorFlux(u);
const CollOfScalar bfluxes = computeBoundaryFlux(u);
const CollOfScalar fluxes = (er.operatorExtend(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorExtend(bfluxes, er.boundaryFaces(), er.allFaces()));
const CollOfScalar residual = ((u - u0) + ((dt / vol) * er.divergence(fluxes)));
return residual;
};
const SeqOfScalar timesteps = er.inputSequenceOfScalar("timesteps");
CollOfScalar u0;
u0 = u_initial;
for (const Scalar& dt : timesteps) {
std::function<CollOfScalar(const CollOfScalar&)> computeResidualLocal = [&](const CollOfScalar& u) -> CollOfScalar {
return computeResidual(u, u0, dt);
};
const CollOfScalar u_guess = u0;
const CollOfScalar u = er.newtonSolve(computeResidualLocal, u_guess);
er.output("u", u);
u0 = u;
}
// ============= Generated code ends here ================
return 0;
}
void ensureRequirements(const EquelleRuntimeCPU& er)
{
}
<|endoftext|> |
<commit_before>// Copyright 2020 Google LLC
//
// 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 "xls/passes/bdd_function.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "xls/common/status/matchers.h"
#include "xls/examples/sample_packages.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/ir_interpreter.h"
#include "xls/ir/ir_test_base.h"
#include "xls/ir/package.h"
#include "xls/ir/value_helpers.h"
namespace xls {
namespace {
using status_testing::IsOkAndHolds;
class BddFunctionTest : public IrTestBase {};
TEST_F(BddFunctionTest, SimpleOr) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
Type* t = p->GetBitsType(8);
fb.Or(fb.Param("x", t), fb.Param("y", t));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
EXPECT_THAT(bdd_function->Evaluate(
{Value(UBits(0b11110000, 8)), Value(UBits(0b10101010, 8))}),
IsOkAndHolds(Value(UBits(0b11111010, 8))));
}
TEST_F(BddFunctionTest, JustAParam) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
fb.Param("x", p->GetBitsType(8));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0b11011011, 8))}),
IsOkAndHolds(Value(UBits(0b11011011, 8))));
}
TEST_F(BddFunctionTest, AndNot) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
Type* t = p->GetBitsType(8);
BValue x = fb.Param("x", t);
fb.And(x, fb.Not(x));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
// AND of a value and its inverse should be zero.
for (int64 i = 0; i < 8; ++i) {
EXPECT_EQ(bdd_function->GetBddNode(f->return_value(), i),
bdd_function->bdd().zero());
}
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0b11000011, 8))}),
IsOkAndHolds(Value(UBits(0, 8))));
}
TEST_F(BddFunctionTest, Parity) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
BValue parity = fb.Literal(UBits(0, 1));
for (int64 i = 0; i < 32; ++i) {
parity = fb.Xor(parity, fb.BitSlice(x, i, 1));
}
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
const int64 kNumSamples = 100;
std::minstd_rand engine;
for (int64 minterm_limit : {0, 10, 1000, 10000}) {
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f, minterm_limit));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0, 32))}),
IsOkAndHolds(Value(UBits(0, 1))));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(1, 32))}),
IsOkAndHolds(Value(UBits(1, 1))));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0xffffffffLL, 32))}),
IsOkAndHolds(Value(UBits(0, 1))));
for (int64 i = 0; i < kNumSamples; ++i) {
std::vector<Value> inputs = RandomFunctionArguments(f, &engine);
XLS_ASSERT_OK_AND_ASSIGN(Value expected, ir_interpreter::Run(f, inputs));
XLS_ASSERT_OK_AND_ASSIGN(Value actual, bdd_function->Evaluate(inputs));
EXPECT_EQ(expected, actual);
}
}
}
TEST_F(BddFunctionTest, BenchmarkTest) {
// Run samples through various bechmarks and verify against the interpreter.
for (std::string benchmark : {"crc32", "sha256"}) {
XLS_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<Package> p,
sample_packages::GetBenchmark(benchmark, /*optimized=*/true));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, p->EntryFunction());
std::minstd_rand engine;
const int64 kSampleCount = 32;
for (int64 minterm_limit : {10, 100, 1000}) {
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(entry, minterm_limit));
for (int64 i = 0; i < kSampleCount; ++i) {
std::vector<Value> inputs = RandomFunctionArguments(entry, &engine);
XLS_ASSERT_OK_AND_ASSIGN(Value expected,
ir_interpreter::Run(entry, inputs));
XLS_ASSERT_OK_AND_ASSIGN(Value actual, bdd_function->Evaluate(inputs));
EXPECT_EQ(expected, actual);
}
}
}
}
} // namespace
} // namespace xls
<commit_msg>Internal-only test cleanup.<commit_after>// Copyright 2020 Google LLC
//
// 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 "xls/passes/bdd_function.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "xls/common/status/matchers.h"
#include "xls/examples/sample_packages.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/ir_interpreter.h"
#include "xls/ir/ir_test_base.h"
#include "xls/ir/package.h"
#include "xls/ir/value_helpers.h"
namespace xls {
namespace {
using status_testing::IsOkAndHolds;
class BddFunctionTest : public IrTestBase {};
TEST_F(BddFunctionTest, SimpleOr) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
Type* t = p->GetBitsType(8);
fb.Or(fb.Param("x", t), fb.Param("y", t));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
EXPECT_THAT(bdd_function->Evaluate(
{Value(UBits(0b11110000, 8)), Value(UBits(0b10101010, 8))}),
IsOkAndHolds(Value(UBits(0b11111010, 8))));
}
TEST_F(BddFunctionTest, JustAParam) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
fb.Param("x", p->GetBitsType(8));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0b11011011, 8))}),
IsOkAndHolds(Value(UBits(0b11011011, 8))));
}
TEST_F(BddFunctionTest, AndNot) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
Type* t = p->GetBitsType(8);
BValue x = fb.Param("x", t);
fb.And(x, fb.Not(x));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f));
// AND of a value and its inverse should be zero.
for (int64 i = 0; i < 8; ++i) {
EXPECT_EQ(bdd_function->GetBddNode(f->return_value(), i),
bdd_function->bdd().zero());
}
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0b11000011, 8))}),
IsOkAndHolds(Value(UBits(0, 8))));
}
TEST_F(BddFunctionTest, Parity) {
auto p = CreatePackage();
FunctionBuilder fb(TestName(), p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
BValue parity = fb.Literal(UBits(0, 1));
for (int64 i = 0; i < 32; ++i) {
parity = fb.Xor(parity, fb.BitSlice(x, i, 1));
}
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
const int64 kNumSamples = 100;
std::minstd_rand engine;
for (int64 minterm_limit : {0, 10, 1000, 10000}) {
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(f, minterm_limit));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0, 32))}),
IsOkAndHolds(Value(UBits(0, 1))));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(1, 32))}),
IsOkAndHolds(Value(UBits(1, 1))));
EXPECT_THAT(bdd_function->Evaluate({Value(UBits(0xffffffffLL, 32))}),
IsOkAndHolds(Value(UBits(0, 1))));
for (int64 i = 0; i < kNumSamples; ++i) {
std::vector<Value> inputs = RandomFunctionArguments(f, &engine);
XLS_ASSERT_OK_AND_ASSIGN(Value expected, ir_interpreter::Run(f, inputs));
XLS_ASSERT_OK_AND_ASSIGN(Value actual, bdd_function->Evaluate(inputs));
EXPECT_EQ(expected, actual);
}
}
}
TEST_F(BddFunctionTest, BenchmarkTest) {
// Run samples through various bechmarks and verify against the interpreter.
for (std::string benchmark : {"crc32", "sha256"}) {
XLS_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<Package> p,
sample_packages::GetBenchmark(benchmark, /*optimized=*/true));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, p->EntryFunction());
std::minstd_rand engine;
const int64 kSampleCount = 32;
for (int64 minterm_limit : {10, 100, 1000}) {
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<BddFunction> bdd_function,
BddFunction::Run(entry, minterm_limit));
for (int64 i = 0; i < kSampleCount; ++i) {
std::vector<Value> inputs = RandomFunctionArguments(entry, &engine);
XLS_ASSERT_OK_AND_ASSIGN(Value expected,
ir_interpreter::Run(entry, inputs));
XLS_ASSERT_OK_AND_ASSIGN(Value actual, bdd_function->Evaluate(inputs));
EXPECT_EQ(expected, actual);
}
}
}
}
} // namespace
} // namespace xls
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: util.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:48:23 $
*
* 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_xmlsecurity.hxx"
#include "util.hxx"
#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/streamhelper.hxx>
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssi = com::sun::star::io;
using namespace ::com::sun::star;
cssu::Reference< cssl::XMultiServiceFactory > CreateDemoServiceFactory()
{
cssu::Reference< cssl::XMultiServiceFactory > xMSF;
try
{
cssu::Reference< cssl::XMultiComponentFactory > xLocalServiceManager = NULL ;
cssu::Reference< cssu::XComponentContext > xLocalComponentContext = NULL ;
cssu::Reference< ::com::sun::star::registry::XSimpleRegistry > xSimpleRegistry
= ::cppu::createSimpleRegistry();
OSL_ENSURE( xSimpleRegistry.is(),
"serviceManager - "
"Cannot create simple registry" ) ;
xSimpleRegistry->open(rtl::OUString::createFromAscii( "demo.rdb" ), sal_True, sal_False);
OSL_ENSURE( xSimpleRegistry->isValid() ,
"serviceManager - "
"Cannot open xml security registry rdb" ) ;
xLocalComponentContext = ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) ;
OSL_ENSURE( xLocalComponentContext.is() ,
"serviceManager - "
"Cannot create intial component context" ) ;
xLocalServiceManager = xLocalComponentContext->getServiceManager() ;
OSL_ENSURE( xLocalServiceManager.is() ,
"serviceManager - "
"Cannot create intial service manager" ) ;
xMSF = cssu::Reference< cssl::XMultiServiceFactory >(xLocalServiceManager, cssu::UNO_QUERY) ;
::comphelper::setProcessServiceFactory( xMSF );
}
catch( cssu::Exception& e )
{
fprintf( stderr , "Error creating ServiceManager, Exception is %s\n" , rtl::OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ) ;
exit (-1);
}
return xMSF;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > OpenInputStream( const ::rtl::OUString& rStreamName )
{
SvFileStream* pStream = new SvFileStream( rStreamName, STREAM_READ );
pStream->Seek( STREAM_SEEK_TO_END );
ULONG nBytes = pStream->Tell();
pStream->Seek( STREAM_SEEK_TO_BEGIN );
SvLockBytesRef xLockBytes = new SvLockBytes( pStream, TRUE );
uno::Reference< io::XInputStream > xInputStream = new utl::OInputStreamHelper( xLockBytes, nBytes );
return xInputStream;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > OpenOutputStream( const ::rtl::OUString& rStreamName )
{
SvFileStream* pStream = new SvFileStream( rStreamName, STREAM_WRITE );
SvLockBytesRef xLockBytes = new SvLockBytes( pStream, TRUE );
uno::Reference< io::XOutputStream > xOutputStream = new utl::OOutputStreamHelper( xLockBytes );
return xOutputStream;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.12.102); FILE MERGED 2008/04/01 16:11:09 thb 1.12.102.2: #i85898# Stripping all external header guards 2008/03/31 16:31:06 rt 1.12.102.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: util.cxx,v $
* $Revision: 1.13 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"
#include "util.hxx"
#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/streamhelper.hxx>
#include <tools/string.hxx>
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssi = com::sun::star::io;
using namespace ::com::sun::star;
cssu::Reference< cssl::XMultiServiceFactory > CreateDemoServiceFactory()
{
cssu::Reference< cssl::XMultiServiceFactory > xMSF;
try
{
cssu::Reference< cssl::XMultiComponentFactory > xLocalServiceManager = NULL ;
cssu::Reference< cssu::XComponentContext > xLocalComponentContext = NULL ;
cssu::Reference< ::com::sun::star::registry::XSimpleRegistry > xSimpleRegistry
= ::cppu::createSimpleRegistry();
OSL_ENSURE( xSimpleRegistry.is(),
"serviceManager - "
"Cannot create simple registry" ) ;
xSimpleRegistry->open(rtl::OUString::createFromAscii( "demo.rdb" ), sal_True, sal_False);
OSL_ENSURE( xSimpleRegistry->isValid() ,
"serviceManager - "
"Cannot open xml security registry rdb" ) ;
xLocalComponentContext = ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) ;
OSL_ENSURE( xLocalComponentContext.is() ,
"serviceManager - "
"Cannot create intial component context" ) ;
xLocalServiceManager = xLocalComponentContext->getServiceManager() ;
OSL_ENSURE( xLocalServiceManager.is() ,
"serviceManager - "
"Cannot create intial service manager" ) ;
xMSF = cssu::Reference< cssl::XMultiServiceFactory >(xLocalServiceManager, cssu::UNO_QUERY) ;
::comphelper::setProcessServiceFactory( xMSF );
}
catch( cssu::Exception& e )
{
fprintf( stderr , "Error creating ServiceManager, Exception is %s\n" , rtl::OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ) ;
exit (-1);
}
return xMSF;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > OpenInputStream( const ::rtl::OUString& rStreamName )
{
SvFileStream* pStream = new SvFileStream( rStreamName, STREAM_READ );
pStream->Seek( STREAM_SEEK_TO_END );
ULONG nBytes = pStream->Tell();
pStream->Seek( STREAM_SEEK_TO_BEGIN );
SvLockBytesRef xLockBytes = new SvLockBytes( pStream, TRUE );
uno::Reference< io::XInputStream > xInputStream = new utl::OInputStreamHelper( xLockBytes, nBytes );
return xInputStream;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > OpenOutputStream( const ::rtl::OUString& rStreamName )
{
SvFileStream* pStream = new SvFileStream( rStreamName, STREAM_WRITE );
SvLockBytesRef xLockBytes = new SvLockBytes( pStream, TRUE );
uno::Reference< io::XOutputStream > xOutputStream = new utl::OOutputStreamHelper( xLockBytes );
return xOutputStream;
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "genericsamplegenerator.h"
// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/lighting/imageimportancesampler.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/localaccumulationframebuffer.h"
#include "renderer/kernel/rendering/sample.h"
#include "renderer/kernel/rendering/samplegeneratorbase.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/image.h"
#include "foundation/math/population.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <vector>
// Forward declarations.
namespace foundation { class LightingConditions; }
using namespace foundation;
using namespace std;
#undef ADAPTIVE_IMAGE_SAMPLING
namespace renderer
{
namespace
{
//
// GenericSampleGenerator class implementation.
//
class PixelSampler
{
public:
PixelSampler(
const size_t width,
const size_t height)
: m_width(width)
, m_height(height)
, m_pixel_history(width * height)
{
const size_t pixel_count = m_pixel_history.size();
for (size_t i = 0; i < pixel_count; ++i)
{
PixelHistory& history = m_pixel_history[i];
history.m_avg = 0.0;
history.m_s = 0.0;
history.m_size = 0;
}
}
double operator()(
const size_t x,
const size_t y) const
{
assert(x < m_width);
assert(y < m_height);
const size_t MinSamplesPerPixel = 4;
const double VariationThreshold = 0.1;
const double LowProbability = 1.0 / 6;
const double HighProbability = 1.0;
const PixelHistory& history = m_pixel_history[y * m_width + x];
if (history.m_size < MinSamplesPerPixel)
return HighProbability;
if (history.m_avg == 0.0)
return HighProbability;
// Compute the standard deviation.
const double deviation = sqrt(history.m_s / history.m_size);
// Compute the coefficient of variation.
const double variation = deviation / history.m_avg;
assert(variation >= 0.0);
#if 0
return variation < VariationThreshold ? LowProbability : HighProbability;
#else
return clamp(variation, LowProbability, HighProbability);
#endif
}
void update_pixel_variance(
const size_t x,
const size_t y,
const float luminance)
{
assert(x < m_width);
assert(y < m_height);
assert(luminance >= 0.0f);
PixelHistory& history = m_pixel_history[y * m_width + x];
const double double_luminance = static_cast<double>(luminance);
// Compute residual value.
const double residual = double_luminance - history.m_avg;
// Compute the new size of the population.
const size_t new_size = history.m_size + 1;
// Compute the new mean value of the population.
const double new_avg = history.m_avg + residual / new_size;
// Update s.
history.m_s += residual * (double_luminance - new_avg);
// Update the mean value of the population.
history.m_avg = new_avg;
// Update the size of the population.
history.m_size = new_size;
}
private:
struct PixelHistory
{
double m_avg;
double m_s;
size_t m_size;
};
const size_t m_width;
const size_t m_height;
vector<PixelHistory> m_pixel_history;
};
class GenericSampleGenerator
: public SampleGeneratorBase
{
public:
GenericSampleGenerator(
const Frame& frame,
ISampleRendererFactory* sample_renderer_factory,
const size_t generator_index,
const size_t generator_count)
: SampleGeneratorBase(generator_index, generator_count)
, m_frame(frame)
, m_frame_props(frame.image().properties())
, m_lighting_conditions(frame.get_lighting_conditions())
, m_sample_renderer(sample_renderer_factory->create())
, m_pixel_sampler(m_frame_props.m_canvas_width, m_frame_props.m_canvas_height)
, m_image_sampler(m_frame_props.m_canvas_width, m_frame_props.m_canvas_height, m_pixel_sampler)
, m_sample_count(0)
{
}
~GenericSampleGenerator()
{
RENDERER_LOG_DEBUG(
"generic sample generator statistics:\n"
" max. samp. dim. avg %.1f min %s max %s dev %.1f\n"
" max. samp. inst. avg %.1f min %s max %s dev %.1f\n",
m_total_sampling_dim.get_avg(),
pretty_uint(m_total_sampling_dim.get_min()).c_str(),
pretty_uint(m_total_sampling_dim.get_max()).c_str(),
m_total_sampling_dim.get_dev(),
m_total_sampling_inst.get_avg(),
pretty_uint(m_total_sampling_inst.get_min()).c_str(),
pretty_uint(m_total_sampling_inst.get_max()).c_str(),
m_total_sampling_inst.get_dev());
}
virtual void release()
{
delete this;
}
virtual void reset()
{
SampleGeneratorBase::reset();
m_rng = MersenneTwister();
}
private:
const Frame& m_frame;
const CanvasProperties& m_frame_props;
const LightingConditions& m_lighting_conditions;
auto_release_ptr<ISampleRenderer> m_sample_renderer;
MersenneTwister m_rng;
PixelSampler m_pixel_sampler;
ImageImportanceSampler<double> m_image_sampler;
size_t m_sample_count;
Population<size_t> m_total_sampling_dim;
Population<size_t> m_total_sampling_inst;
virtual size_t generate_samples(
const size_t sequence_index,
SampleVector& samples)
{
#ifdef ADAPTIVE_IMAGE_SAMPLING
// Generate a uniform sample in [0,1)^2.
const size_t Bases[2] = { 2, 3 };
const Vector2d s = halton_sequence<double, 2>(Bases, sequence_index);
// Choose a pixel.
size_t pixel_x, pixel_y;
double pixel_prob;
m_image_sampler.sample(s, pixel_x, pixel_y, pixel_prob);
// Create a sampling context. We start with an initial dimension of 2,
// corresponding to the Halton sequence used for the sample positions.
SamplingContext sampling_context(
m_rng,
2, // number of dimensions
0, // number of samples
sequence_index); // initial instance number
// Compute the sample position in NDC.
sampling_context.split_in_place(2, 1);
const Vector2d subpixel = sampling_context.next_vector2<2>();
const Vector2d sample_position(
(pixel_x + subpixel.x) * m_frame_props.m_rcp_canvas_width,
(pixel_y + subpixel.y) * m_frame_props.m_rcp_canvas_height);
#else
// Compute the sample position in NDC.
const size_t Bases[2] = { 2, 3 };
const Vector2d sample_position =
halton_sequence<double, 2>(Bases, sequence_index);
// Create a sampling context. We start with an initial dimension of 2,
// corresponding to the Halton sequence used for the sample positions.
SamplingContext sampling_context(
m_rng,
2, // number of dimensions
sequence_index, // number of samples
sequence_index); // initial instance number
#endif
// Render the sample.
ShadingResult shading_result;
m_sample_renderer->render_sample(
sampling_context,
sample_position,
shading_result);
// Transform the sample to the linear RGB color space.
shading_result.transform_to_linear_rgb(m_lighting_conditions);
// Create a single sample.
Sample sample;
sample.m_position = sample_position;
sample.m_color[0] = shading_result.m_color[0];
sample.m_color[1] = shading_result.m_color[1];
sample.m_color[2] = shading_result.m_color[2];
sample.m_color[3] = shading_result.m_alpha[0];
samples.push_back(sample);
#ifdef ADAPTIVE_IMAGE_SAMPLING
// Update pixel variance.
m_pixel_sampler.update_pixel_variance(
pixel_x,
pixel_y,
luminance(sample.m_color.rgb()));
// Rebuild the pixel CDF regularly.
const size_t ImageSamplerUpdatePeriod = 256 * 1000;
if (++m_sample_count == ImageSamplerUpdatePeriod)
{
RENDERER_LOG_DEBUG("rebuilding pixel cdf...");
m_image_sampler.rebuild(m_pixel_sampler);
m_sample_count = 0;
}
#endif
m_total_sampling_dim.insert(sampling_context.get_total_dimension());
m_total_sampling_inst.insert(sampling_context.get_total_instance());
return 1;
}
};
}
//
// GenericSampleGeneratorFactory class implementation.
//
GenericSampleGeneratorFactory::GenericSampleGeneratorFactory(
const Frame& frame,
ISampleRendererFactory* sample_renderer_factory)
: m_frame(frame)
, m_sample_renderer_factory(sample_renderer_factory)
{
}
void GenericSampleGeneratorFactory::release()
{
delete this;
}
ISampleGenerator* GenericSampleGeneratorFactory::create(
const size_t generator_index,
const size_t generator_count)
{
return
new GenericSampleGenerator(
m_frame,
m_sample_renderer_factory,
generator_index,
generator_count);
}
AccumulationFramebuffer* GenericSampleGeneratorFactory::create_accumulation_framebuffer(
const size_t canvas_width,
const size_t canvas_height)
{
return
new LocalAccumulationFramebuffer(
canvas_width,
canvas_height);
}
} // namespace renderer
<commit_msg>wrapped some variables declarations and initializations in #ifdef ADAPTIVE_IMAGE_SAMPLING / #endif.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "genericsamplegenerator.h"
// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/lighting/imageimportancesampler.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/localaccumulationframebuffer.h"
#include "renderer/kernel/rendering/sample.h"
#include "renderer/kernel/rendering/samplegeneratorbase.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/image.h"
#include "foundation/math/population.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <vector>
// Forward declarations.
namespace foundation { class LightingConditions; }
using namespace foundation;
using namespace std;
#undef ADAPTIVE_IMAGE_SAMPLING
namespace renderer
{
namespace
{
//
// GenericSampleGenerator class implementation.
//
class PixelSampler
{
public:
PixelSampler(
const size_t width,
const size_t height)
: m_width(width)
, m_height(height)
, m_pixel_history(width * height)
{
const size_t pixel_count = m_pixel_history.size();
for (size_t i = 0; i < pixel_count; ++i)
{
PixelHistory& history = m_pixel_history[i];
history.m_avg = 0.0;
history.m_s = 0.0;
history.m_size = 0;
}
}
double operator()(
const size_t x,
const size_t y) const
{
assert(x < m_width);
assert(y < m_height);
const size_t MinSamplesPerPixel = 4;
const double VariationThreshold = 0.1;
const double LowProbability = 1.0 / 6;
const double HighProbability = 1.0;
const PixelHistory& history = m_pixel_history[y * m_width + x];
if (history.m_size < MinSamplesPerPixel)
return HighProbability;
if (history.m_avg == 0.0)
return HighProbability;
// Compute the standard deviation.
const double deviation = sqrt(history.m_s / history.m_size);
// Compute the coefficient of variation.
const double variation = deviation / history.m_avg;
assert(variation >= 0.0);
#if 0
return variation < VariationThreshold ? LowProbability : HighProbability;
#else
return clamp(variation, LowProbability, HighProbability);
#endif
}
void update_pixel_variance(
const size_t x,
const size_t y,
const float luminance)
{
assert(x < m_width);
assert(y < m_height);
assert(luminance >= 0.0f);
PixelHistory& history = m_pixel_history[y * m_width + x];
const double double_luminance = static_cast<double>(luminance);
// Compute residual value.
const double residual = double_luminance - history.m_avg;
// Compute the new size of the population.
const size_t new_size = history.m_size + 1;
// Compute the new mean value of the population.
const double new_avg = history.m_avg + residual / new_size;
// Update s.
history.m_s += residual * (double_luminance - new_avg);
// Update the mean value of the population.
history.m_avg = new_avg;
// Update the size of the population.
history.m_size = new_size;
}
private:
struct PixelHistory
{
double m_avg;
double m_s;
size_t m_size;
};
const size_t m_width;
const size_t m_height;
vector<PixelHistory> m_pixel_history;
};
class GenericSampleGenerator
: public SampleGeneratorBase
{
public:
GenericSampleGenerator(
const Frame& frame,
ISampleRendererFactory* sample_renderer_factory,
const size_t generator_index,
const size_t generator_count)
: SampleGeneratorBase(generator_index, generator_count)
, m_frame(frame)
, m_frame_props(frame.image().properties())
, m_lighting_conditions(frame.get_lighting_conditions())
, m_sample_renderer(sample_renderer_factory->create())
#ifdef ADAPTIVE_IMAGE_SAMPLING
, m_pixel_sampler(m_frame_props.m_canvas_width, m_frame_props.m_canvas_height)
, m_image_sampler(m_frame_props.m_canvas_width, m_frame_props.m_canvas_height, m_pixel_sampler)
, m_sample_count(0)
#endif
{
}
~GenericSampleGenerator()
{
RENDERER_LOG_DEBUG(
"generic sample generator statistics:\n"
" max. samp. dim. avg %.1f min %s max %s dev %.1f\n"
" max. samp. inst. avg %.1f min %s max %s dev %.1f\n",
m_total_sampling_dim.get_avg(),
pretty_uint(m_total_sampling_dim.get_min()).c_str(),
pretty_uint(m_total_sampling_dim.get_max()).c_str(),
m_total_sampling_dim.get_dev(),
m_total_sampling_inst.get_avg(),
pretty_uint(m_total_sampling_inst.get_min()).c_str(),
pretty_uint(m_total_sampling_inst.get_max()).c_str(),
m_total_sampling_inst.get_dev());
}
virtual void release()
{
delete this;
}
virtual void reset()
{
SampleGeneratorBase::reset();
m_rng = MersenneTwister();
}
private:
const Frame& m_frame;
const CanvasProperties& m_frame_props;
const LightingConditions& m_lighting_conditions;
auto_release_ptr<ISampleRenderer> m_sample_renderer;
MersenneTwister m_rng;
#ifdef ADAPTIVE_IMAGE_SAMPLING
PixelSampler m_pixel_sampler;
ImageImportanceSampler<double> m_image_sampler;
size_t m_sample_count;
#endif
Population<size_t> m_total_sampling_dim;
Population<size_t> m_total_sampling_inst;
virtual size_t generate_samples(
const size_t sequence_index,
SampleVector& samples)
{
#ifdef ADAPTIVE_IMAGE_SAMPLING
// Generate a uniform sample in [0,1)^2.
const size_t Bases[2] = { 2, 3 };
const Vector2d s = halton_sequence<double, 2>(Bases, sequence_index);
// Choose a pixel.
size_t pixel_x, pixel_y;
double pixel_prob;
m_image_sampler.sample(s, pixel_x, pixel_y, pixel_prob);
// Create a sampling context. We start with an initial dimension of 2,
// corresponding to the Halton sequence used for the sample positions.
SamplingContext sampling_context(
m_rng,
2, // number of dimensions
0, // number of samples
sequence_index); // initial instance number
// Compute the sample position in NDC.
sampling_context.split_in_place(2, 1);
const Vector2d subpixel = sampling_context.next_vector2<2>();
const Vector2d sample_position(
(pixel_x + subpixel.x) * m_frame_props.m_rcp_canvas_width,
(pixel_y + subpixel.y) * m_frame_props.m_rcp_canvas_height);
#else
// Compute the sample position in NDC.
const size_t Bases[2] = { 2, 3 };
const Vector2d sample_position =
halton_sequence<double, 2>(Bases, sequence_index);
// Create a sampling context. We start with an initial dimension of 2,
// corresponding to the Halton sequence used for the sample positions.
SamplingContext sampling_context(
m_rng,
2, // number of dimensions
sequence_index, // number of samples
sequence_index); // initial instance number
#endif
// Render the sample.
ShadingResult shading_result;
m_sample_renderer->render_sample(
sampling_context,
sample_position,
shading_result);
// Transform the sample to the linear RGB color space.
shading_result.transform_to_linear_rgb(m_lighting_conditions);
// Create a single sample.
Sample sample;
sample.m_position = sample_position;
sample.m_color[0] = shading_result.m_color[0];
sample.m_color[1] = shading_result.m_color[1];
sample.m_color[2] = shading_result.m_color[2];
sample.m_color[3] = shading_result.m_alpha[0];
samples.push_back(sample);
#ifdef ADAPTIVE_IMAGE_SAMPLING
// Update pixel variance.
m_pixel_sampler.update_pixel_variance(
pixel_x,
pixel_y,
luminance(sample.m_color.rgb()));
// Rebuild the pixel CDF regularly.
const size_t ImageSamplerUpdatePeriod = 256 * 1000;
if (++m_sample_count == ImageSamplerUpdatePeriod)
{
RENDERER_LOG_DEBUG("rebuilding pixel cdf...");
m_image_sampler.rebuild(m_pixel_sampler);
m_sample_count = 0;
}
#endif
m_total_sampling_dim.insert(sampling_context.get_total_dimension());
m_total_sampling_inst.insert(sampling_context.get_total_instance());
return 1;
}
};
}
//
// GenericSampleGeneratorFactory class implementation.
//
GenericSampleGeneratorFactory::GenericSampleGeneratorFactory(
const Frame& frame,
ISampleRendererFactory* sample_renderer_factory)
: m_frame(frame)
, m_sample_renderer_factory(sample_renderer_factory)
{
}
void GenericSampleGeneratorFactory::release()
{
delete this;
}
ISampleGenerator* GenericSampleGeneratorFactory::create(
const size_t generator_index,
const size_t generator_count)
{
return
new GenericSampleGenerator(
m_frame,
m_sample_renderer_factory,
generator_index,
generator_count);
}
AccumulationFramebuffer* GenericSampleGeneratorFactory::create_accumulation_framebuffer(
const size_t canvas_width,
const size_t canvas_height)
{
return
new LocalAccumulationFramebuffer(
canvas_width,
canvas_height);
}
} // namespace renderer
<|endoftext|> |
<commit_before>#pragma once
#include "libkrbn/libkrbn.h"
#include "monitor/connected_devices_monitor.hpp"
namespace {
class libkrbn_connected_devices_class final {
public:
libkrbn_connected_devices_class(const krbn::connected_devices::connected_devices& connected_devices) : connected_devices_(connected_devices) {
}
krbn::connected_devices::connected_devices& get_connected_devices(void) {
return connected_devices_;
}
private:
krbn::connected_devices::connected_devices connected_devices_;
};
class libkrbn_connected_devices_monitor final {
public:
libkrbn_connected_devices_monitor(const libkrbn_connected_devices_monitor&) = delete;
libkrbn_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback, void* refcon) {
krbn::logger::get_logger()->info(__func__);
monitor_ = std::make_unique<krbn::connected_devices_monitor>(
krbn::constants::get_devices_json_file_path());
monitor_->connected_devices_updated.connect([callback, refcon](auto&& weak_connected_devices) {
if (auto connected_devices = weak_connected_devices.lock()) {
if (callback) {
auto* p = new libkrbn_connected_devices_class(*connected_devices);
callback(p, refcon);
}
}
});
monitor_->async_start();
}
~libkrbn_connected_devices_monitor(void) {
krbn::logger::get_logger()->info(__func__);
}
private:
std::unique_ptr<krbn::connected_devices_monitor> monitor_;
};
} // namespace
<commit_msg>update #include<commit_after>#pragma once
#include "constants.hpp"
#include "libkrbn/libkrbn.h"
#include "monitor/connected_devices_monitor.hpp"
namespace {
class libkrbn_connected_devices_class final {
public:
libkrbn_connected_devices_class(const krbn::connected_devices::connected_devices& connected_devices) : connected_devices_(connected_devices) {
}
krbn::connected_devices::connected_devices& get_connected_devices(void) {
return connected_devices_;
}
private:
krbn::connected_devices::connected_devices connected_devices_;
};
class libkrbn_connected_devices_monitor final {
public:
libkrbn_connected_devices_monitor(const libkrbn_connected_devices_monitor&) = delete;
libkrbn_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback, void* refcon) {
krbn::logger::get_logger()->info(__func__);
monitor_ = std::make_unique<krbn::connected_devices_monitor>(
krbn::constants::get_devices_json_file_path());
monitor_->connected_devices_updated.connect([callback, refcon](auto&& weak_connected_devices) {
if (auto connected_devices = weak_connected_devices.lock()) {
if (callback) {
auto* p = new libkrbn_connected_devices_class(*connected_devices);
callback(p, refcon);
}
}
});
monitor_->async_start();
}
~libkrbn_connected_devices_monitor(void) {
krbn::logger::get_logger()->info(__func__);
}
private:
std::unique_ptr<krbn::connected_devices_monitor> monitor_;
};
} // namespace
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Eckhart Wörner <ewoerner@kde.org>
// Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "PlacemarkPositionProviderPlugin.h"
#include "GeoDataPlacemark.h"
#include "MarbleClock.h"
#include "MarbleMath.h"
#include "MarbleModel.h"
#include "MarbleDebug.h"
using namespace Marble;
PlacemarkPositionProviderPlugin::PlacemarkPositionProviderPlugin()
: PositionProviderPlugin(),
m_placemark( 0 ),
m_speed( 0 ),
m_status( PositionProviderStatusUnavailable ),
m_isInitialized( false )
{
m_accuracy.level = GeoDataAccuracy::Detailed;
}
QString PlacemarkPositionProviderPlugin::name() const
{
return tr( "Placemark position provider Plugin" );
}
QString PlacemarkPositionProviderPlugin::nameId() const
{
return QString::fromLatin1( "Placemark" );
}
QString PlacemarkPositionProviderPlugin::guiString() const
{
return tr( "Placemark" );
}
QString PlacemarkPositionProviderPlugin::description() const
{
return tr( "Reports the position of a placemark" );
}
QIcon PlacemarkPositionProviderPlugin::icon() const
{
return QIcon();
}
void PlacemarkPositionProviderPlugin::initialize()
{
if ( marbleModel() ) {
setPlacemark( marbleModel()->trackedPlacemark() );
} else {
mDebug() << "PlacemarkPositionProviderPlugin: MarbleModel not set, cannot track placemarks.";
}
m_isInitialized = true;
}
bool PlacemarkPositionProviderPlugin::isInitialized() const
{
return true;
}
PositionProviderPlugin* PlacemarkPositionProviderPlugin::newInstance() const
{
return new PlacemarkPositionProviderPlugin();
}
PositionProviderStatus PlacemarkPositionProviderPlugin::status() const
{
return m_status;
}
GeoDataCoordinates PlacemarkPositionProviderPlugin::position() const
{
if ( m_placemark == 0 ) {
return GeoDataCoordinates();
}
return m_placemark->coordinate();
}
GeoDataAccuracy PlacemarkPositionProviderPlugin::accuracy() const
{
return m_accuracy;
}
qreal PlacemarkPositionProviderPlugin::speed() const
{
return m_speed;
}
void PlacemarkPositionProviderPlugin::setPlacemark( const GeoDataPlacemark *placemark )
{
disconnect( marbleModel()->clock(), SIGNAL( timeChanged() ), this, SLOT( updatePosition() ) );
m_coordinates = GeoDataCoordinates();
m_timestamp = QDateTime();
m_placemark = placemark;
if ( placemark ) {
connect( marbleModel()->clock(), SIGNAL( timeChanged() ), this, SLOT( updatePosition() ) );
}
update();
}
void PlacemarkPositionProviderPlugin::updatePosition()
{
if ( m_placemark == 0 ) {
return;
}
Q_ASSERT( marbleModel() && "MarbleModel missing in PlacemarkPositionProviderPlugin" );
const GeoDataCoordinates previousCoordinates = m_coordinates;
m_coordinates = m_placemark->coordinate( marbleModel()->clock()->dateTime() );
if ( m_timestamp.isValid() ) {
const qreal averageAltitude = ( m_coordinates.altitude() + m_coordinates.altitude() ) / 2.0 + marbleModel()->planetRadius();
const qreal distance = distanceSphere( previousCoordinates, m_coordinates ) * averageAltitude;
const qreal seconds = m_timestamp.msecsTo( marbleModel()->clockDateTime() ) / 1000.0;
m_speed = ( seconds > 0 ) ? ( distance / seconds ) : 0;
}
else {
m_speed = 0;
}
m_timestamp = marbleModel()->clockDateTime();
emit positionChanged( m_coordinates, m_accuracy );
}
void PlacemarkPositionProviderPlugin::update()
{
if ( m_placemark != 0 ) {
m_status = PositionProviderStatusAvailable;
} else {
m_status = PositionProviderStatusUnavailable;
}
emit statusChanged( m_status );
}
Q_EXPORT_PLUGIN2( PlacemarkPositionProviderPlugin, Marble::PlacemarkPositionProviderPlugin )
#include "PlacemarkPositionProviderPlugin.moc"
<commit_msg>Changes: Fix compilation with Qt 4.6<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Eckhart Wörner <ewoerner@kde.org>
// Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "PlacemarkPositionProviderPlugin.h"
#include "GeoDataPlacemark.h"
#include "MarbleClock.h"
#include "MarbleMath.h"
#include "MarbleModel.h"
#include "MarbleDebug.h"
using namespace Marble;
PlacemarkPositionProviderPlugin::PlacemarkPositionProviderPlugin()
: PositionProviderPlugin(),
m_placemark( 0 ),
m_speed( 0 ),
m_status( PositionProviderStatusUnavailable ),
m_isInitialized( false )
{
m_accuracy.level = GeoDataAccuracy::Detailed;
}
QString PlacemarkPositionProviderPlugin::name() const
{
return tr( "Placemark position provider Plugin" );
}
QString PlacemarkPositionProviderPlugin::nameId() const
{
return QString::fromLatin1( "Placemark" );
}
QString PlacemarkPositionProviderPlugin::guiString() const
{
return tr( "Placemark" );
}
QString PlacemarkPositionProviderPlugin::description() const
{
return tr( "Reports the position of a placemark" );
}
QIcon PlacemarkPositionProviderPlugin::icon() const
{
return QIcon();
}
void PlacemarkPositionProviderPlugin::initialize()
{
if ( marbleModel() ) {
setPlacemark( marbleModel()->trackedPlacemark() );
} else {
mDebug() << "PlacemarkPositionProviderPlugin: MarbleModel not set, cannot track placemarks.";
}
m_isInitialized = true;
}
bool PlacemarkPositionProviderPlugin::isInitialized() const
{
return true;
}
PositionProviderPlugin* PlacemarkPositionProviderPlugin::newInstance() const
{
return new PlacemarkPositionProviderPlugin();
}
PositionProviderStatus PlacemarkPositionProviderPlugin::status() const
{
return m_status;
}
GeoDataCoordinates PlacemarkPositionProviderPlugin::position() const
{
if ( m_placemark == 0 ) {
return GeoDataCoordinates();
}
return m_placemark->coordinate();
}
GeoDataAccuracy PlacemarkPositionProviderPlugin::accuracy() const
{
return m_accuracy;
}
qreal PlacemarkPositionProviderPlugin::speed() const
{
return m_speed;
}
void PlacemarkPositionProviderPlugin::setPlacemark( const GeoDataPlacemark *placemark )
{
disconnect( marbleModel()->clock(), SIGNAL( timeChanged() ), this, SLOT( updatePosition() ) );
m_coordinates = GeoDataCoordinates();
m_timestamp = QDateTime();
m_placemark = placemark;
if ( placemark ) {
connect( marbleModel()->clock(), SIGNAL( timeChanged() ), this, SLOT( updatePosition() ) );
}
update();
}
void PlacemarkPositionProviderPlugin::updatePosition()
{
if ( m_placemark == 0 ) {
return;
}
Q_ASSERT( marbleModel() && "MarbleModel missing in PlacemarkPositionProviderPlugin" );
const GeoDataCoordinates previousCoordinates = m_coordinates;
m_coordinates = m_placemark->coordinate( marbleModel()->clock()->dateTime() );
if ( m_timestamp.isValid() ) {
const qreal averageAltitude = ( m_coordinates.altitude() + m_coordinates.altitude() ) / 2.0 + marbleModel()->planetRadius();
const qreal distance = distanceSphere( previousCoordinates, m_coordinates ) * averageAltitude;
#if QT_VERSION >= 0x40700
const qreal seconds = m_timestamp.msecsTo( marbleModel()->clockDateTime() ) / 1000.0;
#else
const qreal seconds = m_timestamp.secsTo( marbleModel()->clockDateTime() );
#endif
m_speed = ( seconds > 0 ) ? ( distance / seconds ) : 0;
}
else {
m_speed = 0;
}
m_timestamp = marbleModel()->clockDateTime();
emit positionChanged( m_coordinates, m_accuracy );
}
void PlacemarkPositionProviderPlugin::update()
{
if ( m_placemark != 0 ) {
m_status = PositionProviderStatusAvailable;
} else {
m_status = PositionProviderStatusUnavailable;
}
emit statusChanged( m_status );
}
Q_EXPORT_PLUGIN2( PlacemarkPositionProviderPlugin, Marble::PlacemarkPositionProviderPlugin )
#include "PlacemarkPositionProviderPlugin.moc"
<|endoftext|> |
<commit_before>#pragma once
#define WRD_NULL 0x00
#define WRD_IDX_ERROR -1
#ifdef UNICODE
#define tchar wchar_t
#define tmain wmain
#define tcslen wcslen
#define tcscat wcscat
#define tcscpy wcscpy
#define tcsncpy wcsncpy
#define tcscmp wcscmp
#define tcsncmp wcsncmp
#define tprintf wprintf
#define tscanf wscanf
#define fgetts fgetws
#define fputts fputws
#else
#define tchar char
#define tcslen strlen
#define tcscat strcat
#define tcscpy strcpy
#define tcsncpy strncpy
#define tcscmp strcmp
#define tcsncmp strncmp
#define tprintf printf
#define tscanf scanf
#define fgetts fgets
#define fputts fputs
#endif
<commit_msg>+ [indep] replace constexpr instead of define.<commit_after>#pragma once
#define WRD_NULL 0x00
constexpr widx WRD_INDEX_ERROR = -1;
#ifdef UNICODE
#define tchar wchar_t
#define tmain wmain
#define tcslen wcslen
#define tcscat wcscat
#define tcscpy wcscpy
#define tcsncpy wcsncpy
#define tcscmp wcscmp
#define tcsncmp wcsncmp
#define tprintf wprintf
#define tscanf wscanf
#define fgetts fgetws
#define fputts fputws
#else
#define tchar char
#define tcslen strlen
#define tcscat strcat
#define tcscpy strcpy
#define tcsncpy strncpy
#define tcscmp strcmp
#define tcsncmp strncmp
#define tprintf printf
#define tscanf scanf
#define fgetts fgets
#define fputts fputs
#endif
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
/*
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
#define USE_IPP_CANNY 1
#else
#undef USE_IPP_CANNY
#endif
*/
#ifdef USE_IPP_CANNY
namespace cv
{
static bool ippCanny(const Mat& _src, Mat& _dst, float low, float high)
{
int size = 0, size1 = 0;
IppiSize roi = { _src.cols, _src.rows };
ippiFilterSobelNegVertGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size);
ippiFilterSobelHorizGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size1);
size = std::max(size, size1);
ippiCannyGetSize(roi, &size1);
size = std::max(size, size1);
AutoBuffer<uchar> buf(size + 64);
uchar* buffer = alignPtr((uchar*)buf, 32);
Mat _dx(_src.rows, _src.cols, CV_16S);
if( ippiFilterSobelNegVertBorder_8u16s_C1R(_src.data, (int)_src.step,
_dx.ptr<short>(), (int)_dx.step, roi,
ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 )
return false;
Mat _dy(_src.rows, _src.cols, CV_16S);
if( ippiFilterSobelHorizBorder_8u16s_C1R(_src.data, (int)_src.step,
_dy.ptr<short>(), (int)_dy.step, roi,
ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 )
return false;
if( ippiCanny_16s8u_C1R(_dx.ptr<short>(), (int)_dx.step,
_dy.ptr<short>(), (int)_dy.step,
_dst.data, (int)_dst.step, roi, low, high, buffer) < 0 )
return false;
return true;
}
}
#endif
void cv::Canny( InputArray _src, OutputArray _dst,
double low_thresh, double high_thresh,
int aperture_size, bool L2gradient )
{
Mat src = _src.getMat();
CV_Assert( src.depth() == CV_8U );
_dst.create(src.size(), CV_8U);
Mat dst = _dst.getMat();
if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)
{
//backward compatibility
aperture_size &= ~CV_CANNY_L2_GRADIENT;
L2gradient = true;
}
if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7)))
CV_Error(CV_StsBadFlag, "");
if (low_thresh > high_thresh)
std::swap(low_thresh, high_thresh);
#ifdef HAVE_TEGRA_OPTIMIZATION
if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient))
return;
#endif
#ifdef USE_IPP_CANNY
if( aperture_size == 3 && !L2gradient &&
ippCanny(src, dst, (float)low_thresh, (float)high_thresh) )
return;
#endif
const int cn = src.channels();
Mat dx(src.rows, src.cols, CV_16SC(cn));
Mat dy(src.rows, src.cols, CV_16SC(cn));
Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE);
Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE);
if (L2gradient)
{
low_thresh = std::min(32767.0, low_thresh);
high_thresh = std::min(32767.0, high_thresh);
if (low_thresh > 0) low_thresh *= low_thresh;
if (high_thresh > 0) high_thresh *= high_thresh;
}
int low = cvFloor(low_thresh);
int high = cvFloor(high_thresh);
ptrdiff_t mapstep = src.cols + 2;
AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int));
int* mag_buf[3];
mag_buf[0] = (int*)(uchar*)buffer;
mag_buf[1] = mag_buf[0] + mapstep*cn;
mag_buf[2] = mag_buf[1] + mapstep*cn;
memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));
uchar* map = (uchar*)(mag_buf[2] + mapstep*cn);
memset(map, 1, mapstep);
memset(map + mapstep*(src.rows + 1), 1, mapstep);
int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
std::vector<uchar*> stack(maxsize);
uchar **stack_top = &stack[0];
uchar **stack_bottom = &stack[0];
/* sector numbers
(Top-Left Origin)
1 2 3
* * *
* * *
0*******0
* * *
* * *
3 2 1
*/
#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d) (d) = *--stack_top
// calculate magnitude and angle of gradient, perform non-maxima suppression.
// fill the map with one of the following values:
// 0 - the pixel might belong to an edge
// 1 - the pixel can not belong to an edge
// 2 - the pixel does belong to an edge
for (int i = 0; i <= src.rows; i++)
{
int* _norm = mag_buf[(i > 0) + 1] + 1;
if (i < src.rows)
{
short* _dx = dx.ptr<short>(i);
short* _dy = dy.ptr<short>(i);
if (!L2gradient)
{
for (int j = 0; j < src.cols*cn; j++)
_norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));
}
else
{
for (int j = 0; j < src.cols*cn; j++)
_norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
}
if (cn > 1)
{
for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn)
{
int maxIdx = jn;
for(int k = 1; k < cn; ++k)
if(_norm[jn + k] > _norm[maxIdx]) maxIdx = jn + k;
_norm[j] = _norm[maxIdx];
_dx[j] = _dx[maxIdx];
_dy[j] = _dy[maxIdx];
}
}
_norm[-1] = _norm[src.cols] = 0;
}
else
memset(_norm-1, 0, /* cn* */mapstep*sizeof(int));
// at the very beginning we do not have a complete ring
// buffer of 3 magnitude rows for non-maxima suppression
if (i == 0)
continue;
uchar* _map = map + mapstep*i + 1;
_map[-1] = _map[src.cols] = 1;
int* _mag = mag_buf[1] + 1; // take the central row
ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];
const short* _x = dx.ptr<short>(i-1);
const short* _y = dy.ptr<short>(i-1);
if ((stack_top - stack_bottom) + src.cols > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = maxsize * 3/2;
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
int prev_flag = 0;
for (int j = 0; j < src.cols; j++)
{
#define CANNY_SHIFT 15
const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5);
int m = _mag[j];
if (m > low)
{
int xs = _x[j];
int ys = _y[j];
int x = std::abs(xs);
int y = std::abs(ys) << CANNY_SHIFT;
int tg22x = x * TG22;
if (y < tg22x)
{
if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push;
}
else
{
int tg67x = tg22x + (x << (CANNY_SHIFT+1));
if (y > tg67x)
{
if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push;
}
else
{
int s = (xs ^ ys) < 0 ? -1 : 1;
if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push;
}
}
}
prev_flag = 0;
_map[j] = uchar(1);
continue;
__ocv_canny_push:
if (!prev_flag && m > high && _map[j-mapstep] != 2)
{
CANNY_PUSH(_map + j);
prev_flag = 1;
}
else
_map[j] = 0;
}
// scroll the ring buffer
_mag = mag_buf[0];
mag_buf[0] = mag_buf[1];
mag_buf[1] = mag_buf[2];
mag_buf[2] = _mag;
}
// now track the edges (hysteresis thresholding)
while (stack_top > stack_bottom)
{
uchar* m;
if ((stack_top - stack_bottom) + 8 > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = maxsize * 3/2;
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
CANNY_POP(m);
if (!m[-1]) CANNY_PUSH(m - 1);
if (!m[1]) CANNY_PUSH(m + 1);
if (!m[-mapstep-1]) CANNY_PUSH(m - mapstep - 1);
if (!m[-mapstep]) CANNY_PUSH(m - mapstep);
if (!m[-mapstep+1]) CANNY_PUSH(m - mapstep + 1);
if (!m[mapstep-1]) CANNY_PUSH(m + mapstep - 1);
if (!m[mapstep]) CANNY_PUSH(m + mapstep);
if (!m[mapstep+1]) CANNY_PUSH(m + mapstep + 1);
}
// the final pass, form the final image
const uchar* pmap = map + mapstep + 1;
uchar* pdst = dst.ptr();
for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
{
for (int j = 0; j < src.cols; j++)
pdst[j] = (uchar)-(pmap[j] >> 1);
}
}
void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
double threshold2, int aperture_size )
{
cv::Mat src = cv::cvarrToMat(image), dst = cv::cvarrToMat(edges);
CV_Assert( src.size == dst.size && src.depth() == CV_8U && dst.type() == CV_8U );
cv::Canny(src, dst, threshold1, threshold2, aperture_size & 255,
(aperture_size & CV_CANNY_L2_GRADIENT) != 0);
}
/* End of file. */
<commit_msg>fix potential buffer overflow as in 3.0<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
/*
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
#define USE_IPP_CANNY 1
#else
#undef USE_IPP_CANNY
#endif
*/
#ifdef USE_IPP_CANNY
namespace cv
{
static bool ippCanny(const Mat& _src, Mat& _dst, float low, float high)
{
int size = 0, size1 = 0;
IppiSize roi = { _src.cols, _src.rows };
ippiFilterSobelNegVertGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size);
ippiFilterSobelHorizGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size1);
size = std::max(size, size1);
ippiCannyGetSize(roi, &size1);
size = std::max(size, size1);
AutoBuffer<uchar> buf(size + 64);
uchar* buffer = alignPtr((uchar*)buf, 32);
Mat _dx(_src.rows, _src.cols, CV_16S);
if( ippiFilterSobelNegVertBorder_8u16s_C1R(_src.data, (int)_src.step,
_dx.ptr<short>(), (int)_dx.step, roi,
ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 )
return false;
Mat _dy(_src.rows, _src.cols, CV_16S);
if( ippiFilterSobelHorizBorder_8u16s_C1R(_src.data, (int)_src.step,
_dy.ptr<short>(), (int)_dy.step, roi,
ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 )
return false;
if( ippiCanny_16s8u_C1R(_dx.ptr<short>(), (int)_dx.step,
_dy.ptr<short>(), (int)_dy.step,
_dst.data, (int)_dst.step, roi, low, high, buffer) < 0 )
return false;
return true;
}
}
#endif
void cv::Canny( InputArray _src, OutputArray _dst,
double low_thresh, double high_thresh,
int aperture_size, bool L2gradient )
{
Mat src = _src.getMat();
CV_Assert( src.depth() == CV_8U );
_dst.create(src.size(), CV_8U);
Mat dst = _dst.getMat();
if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)
{
//backward compatibility
aperture_size &= ~CV_CANNY_L2_GRADIENT;
L2gradient = true;
}
if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7)))
CV_Error(CV_StsBadFlag, "");
if (low_thresh > high_thresh)
std::swap(low_thresh, high_thresh);
#ifdef HAVE_TEGRA_OPTIMIZATION
if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient))
return;
#endif
#ifdef USE_IPP_CANNY
if( aperture_size == 3 && !L2gradient &&
ippCanny(src, dst, (float)low_thresh, (float)high_thresh) )
return;
#endif
const int cn = src.channels();
Mat dx(src.rows, src.cols, CV_16SC(cn));
Mat dy(src.rows, src.cols, CV_16SC(cn));
Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE);
Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE);
if (L2gradient)
{
low_thresh = std::min(32767.0, low_thresh);
high_thresh = std::min(32767.0, high_thresh);
if (low_thresh > 0) low_thresh *= low_thresh;
if (high_thresh > 0) high_thresh *= high_thresh;
}
int low = cvFloor(low_thresh);
int high = cvFloor(high_thresh);
ptrdiff_t mapstep = src.cols + 2;
AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int));
int* mag_buf[3];
mag_buf[0] = (int*)(uchar*)buffer;
mag_buf[1] = mag_buf[0] + mapstep*cn;
mag_buf[2] = mag_buf[1] + mapstep*cn;
memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));
uchar* map = (uchar*)(mag_buf[2] + mapstep*cn);
memset(map, 1, mapstep);
memset(map + mapstep*(src.rows + 1), 1, mapstep);
int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
std::vector<uchar*> stack(maxsize);
uchar **stack_top = &stack[0];
uchar **stack_bottom = &stack[0];
/* sector numbers
(Top-Left Origin)
1 2 3
* * *
* * *
0*******0
* * *
* * *
3 2 1
*/
#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d) (d) = *--stack_top
// calculate magnitude and angle of gradient, perform non-maxima suppression.
// fill the map with one of the following values:
// 0 - the pixel might belong to an edge
// 1 - the pixel can not belong to an edge
// 2 - the pixel does belong to an edge
for (int i = 0; i <= src.rows; i++)
{
int* _norm = mag_buf[(i > 0) + 1] + 1;
if (i < src.rows)
{
short* _dx = dx.ptr<short>(i);
short* _dy = dy.ptr<short>(i);
if (!L2gradient)
{
for (int j = 0; j < src.cols*cn; j++)
_norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));
}
else
{
for (int j = 0; j < src.cols*cn; j++)
_norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
}
if (cn > 1)
{
for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn)
{
int maxIdx = jn;
for(int k = 1; k < cn; ++k)
if(_norm[jn + k] > _norm[maxIdx]) maxIdx = jn + k;
_norm[j] = _norm[maxIdx];
_dx[j] = _dx[maxIdx];
_dy[j] = _dy[maxIdx];
}
}
_norm[-1] = _norm[src.cols] = 0;
}
else
memset(_norm-1, 0, /* cn* */mapstep*sizeof(int));
// at the very beginning we do not have a complete ring
// buffer of 3 magnitude rows for non-maxima suppression
if (i == 0)
continue;
uchar* _map = map + mapstep*i + 1;
_map[-1] = _map[src.cols] = 1;
int* _mag = mag_buf[1] + 1; // take the central row
ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];
const short* _x = dx.ptr<short>(i-1);
const short* _y = dy.ptr<short>(i-1);
if ((stack_top - stack_bottom) + src.cols > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = std::max(sz + src.cols, maxsize * 3/2);
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
int prev_flag = 0;
for (int j = 0; j < src.cols; j++)
{
#define CANNY_SHIFT 15
const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5);
int m = _mag[j];
if (m > low)
{
int xs = _x[j];
int ys = _y[j];
int x = std::abs(xs);
int y = std::abs(ys) << CANNY_SHIFT;
int tg22x = x * TG22;
if (y < tg22x)
{
if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push;
}
else
{
int tg67x = tg22x + (x << (CANNY_SHIFT+1));
if (y > tg67x)
{
if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push;
}
else
{
int s = (xs ^ ys) < 0 ? -1 : 1;
if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push;
}
}
}
prev_flag = 0;
_map[j] = uchar(1);
continue;
__ocv_canny_push:
if (!prev_flag && m > high && _map[j-mapstep] != 2)
{
CANNY_PUSH(_map + j);
prev_flag = 1;
}
else
_map[j] = 0;
}
// scroll the ring buffer
_mag = mag_buf[0];
mag_buf[0] = mag_buf[1];
mag_buf[1] = mag_buf[2];
mag_buf[2] = _mag;
}
// now track the edges (hysteresis thresholding)
while (stack_top > stack_bottom)
{
uchar* m;
if ((stack_top - stack_bottom) + 8 > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = maxsize * 3/2;
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
CANNY_POP(m);
if (!m[-1]) CANNY_PUSH(m - 1);
if (!m[1]) CANNY_PUSH(m + 1);
if (!m[-mapstep-1]) CANNY_PUSH(m - mapstep - 1);
if (!m[-mapstep]) CANNY_PUSH(m - mapstep);
if (!m[-mapstep+1]) CANNY_PUSH(m - mapstep + 1);
if (!m[mapstep-1]) CANNY_PUSH(m + mapstep - 1);
if (!m[mapstep]) CANNY_PUSH(m + mapstep);
if (!m[mapstep+1]) CANNY_PUSH(m + mapstep + 1);
}
// the final pass, form the final image
const uchar* pmap = map + mapstep + 1;
uchar* pdst = dst.ptr();
for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
{
for (int j = 0; j < src.cols; j++)
pdst[j] = (uchar)-(pmap[j] >> 1);
}
}
void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
double threshold2, int aperture_size )
{
cv::Mat src = cv::cvarrToMat(image), dst = cv::cvarrToMat(edges);
CV_Assert( src.size == dst.size && src.depth() == CV_8U && dst.type() == CV_8U );
cv::Canny(src, dst, threshold1, threshold2, aperture_size & 255,
(aperture_size & CV_CANNY_L2_GRADIENT) != 0);
}
/* End of file. */
<|endoftext|> |
<commit_before>/*******************************************************************************
* Code contributed to the webinos project
*
* 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 2012 Torsec -Computer and network security group-
* Politecnico di Torino
*
******************************************************************************/
#include "TriggersSet.h"
TriggersSet::TriggersSet(TiXmlElement* triggersset){
// Trigger Tag
if(triggersset->FirstChild("TriggerAtTime")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerAtTime"); child;
child = (TiXmlElement*)child->NextSibling("TriggerAtTime") ) {
trigger["triggerID"] = "TriggerAtTime";
// read start parameter
TiXmlElement * start = (TiXmlElement*)child->FirstChild("Start");
if ((TiXmlElement*)start->FirstChild("StartNow"))
trigger["Start"]="StartNow";
if ((TiXmlElement*)start->FirstChild("DateAndTime"))
trigger["Start"]=((TiXmlElement*)start->FirstChild("DateAndTime"))->GetText();
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerPersonalDataAccessedForPurpose")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerPersonalDataAccessedForPurpose"); child;
child = (TiXmlElement*)child->NextSibling("TriggerPersonalDataAccessedForPurpose") ) {
trigger["triggerID"] = "TriggerPersonalDataAccessedForPurpose";
// read Purpose parameters
for(TiXmlElement * purpose = (TiXmlElement*)child->FirstChild("Purpose"); purpose;
purpose = (TiXmlElement*)child->NextSibling("Purpose") ) {
}
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerPersonalDataDeleted")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerPersonalDataDeleted"); child;
child = (TiXmlElement*)child->NextSibling("TriggerPersonalDataDeleted") ) {
trigger["triggerID"] = "TriggerPersonalDataDeleted";
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerDataSubjectAccess")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerDataSubjectAccess"); child;
child = (TiXmlElement*)child->NextSibling("TriggerDataSubjectAccess") ) {
trigger["triggerID"] = "TriggerDataSubjectAccess";
// read url parameter
trigger["url"] = ((TiXmlElement*)child->FirstChild("url"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
}
TriggersSet::~TriggersSet(){
}
bool TriggersSet::evaluate(vector< map<string, string> > triggers){
}
<commit_msg>Added Trigger Purposes reading<commit_after>/*******************************************************************************
* Code contributed to the webinos project
*
* 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 2012 Torsec -Computer and network security group-
* Politecnico di Torino
*
******************************************************************************/
#include "TriggersSet.h"
#include "AuthorizationsSet.h"
TriggersSet::TriggersSet(TiXmlElement* triggersset){
string p, purposes;
for(unsigned int i=0; i<PURPOSES_NUMBER; i++)
purposes.append("0");
// Trigger Tag
if(triggersset->FirstChild("TriggerAtTime")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerAtTime"); child;
child = (TiXmlElement*)child->NextSibling("TriggerAtTime") ) {
trigger["triggerID"] = "TriggerAtTime";
// read start parameter
TiXmlElement * start = (TiXmlElement*)child->FirstChild("Start");
if ((TiXmlElement*)start->FirstChild("StartNow"))
trigger["Start"]="StartNow";
if ((TiXmlElement*)start->FirstChild("DateAndTime"))
trigger["Start"]=((TiXmlElement*)start->FirstChild("DateAndTime"))->GetText();
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerPersonalDataAccessedForPurpose")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerPersonalDataAccessedForPurpose"); child;
child = (TiXmlElement*)child->NextSibling("TriggerPersonalDataAccessedForPurpose") ) {
trigger["triggerID"] = "TriggerPersonalDataAccessedForPurpose";
// read Purpose parameters
for(TiXmlElement * purpose = (TiXmlElement*)child->FirstChild("Purpose"); purpose;
purpose = (TiXmlElement*)child->NextSibling("Purpose") ) {
p = ((TiXmlElement*)child->FirstChild("Purpose"))->GetText();
for(unsigned int i = 0; i<PURPOSES_NUMBER; i++){
if (p.compare(ontology_vector[i]) == 0)
purposes[i]='1';
}
}
trigger["Purpose"]=purposes;
for(unsigned int i=0; i<PURPOSES_NUMBER; i++)
purposes[i]='0';
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerPersonalDataDeleted")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerPersonalDataDeleted"); child;
child = (TiXmlElement*)child->NextSibling("TriggerPersonalDataDeleted") ) {
trigger["triggerID"] = "TriggerPersonalDataDeleted";
// read MaxDelay parameter
TiXmlElement * maxdelay = (TiXmlElement*)child->FirstChild("MaxDelay");
trigger["MaxDelay"]=((TiXmlElement*)maxdelay->FirstChild("Duration"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
if(triggersset->FirstChild("TriggerDataSubjectAccess")){
for(TiXmlElement * child = (TiXmlElement*)triggersset->FirstChild("TriggerDataSubjectAccess"); child;
child = (TiXmlElement*)child->NextSibling("TriggerDataSubjectAccess") ) {
trigger["triggerID"] = "TriggerDataSubjectAccess";
// read url parameter
trigger["url"] = ((TiXmlElement*)child->FirstChild("url"))->GetText();
triggers.push_back(trigger);
trigger.clear();
}
}
}
TriggersSet::~TriggersSet(){
}
bool TriggersSet::evaluate(vector< map<string, string> > triggers){
}
<|endoftext|> |
<commit_before>/*
* NotebookQueue.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookQueue.hpp"
#include "NotebookQueueUnit.hpp"
#include "NotebookExec.hpp"
#include "NotebookDocQueue.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include "../../SessionClientEventService.hpp"
#include <boost/foreach.hpp>
#include <r/RInterface.hpp>
#include <r/RExec.hpp>
#include <core/Exec.hpp>
#include <core/Thread.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionClientEvent.hpp>
#include <session/http/SessionRequest.hpp>
#define kThreadQuitCommand "thread_quit"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
enum ChunkExecState
{
ChunkExecStarted = 0,
ChunkExecFinished = 1,
ChunkExecCancelled = 2
};
// represents the global queue of work
class NotebookQueue
{
public:
NotebookQueue()
{
// launch a thread to process console input
pInput_ =
boost::make_shared<core::thread::ThreadsafeQueue<std::string> >();
thread::safeLaunchThread(boost::bind(
&NotebookQueue::consoleThreadMain, this), &console_);
// register handler for chunk exec complete
handlers_.push_back(events().onChunkExecCompleted.connect(
boost::bind(&NotebookQueue::onChunkExecCompleted, this, _1, _2, _3)));
}
~NotebookQueue()
{
// let thread clean up asynchronously
pInput_->enque(kThreadQuitCommand);
// unregister handlers
BOOST_FOREACH(boost::signals::connection connection, handlers_)
{
connection.disconnect();
}
}
bool complete()
{
return queue_.empty();
}
Error process(ExpressionMode mode)
{
// if list is empty, we're done
if (queue_.empty())
return Success();
// defer if R is currently executing code (we'll initiate processing when
// the console continues)
if (r::getGlobalContext()->nextcontext != NULL)
return Success();
// if we have a currently executing unit, execute it; otherwise, pop the
// next unit off the stack
if (execUnit_)
{
if (execContext_ && execContext_->hasErrors())
{
// when an error occurs, see what the chunk options say; if they
// have error = TRUE we can keep going, but in all other
// circumstances we should stop right away
const json::Object& options = execContext_->options();
bool error = false;
json::readObject(options, "error", &error);
if (!error)
{
clear();
return Success();
}
}
if (execUnit_->complete())
{
bool incomplete = false;
// if we're still in continuation mode but we're at the end of the
// chunk, generate an error
if (mode == ExprModeContinuation &&
execUnit_->execScope() == ExecScopeChunk)
{
incomplete = true;
sendIncompleteError(execUnit_);
}
// unit has finished executing; remove it from the queue
popUnit(execUnit_);
// notify client
enqueueExecStateChanged(ChunkExecFinished, execContext_->options());
// clean up current exec unit
execContext_->disconnect();
execContext_.reset();
execUnit_.reset();
// if the unit was incomplete, we need to wait for the interrupt
// to complete before we execute more code
if (incomplete)
return Success();
}
else
return executeCurrentUnit(mode);
}
return executeNextUnit(mode);
}
Error update(boost::shared_ptr<NotebookQueueUnit> pUnit, QueueOperation op,
const std::string& before)
{
// find the document queue corresponding to this unit
BOOST_FOREACH(const boost::shared_ptr<NotebookDocQueue> queue, queue_)
{
if (queue->docId() == pUnit->docId())
{
queue->update(pUnit, op, before);
break;
}
}
return Success();
}
void add(boost::shared_ptr<NotebookDocQueue> pQueue)
{
queue_.push_back(pQueue);
}
void clear()
{
// clean up any active execution context
if (execContext_)
execContext_->disconnect();
// remove all document queues
queue_.clear();
}
json::Value getDocQueue(const std::string& docId)
{
BOOST_FOREACH(boost::shared_ptr<NotebookDocQueue> pQueue, queue_)
{
if (pQueue->docId() == docId)
return pQueue->toJson();
}
return json::Value();
}
void onConsolePrompt(const std::string& prompt)
{
if (prompt == "+ ")
process(ExprModeContinuation);
else
process(ExprModeNew);
}
private:
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId)
{
if (!execUnit_)
return;
// if this is the currently executing chunk but it doesn't have an R
// execution context, it must be executing with an alternate engine;
// this event signals that the alternate engine is finished, so move to
// the next document in the queue
if (execUnit_->docId() == docId && execUnit_->chunkId() == chunkId &&
!execContext_)
{
// remove from the queue
popUnit(execUnit_);
// signal client
enqueueExecStateChanged(ChunkExecFinished, json::Object());
// execute the next chunk, if any
execUnit_.reset();
process(ExprModeNew);
}
}
// execute the next line or expression in the current execution unit
Error executeCurrentUnit(ExpressionMode mode)
{
// ensure we have a unit to execute
if (!execUnit_)
return Success();
// if this isn't the continuation of an expression, perform any
// post-expression operations
if (mode == ExprModeNew && execContext_)
execContext_->onExprComplete();
ExecRange range;
std::string code = execUnit_->popExecRange(&range, mode);
sendConsoleInput(execUnit_->chunkId(), code);
// let client know the range has been sent to R
json::Object exec;
exec["doc_id"] = execUnit_->docId();
exec["chunk_id"] = execUnit_->chunkId();
exec["exec_range"] = range.toJson();
exec["expr_mode"] = mode;
exec["code"] = code;
module_context::enqueClientEvent(
ClientEvent(client_events::kNotebookRangeExecuted, exec));
return Success();
}
void sendConsoleInput(const std::string& chunkId, const json::Value& input)
{
json::Array arr;
ExecRange range(0, 0);
arr.push_back(input);
arr.push_back(chunkId);
// formulate request body
json::Object rpc;
rpc["method"] = "console_input";
rpc["params"] = arr;
rpc["clientId"] = clientEventService().clientId();
// serialize RPC body and send it to helper thread for submission
std::ostringstream oss;
json::write(rpc, oss);
pInput_->enque(oss.str());
}
Error executeNextUnit(ExpressionMode mode)
{
// no work to do if we have no documents
if (queue_.empty())
return Success();
// get the next execution unit from the current queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
// establish execution context for the unit
json::Object options;
Error error = unit->parseOptions(&options);
if (error)
return error;
// in batch mode, make sure unit should be evaluated -- note that
// eval=FALSE units generally do not get sent up in the first place, so
// if we're here it's because the unit has eval=<expr>
if (unit->execMode() == ExecModeBatch)
{
bool eval = true;
json::readObject(options, "eval", &eval);
if (!eval)
return skipUnit();
}
// compute context
std::string ctx = docQueue->commitMode() == ModeCommitted ?
kSavedCtx : notebookCtxId();
// compute engine
std::string engine = "r";
json::readObject(options, "engine", &engine);
if (engine == "r")
{
execContext_ = boost::make_shared<ChunkExecContext>(
unit->docId(), unit->chunkId(), ctx, unit->execScope(), options,
docQueue->pixelWidth(), docQueue->charWidth());
execContext_->connect();
}
else
{
// execute with alternate engine
std::string innerCode;
error = unit->innerCode(&innerCode);
if (error)
{
LOG_ERROR(error);
}
else
{
error = executeAlternateEngineChunk(
unit->docId(), unit->chunkId(), ctx, engine, innerCode, options);
if (error)
LOG_ERROR(error);
}
}
// if there was an error, skip the chunk
if (error)
return skipUnit();
// notify client
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecStarted, options);
if (engine == "r")
executeCurrentUnit(ExprModeNew);
return Success();
}
// main function for thread which receives console input
void consoleThreadMain()
{
// create our own reference to the threadsafe queue (this prevents it
// from getting cleaned up when the parent detaches)
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput =
pInput_;
std::string input;
while (pInput->deque(&input, boost::posix_time::not_a_date_time))
{
// if we were asked to quit, stop processing now
if (input == kThreadQuitCommand)
return;
// loop back console input request to session -- this allows us to treat
// notebook console input exactly as user console input
core::http::Response response;
Error error = session::http::sendSessionRequest(
"/rpc/console_input", input, &response);
if (error)
LOG_ERROR(error);
}
}
void enqueueExecStateChanged(ChunkExecState state,
const json::Object& options)
{
json::Object event;
event["doc_id"] = execUnit_->docId();
event["chunk_id"] = execUnit_->chunkId();
event["exec_state"] = state;
event["options"] = options;
module_context::enqueClientEvent(ClientEvent(
client_events::kChunkExecStateChanged, event));
}
Error skipUnit()
{
if (queue_.empty())
return Success();
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
popUnit(unit);
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecCancelled, json::Object());
return executeNextUnit(ExprModeNew);
}
void popUnit(boost::shared_ptr<NotebookQueueUnit> pUnit)
{
if (queue_.empty())
return;
// remove this unit from the queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
docQueue->update(pUnit, QueueDelete, "");
// advance if queue is complete
if (docQueue->complete())
queue_.pop_front();
}
void sendIncompleteError(boost::shared_ptr<NotebookQueueUnit> unit)
{
// raise an error
r::exec::error("Incomplete expression: " + unit->executingCode());
// send an interrupt to the console to abort the unterminated
// expression
sendConsoleInput(execUnit_->chunkId(), json::Value());
}
// the documents with active queues
std::list<boost::shared_ptr<NotebookDocQueue> > queue_;
// the execution context for the currently executing chunk
boost::shared_ptr<NotebookQueueUnit> execUnit_;
boost::shared_ptr<ChunkExecContext> execContext_;
// registered signal handlers
std::vector<boost::signals::connection> handlers_;
// the thread which submits console input, and the queue which feeds it
boost::thread console_;
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput_;
};
static boost::shared_ptr<NotebookQueue> s_queue;
Error updateExecQueue(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object unitJson;
int op = 0;
std::string before;
Error error = json::readParams(request.params, &unitJson, &op, &before);
if (error)
return error;
boost::shared_ptr<NotebookQueueUnit> pUnit =
boost::make_shared<NotebookQueueUnit>();
error = NotebookQueueUnit::fromJson(unitJson, &pUnit);
if (error)
return error;
if (!s_queue)
return Success();
return s_queue->update(pUnit, static_cast<QueueOperation>(op), before);
}
Error executeNotebookChunks(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object docObj;
Error error = json::readParams(request.params, &docObj);
boost::shared_ptr<NotebookDocQueue> pQueue =
boost::make_shared<NotebookDocQueue>();
error = NotebookDocQueue::fromJson(docObj, &pQueue);
if (error)
return error;
// create queue if it doesn't exist
if (!s_queue)
s_queue = boost::make_shared<NotebookQueue>();
// add the queue and process immediately
s_queue->add(pQueue);
s_queue->process(ExprModeNew);
return Success();
}
void onConsolePrompt(const std::string& prompt)
{
if (s_queue)
{
s_queue->onConsolePrompt(prompt);
}
// clean up queue if it's finished executing
if (s_queue && s_queue->complete())
{
s_queue.reset();
}
}
void onUserInterrupt()
{
if (s_queue)
{
s_queue->clear();
s_queue.reset();
}
}
} // anonymous namespace
json::Value getDocQueue(const std::string& docId)
{
if (!s_queue)
return json::Value();
return s_queue->getDocQueue(docId);
}
Error initQueue()
{
using boost::bind;
using namespace module_context;
module_context::events().onConsolePrompt.connect(onConsolePrompt);
module_context::events().onUserInterrupt.connect(onUserInterrupt);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "update_notebook_exec_queue", updateExecQueue))
(bind(registerRpcMethod, "execute_notebook_chunks", executeNotebookChunks));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>improve chain execution of chunks w/ alternate engines; more logging<commit_after>/*
* NotebookQueue.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookQueue.hpp"
#include "NotebookQueueUnit.hpp"
#include "NotebookExec.hpp"
#include "NotebookDocQueue.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include "../../SessionClientEventService.hpp"
#include <boost/foreach.hpp>
#include <r/RInterface.hpp>
#include <r/RExec.hpp>
#include <core/Exec.hpp>
#include <core/Thread.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionClientEvent.hpp>
#include <session/http/SessionRequest.hpp>
#define kThreadQuitCommand "thread_quit"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
enum ChunkExecState
{
ChunkExecStarted = 0,
ChunkExecFinished = 1,
ChunkExecCancelled = 2
};
// represents the global queue of work
class NotebookQueue
{
public:
NotebookQueue()
{
// launch a thread to process console input
pInput_ =
boost::make_shared<core::thread::ThreadsafeQueue<std::string> >();
thread::safeLaunchThread(boost::bind(
&NotebookQueue::consoleThreadMain, this), &console_);
// register handler for chunk exec complete
handlers_.push_back(events().onChunkExecCompleted.connect(
boost::bind(&NotebookQueue::onChunkExecCompleted, this, _1, _2, _3)));
}
~NotebookQueue()
{
// let thread clean up asynchronously
pInput_->enque(kThreadQuitCommand);
// unregister handlers
BOOST_FOREACH(boost::signals::connection connection, handlers_)
{
connection.disconnect();
}
}
bool complete()
{
return queue_.empty();
}
Error process(ExpressionMode mode)
{
// if list is empty, we're done
if (queue_.empty())
return Success();
// defer if R is currently executing code (we'll initiate processing when
// the console continues)
if (r::getGlobalContext()->nextcontext != NULL)
return Success();
// if we have a currently executing unit, execute it; otherwise, pop the
// next unit off the stack
if (execUnit_)
{
if (execContext_ && execContext_->hasErrors())
{
// when an error occurs, see what the chunk options say; if they
// have error = TRUE we can keep going, but in all other
// circumstances we should stop right away
const json::Object& options = execContext_->options();
bool error = false;
json::readObject(options, "error", &error);
if (!error)
{
clear();
return Success();
}
}
if (execUnit_->complete())
{
bool incomplete = false;
// if we're still in continuation mode but we're at the end of the
// chunk, generate an error
if (mode == ExprModeContinuation &&
execUnit_->execScope() == ExecScopeChunk)
{
incomplete = true;
sendIncompleteError(execUnit_);
}
// unit has finished executing; remove it from the queue
popUnit(execUnit_);
// notify client
enqueueExecStateChanged(ChunkExecFinished, execContext_ ?
execContext_->options() : json::Object());
// clean up current exec unit
if (execContext_)
{
execContext_->disconnect();
execContext_.reset();
}
execUnit_.reset();
// if the unit was incomplete, we need to wait for the interrupt
// to complete before we execute more code
if (incomplete)
return Success();
}
else
return executeCurrentUnit(mode);
}
return executeNextUnit(mode);
}
Error update(boost::shared_ptr<NotebookQueueUnit> pUnit, QueueOperation op,
const std::string& before)
{
// find the document queue corresponding to this unit
BOOST_FOREACH(const boost::shared_ptr<NotebookDocQueue> queue, queue_)
{
if (queue->docId() == pUnit->docId())
{
queue->update(pUnit, op, before);
break;
}
}
return Success();
}
void add(boost::shared_ptr<NotebookDocQueue> pQueue)
{
queue_.push_back(pQueue);
}
void clear()
{
// clean up any active execution context
if (execContext_)
execContext_->disconnect();
if (execUnit_)
execUnit_.reset();
// remove all document queues
queue_.clear();
}
json::Value getDocQueue(const std::string& docId)
{
BOOST_FOREACH(boost::shared_ptr<NotebookDocQueue> pQueue, queue_)
{
if (pQueue->docId() == docId)
return pQueue->toJson();
}
return json::Value();
}
void onConsolePrompt(const std::string& prompt)
{
Error error = process(prompt == "+ " ? ExprModeContinuation :
ExprModeNew);
if (error)
LOG_ERROR(error);
}
private:
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId)
{
if (!execUnit_)
return;
// if this is the currently executing chunk but it doesn't have an R
// execution context, it must be executing with an alternate engine;
// this event signals that the alternate engine is finished, so move to
// the next document in the queue
if (execUnit_->docId() == docId && execUnit_->chunkId() == chunkId &&
!execContext_)
{
// remove from the queue
popUnit(execUnit_);
// signal client
enqueueExecStateChanged(ChunkExecFinished, json::Object());
// execute the next chunk, if any
execUnit_.reset();
process(ExprModeNew);
}
}
// execute the next line or expression in the current execution unit
Error executeCurrentUnit(ExpressionMode mode)
{
// ensure we have a unit to execute
if (!execUnit_)
return Success();
// if this isn't the continuation of an expression, perform any
// post-expression operations
if (mode == ExprModeNew && execContext_)
execContext_->onExprComplete();
ExecRange range;
std::string code = execUnit_->popExecRange(&range, mode);
sendConsoleInput(execUnit_->chunkId(), code);
// let client know the range has been sent to R
json::Object exec;
exec["doc_id"] = execUnit_->docId();
exec["chunk_id"] = execUnit_->chunkId();
exec["exec_range"] = range.toJson();
exec["expr_mode"] = mode;
exec["code"] = code;
module_context::enqueClientEvent(
ClientEvent(client_events::kNotebookRangeExecuted, exec));
return Success();
}
void sendConsoleInput(const std::string& chunkId, const json::Value& input)
{
json::Array arr;
ExecRange range(0, 0);
arr.push_back(input);
arr.push_back(chunkId);
// formulate request body
json::Object rpc;
rpc["method"] = "console_input";
rpc["params"] = arr;
rpc["clientId"] = clientEventService().clientId();
// serialize RPC body and send it to helper thread for submission
std::ostringstream oss;
json::write(rpc, oss);
pInput_->enque(oss.str());
}
Error executeNextUnit(ExpressionMode mode)
{
// no work to do if we have no documents
if (queue_.empty())
return Success();
// get the next execution unit from the current queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
// establish execution context for the unit
json::Object options;
Error error = unit->parseOptions(&options);
if (error)
LOG_ERROR(error);
// in batch mode, make sure unit should be evaluated -- note that
// eval=FALSE units generally do not get sent up in the first place, so
// if we're here it's because the unit has eval=<expr>
if (unit->execMode() == ExecModeBatch)
{
bool eval = true;
json::readObject(options, "eval", &eval);
if (!eval)
{
return skipUnit();
}
}
// compute context
std::string ctx = docQueue->commitMode() == ModeCommitted ?
kSavedCtx : notebookCtxId();
// compute engine
std::string engine = "r";
json::readObject(options, "engine", &engine);
if (engine == "r")
{
execContext_ = boost::make_shared<ChunkExecContext>(
unit->docId(), unit->chunkId(), ctx, unit->execScope(), options,
docQueue->pixelWidth(), docQueue->charWidth());
execContext_->connect();
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecStarted, options);
}
else
{
// execute with alternate engine
std::string innerCode;
error = unit->innerCode(&innerCode);
if (error)
{
LOG_ERROR(error);
}
else
{
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecStarted, options);
error = executeAlternateEngineChunk(
unit->docId(), unit->chunkId(), ctx, engine, innerCode, options);
if (error)
LOG_ERROR(error);
}
}
// if there was an error, skip the chunk
if (error)
return skipUnit();
if (engine == "r")
{
error = executeCurrentUnit(ExprModeNew);
if (error)
LOG_ERROR(error);
}
return Success();
}
// main function for thread which receives console input
void consoleThreadMain()
{
// create our own reference to the threadsafe queue (this prevents it
// from getting cleaned up when the parent detaches)
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput =
pInput_;
std::string input;
while (pInput->deque(&input, boost::posix_time::not_a_date_time))
{
// if we were asked to quit, stop processing now
if (input == kThreadQuitCommand)
return;
// loop back console input request to session -- this allows us to treat
// notebook console input exactly as user console input
core::http::Response response;
Error error = session::http::sendSessionRequest(
"/rpc/console_input", input, &response);
if (error)
LOG_ERROR(error);
}
}
void enqueueExecStateChanged(ChunkExecState state,
const json::Object& options)
{
json::Object event;
event["doc_id"] = execUnit_->docId();
event["chunk_id"] = execUnit_->chunkId();
event["exec_state"] = state;
event["options"] = options;
module_context::enqueClientEvent(ClientEvent(
client_events::kChunkExecStateChanged, event));
}
Error skipUnit()
{
if (queue_.empty())
return Success();
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
popUnit(unit);
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecCancelled, json::Object());
return executeNextUnit(ExprModeNew);
}
void popUnit(boost::shared_ptr<NotebookQueueUnit> pUnit)
{
if (queue_.empty())
return;
// remove this unit from the queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
docQueue->update(pUnit, QueueDelete, "");
// advance if queue is complete
if (docQueue->complete())
queue_.pop_front();
}
void sendIncompleteError(boost::shared_ptr<NotebookQueueUnit> unit)
{
// raise an error
r::exec::error("Incomplete expression: " + unit->executingCode());
// send an interrupt to the console to abort the unterminated
// expression
sendConsoleInput(execUnit_->chunkId(), json::Value());
}
// the documents with active queues
std::list<boost::shared_ptr<NotebookDocQueue> > queue_;
// the execution context for the currently executing chunk
boost::shared_ptr<NotebookQueueUnit> execUnit_;
boost::shared_ptr<ChunkExecContext> execContext_;
// registered signal handlers
std::vector<boost::signals::connection> handlers_;
// the thread which submits console input, and the queue which feeds it
boost::thread console_;
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput_;
};
static boost::shared_ptr<NotebookQueue> s_queue;
Error updateExecQueue(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object unitJson;
int op = 0;
std::string before;
Error error = json::readParams(request.params, &unitJson, &op, &before);
if (error)
return error;
boost::shared_ptr<NotebookQueueUnit> pUnit =
boost::make_shared<NotebookQueueUnit>();
error = NotebookQueueUnit::fromJson(unitJson, &pUnit);
if (error)
return error;
if (!s_queue)
return Success();
return s_queue->update(pUnit, static_cast<QueueOperation>(op), before);
}
Error executeNotebookChunks(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object docObj;
Error error = json::readParams(request.params, &docObj);
boost::shared_ptr<NotebookDocQueue> pQueue =
boost::make_shared<NotebookDocQueue>();
error = NotebookDocQueue::fromJson(docObj, &pQueue);
if (error)
return error;
// create queue if it doesn't exist
if (!s_queue)
s_queue = boost::make_shared<NotebookQueue>();
// add the queue and process immediately
s_queue->add(pQueue);
s_queue->process(ExprModeNew);
return Success();
}
void onConsolePrompt(const std::string& prompt)
{
if (s_queue)
{
s_queue->onConsolePrompt(prompt);
}
// clean up queue if it's finished executing
if (s_queue && s_queue->complete())
{
s_queue.reset();
}
}
void onUserInterrupt()
{
if (s_queue)
{
s_queue->clear();
s_queue.reset();
}
}
} // anonymous namespace
json::Value getDocQueue(const std::string& docId)
{
if (!s_queue)
return json::Value();
return s_queue->getDocQueue(docId);
}
Error initQueue()
{
using boost::bind;
using namespace module_context;
module_context::events().onConsolePrompt.connect(onConsolePrompt);
module_context::events().onUserInterrupt.connect(onUserInterrupt);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "update_notebook_exec_queue", updateExecQueue))
(bind(registerRpcMethod, "execute_notebook_chunks", executeNotebookChunks));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>//
// Copyright (c) 2016 CNRS
// Author: Florent Lamiraux
//
// This file is part of Pinocchio
// Pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
/** \page pinocchio_page_loading Loading a model
\section pinocchio_page_loading_introduction Introduction
The most convenient way to build a robot model consists in parsing a description
file.
\section pinocchio_page_loading_supported_formats Supported formats
Two format are supported.
\subsection pinocchio_page_loading_urdf Format urdf
To load an urdf file in C++ code, copy the following lines:
\code
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/multibody/parser/urdf.hpp>
#include <pinocchio/multibody/parser/utils.hpp>
bool verbose = false;
se3::Model model = se3::urdf::buildModel (filename, verbose);
\endcode
\subsection pinocchio_page_loading_lua Format lua
To load an lua file in C++ code, copy the following lines:
\code
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/multibody/parser/lua.hpp>
#include <pinocchio/multibody/parser/utils.hpp>
bool verbose = false;
se3::Model model = se3::lua::buildModel (filename, false, verbose);
\endcode
*/
<commit_msg>Enhance documentation<commit_after>//
// Copyright (c) 2016 CNRS
// Author: Florent Lamiraux
//
// This file is part of Pinocchio
// Pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
/** \page pinocchio_page_loading Loading a model
\section pinocchio_page_loading_introduction Introduction
The most convenient way to build a robot model consists in parsing a description
file.
\section pinocchio_page_loading_supported_formats Supported formats
Two format are supported.
\subsection pinocchio_page_loading_urdf Format urdf
To load an urdf file in C++ code, copy the following lines:
\code
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/multibody/parser/urdf.hpp>
#include <pinocchio/multibody/parser/utils.hpp>
#include <pinocchio/multibody/joint.hpp>
bool verbose = false;
se3::JointModelFreeflyer rootJoint;
se3::Model model = se3::urdf::buildModel (filename, rootJoint, verbose);
se3::Data data (model);
\endcode
\subsection pinocchio_page_loading_lua Format lua
To load an lua file in C++ code, copy the following lines:
\code
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/multibody/parser/lua.hpp>
#include <pinocchio/multibody/parser/utils.hpp>
#include <pinocchio/multibody/joint.hpp>
bool freeflyer = true;
se3::Model model = se3::lua::buildModel (filename, freeflyer);
se3::Data data (model);
\endcode
*/
<|endoftext|> |
<commit_before>#include "SmashcastClient.h"
#include "Curl.h"
#include "JSON.h"
namespace rustla2 {
namespace smashcast {
rapidjson::Document ChannelResult::GetSchema() {
rapidjson::Document schema;
schema.Parse(R"json(
{
"type": "object",
"properties": {
"livestream": {
"type": "array",
"items": {
"type": "object",
"properties": {
"media_title": {"type": "string"},
"media_is_live": {"type": "string"},
"media_thumbnail": {"type": "string"},
"media_views": {
"type": "string",
"pattern": "^[0-9]+$"
}
},
"required": [
"media_title",
"media_is_live",
"media_thumbnail",
"media_views"
]
},
"minItems": 1
}
},
"required": ["livestream"]
}
)json");
return schema;
}
std::string ChannelResult::GetTitle() const {
return json::StringRef(GetLivestream()["media_title"]);
}
bool ChannelResult::GetLive() const {
return json::StringRef(GetLivestream()["media_is_live"]) == "1";
}
std::string ChannelResult::GetThumbnail() const {
return "https://edge.sf.hitbox.tv" +
std::string(json::StringRef(GetLivestream()["media_thumbnail"]));
}
uint64_t ChannelResult::GetViewers() const {
return std::stoull(
std::string(json::StringRef(GetLivestream()["media_views"])));
}
const rapidjson::Value& ChannelResult::GetLivestream() const {
return GetData()["livestream"][0];
}
Status Client::GetChannelByName(const std::string& name,
ChannelResult* result) {
CurlRequest req("https://api.smashcast.tv/media/live/" + name);
req.Submit();
if (!req.Ok()) {
return Status(StatusCode::HTTP_ERROR, req.GetErrorMessage());
}
if (req.GetResponseCode() != 200) {
return Status(
StatusCode::API_ERROR, "received non 200 response",
"api returned status code " + std::to_string(req.GetResponseCode()));
}
const auto& response = req.GetResponse();
return result->SetData(response.c_str(), response.size());
}
} // namespace smashcast
} // namespace rustla2
<commit_msg>fix smashcast title<commit_after>#include "SmashcastClient.h"
#include "Curl.h"
#include "JSON.h"
namespace rustla2 {
namespace smashcast {
rapidjson::Document ChannelResult::GetSchema() {
rapidjson::Document schema;
schema.Parse(R"json(
{
"type": "object",
"properties": {
"livestream": {
"type": "array",
"items": {
"type": "object",
"properties": {
"media_status": {"type": "string"},
"media_is_live": {"type": "string"},
"media_thumbnail": {"type": "string"},
"media_views": {
"type": "string",
"pattern": "^[0-9]+$"
}
},
"required": [
"media_status",
"media_is_live",
"media_thumbnail",
"media_views"
]
},
"minItems": 1
}
},
"required": ["livestream"]
}
)json");
return schema;
}
std::string ChannelResult::GetTitle() const {
return json::StringRef(GetLivestream()["media_status"]);
}
bool ChannelResult::GetLive() const {
return json::StringRef(GetLivestream()["media_is_live"]) == "1";
}
std::string ChannelResult::GetThumbnail() const {
return "https://edge.sf.hitbox.tv" +
std::string(json::StringRef(GetLivestream()["media_thumbnail"]));
}
uint64_t ChannelResult::GetViewers() const {
return std::stoull(
std::string(json::StringRef(GetLivestream()["media_views"])));
}
const rapidjson::Value& ChannelResult::GetLivestream() const {
return GetData()["livestream"][0];
}
Status Client::GetChannelByName(const std::string& name,
ChannelResult* result) {
CurlRequest req("https://api.smashcast.tv/media/live/" + name);
req.Submit();
if (!req.Ok()) {
return Status(StatusCode::HTTP_ERROR, req.GetErrorMessage());
}
if (req.GetResponseCode() != 200) {
return Status(
StatusCode::API_ERROR, "received non 200 response",
"api returned status code " + std::to_string(req.GetResponseCode()));
}
const auto& response = req.GetResponse();
return result->SetData(response.c_str(), response.size());
}
} // namespace smashcast
} // namespace rustla2
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2012 Jose Fonseca
* All Rights Reserved.
*
* 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 <string.h>
#include <limits.h> // for CHAR_MAX
#include <getopt.h>
#include "pickle.hpp"
#include "os_binary.hpp"
#include "cli.hpp"
#include "cli_pager.hpp"
#include "trace_parser.hpp"
#include "trace_model.hpp"
#include "trace_callset.hpp"
using namespace trace;
class PickleVisitor : public trace::Visitor
{
protected:
PickleWriter &writer;
bool symbolic;
public:
PickleVisitor(PickleWriter &_writer, bool _symbolic) :
writer(_writer),
symbolic(_symbolic) {
}
void visit(Null *node) {
writer.writeInt(0);
}
void visit(Bool *node) {
writer.writeBool(node->value);
}
void visit(SInt *node) {
writer.writeInt(node->value);
}
void visit(UInt *node) {
writer.writeInt(node->value);
}
void visit(Float *node) {
writer.writeFloat(node->value);
}
void visit(Double *node) {
writer.writeFloat(node->value);
}
void visit(String *node) {
writer.writeString(node->value);
}
void visit(Enum *node) {
if (symbolic) {
const EnumValue *it = node->lookup();
if (it) {
writer.writeString(it->name);
return;
}
}
writer.writeInt(node->value);
}
void visit(Bitmask *node) {
if (symbolic) {
unsigned long long value = node->value;
const BitmaskSig *sig = node->sig;
writer.beginList();
for (const BitmaskFlag *it = sig->flags; it != sig->flags + sig->num_flags; ++it) {
if ((it->value && (value & it->value) == it->value) ||
(!it->value && value == 0)) {
writer.writeString(it->name);
value &= ~it->value;
}
if (value == 0) {
break;
}
}
if (value) {
writer.writeInt(value);
}
writer.endList();
} else {
writer.writeInt(node->value);
}
}
void visit(Struct *node) {
if (false) {
writer.beginDict();
for (unsigned i = 0; i < node->sig->num_members; ++i) {
writer.beginItem(node->sig->member_names[i]);
_visit(node->members[i]);
writer.endItem();
}
writer.endDict();
} else {
writer.beginTuple();
for (unsigned i = 0; i < node->sig->num_members; ++i) {
_visit(node->members[i]);
}
writer.endTuple();
}
}
void visit(Array *node) {
writer.beginList();
for (std::vector<Value *>::iterator it = node->values.begin(); it != node->values.end(); ++it) {
_visit(*it);
}
writer.endList();
}
void visit(Blob *node) {
writer.writeByteArray(node->buf, node->size);
}
void visit(Pointer *node) {
writer.writeInt(node->value);
}
void visit(Call *call) {
writer.beginTuple();
writer.writeInt(call->no);
writer.writeString(call->name());
writer.beginList();
for (unsigned i = 0; i < call->args.size(); ++i) {
if (call->args[i].value) {
_visit(call->args[i].value);
} else {
writer.writeNone();
}
}
writer.endList();
if (call->ret) {
_visit(call->ret);
} else {
writer.writeNone();
}
writer.endTuple();
}
};
static trace::CallSet calls(trace::FREQUENCY_ALL);
static const char *synopsis = "Pickle given trace(s) to standard output.";
static void
usage(void)
{
std::cout
<< "usage: apitrace pickle [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help show this help message and exit\n"
" -s, --symbolic dump symbolic names\n"
" --calls=CALLSET only dump specified calls\n"
;
}
enum {
CALLS_OPT = CHAR_MAX + 1,
};
const static char *
shortOptions = "hs";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"symbolic", no_argument, 0, 's'},
{"calls", required_argument, 0, CALLS_OPT},
{0, 0, 0, 0}
};
static int
command(int argc, char *argv[])
{
bool symbolic;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 's':
symbolic = true;
break;
case CALLS_OPT:
calls = trace::CallSet(optarg);
break;
default:
std::cerr << "error: unexpected option `" << opt << "`\n";
usage();
return 1;
}
}
os::setBinaryMode(stdout);
std::cout.sync_with_stdio(false);
PickleWriter writer(std::cout);
PickleVisitor visitor(writer, symbolic);
for (int i = optind; i < argc; ++i) {
trace::Parser parser;
if (!parser.open(argv[i])) {
std::cerr << "error: failed to open " << argv[i] << "\n";
return 1;
}
trace::Call *call;
while ((call = parser.parse_call())) {
if (calls.contains(*call)) {
writer.begin();
visitor.visit(call);
writer.end();
}
delete call;
}
}
return 0;
}
const Command pickle_command = {
"pickle",
synopsis,
usage,
command
};
<commit_msg>Pickle Repr nodes too.<commit_after>/**************************************************************************
*
* Copyright 2012 Jose Fonseca
* All Rights Reserved.
*
* 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 <string.h>
#include <limits.h> // for CHAR_MAX
#include <getopt.h>
#include "pickle.hpp"
#include "os_binary.hpp"
#include "cli.hpp"
#include "cli_pager.hpp"
#include "trace_parser.hpp"
#include "trace_model.hpp"
#include "trace_callset.hpp"
using namespace trace;
class PickleVisitor : public trace::Visitor
{
protected:
PickleWriter &writer;
bool symbolic;
public:
PickleVisitor(PickleWriter &_writer, bool _symbolic) :
writer(_writer),
symbolic(_symbolic) {
}
void visit(Null *node) {
writer.writeInt(0);
}
void visit(Bool *node) {
writer.writeBool(node->value);
}
void visit(SInt *node) {
writer.writeInt(node->value);
}
void visit(UInt *node) {
writer.writeInt(node->value);
}
void visit(Float *node) {
writer.writeFloat(node->value);
}
void visit(Double *node) {
writer.writeFloat(node->value);
}
void visit(String *node) {
writer.writeString(node->value);
}
void visit(Enum *node) {
if (symbolic) {
const EnumValue *it = node->lookup();
if (it) {
writer.writeString(it->name);
return;
}
}
writer.writeInt(node->value);
}
void visit(Bitmask *node) {
if (symbolic) {
unsigned long long value = node->value;
const BitmaskSig *sig = node->sig;
writer.beginList();
for (const BitmaskFlag *it = sig->flags; it != sig->flags + sig->num_flags; ++it) {
if ((it->value && (value & it->value) == it->value) ||
(!it->value && value == 0)) {
writer.writeString(it->name);
value &= ~it->value;
}
if (value == 0) {
break;
}
}
if (value) {
writer.writeInt(value);
}
writer.endList();
} else {
writer.writeInt(node->value);
}
}
void visit(Struct *node) {
if (false) {
writer.beginDict();
for (unsigned i = 0; i < node->sig->num_members; ++i) {
writer.beginItem(node->sig->member_names[i]);
_visit(node->members[i]);
writer.endItem();
}
writer.endDict();
} else {
writer.beginTuple();
for (unsigned i = 0; i < node->sig->num_members; ++i) {
_visit(node->members[i]);
}
writer.endTuple();
}
}
void visit(Array *node) {
writer.beginList();
for (std::vector<Value *>::iterator it = node->values.begin(); it != node->values.end(); ++it) {
_visit(*it);
}
writer.endList();
}
void visit(Blob *node) {
writer.writeByteArray(node->buf, node->size);
}
void visit(Pointer *node) {
writer.writeInt(node->value);
}
void visit(Repr *r) {
if (symbolic) {
_visit(r->humanValue);
} else {
_visit(r->machineValue);
}
}
void visit(Call *call) {
writer.beginTuple();
writer.writeInt(call->no);
writer.writeString(call->name());
writer.beginList();
for (unsigned i = 0; i < call->args.size(); ++i) {
if (call->args[i].value) {
_visit(call->args[i].value);
} else {
writer.writeNone();
}
}
writer.endList();
if (call->ret) {
_visit(call->ret);
} else {
writer.writeNone();
}
writer.endTuple();
}
};
static trace::CallSet calls(trace::FREQUENCY_ALL);
static const char *synopsis = "Pickle given trace(s) to standard output.";
static void
usage(void)
{
std::cout
<< "usage: apitrace pickle [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help show this help message and exit\n"
" -s, --symbolic dump symbolic names\n"
" --calls=CALLSET only dump specified calls\n"
;
}
enum {
CALLS_OPT = CHAR_MAX + 1,
};
const static char *
shortOptions = "hs";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"symbolic", no_argument, 0, 's'},
{"calls", required_argument, 0, CALLS_OPT},
{0, 0, 0, 0}
};
static int
command(int argc, char *argv[])
{
bool symbolic;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 's':
symbolic = true;
break;
case CALLS_OPT:
calls = trace::CallSet(optarg);
break;
default:
std::cerr << "error: unexpected option `" << opt << "`\n";
usage();
return 1;
}
}
os::setBinaryMode(stdout);
std::cout.sync_with_stdio(false);
PickleWriter writer(std::cout);
PickleVisitor visitor(writer, symbolic);
for (int i = optind; i < argc; ++i) {
trace::Parser parser;
if (!parser.open(argv[i])) {
std::cerr << "error: failed to open " << argv[i] << "\n";
return 1;
}
trace::Call *call;
while ((call = parser.parse_call())) {
if (calls.contains(*call)) {
writer.begin();
visitor.visit(call);
writer.end();
}
delete call;
}
}
return 0;
}
const Command pickle_command = {
"pickle",
synopsis,
usage,
command
};
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.