text stringlengths 54 60.6k |
|---|
<commit_before>ff34767d-2e4e-11e5-9263-28cfe91dbc4b<commit_msg>ff3cd3dc-2e4e-11e5-bade-28cfe91dbc4b<commit_after>ff3cd3dc-2e4e-11e5-bade-28cfe91dbc4b<|endoftext|> |
<commit_before>1bae5d68-2e4f-11e5-8c35-28cfe91dbc4b<commit_msg>1bb5cc80-2e4f-11e5-8f48-28cfe91dbc4b<commit_after>1bb5cc80-2e4f-11e5-8f48-28cfe91dbc4b<|endoftext|> |
<commit_before>#ifndef MYSLICER_HPP
#define MYSLICER_HPP
#include "distribution.hpp"
#include "error_handler.hpp"
#include "base_urand.hpp"
#include <algorithm>
#include <limits>
//#define DEBUG
#ifdef DEBUG
#include <fstream>
#endif
#include <cassert>
#include <list>
#include <utility>
#include <limits>
#include <cmath>
namespace mcmc_utilities
{
template <typename T>
class slice_sampler
{
private:
bool adapt;
T width;
size_t nmax;
size_t nmin;
size_t niter;
T sumdiff;
const size_t min_adapt;
const probability_density_1d<T>& pd;
public:
slice_sampler(const probability_density_1d<T>& _pd, const T& _width,size_t _nmax,size_t _nmin)
:adapt(true),width(_width),nmax(_nmax),nmin(_nmin),niter(0),sumdiff(0),min_adapt(50),pd(_pd)
{
}
private:
T exponential(base_urand<T>& rnd)const
{
T result=0;
do
{
result=-std::log(1-rnd());
}
while(std::isinf(result));
return result;
}
bool accept(const T& xold,const T& xnew,const T& z,T L, T R,
const T& lower, const T& upper)const
{
bool d = false;
while ((R - L) > static_cast<T>(1.1) * width)
{
T M = (L + R)/2;
if ((xold < M && xnew >= M) || (xold >= M && xnew < M))
d = true;
if (xnew < M)
{
R = M;
}
else
{
L = M;
}
if (d)
{
bool right_ok = true;
if (R <= upper)
{
right_ok = pd.eval_log(R) < z;
}
bool left_ok = true;
if (L >= lower)
{
left_ok = pd.eval_log(L) < z;
}
if (left_ok && right_ok)
{
return false;
}
}
}
return true;
}
public:
T sample_double(T& xcur,base_urand<T>& rng)
{
for(size_t i=0;i<nmin;++i)
{
sample1_double(xcur,rng);
}
return xcur;
}
T sample1_double(T& xcur,base_urand<T>& rng)
{
T lower = 0;
T upper = 0;
auto xrange=pd.var_range();
lower=xrange.first;
upper=xrange.second;
if(xcur<xrange.first||xcur>xrange.second)
{
throw var_out_of_range();
}
T g0 = pd.eval_log(xcur);
if (std::isnan(g0)||std::isinf(g0))
{
throw nan_or_inf();
}
// Generate auxiliary variable
T z = g0 - exponential(rng);
// Generate random interval of width "_width" about current value
T xold = xcur;
T L = xold - rng() * width;
T R = L + width;
// Doubling
bool left_ok = false, right_ok = false;
for (size_t i = 0; i < nmax; ++i) {
if (rng() < static_cast<T>(0.5))
{
if (L >= lower)
{
L = 2*L - R;
if (L < lower)
{
left_ok = true;
}
else
{
xcur=L;
left_ok = pd.eval_log(xcur) < z;
}
}
else
{
left_ok = true;
}
}
else
{
if (R <= upper)
{
R = 2*R - L;
if (R > upper)
{
right_ok = true;
}
else
{
xcur=R;
right_ok = pd.eval_log(xcur) < z;
}
}
else
{
right_ok = true;
}
}
if (left_ok && right_ok)
{
break;
}
}
T Lbar = L, Rbar = R;
T xnew;
for(;;)
{
xnew = Lbar + rng() * (Rbar - Lbar);
if (xnew >= lower && xnew <= upper)
{
xcur=xnew;
T g = pd.eval_log(xnew);
if (g >= z && accept(xold, xnew, z, L, R, lower, upper))
{
xcur=xnew;
break;
}
}
if (xnew <= xold)
{
Lbar = xnew;
}
else
{
Rbar = xnew;
}
}
if (adapt)
{
sumdiff += niter * std::abs(xnew - xold);
++niter;
if (niter > min_adapt)
{
width = 2 * sumdiff / niter / (niter - 1);
}
}
return xcur;
}
T sample_step(T& xcur,base_urand<T>& rng)
{
for(size_t i=0;i<nmin;++i)
{
sample1_step(xcur,rng);
}
return xcur;
}
T sample1_step(T& xcur,base_urand<T>& rng)
{
T lower = 0;
T upper = 0;
auto xrange=pd.var_range();
lower=xrange.first;
upper=xrange.second;
if(xcur<xrange.first||xcur>xrange.second)
{
throw var_out_of_range();
}
T g0 = pd.eval_log(xcur);
if (std::isinf(g0))
{
throw nan_or_inf();
}
// Generate auxiliary variable
T z = g0 - exponential(rng);
// Generate random interval of width "_width" about current value
T xold = xcur;
T L = xold - rng() * width;
T R = L + width;
size_t j = static_cast<size_t>(rng() * nmax);
size_t k = nmax - 1 - j;
if (L < lower)
{
L = lower;
}
else
{
//setValue(L);
xcur=L;
while (j-- > 0 && pd.eval_log(xcur) > z)
{
L -= width;
if (L < lower)
{
L = lower;
break;
}
//setValue(L);
xcur=L;
}
}
if (R > upper)
{
R = upper;
}
else
{
//setValue(R);
xcur=R;
while (k-- > 0 && pd.eval_log(xcur) > z)
{
R += width;
if (R > upper)
{
R = upper;
break;
}
xcur = R;
}
}
T xnew;
for(;;)
{
xnew = L + rng() * (R - L);
xcur=xnew;
T g = pd.eval_log(xcur);
if (g >= z - std::numeric_limits<T>::epsilon())
{
break;
}
else
{
if (xnew < xold)
{
L = xnew;
}
else
{
R = xnew;
}
}
}
if (adapt)
{
sumdiff += niter * std::abs(xnew - xold);
++niter;
if ( niter > min_adapt)
{
width = 2 * sumdiff / niter / (niter - 1);
}
}
return xcur;
}
};
}
#endif
<commit_msg> modified: core/slicer.hpp<commit_after>#ifndef MYSLICER_HPP
#define MYSLICER_HPP
#include "distribution.hpp"
#include "error_handler.hpp"
#include "base_urand.hpp"
#include <algorithm>
#include <limits>
//#define DEBUG
#ifdef DEBUG
#include <fstream>
#endif
#include <cassert>
#include <list>
#include <utility>
#include <limits>
#include <cmath>
namespace mcmc_utilities
{
template <typename T>
class slice_sampler
{
private:
bool adapt;
T width;
size_t nmax;
size_t nmin;
size_t niter;
T sumdiff;
const size_t min_adapt;
const probability_density_1d<T>& pd;
public:
slice_sampler(const probability_density_1d<T>& _pd, const T& _width,size_t _nmax,size_t _nmin)
:adapt(true),width(_width),nmax(_nmax),nmin(_nmin),niter(0),sumdiff(0),min_adapt(50),pd(_pd)
{
}
private:
T exponential(base_urand<T>& rnd)const
{
T result=0;
do
{
result=-std::log(1-rnd());
}
while(std::isinf(result));
return result;
}
bool accept(const T& xold,const T& xnew,const T& z,T L, T R,
const T& lower, const T& upper)const
{
bool d = false;
while ((R - L) > static_cast<T>(1.1) * width)
{
T M = (L + R)/2;
if ((xold < M && xnew >= M) || (xold >= M && xnew < M))
d = true;
if (xnew < M)
{
R = M;
}
else
{
L = M;
}
if (d)
{
bool right_ok = true;
if (R <= upper)
{
right_ok = pd.eval_log(R) < z;
}
bool left_ok = true;
if (L >= lower)
{
left_ok = pd.eval_log(L) < z;
}
if (left_ok && right_ok)
{
return false;
}
}
}
return true;
}
public:
T sample_double(T& xcur,base_urand<T>& rng)
{
for(size_t i=0;i<nmin;++i)
{
sample1_double(xcur,rng);
}
return xcur;
}
T sample1_double(T& xcur,base_urand<T>& rng)
{
T lower = 0;
T upper = 0;
auto xrange=pd.var_range();
lower=xrange.first;
upper=xrange.second;
if(xcur<xrange.first||xcur>xrange.second)
{
std::cerr<<"xcur="<<xcur<<" ("<<xrange.first<<" , "<<xrange.second<<")"<<std::endl;
throw var_out_of_range();
}
T g0 = pd.eval_log(xcur);
if (std::isnan(g0)||std::isinf(g0))
{
throw nan_or_inf();
}
// Generate auxiliary variable
T z = g0 - exponential(rng);
// Generate random interval of width "_width" about current value
T xold = xcur;
T L = xold - rng() * width;
T R = L + width;
// Doubling
bool left_ok = false, right_ok = false;
for (size_t i = 0; i < nmax; ++i) {
if (rng() < static_cast<T>(0.5))
{
if (L >= lower)
{
L = 2*L - R;
if (L < lower)
{
left_ok = true;
}
else
{
xcur=L;
left_ok = pd.eval_log(xcur) < z;
}
}
else
{
left_ok = true;
}
}
else
{
if (R <= upper)
{
R = 2*R - L;
if (R > upper)
{
right_ok = true;
}
else
{
xcur=R;
right_ok = pd.eval_log(xcur) < z;
}
}
else
{
right_ok = true;
}
}
if (left_ok && right_ok)
{
break;
}
}
T Lbar = L, Rbar = R;
T xnew;
for(;;)
{
xnew = Lbar + rng() * (Rbar - Lbar);
if (xnew >= lower && xnew <= upper)
{
xcur=xnew;
T g = pd.eval_log(xnew);
if (g >= z && accept(xold, xnew, z, L, R, lower, upper))
{
xcur=xnew;
break;
}
}
if (xnew <= xold)
{
Lbar = xnew;
}
else
{
Rbar = xnew;
}
}
if (adapt)
{
sumdiff += niter * std::abs(xnew - xold);
++niter;
if (niter > min_adapt)
{
width = 2 * sumdiff / niter / (niter - 1);
}
}
return xcur;
}
T sample_step(T& xcur,base_urand<T>& rng)
{
for(size_t i=0;i<nmin;++i)
{
sample1_step(xcur,rng);
}
return xcur;
}
T sample1_step(T& xcur,base_urand<T>& rng)
{
T lower = 0;
T upper = 0;
auto xrange=pd.var_range();
lower=xrange.first;
upper=xrange.second;
if(xcur<xrange.first||xcur>xrange.second)
{
std::cerr<<"xcur="<<xcur<<" ("<<xrange.first<<" , "<<xrange.second<<")"<<std::endl;
throw var_out_of_range();
}
T g0 = pd.eval_log(xcur);
if (std::isinf(g0))
{
std::cerr<<"xcur="<<xcur<<std::endl;
throw nan_or_inf();
}
// Generate auxiliary variable
T z = g0 - exponential(rng);
// Generate random interval of width "_width" about current value
T xold = xcur;
T L = xold - rng() * width;
T R = L + width;
size_t j = static_cast<size_t>(rng() * nmax);
size_t k = nmax - 1 - j;
if (L < lower)
{
L = lower;
}
else
{
//setValue(L);
xcur=L;
while (j-- > 0 && pd.eval_log(xcur) > z)
{
L -= width;
if (L < lower)
{
L = lower;
break;
}
//setValue(L);
xcur=L;
}
}
if (R > upper)
{
R = upper;
}
else
{
//setValue(R);
xcur=R;
while (k-- > 0 && pd.eval_log(xcur) > z)
{
R += width;
if (R > upper)
{
R = upper;
break;
}
xcur = R;
}
}
T xnew;
for(;;)
{
xnew = L + rng() * (R - L);
xcur=xnew;
T g = pd.eval_log(xcur);
if (g >= z - std::numeric_limits<T>::epsilon())
{
break;
}
else
{
if (xnew < xold)
{
L = xnew;
}
else
{
R = xnew;
}
}
}
if (adapt)
{
sumdiff += niter * std::abs(xnew - xold);
++niter;
if ( niter > min_adapt)
{
width = 2 * sumdiff / niter / (niter - 1);
}
}
return xcur;
}
};
}
#endif
<|endoftext|> |
<commit_before>f313b77a-585a-11e5-9bb7-6c40088e03e4<commit_msg>f319e7a8-585a-11e5-b3ab-6c40088e03e4<commit_after>f319e7a8-585a-11e5-b3ab-6c40088e03e4<|endoftext|> |
<commit_before>a0a608eb-327f-11e5-a1c2-9cf387a8033e<commit_msg>a0abec19-327f-11e5-ab17-9cf387a8033e<commit_after>a0abec19-327f-11e5-ab17-9cf387a8033e<|endoftext|> |
<commit_before>#include "main.h"
#include <chrono>
int num_rows;
int num_cols;
int num_nonzeros;
std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;
#include "utils.h"
void ReadSparse(COO& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
size_t i, j;
double v;
while (true) {
ss >> i;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
ss >> j >> v;
data.row.push_back(i);
data.col.push_back(j);
data.val.push_back(v);
}
data.update();
}
void ReadVector(std::vector<double>& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
double v;
while (true) {
ss >> v;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
data.push_back(v);
}
}
int main(int argc, char* argv[]) {
COO D_T, M_invD;
std::vector<double> gamma;
std::cout << " Read in data to sparse COO structure: \n";
start = std::chrono::system_clock::now();
ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to read data from file: " << elapsed.count();
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Blaze: " << elapsed.count();
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load M_invD Blaze: " << elapsed.count();
blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);
{
std::cout << "Blaze Test:\n";
BlazeTest blaze_test;
start = std::chrono::system_clock::now();
blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Blaze Time: " << elapsed.count();
}
std::cout << "Eigen Convert:\n";
// Convert the COO into Eigen triplets
// Timing this part isn't important, in practice you would not need to do this
std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);
start = std::chrono::system_clock::now();
Eigen::SparseMatrix<double> D_T_eigen = EigenTest::ConvertMatrix(D_T_triplet, D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count();
start = std::chrono::system_clock::now();
Eigen::SparseMatrix<double> M_invD_eigen = EigenTest::ConvertMatrix(M_invD_triplet, M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count();
Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);
{
std::cout << "Eigen Test:\n";
start = std::chrono::system_clock::now();
EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Eigen Time: " << elapsed.count();
}
//
// {
// VexCLTest vexcl_test;
// vexcl_test.CreateContext();
// vexcl_test.WarmUp();
// CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
// CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
// vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
// vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
// vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
//
// start = std::chrono::system_clock::now();
// vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
// end = std::chrono::system_clock::now();
// vexcl_time = end - start;
// }
//
// // Compute some metrics and print them out
// num_rows = D_T_blaze.rows();
// num_cols = D_T_blaze.columns();
// num_nonzeros = D_T_blaze.nonZeros();
// printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
// printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
// ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
//
// // printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// // printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// // printf("gamma: size: %d\n", gamma_blaze.size());
// // printf("b: size: %d\n", rhs_blaze.size());
//
// {
// ViennaCLTest viennacl_test;
// viennacl_test.WarmUp();
//
// viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
// viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
// viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
//
// start = std::chrono::system_clock::now();
// viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
// end = std::chrono::system_clock::now();
// vcl_time = end - start;
// }
//
//
// // Two Spmv each with 2*nnz operations
// uint operations = 2 * 2 * num_nonzeros;
// uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
//
// double blaze_single = blaze_time.count() / RUNS;
// double vex_single = vexcl_time.count() / RUNS;
// double vcl_single = vcl_time.count() / RUNS;
// // double eig_single = eigen_time.count() / RUNS;
//
// printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
// printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
// printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
//
// // printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
// // printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
// // moved / vex_single / GFLOP);
// // //
// // printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// // printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// // printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// // printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
// //
// // printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// // printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<commit_msg>Add some endless after text output<commit_after>#include "main.h"
#include <chrono>
int num_rows;
int num_cols;
int num_nonzeros;
std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;
#include "utils.h"
void ReadSparse(COO& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
size_t i, j;
double v;
while (true) {
ss >> i;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
ss >> j >> v;
data.row.push_back(i);
data.col.push_back(j);
data.val.push_back(v);
}
data.update();
}
void ReadVector(std::vector<double>& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
double v;
while (true) {
ss >> v;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
data.push_back(v);
}
}
int main(int argc, char* argv[]) {
COO D_T, M_invD;
std::vector<double> gamma;
std::cout << "Read in data to sparse COO structure: \n";
start = std::chrono::system_clock::now();
ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to read data from file: " << elapsed.count()<<std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Blaze: " << elapsed.count()<<std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load M_invD Blaze: " << elapsed.count()<<std::endl;
blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);
{
std::cout << "Blaze Test:\n";
BlazeTest blaze_test;
start = std::chrono::system_clock::now();
blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Blaze Time: " << elapsed.count()<<std::endl;
}
std::cout << "Eigen Triplet:\n";
// Convert the COO into Eigen triplets
// Timing this part isn't important, in practice you would not need to do this
std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);
std::cout << "Eigen Convert:\n";
start = std::chrono::system_clock::now();
Eigen::SparseMatrix<double> D_T_eigen = EigenTest::ConvertMatrix(D_T_triplet, D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count()<<std::endl;
start = std::chrono::system_clock::now();
Eigen::SparseMatrix<double> M_invD_eigen = EigenTest::ConvertMatrix(M_invD_triplet, M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count()<<std::endl;
Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);
{
std::cout << "Eigen Test:\n";
start = std::chrono::system_clock::now();
EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Eigen Time: " << elapsed.count()<<std::endl;
}
//
// {
// VexCLTest vexcl_test;
// vexcl_test.CreateContext();
// vexcl_test.WarmUp();
// CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
// CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
// vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
// vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
// vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
//
// start = std::chrono::system_clock::now();
// vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
// end = std::chrono::system_clock::now();
// vexcl_time = end - start;
// }
//
// // Compute some metrics and print them out
// num_rows = D_T_blaze.rows();
// num_cols = D_T_blaze.columns();
// num_nonzeros = D_T_blaze.nonZeros();
// printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
// printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
// ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
//
// // printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// // printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// // printf("gamma: size: %d\n", gamma_blaze.size());
// // printf("b: size: %d\n", rhs_blaze.size());
//
// {
// ViennaCLTest viennacl_test;
// viennacl_test.WarmUp();
//
// viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
// viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
// viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
//
// start = std::chrono::system_clock::now();
// viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
// end = std::chrono::system_clock::now();
// vcl_time = end - start;
// }
//
//
// // Two Spmv each with 2*nnz operations
// uint operations = 2 * 2 * num_nonzeros;
// uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
//
// double blaze_single = blaze_time.count() / RUNS;
// double vex_single = vexcl_time.count() / RUNS;
// double vcl_single = vcl_time.count() / RUNS;
// // double eig_single = eigen_time.count() / RUNS;
//
// printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
// printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
// printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
//
// // printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
// // printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
// // moved / vex_single / GFLOP);
// // //
// // printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// // printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// // printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// // printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
// //
// // printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// // printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<|endoftext|> |
<commit_before>9101ada2-2d14-11e5-af21-0401358ea401<commit_msg>9101ada3-2d14-11e5-af21-0401358ea401<commit_after>9101ada3-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>20066228-585b-11e5-9e07-6c40088e03e4<commit_msg>200f0734-585b-11e5-a041-6c40088e03e4<commit_after>200f0734-585b-11e5-a041-6c40088e03e4<|endoftext|> |
<commit_before>7846127c-2d53-11e5-baeb-247703a38240<commit_msg>78469152-2d53-11e5-baeb-247703a38240<commit_after>78469152-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
//#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
static const GLfloat globVertexBufferData[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
bool checkShaderCompileStatus(GLuint obj) {
GLint status;
glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
if(status == GL_FALSE) {
GLint length;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log((unsigned long)length);
glGetShaderInfoLog(obj, length, &length, &log[0]);
std::cerr << &log[0];
return true;
}
return false;
}
bool checkProgramLinkStatus(GLuint obj) {
GLint status;
glGetProgramiv(obj, GL_LINK_STATUS, &status);
if(status == GL_FALSE) {
GLint length;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log((unsigned long)length);
glGetProgramInfoLog(obj, length, &length, &log[0]);
std::cerr << &log[0];
return true;
}
return false;
}
GLuint prepareProgram(bool *errorFlagPtr) {
*errorFlagPtr = false;
std::string vertexShaderSource = ""
"#version 330 core\n"
"layout(location = 0) in vec3 vertexPosition_modelspace;\n"
"void main(){\n"
" gl_Position.xyz = vertexPosition_modelspace;\n"
" gl_Position.w = 1.0;\n"
"}";
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
char const * vertexShaderSourcePtr = vertexShaderSource.c_str();
glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
glCompileShader(vertexShaderId);
*errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
if(*errorFlagPtr) return 0;
std::string fragmentShaderSource = ""
"#version 330 core\n"
"out vec3 color;\n"
"void main() { color = vec3(1,0,0); }\n";
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
char const * fragmentShaderSourcePtr = fragmentShaderSource.c_str();
glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
glCompileShader(fragmentShaderId);
*errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
if(*errorFlagPtr) return 0;
GLuint programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, fragmentShaderId);
glLinkProgram(programId);
*errorFlagPtr = checkProgramLinkStatus(programId);
if(*errorFlagPtr) return 0;
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
return programId;
}
void windowSizeCallback(GLFWwindow *, int width, int height) {
glViewport(0, 0, width, height);
}
int main() {
if(glfwInit() == GL_FALSE) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
nullptr, nullptr);
if(window == nullptr) {
std::cerr << "Failed to open GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if(glxwInit()) {
std::cerr << "Failed to init GLXW" << std::endl;
glfwDestroyWindow(window);
glfwTerminate();
return 1;
}
glfwSwapInterval(1);
glfwSetWindowSizeCallback(window, windowSizeCallback);
glfwShowWindow(window);
glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
glDepthFunc(GL_LESS);
glClearColor(0, 0, 0, 1);
// glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
// glMatrixMode(GL_PROJECTION);
// glLoadMatrixf(glm::value_ptr(m));
bool errorFlag;
GLuint programId = prepareProgram(&errorFlag);
if(errorFlag) {
glfwDestroyWindow(window);
glfwTerminate();
return -1;
}
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
while(glfwWindowShouldClose(window) == GL_FALSE) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programId);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
nullptr // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glDisableVertexAttribArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
// glDetachShader(shader_program, vertex_shader);
// glDetachShader(shader_program, fragment_shader);
// glDeleteShader(vertex_shader);
// glDeleteShader(fragment_shader);
glDeleteProgram(programId);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}<commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
//#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
static const GLfloat globVertexBufferData[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
bool checkShaderCompileStatus(GLuint obj) {
GLint status;
glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
if(status == GL_FALSE) {
GLint length;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log((unsigned long)length);
glGetShaderInfoLog(obj, length, &length, &log[0]);
std::cerr << &log[0];
return true;
}
return false;
}
bool checkProgramLinkStatus(GLuint obj) {
GLint status;
glGetProgramiv(obj, GL_LINK_STATUS, &status);
if(status == GL_FALSE) {
GLint length;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log((unsigned long)length);
glGetProgramInfoLog(obj, length, &length, &log[0]);
std::cerr << &log[0];
return true;
}
return false;
}
GLuint prepareProgram(bool *errorFlagPtr) {
*errorFlagPtr = false;
std::string vertexShaderSource = ""
"#version 330 core\n"
"layout(location = 0) in vec3 vertexPosition_modelspace;\n"
"void main(){\n"
" gl_Position.xyz = vertexPosition_modelspace;\n"
" gl_Position.w = 1.0;\n"
"}";
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
const GLchar * const vertexShaderSourcePtr = vertexShaderSource.c_str();
glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
glCompileShader(vertexShaderId);
*errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
if(*errorFlagPtr) return 0;
std::string fragmentShaderSource = ""
"#version 330 core\n"
"out vec3 color;\n"
"void main() { color = vec3(1,0,0); }\n";
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar * const fragmentShaderSourcePtr = fragmentShaderSource.c_str();
glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
glCompileShader(fragmentShaderId);
*errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
if(*errorFlagPtr) return 0;
GLuint programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, fragmentShaderId);
glLinkProgram(programId);
*errorFlagPtr = checkProgramLinkStatus(programId);
if(*errorFlagPtr) return 0;
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
return programId;
}
void windowSizeCallback(GLFWwindow *, int width, int height) {
glViewport(0, 0, width, height);
}
int main() {
if(glfwInit() == GL_FALSE) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
nullptr, nullptr);
if(window == nullptr) {
std::cerr << "Failed to open GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if(glxwInit()) {
std::cerr << "Failed to init GLXW" << std::endl;
glfwDestroyWindow(window);
glfwTerminate();
return 1;
}
glfwSwapInterval(1);
glfwSetWindowSizeCallback(window, windowSizeCallback);
glfwShowWindow(window);
glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
glDepthFunc(GL_LESS);
glClearColor(0, 0, 0, 1);
// glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
// glMatrixMode(GL_PROJECTION);
// glLoadMatrixf(glm::value_ptr(m));
bool errorFlag;
GLuint programId = prepareProgram(&errorFlag);
if(errorFlag) {
glfwDestroyWindow(window);
glfwTerminate();
return -1;
}
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
while(glfwWindowShouldClose(window) == GL_FALSE) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programId);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
nullptr // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glDisableVertexAttribArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteProgram(programId);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}<|endoftext|> |
<commit_before>f4d60575-2e4e-11e5-a4ca-28cfe91dbc4b<commit_msg>f4dc697a-2e4e-11e5-b6d0-28cfe91dbc4b<commit_after>f4dc697a-2e4e-11e5-b6d0-28cfe91dbc4b<|endoftext|> |
<commit_before>f3b11126-327f-11e5-a8e4-9cf387a8033e<commit_msg>f3b6fe21-327f-11e5-a116-9cf387a8033e<commit_after>f3b6fe21-327f-11e5-a116-9cf387a8033e<|endoftext|> |
<commit_before>4e5d5bd1-2e4f-11e5-b0ea-28cfe91dbc4b<commit_msg>4e64b54a-2e4f-11e5-b2dd-28cfe91dbc4b<commit_after>4e64b54a-2e4f-11e5-b2dd-28cfe91dbc4b<|endoftext|> |
<commit_before>d3867b26-313a-11e5-85e6-3c15c2e10482<commit_msg>d38c7347-313a-11e5-b0b7-3c15c2e10482<commit_after>d38c7347-313a-11e5-b0b7-3c15c2e10482<|endoftext|> |
<commit_before>// PDTK
#include <application.h>
#include <cxxutils/syslogstream.h>
// project
#include "configserver.h"
constexpr const char* const appname = "SXconfigd";
constexpr const char* const username = "config";
void exiting(void)
{
posix::syslog << posix::priority::notice << "daemon has exited." << posix::eom;
}
int main(int argc, char *argv[]) noexcept
{
(void)argc;
(void)argv;
::atexit(exiting);
posix::syslog.open(appname, posix::facility::daemon);
if(posix::getusername(::getuid()) != username)
{
posix::syslog << posix::priority::critical << "daemon must be launched as username " << '"' << username << '"' << posix::eom;
::exit(-1);
}
Application app;
ConfigServer server(username, "file_monitor");
return app.exec();
}
#if 0
// STL
#include <iostream>
// C++
#include <cassert>
// PDTK
#include <cxxutils/configmanip.h>
int main(int argc, char *argv[]) noexcept
{
std::string data = "[config]\nkey=original value\n # ORLY?\nKey = Value; yeah rly\n/config/key=\"overwritten\"; stuff\n[config]key=\"oh my\"\n";
ConfigManip conf;
assert(conf.read(data));
std::string dout;
assert(conf.write(dout));
std::cout << "OUTPUT" << std::endl << '"' << dout << '"' << std::endl;
//return 0;
auto node = conf.findNode("/config/1/key");
if(node != nullptr)
std::cout << "node: " << '"' << node->value << '"' << std::endl;
else
std::cout << "not found!" << std::endl;
return 0;
}
#endif
<commit_msg>socket demo code<commit_after>// PDTK
#include <application.h>
#include <object.h>
#include <cxxutils/syslogstream.h>
// project
#include "configserver.h"
constexpr const char* const appname = "SXconfigd";
constexpr const char* const username = "config";
void exiting(void)
{
posix::syslog << posix::priority::notice << "daemon has exited." << posix::eom;
}
void allfunc(void)
{
posix::syslog << "tada!" << posix::eom;
}
int main(int argc, char *argv[]) noexcept
{
(void)argc;
(void)argv;
::atexit(exiting);
posix::syslog.open(appname, posix::facility::daemon);
if(posix::getusername(::getuid()) != username)
{
posix::syslog << posix::priority::critical << "daemon must be launched as username " << '"' << username << '"' << posix::eom;
::exit(-1);
}
Application app;
ConfigServer server(username, "file_monitor");
Object::connect(server.getAllCall, allfunc);
return app.exec();
}
#if 0
// STL
#include <iostream>
// C++
#include <cassert>
// PDTK
#include <cxxutils/configmanip.h>
int main(int argc, char *argv[]) noexcept
{
std::string data = "[config]\nkey=original value\n # ORLY?\nKey = Value; yeah rly\n/config/key=\"overwritten\"; stuff\n[config]key=\"oh my\"\n";
ConfigManip conf;
assert(conf.read(data));
std::string dout;
assert(conf.write(dout));
std::cout << "OUTPUT" << std::endl << '"' << dout << '"' << std::endl;
//return 0;
auto node = conf.findNode("/config/1/key");
if(node != nullptr)
std::cout << "node: " << '"' << node->value << '"' << std::endl;
else
std::cout << "not found!" << std::endl;
return 0;
}
#endif
<|endoftext|> |
<commit_before>809e925d-2d15-11e5-af21-0401358ea401<commit_msg>809e925e-2d15-11e5-af21-0401358ea401<commit_after>809e925e-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <fstream>
#include "Game/Game.h"
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Players/Genetic_AI.h"
#include "Players/Human_Player.h"
#include "Players/Random_AI.h"
#include "Players/Outside_Player.h"
#include "Genes/Gene_Pool.h"
#include "Exceptions/Illegal_Move_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
#include "Testing.h"
void print_help();
int find_last_id(const std::string& filename);
int main(int argc, char *argv[])
{
try
{
run_tests();
if(argc > 1)
{
if(std::string(argv[1]) == "-genepool")
{
std::string gene_pool_config_file_name;
if(argc > 2)
{
gene_pool_config_file_name = argv[2];
}
gene_pool(gene_pool_config_file_name);
}
else if(std::string(argv[1]) == "-replay")
{
if(argc > 2)
{
Board board;
std::string file_name = argv[2];
std::ifstream ifs(file_name);
std::string line;
bool game_started = false;
while( ! board.game_has_ended() && std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
line = String::strip_block_comment(line, '{', '}');
line = String::strip_comments(line, ';');
if(line.empty())
{
if(game_started)
{
break;
}
else
{
continue;
}
}
if(line[0] == '[')
{
std::cout << line << std::endl;
continue;
}
for(const auto& s : String::split(line))
{
try
{
board.submit_move(board.get_complete_move(s));
}
catch(const Illegal_Move_Exception&)
{
std::cout << "Ignoring: " << s << std::endl;
continue;
}
catch(const Game_Ending_Exception& e)
{
std::cout << e.what() << std::endl;
}
board.ascii_draw(WHITE);
game_started = true;
std::cout << "Last move: ";
std::cout << (board.get_game_record().size() + 1)/2 << ". ";
std::cout << (board.whose_turn() == WHITE ? "... " : "");
std::cout << board.get_game_record().back() << std::endl;
if(board.game_has_ended())
{
break;
}
std::cout << "Enter \"y\" to play game from here: " << std::endl;
char response = std::cin.get();
if(std::tolower(response) == 'y')
{
play_game_with_board(Human_Player(),
Human_Player(),
0,
0,
0,
file_name + "_continued.pgn",
board);
break;
}
}
}
}
else
{
std::cerr << "-replay must be followed by a file name." << std::endl;
return 1;
}
}
else
{
std::unique_ptr<Player> white;
std::unique_ptr<Player> black;
std::unique_ptr<Player> latest;
int game_time = 0;
int moves_per_reset = 0;
int increment_time = 0;
for(int i = 1; i < argc; ++i)
{
std::string opt = argv[i];
if(opt == "-human")
{
latest.reset(new Human_Player());
}
else if(opt == "-random")
{
latest.reset(new Random_AI());
}
else if(opt == "-genetic")
{
Genetic_AI *genetic_ptr = nullptr;
std::string filename;
int id = -1;
if(i + 1 < argc)
{
filename = argv[i+1];
if(filename.front() == '-')
{
filename.clear();
}
}
if(i + 2 < argc)
{
try
{
id = std::stoi(argv[i+2]);
}
catch(const std::exception&)
{
}
}
if(filename.empty())
{
genetic_ptr = new Genetic_AI;
for(int j = 0; j < 100; ++j)
{
genetic_ptr->mutate();
}
genetic_ptr->print_genome("single_game_player.txt");
}
else
{
if(id < 0)
{
genetic_ptr = new Genetic_AI(filename, find_last_id(filename));
i += 1;
}
else
{
genetic_ptr = new Genetic_AI(filename, id);
i += 2;
}
}
latest.reset(genetic_ptr);
}
else if(opt == "-time")
{
game_time = std::stoi(argv[++i]);
}
else if(opt == "-reset_moves")
{
moves_per_reset = std::stoi(argv[++i]);
}
else if(opt == "-increment_time")
{
increment_time = std::stoi(argv[++i]);
}
else
{
throw std::runtime_error("Invalid option: " + opt);
}
if(latest)
{
if( ! white)
{
white = std::move(latest);
continue;
}
if( ! black)
{
black = std::move(latest);
continue;
}
}
}
std::string game_file_name = "game.pgn";
if(black)
{
play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
auto outside = connect_to_outside(*white);
game_time = outside->get_game_time();
moves_per_reset = outside->get_reset_moves();
increment_time = outside->get_increment();
if(outside->get_ai_color() == WHITE)
{
play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name);
}
}
}
}
else
{
print_help();
}
}
catch(const std::exception& e)
{
std::cerr << "\n\nERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
void print_help()
{
std::cout << "\n\nGenetic Chess" << std::endl
<< "=============" << std::endl << std::endl
<< "Options:" << std::endl
<< "\t-genepool [file name]" << std::endl
<< "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl
<< "\t-replay [filename]" << std::endl
<< "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl
<< "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl
<< "\t-human" << std::endl
<< "\t\tSpecify a human player for a game." << std::endl << std::endl
<< "\t-genetic [filename [number]]" << std::endl
<< "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl
<< "\t-random" << std::endl
<< "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl
<< "\t-time [number]" << std::endl
<< "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl
<< "\t-reset_moves [number]" << std::endl
<< "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl
<< "\t-increment_time [number]" << std::endl
<< "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl;
}
int find_last_id(const std::string& filename)
{
std::ifstream ifs(filename);
std::string line;
std::string id_line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "ID:"))
{
id_line = line;
}
}
if(id_line.empty())
{
throw std::runtime_error("No Genetic AIs found in " + filename);
}
else
{
return std::stoi(String::split(id_line)[1]);
}
}
<commit_msg>Explanatory comment<commit_after>#include <iostream>
#include <memory>
#include <fstream>
#include "Game/Game.h"
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Players/Genetic_AI.h"
#include "Players/Human_Player.h"
#include "Players/Random_AI.h"
#include "Players/Outside_Player.h"
#include "Genes/Gene_Pool.h"
#include "Exceptions/Illegal_Move_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
#include "Testing.h"
void print_help();
int find_last_id(const std::string& filename);
int main(int argc, char *argv[])
{
try
{
run_tests();
if(argc > 1)
{
if(std::string(argv[1]) == "-genepool")
{
std::string gene_pool_config_file_name;
if(argc > 2)
{
gene_pool_config_file_name = argv[2];
}
gene_pool(gene_pool_config_file_name);
}
else if(std::string(argv[1]) == "-replay")
{
if(argc > 2)
{
Board board;
std::string file_name = argv[2];
std::ifstream ifs(file_name);
std::string line;
bool game_started = false;
while( ! board.game_has_ended() && std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
line = String::strip_block_comment(line, '{', '}');
line = String::strip_comments(line, ';');
if(line.empty())
{
if(game_started)
{
break;
}
else
{
continue;
}
}
if(line[0] == '[')
{
std::cout << line << std::endl;
continue;
}
for(const auto& s : String::split(line))
{
try
{
board.submit_move(board.get_complete_move(s));
}
catch(const Illegal_Move_Exception&)
{
std::cout << "Ignoring: " << s << std::endl;
continue;
}
catch(const Game_Ending_Exception& e)
{
std::cout << e.what() << std::endl;
}
board.ascii_draw(WHITE);
game_started = true;
std::cout << "Last move: ";
std::cout << (board.get_game_record().size() + 1)/2 << ". ";
std::cout << (board.whose_turn() == WHITE ? "... " : "");
std::cout << board.get_game_record().back() << std::endl;
if(board.game_has_ended())
{
break;
}
std::cout << "Enter \"y\" to play game from here: " << std::endl;
char response = std::cin.get();
if(std::tolower(response) == 'y')
{
play_game_with_board(Human_Player(),
Human_Player(),
0,
0,
0,
file_name + "_continued.pgn",
board);
break;
}
}
}
}
else
{
std::cerr << "-replay must be followed by a file name." << std::endl;
return 1;
}
}
else
{
// Use pointers since each player could be Human, Genetic, Random, etc.
std::unique_ptr<Player> white;
std::unique_ptr<Player> black;
std::unique_ptr<Player> latest;
int game_time = 0;
int moves_per_reset = 0;
int increment_time = 0;
for(int i = 1; i < argc; ++i)
{
std::string opt = argv[i];
if(opt == "-human")
{
latest.reset(new Human_Player());
}
else if(opt == "-random")
{
latest.reset(new Random_AI());
}
else if(opt == "-genetic")
{
Genetic_AI *genetic_ptr = nullptr;
std::string filename;
int id = -1;
if(i + 1 < argc)
{
filename = argv[i+1];
if(filename.front() == '-')
{
filename.clear();
}
}
if(i + 2 < argc)
{
try
{
id = std::stoi(argv[i+2]);
}
catch(const std::exception&)
{
}
}
if(filename.empty())
{
genetic_ptr = new Genetic_AI;
for(int j = 0; j < 100; ++j)
{
genetic_ptr->mutate();
}
genetic_ptr->print_genome("single_game_player.txt");
}
else
{
if(id < 0)
{
genetic_ptr = new Genetic_AI(filename, find_last_id(filename));
i += 1;
}
else
{
genetic_ptr = new Genetic_AI(filename, id);
i += 2;
}
}
latest.reset(genetic_ptr);
}
else if(opt == "-time")
{
game_time = std::stoi(argv[++i]);
}
else if(opt == "-reset_moves")
{
moves_per_reset = std::stoi(argv[++i]);
}
else if(opt == "-increment_time")
{
increment_time = std::stoi(argv[++i]);
}
else
{
throw std::runtime_error("Invalid option: " + opt);
}
if(latest)
{
if( ! white)
{
white = std::move(latest);
continue;
}
if( ! black)
{
black = std::move(latest);
continue;
}
}
}
std::string game_file_name = "game.pgn";
if(black)
{
play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
auto outside = connect_to_outside(*white);
game_time = outside->get_game_time();
moves_per_reset = outside->get_reset_moves();
increment_time = outside->get_increment();
if(outside->get_ai_color() == WHITE)
{
play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name);
}
}
}
}
else
{
print_help();
}
}
catch(const std::exception& e)
{
std::cerr << "\n\nERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
void print_help()
{
std::cout << "\n\nGenetic Chess" << std::endl
<< "=============" << std::endl << std::endl
<< "Options:" << std::endl
<< "\t-genepool [file name]" << std::endl
<< "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl
<< "\t-replay [filename]" << std::endl
<< "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl
<< "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl
<< "\t-human" << std::endl
<< "\t\tSpecify a human player for a game." << std::endl << std::endl
<< "\t-genetic [filename [number]]" << std::endl
<< "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl
<< "\t-random" << std::endl
<< "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl
<< "\t-time [number]" << std::endl
<< "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl
<< "\t-reset_moves [number]" << std::endl
<< "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl
<< "\t-increment_time [number]" << std::endl
<< "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl;
}
int find_last_id(const std::string& filename)
{
std::ifstream ifs(filename);
std::string line;
std::string id_line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "ID:"))
{
id_line = line;
}
}
if(id_line.empty())
{
throw std::runtime_error("No Genetic AIs found in " + filename);
}
else
{
return std::stoi(String::split(id_line)[1]);
}
}
<|endoftext|> |
<commit_before>
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>
#include <sys/mman.h>
#include <stdlib.h>
#include "sock_utils.h"
#define MAX_DMA_PORTS 4
#define MAX_DMA_IDS 32
typedef struct {
int fd;
unsigned char *buffer;
uint32_t buffer_len;
int size_accum;
} DMAINFO[MAX_DMA_IDS];
static DMAINFO dma_info[MAX_DMA_PORTS];
static int dma_trace ;//= 1;
#define BUFFER_CHECK \
if (!dma_info[id][pref].buffer || offset >= dma_info[id][pref].buffer_len) { \
fprintf(stderr, "BsimDma: buffer %p len %d; reference id %d pref %d offset %d\n", dma_info[id][pref].buffer, dma_info[id][pref].buffer_len, id, pref, offset); \
exit(-1); \
}
extern "C" void write_pareff32(uint32_t pref, uint32_t offset, unsigned int data)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
*(unsigned int *)&dma_info[id][pref].buffer[offset] = data;
}
extern "C" unsigned int read_pareff32(uint32_t pref, uint32_t offset)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
return *(unsigned int *)&dma_info[id][pref].buffer[offset];
}
extern "C" void write_pareff64(uint32_t pref, uint32_t offset, uint64_t data)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
*(uint64_t *)&dma_info[id][pref].buffer[offset] = data;
}
extern "C" uint64_t read_pareff64(uint32_t pref, uint32_t offset)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d buffer_len %d\n", __FUNCTION__, id, pref, offset, dma_info[id][pref].buffer_len);
BUFFER_CHECK
return *(uint64_t *)&dma_info[id][pref].buffer[offset];
}
extern "C" void pareff_initfd(uint32_t aid, uint32_t fd)
{
uint32_t id = aid >> 16;
uint32_t pref = aid & 0xffff;
if (dma_trace)
fprintf(stderr, "%s: id=%d pref=%d fd=%d\n", __FUNCTION__, id, pref, fd);
dma_info[id][pref].fd = fd;
}
extern "C" void pareff_init(uint32_t id, uint32_t pref, uint32_t size)
{
if (dma_trace)
fprintf(stderr, "pareff_init: id=%d pref=%d, size=%08x size_accum=%08x\n", id, pref, size, dma_info[id][pref].size_accum);
assert(pref < MAX_DMA_IDS);
dma_info[id][pref].size_accum += size;
if(size == 0){
if (dma_trace)
fprintf(stderr, "%s: id=%d pref=%d fd=%d\n", __FUNCTION__, id, pref, dma_info[id][pref].fd);
dma_info[id][pref].buffer = (unsigned char *)mmap(0,
dma_info[id][pref].size_accum, PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, dma_info[id][pref].fd, 0);
if (dma_info[id][pref].buffer == MAP_FAILED) {
fprintf(stderr, "pareff_init: mmap failed fd %x buffer %p size %x errno %d\n", dma_info[id][pref].fd, dma_info[id][pref].buffer, size, errno);
exit(-1);
}
dma_info[id][pref].buffer_len = dma_info[id][pref].size_accum;
}
if (dma_trace)
fprintf(stderr, "pareff_init: done\n");
}
<commit_msg>added function name to BUFFER_CHECK message<commit_after>
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>
#include <sys/mman.h>
#include <stdlib.h>
#include "sock_utils.h"
#define MAX_DMA_PORTS 4
#define MAX_DMA_IDS 32
typedef struct {
int fd;
unsigned char *buffer;
uint32_t buffer_len;
int size_accum;
} DMAINFO[MAX_DMA_IDS];
static DMAINFO dma_info[MAX_DMA_PORTS];
static int dma_trace ;//= 1;
#define BUFFER_CHECK \
if (!dma_info[id][pref].buffer || offset >= dma_info[id][pref].buffer_len) { \
fprintf(stderr, "BsimDma [%s:%d]: buffer %p len %d; reference id %d pref %d offset %d\n", __FUNCTION__, __LINE__, dma_info[id][pref].buffer, dma_info[id][pref].buffer_len, id, pref, offset); \
exit(-1); \
}
extern "C" void write_pareff32(uint32_t pref, uint32_t offset, unsigned int data)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
*(unsigned int *)&dma_info[id][pref].buffer[offset] = data;
}
extern "C" unsigned int read_pareff32(uint32_t pref, uint32_t offset)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
return *(unsigned int *)&dma_info[id][pref].buffer[offset];
}
extern "C" void write_pareff64(uint32_t pref, uint32_t offset, uint64_t data)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d\n", __FUNCTION__, id, pref, offset);
BUFFER_CHECK
*(uint64_t *)&dma_info[id][pref].buffer[offset] = data;
}
extern "C" uint64_t read_pareff64(uint32_t pref, uint32_t offset)
{
uint32_t id = pref>>5;
pref -= id<<5;
if (dma_trace)
fprintf(stderr, "%s: %d %d %d buffer_len %d\n", __FUNCTION__, id, pref, offset, dma_info[id][pref].buffer_len);
BUFFER_CHECK
return *(uint64_t *)&dma_info[id][pref].buffer[offset];
}
extern "C" void pareff_initfd(uint32_t aid, uint32_t fd)
{
uint32_t id = aid >> 16;
uint32_t pref = aid & 0xffff;
if (dma_trace)
fprintf(stderr, "%s: id=%d pref=%d fd=%d\n", __FUNCTION__, id, pref, fd);
dma_info[id][pref].fd = fd;
}
extern "C" void pareff_init(uint32_t id, uint32_t pref, uint32_t size)
{
if (dma_trace)
fprintf(stderr, "pareff_init: id=%d pref=%d, size=%08x size_accum=%08x\n", id, pref, size, dma_info[id][pref].size_accum);
assert(pref < MAX_DMA_IDS);
dma_info[id][pref].size_accum += size;
if(size == 0){
if (dma_trace)
fprintf(stderr, "%s: id=%d pref=%d fd=%d\n", __FUNCTION__, id, pref, dma_info[id][pref].fd);
dma_info[id][pref].buffer = (unsigned char *)mmap(0,
dma_info[id][pref].size_accum, PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, dma_info[id][pref].fd, 0);
if (dma_info[id][pref].buffer == MAP_FAILED) {
fprintf(stderr, "pareff_init: mmap failed fd %x buffer %p size %x errno %d\n", dma_info[id][pref].fd, dma_info[id][pref].buffer, size, errno);
exit(-1);
}
dma_info[id][pref].buffer_len = dma_info[id][pref].size_accum;
}
if (dma_trace)
fprintf(stderr, "pareff_init: done\n");
}
<|endoftext|> |
<commit_before>ca33b1e1-2e4e-11e5-9b39-28cfe91dbc4b<commit_msg>ca3c9d02-2e4e-11e5-a98a-28cfe91dbc4b<commit_after>ca3c9d02-2e4e-11e5-a98a-28cfe91dbc4b<|endoftext|> |
<commit_before>76e03b74-2d53-11e5-baeb-247703a38240<commit_msg>76e0b9dc-2d53-11e5-baeb-247703a38240<commit_after>76e0b9dc-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>#include "session.h"
#include <functional>
#include <curl/curl.h>
#include "curlholder.h"
#include "util.h"
class Session::Impl {
public:
Impl();
void SetUrl(Url url);
void SetUrl(Url url, Parameters parameters);
void SetHeader(Header header);
void SetTimeout(Timeout timeout);
void SetAuth(Authentication auth);
void SetPayload(Payload payload);
void SetRedirect(bool redirect);
void SetMaxRedirects(long max_redirects);
// void SetCookie(); Unimplemented
// void SetCookies(); Unimplemented
Response Get();
Response Post();
private:
std::unique_ptr<CurlHolder, std::function<void(CurlHolder*)>> curl_;
static void freeHolder(CurlHolder* holder);
static CurlHolder* newHolder();
};
Session::Impl::Impl() {
curl_ = std::unique_ptr<CurlHolder, std::function<void(CurlHolder*)>>(newHolder(), &Impl::freeHolder);
auto curl = curl_->handle;
if (curl) {
// Set up some sensible defaults
auto version_info = curl_version_info(CURLVERSION_NOW);
auto version = std::string{"curl/"} + std::string{version_info->version};
curl_easy_setopt(curl, CURLOPT_USERAGENT, version.data());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_->error);
#if LIBCURL_VERSION_MAJOR >= 7
#if LIBCURL_VERSION_MINOR >= 25
#if LIBCURL_VERSION_PATCH >= 0
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
#endif
#endif
#endif
}
}
void Session::Impl::freeHolder(CurlHolder* holder) {
curl_easy_cleanup(holder->handle);
curl_slist_free_all(holder->chunk);
}
CurlHolder* Session::Impl::newHolder() {
CurlHolder* holder = new CurlHolder();
holder->handle = curl_easy_init();
return holder;
}
void Session::Impl::SetUrl(Url url) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.data());
}
}
void Session::Impl::SetUrl(Url url, Parameters parameters) {
auto curl = curl_->handle;
if (curl) {
Url new_url{url + "?"};
for(auto parameter = parameters.cbegin(); parameter != parameters.cend(); ++parameter) {
new_url += parameter->first + "=" + parameter->second + "&";
}
new_url = new_url.substr(0, new_url.size() - 1);
curl_easy_setopt(curl, CURLOPT_URL, new_url.data());
}
}
void Session::Impl::SetHeader(Header header) {
auto curl = curl_->handle;
if (curl) {
struct curl_slist* chunk = NULL;
for (auto item = header.cbegin(); item != header.cend(); ++item) {
auto header_string = std::string{item->first};
if (item->second.empty()) {
header_string += ";";
} else {
header_string += ": " + item->second;
}
chunk = curl_slist_append(chunk, header_string.data());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_->chunk = chunk;
}
}
}
void Session::Impl::SetTimeout(long timeout) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, timeout);
}
}
void Session::Impl::SetAuth(Authentication auth) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, auth.GetAuthString());
}
}
void Session::Impl::SetPayload(Payload payload) {
auto curl = curl_->handle;
if (curl) {
struct curl_slist* chunk = NULL;
auto payload_string = std::string{};
for (auto item = payload.cbegin(); item != payload.cend(); ++item) {
if (!payload_string.empty()) {
payload_string += "&";
}
payload_string += item->first + "=" + item->second;
}
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, payload_string.length());
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, payload_string.data());
}
}
void Session::Impl::SetRedirect(bool redirect) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, long(redirect));
}
}
void Session::Impl::SetMaxRedirects(long max_redirects) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, max_redirects);
}
}
Response Session::Impl::Get() {
auto curl = curl_->handle;
CURLcode res;
Response response{0, "Curl could not start", Header{}, Url{}, 0.0};
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 0L);
std::string response_string;
std::string header_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string);
res = curl_easy_perform(curl);
char* raw_url;
long response_code;
double elapsed;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url);
auto header = cpr::util::parseHeader(header_string);
response_string = cpr::util::parseResponse(response_string);
response = {response_code, response_string, header, raw_url, elapsed};
}
return response;
}
Response Session::Impl::Post() {
auto curl = curl_->handle;
CURLcode res;
Response response{0, "Curl could not start", Header{}, Url{}, 0.0};
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 0L);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
std::string response_string;
std::string header_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string);
res = curl_easy_perform(curl);
char* raw_url;
long response_code;
double elapsed;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url);
auto header = cpr::util::parseHeader(header_string);
response_string = cpr::util::parseResponse(response_string);
response = {response_code, response_string, header, raw_url, elapsed};
}
return response;
}
Session::Session() : pimpl_{ new Impl{} } {}
Session::~Session() {}
void Session::SetUrl(Url url) { pimpl_->SetUrl(url); }
void Session::SetUrl(Url url, Parameters parameters) { pimpl_->SetUrl(url, parameters); }
void Session::SetHeader(Header header) { pimpl_->SetHeader(header); }
void Session::SetTimeout(Timeout timeout) { pimpl_->SetTimeout(timeout); }
void Session::SetAuth(Authentication auth) { pimpl_->SetAuth(auth); }
void Session::SetPayload(Payload payload) { pimpl_->SetPayload(payload); }
void Session::SetRedirect(bool redirect) { pimpl_->SetRedirect(redirect); }
void Session::SetMaxRedirects(long max_redirects) { pimpl_->SetMaxRedirects(max_redirects); }
// void SetCookie(); Unimplemented
// void SetCookies(); Unimplemented
Response Session::Get() { return pimpl_->Get(); }
Response Session::Post() { return pimpl_->Post(); }
<commit_msg>Consolidate common code into a makeRequest method<commit_after>#include "session.h"
#include <functional>
#include <curl/curl.h>
#include "curlholder.h"
#include "util.h"
class Session::Impl {
public:
Impl();
void SetUrl(Url url);
void SetUrl(Url url, Parameters parameters);
void SetHeader(Header header);
void SetTimeout(Timeout timeout);
void SetAuth(Authentication auth);
void SetPayload(Payload payload);
void SetRedirect(bool redirect);
void SetMaxRedirects(long max_redirects);
// void SetCookie(); Unimplemented
// void SetCookies(); Unimplemented
Response Get();
Response Post();
private:
std::unique_ptr<CurlHolder, std::function<void(CurlHolder*)>> curl_;
Response makeRequest(CURL* curl);
static void freeHolder(CurlHolder* holder);
static CurlHolder* newHolder();
};
Session::Impl::Impl() {
curl_ = std::unique_ptr<CurlHolder, std::function<void(CurlHolder*)>>(newHolder(), &Impl::freeHolder);
auto curl = curl_->handle;
if (curl) {
// Set up some sensible defaults
auto version_info = curl_version_info(CURLVERSION_NOW);
auto version = std::string{"curl/"} + std::string{version_info->version};
curl_easy_setopt(curl, CURLOPT_USERAGENT, version.data());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_->error);
#if LIBCURL_VERSION_MAJOR >= 7
#if LIBCURL_VERSION_MINOR >= 25
#if LIBCURL_VERSION_PATCH >= 0
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
#endif
#endif
#endif
}
}
void Session::Impl::freeHolder(CurlHolder* holder) {
curl_easy_cleanup(holder->handle);
curl_slist_free_all(holder->chunk);
}
CurlHolder* Session::Impl::newHolder() {
CurlHolder* holder = new CurlHolder();
holder->handle = curl_easy_init();
return holder;
}
void Session::Impl::SetUrl(Url url) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.data());
}
}
void Session::Impl::SetUrl(Url url, Parameters parameters) {
auto curl = curl_->handle;
if (curl) {
Url new_url{url + "?"};
for(auto parameter = parameters.cbegin(); parameter != parameters.cend(); ++parameter) {
new_url += parameter->first + "=" + parameter->second + "&";
}
new_url = new_url.substr(0, new_url.size() - 1);
curl_easy_setopt(curl, CURLOPT_URL, new_url.data());
}
}
void Session::Impl::SetHeader(Header header) {
auto curl = curl_->handle;
if (curl) {
struct curl_slist* chunk = NULL;
for (auto item = header.cbegin(); item != header.cend(); ++item) {
auto header_string = std::string{item->first};
if (item->second.empty()) {
header_string += ";";
} else {
header_string += ": " + item->second;
}
chunk = curl_slist_append(chunk, header_string.data());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_->chunk = chunk;
}
}
}
void Session::Impl::SetTimeout(long timeout) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, timeout);
}
}
void Session::Impl::SetAuth(Authentication auth) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, auth.GetAuthString());
}
}
void Session::Impl::SetPayload(Payload payload) {
auto curl = curl_->handle;
if (curl) {
struct curl_slist* chunk = NULL;
auto payload_string = std::string{};
for (auto item = payload.cbegin(); item != payload.cend(); ++item) {
if (!payload_string.empty()) {
payload_string += "&";
}
payload_string += item->first + "=" + item->second;
}
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, payload_string.length());
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, payload_string.data());
}
}
void Session::Impl::SetRedirect(bool redirect) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, long(redirect));
}
}
void Session::Impl::SetMaxRedirects(long max_redirects) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, max_redirects);
}
}
Response Session::Impl::Get() {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 0L);
}
return makeRequest(curl);
}
Response Session::Impl::Post() {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 0L);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
}
return makeRequest(curl);
}
Response Session::Impl::makeRequest(CURL* curl) {
std::string response_string;
std::string header_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string);
curl_easy_perform(curl);
char* raw_url;
long response_code;
double elapsed;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url);
auto header = cpr::util::parseHeader(header_string);
response_string = cpr::util::parseResponse(response_string);
return Response{response_code, response_string, header, raw_url, elapsed};
}
Session::Session() : pimpl_{ new Impl{} } {}
Session::~Session() {}
void Session::SetUrl(Url url) { pimpl_->SetUrl(url); }
void Session::SetUrl(Url url, Parameters parameters) { pimpl_->SetUrl(url, parameters); }
void Session::SetHeader(Header header) { pimpl_->SetHeader(header); }
void Session::SetTimeout(Timeout timeout) { pimpl_->SetTimeout(timeout); }
void Session::SetAuth(Authentication auth) { pimpl_->SetAuth(auth); }
void Session::SetPayload(Payload payload) { pimpl_->SetPayload(payload); }
void Session::SetRedirect(bool redirect) { pimpl_->SetRedirect(redirect); }
void Session::SetMaxRedirects(long max_redirects) { pimpl_->SetMaxRedirects(max_redirects); }
// void SetCookie(); Unimplemented
// void SetCookies(); Unimplemented
Response Session::Get() { return pimpl_->Get(); }
Response Session::Post() { return pimpl_->Post(); }
<|endoftext|> |
<commit_before>8cdd2cfa-2e4f-11e5-bd30-28cfe91dbc4b<commit_msg>8ce50cb8-2e4f-11e5-94e0-28cfe91dbc4b<commit_after>8ce50cb8-2e4f-11e5-94e0-28cfe91dbc4b<|endoftext|> |
<commit_before>f7067b8a-585a-11e5-96ad-6c40088e03e4<commit_msg>f70e3f92-585a-11e5-a252-6c40088e03e4<commit_after>f70e3f92-585a-11e5-a252-6c40088e03e4<|endoftext|> |
<commit_before>5afc976e-2e4f-11e5-b0a5-28cfe91dbc4b<commit_msg>5b03e123-2e4f-11e5-8330-28cfe91dbc4b<commit_after>5b03e123-2e4f-11e5-8330-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* 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 copyright holders 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 <fstream>
#include <iomanip>
#include "sim/param.hh"
#include "encumbered/cpu/full/dyn_inst.hh"
#include "encumbered/cpu/full/spec_state.hh"
#include "encumbered/cpu/full/issue.hh"
#include "cpu/exetrace.hh"
#include "cpu/exec_context.hh"
#include "base/loader/symtab.hh"
#include "cpu/base.hh"
#include "cpu/static_inst.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// Methods for the InstRecord object
//
void
Trace::InstRecord::dump(ostream &outs)
{
if (flags[INTEL_FORMAT]) {
if (cpu->system->name() == trace_system) {
ccprintf(outs, "%7d ) ", cycle);
outs << "0x" << hex << PC << ":\t";
if (staticInst->isLoad()) {
outs << "<RD 0x" << hex << addr;
outs << ">";
} else if (staticInst->isStore()) {
outs << "<WR 0x" << hex << addr;
outs << ">";
}
outs << endl;
}
} else {
if (flags[PRINT_CYCLE])
ccprintf(outs, "%7d: ", cycle);
outs << cpu->name() << " ";
if (flags[TRACE_MISSPEC])
outs << (misspeculating ? "-" : "+") << " ";
if (flags[PRINT_THREAD_NUM])
outs << "T" << thread << " : ";
std::string sym_str;
Addr sym_addr;
if (debugSymbolTable
&& debugSymbolTable->findNearestSymbol(PC, sym_str, sym_addr)) {
if (PC != sym_addr)
sym_str += csprintf("+%d", PC - sym_addr);
outs << "@" << sym_str << " : ";
}
else {
outs << "0x" << hex << PC << " : ";
}
//
// Print decoded instruction
//
#if defined(__GNUC__) && (__GNUC__ < 3)
// There's a bug in gcc 2.x library that prevents setw()
// from working properly on strings
string mc(staticInst->disassemble(PC, debugSymbolTable));
while (mc.length() < 26)
mc += " ";
outs << mc;
#else
outs << setw(26) << left << staticInst->disassemble(PC, debugSymbolTable);
#endif
outs << " : ";
if (flags[PRINT_OP_CLASS]) {
outs << opClassStrings[staticInst->opClass()] << " : ";
}
if (flags[PRINT_RESULT_DATA] && data_status != DataInvalid) {
outs << " D=";
#if 0
if (data_status == DataDouble)
ccprintf(outs, "%f", data.as_double);
else
ccprintf(outs, "%#018x", data.as_int);
#else
ccprintf(outs, "%#018x", data.as_int);
#endif
}
if (flags[PRINT_EFF_ADDR] && addr_valid)
outs << " A=0x" << hex << addr;
if (flags[PRINT_INT_REGS] && regs_valid) {
for (int i = 0; i < 32;)
for (int j = i + 1; i <= j; i++)
ccprintf(outs, "r%02d = %#018x%s", i, iregs->regs[i],
((i == j) ? "\n" : " "));
outs << "\n";
}
if (flags[PRINT_FETCH_SEQ] && fetch_seq_valid)
outs << " FetchSeq=" << dec << fetch_seq;
if (flags[PRINT_CP_SEQ] && cp_seq_valid)
outs << " CPSeq=" << dec << cp_seq;
//
// End of line...
//
outs << endl;
}
}
vector<bool> Trace::InstRecord::flags(NUM_BITS);
string Trace::InstRecord::trace_system;
////////////////////////////////////////////////////////////////////////
//
// Parameter space for per-cycle execution address tracing options.
// Derive from ParamContext so we can override checkParams() function.
//
class ExecutionTraceParamContext : public ParamContext
{
public:
ExecutionTraceParamContext(const string &_iniSection)
: ParamContext(_iniSection)
{
}
void checkParams(); // defined at bottom of file
};
ExecutionTraceParamContext exeTraceParams("exetrace");
Param<bool> exe_trace_spec(&exeTraceParams, "speculative",
"capture speculative instructions", true);
Param<bool> exe_trace_print_cycle(&exeTraceParams, "print_cycle",
"print cycle number", true);
Param<bool> exe_trace_print_opclass(&exeTraceParams, "print_opclass",
"print op class", true);
Param<bool> exe_trace_print_thread(&exeTraceParams, "print_thread",
"print thread number", true);
Param<bool> exe_trace_print_effaddr(&exeTraceParams, "print_effaddr",
"print effective address", true);
Param<bool> exe_trace_print_data(&exeTraceParams, "print_data",
"print result data", true);
Param<bool> exe_trace_print_iregs(&exeTraceParams, "print_iregs",
"print all integer regs", false);
Param<bool> exe_trace_print_fetchseq(&exeTraceParams, "print_fetchseq",
"print fetch sequence number", false);
Param<bool> exe_trace_print_cp_seq(&exeTraceParams, "print_cpseq",
"print correct-path sequence number", false);
Param<bool> exe_trace_intel_format(&exeTraceParams, "intel_format",
"print trace in intel compatible format", false);
Param<string> exe_trace_system(&exeTraceParams, "trace_system",
"print trace of which system (client or server)",
"client");
//
// Helper function for ExecutionTraceParamContext::checkParams() just
// to get us into the InstRecord namespace
//
void
Trace::InstRecord::setParams()
{
flags[TRACE_MISSPEC] = exe_trace_spec;
flags[PRINT_CYCLE] = exe_trace_print_cycle;
flags[PRINT_OP_CLASS] = exe_trace_print_opclass;
flags[PRINT_THREAD_NUM] = exe_trace_print_thread;
flags[PRINT_RESULT_DATA] = exe_trace_print_effaddr;
flags[PRINT_EFF_ADDR] = exe_trace_print_data;
flags[PRINT_INT_REGS] = exe_trace_print_iregs;
flags[PRINT_FETCH_SEQ] = exe_trace_print_fetchseq;
flags[PRINT_CP_SEQ] = exe_trace_print_cp_seq;
flags[INTEL_FORMAT] = exe_trace_intel_format;
trace_system = exe_trace_system;
}
void
ExecutionTraceParamContext::checkParams()
{
Trace::InstRecord::setParams();
}
<commit_msg>Fix Lisa's CPU trace system check for syscall emulation.<commit_after>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* 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 copyright holders 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 <fstream>
#include <iomanip>
#include "sim/param.hh"
#include "encumbered/cpu/full/dyn_inst.hh"
#include "encumbered/cpu/full/spec_state.hh"
#include "encumbered/cpu/full/issue.hh"
#include "cpu/exetrace.hh"
#include "cpu/exec_context.hh"
#include "base/loader/symtab.hh"
#include "cpu/base.hh"
#include "cpu/static_inst.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// Methods for the InstRecord object
//
void
Trace::InstRecord::dump(ostream &outs)
{
if (flags[INTEL_FORMAT]) {
#if FULL_SYSTEM
bool is_trace_system = (cpu->system->name() == trace_system);
#else
bool is_trace_system = true;
#endif
if (is_trace_system) {
ccprintf(outs, "%7d ) ", cycle);
outs << "0x" << hex << PC << ":\t";
if (staticInst->isLoad()) {
outs << "<RD 0x" << hex << addr;
outs << ">";
} else if (staticInst->isStore()) {
outs << "<WR 0x" << hex << addr;
outs << ">";
}
outs << endl;
}
} else {
if (flags[PRINT_CYCLE])
ccprintf(outs, "%7d: ", cycle);
outs << cpu->name() << " ";
if (flags[TRACE_MISSPEC])
outs << (misspeculating ? "-" : "+") << " ";
if (flags[PRINT_THREAD_NUM])
outs << "T" << thread << " : ";
std::string sym_str;
Addr sym_addr;
if (debugSymbolTable
&& debugSymbolTable->findNearestSymbol(PC, sym_str, sym_addr)) {
if (PC != sym_addr)
sym_str += csprintf("+%d", PC - sym_addr);
outs << "@" << sym_str << " : ";
}
else {
outs << "0x" << hex << PC << " : ";
}
//
// Print decoded instruction
//
#if defined(__GNUC__) && (__GNUC__ < 3)
// There's a bug in gcc 2.x library that prevents setw()
// from working properly on strings
string mc(staticInst->disassemble(PC, debugSymbolTable));
while (mc.length() < 26)
mc += " ";
outs << mc;
#else
outs << setw(26) << left << staticInst->disassemble(PC, debugSymbolTable);
#endif
outs << " : ";
if (flags[PRINT_OP_CLASS]) {
outs << opClassStrings[staticInst->opClass()] << " : ";
}
if (flags[PRINT_RESULT_DATA] && data_status != DataInvalid) {
outs << " D=";
#if 0
if (data_status == DataDouble)
ccprintf(outs, "%f", data.as_double);
else
ccprintf(outs, "%#018x", data.as_int);
#else
ccprintf(outs, "%#018x", data.as_int);
#endif
}
if (flags[PRINT_EFF_ADDR] && addr_valid)
outs << " A=0x" << hex << addr;
if (flags[PRINT_INT_REGS] && regs_valid) {
for (int i = 0; i < 32;)
for (int j = i + 1; i <= j; i++)
ccprintf(outs, "r%02d = %#018x%s", i, iregs->regs[i],
((i == j) ? "\n" : " "));
outs << "\n";
}
if (flags[PRINT_FETCH_SEQ] && fetch_seq_valid)
outs << " FetchSeq=" << dec << fetch_seq;
if (flags[PRINT_CP_SEQ] && cp_seq_valid)
outs << " CPSeq=" << dec << cp_seq;
//
// End of line...
//
outs << endl;
}
}
vector<bool> Trace::InstRecord::flags(NUM_BITS);
string Trace::InstRecord::trace_system;
////////////////////////////////////////////////////////////////////////
//
// Parameter space for per-cycle execution address tracing options.
// Derive from ParamContext so we can override checkParams() function.
//
class ExecutionTraceParamContext : public ParamContext
{
public:
ExecutionTraceParamContext(const string &_iniSection)
: ParamContext(_iniSection)
{
}
void checkParams(); // defined at bottom of file
};
ExecutionTraceParamContext exeTraceParams("exetrace");
Param<bool> exe_trace_spec(&exeTraceParams, "speculative",
"capture speculative instructions", true);
Param<bool> exe_trace_print_cycle(&exeTraceParams, "print_cycle",
"print cycle number", true);
Param<bool> exe_trace_print_opclass(&exeTraceParams, "print_opclass",
"print op class", true);
Param<bool> exe_trace_print_thread(&exeTraceParams, "print_thread",
"print thread number", true);
Param<bool> exe_trace_print_effaddr(&exeTraceParams, "print_effaddr",
"print effective address", true);
Param<bool> exe_trace_print_data(&exeTraceParams, "print_data",
"print result data", true);
Param<bool> exe_trace_print_iregs(&exeTraceParams, "print_iregs",
"print all integer regs", false);
Param<bool> exe_trace_print_fetchseq(&exeTraceParams, "print_fetchseq",
"print fetch sequence number", false);
Param<bool> exe_trace_print_cp_seq(&exeTraceParams, "print_cpseq",
"print correct-path sequence number", false);
Param<bool> exe_trace_intel_format(&exeTraceParams, "intel_format",
"print trace in intel compatible format", false);
Param<string> exe_trace_system(&exeTraceParams, "trace_system",
"print trace of which system (client or server)",
"client");
//
// Helper function for ExecutionTraceParamContext::checkParams() just
// to get us into the InstRecord namespace
//
void
Trace::InstRecord::setParams()
{
flags[TRACE_MISSPEC] = exe_trace_spec;
flags[PRINT_CYCLE] = exe_trace_print_cycle;
flags[PRINT_OP_CLASS] = exe_trace_print_opclass;
flags[PRINT_THREAD_NUM] = exe_trace_print_thread;
flags[PRINT_RESULT_DATA] = exe_trace_print_effaddr;
flags[PRINT_EFF_ADDR] = exe_trace_print_data;
flags[PRINT_INT_REGS] = exe_trace_print_iregs;
flags[PRINT_FETCH_SEQ] = exe_trace_print_fetchseq;
flags[PRINT_CP_SEQ] = exe_trace_print_cp_seq;
flags[INTEL_FORMAT] = exe_trace_intel_format;
trace_system = exe_trace_system;
}
void
ExecutionTraceParamContext::checkParams()
{
Trace::InstRecord::setParams();
}
<|endoftext|> |
<commit_before>ae05348c-327f-11e5-8659-9cf387a8033e<commit_msg>ae0c6da8-327f-11e5-8d64-9cf387a8033e<commit_after>ae0c6da8-327f-11e5-8d64-9cf387a8033e<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
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 Jolla Ltd 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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 100;
int population = 32;
int children = 32;
int mutationRate = 0.1;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
omp_set_num_threads(omp_get_num_procs()*2);
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
for(int i = 0; i < population; ++i)
{
currentPopulation.append(Gene(mutationRate));
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
Gene children = currentPopulation[qrand()%population];
children.mutate();
newPopulation.append(children);
}
for(int testnr=0; testnr < population+children; ++testnr)
{
qDebug() << "\tGene " << testnr;
int score = 0;
newPopulation[testnr].saveFiles();
#pragma omp parallel for private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
newPopulation[testnr].saveScore(score);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden.endOfRound.txt", "./hiddenToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<commit_msg>Improved parallel running<commit_after>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
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 Jolla Ltd 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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 100;
int population = 32;
int children = 32;
int mutationRate = 0.1;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
omp_set_num_threads(omp_get_num_procs()*2);
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
for(int i = 0; i < population; ++i)
{
currentPopulation.append(Gene(mutationRate));
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
Gene children = currentPopulation[qrand()%population];
children.mutate();
newPopulation.append(children);
}
for(int testnr=0; testnr < population+children; ++testnr)
{
qDebug() << "\tGene " << testnr;
int score = 0;
newPopulation[testnr].saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
newPopulation[testnr].saveScore(score);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden.endOfRound.txt", "./hiddenToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<|endoftext|> |
<commit_before>#include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
pushall(h,i,j,k)
i <- d == 0
jnzrel(i, L_done)
h <- 1
b <- 0
j <- c >> 31 // save sign bit in j
j <- -j // convert sign to flag
c <- c ^ j // adjust multiplicand
c <- c - j
k <- d >> 31 // save sign bit in k
k <- -k // convert sign to flag
d <- d ^ k // adjust multiplier
d <- d - k
j <- j ^ k // final flip flag is in j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
L_done:
b <- b ^ j // adjust product for signed math
b <- b - j
popall(h,i,j,k)
ret
<commit_msg>Simplify imul (no need to check both signs)<commit_after>#include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
pushall(h,i,j)
i <- d == 0
jnzrel(i, L_done)
h <- 1
b <- 0
j <- d >> 31 // save sign bit in j
j <- -j // convert sign to flag
d <- d ^ j // adjust multiplier
d <- d - j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
L_done:
b <- b ^ j // adjust product for signed math
b <- b - j
popall(h,i,j)
ret
<|endoftext|> |
<commit_before><commit_msg>fixed race condition on session termination<commit_after><|endoftext|> |
<commit_before>4530c175-2e4f-11e5-9fef-28cfe91dbc4b<commit_msg>45378999-2e4f-11e5-9194-28cfe91dbc4b<commit_after>45378999-2e4f-11e5-9194-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
/* This must be included before anything else */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <yajr/internal/comms.hpp>
#include <yajr/rpc/methods.hpp>
#include <yajr/rpc/rpc.hpp>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
namespace yajr {
namespace rpc {
Message::PayloadKeys Message::kPayloadKey = {
"params",
"result",
"error"
};
bool operator< (rapidjson::Value const & l, rapidjson::Value const & r) {
rapidjson::Type lt = l.GetType();
rapidjson::Type rt = r.GetType();
if (lt < rt) {
return true;
}
if (lt > rt) {
return false;
}
/* same type */
std::size_t lh = hash_value(l);
std::size_t rh = hash_value(r);
return (lh < rh);
}
bool OutboundMessage::Accept(yajr::rpc::SendHandler& handler) {
VLOG(5);
return handler.StartObject()
&& handler.String("id")
&& emitId(handler)
&& emitMethod(handler)
&& handler.String(getPayloadKey())
&& payloadGenerator_(handler)
&& handler.EndObject()
;
}
bool OutboundMessage::send() {
VLOG(5);
::yajr::comms::internal::CommunicationPeer const * cP =
dynamic_cast< ::yajr::comms::internal::CommunicationPeer const * >
(peer_);
assert(cP &&
"peer needs to be set "
"to a proper communication peer "
"before outbound messages are sent");
unsigned char connected = cP->connected_;
assert(connected);
if (!connected) {
return false;
}
assert(cP->__checkInvariants());
Accept(cP->getWriter());
assert(cP->__checkInvariants());
cP->delimitFrame();
assert(cP->__checkInvariants());
cP->write();
assert(cP->__checkInvariants());
return true;
}
bool OutboundRequest::send(
::yajr::Peer const & peer
) {
VLOG(3);
setPeer(&peer);
return send();
}
InboundResponse::InboundResponse(
yajr::Peer const & peer, /**< [in] where we received from */
rapidjson::Value const & response,/**< [in] the error/result received */
rapidjson::Value const & id /**< [in] the id of this message */
)
:
InboundMessage(peer, response),
LocalIdentifier(
MessageFactory::lookupMethod(
id[rapidjson::SizeType(0)].GetString()
),
id[1].GetUint64()
)
{}
uv_loop_t const *
yajr::rpc::Message::getUvLoop() const {
return dynamic_cast< ::yajr::comms::internal::CommunicationPeer const * >
(getPeer())->getUvLoop();
}
std::size_t hash_value(rapidjson::Value const& v) {
/* switch(v.GetType()) { <-- would be more efficient but would have to
rely on private stuff from Value */
if(v.IsDouble()) {
return boost::hash<double>()(v.GetDouble());
}
if(v.IsUint64()) {
return boost::hash<uint64_t>()(v.GetUint64());
}
if(v.IsInt64()) {
return boost::hash<int64_t>()(v.GetInt64());
}
if(v.IsBool()) {
return boost::hash<bool>()(v.GetBool());
}
if(v.IsNull()) {
return boost::hash<uintptr_t>()(0);
}
if(v.IsArray()) {
std::size_t h = 0;
for (rapidjson::Value::ConstValueIterator
itr = v.Begin(); itr != v.End(); ++itr) {
h ^= hash_value(*itr);
}
return h;
}
if(v.IsObject()) {
std::size_t h = 0;
for (rapidjson::Value::ConstMemberIterator
itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) {
h ^= boost::hash<char const *>()(itr->name.GetString());
h ^= hash_value(itr->value);
}
return h;
}
if (v.IsString()) {
return boost::hash<std::string>()(std::string(v.GetString()));
}
assert(0);
return 0;
}
std::size_t hash_value(yajr::rpc::LocalId const & id) {
return
boost::hash<MethodName*>()(id.methodName_)
^
boost::hash<uint64_t>()(id.id_)
;
}
std::size_t hash_value(yajr::rpc::LocalIdentifier const & id) {
return boost::hash<yajr::rpc::LocalId>()(id.getLocalId());
}
std::size_t hash_value(yajr::rpc::RemoteIdentifier const & id) {
return hash_value(id.getRemoteId());
}
MethodName method::unknown("unknown");
MethodName method::echo("echo");
MethodName method::send_identity("send_identity");
MethodName method::policy_resolve("policy_resolve");
MethodName method::policy_unresolve("policy_unresolve");
MethodName method::policy_update("policy_update");
MethodName method::endpoint_declare("endpoint_declare");
MethodName method::endpoint_undeclare("endpoint_undeclare");
MethodName method::endpoint_resolve("endpoint_resolve");
MethodName method::endpoint_unresolve("endpoint_unresolve");
MethodName method::endpoint_update("endpoint_update");
MethodName method::state_report("state_report");
} /* yajr::rpc namespace */
} /* yajr namespace */
<commit_msg>return UV_ENOTCONN when a message is being sent to an offline peer<commit_after>/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
/* This must be included before anything else */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <yajr/internal/comms.hpp>
#include <yajr/rpc/methods.hpp>
#include <yajr/rpc/rpc.hpp>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
namespace yajr {
namespace rpc {
Message::PayloadKeys Message::kPayloadKey = {
"params",
"result",
"error"
};
bool operator< (rapidjson::Value const & l, rapidjson::Value const & r) {
rapidjson::Type lt = l.GetType();
rapidjson::Type rt = r.GetType();
if (lt < rt) {
return true;
}
if (lt > rt) {
return false;
}
/* same type */
std::size_t lh = hash_value(l);
std::size_t rh = hash_value(r);
return (lh < rh);
}
bool OutboundMessage::Accept(yajr::rpc::SendHandler& handler) {
VLOG(5);
return handler.StartObject()
&& handler.String("id")
&& emitId(handler)
&& emitMethod(handler)
&& handler.String(getPayloadKey())
&& payloadGenerator_(handler)
&& handler.EndObject()
;
}
bool OutboundMessage::send() {
VLOG(5);
::yajr::comms::internal::CommunicationPeer const * cP =
dynamic_cast< ::yajr::comms::internal::CommunicationPeer const * >
(peer_);
assert(cP &&
"peer needs to be set "
"to a proper communication peer "
"before outbound messages are sent");
unsigned char connected = cP->connected_;
if (!connected) {
cP->onError(UV_ENOTCONN);
assert(connected);
return false;
}
assert(cP->__checkInvariants());
Accept(cP->getWriter());
assert(cP->__checkInvariants());
cP->delimitFrame();
assert(cP->__checkInvariants());
cP->write();
assert(cP->__checkInvariants());
return true;
}
bool OutboundRequest::send(
::yajr::Peer const & peer
) {
VLOG(3);
setPeer(&peer);
return send();
}
InboundResponse::InboundResponse(
yajr::Peer const & peer, /**< [in] where we received from */
rapidjson::Value const & response,/**< [in] the error/result received */
rapidjson::Value const & id /**< [in] the id of this message */
)
:
InboundMessage(peer, response),
LocalIdentifier(
MessageFactory::lookupMethod(
id[rapidjson::SizeType(0)].GetString()
),
id[1].GetUint64()
)
{}
uv_loop_t const *
yajr::rpc::Message::getUvLoop() const {
return dynamic_cast< ::yajr::comms::internal::CommunicationPeer const * >
(getPeer())->getUvLoop();
}
std::size_t hash_value(rapidjson::Value const& v) {
/* switch(v.GetType()) { <-- would be more efficient but would have to
rely on private stuff from Value */
if(v.IsDouble()) {
return boost::hash<double>()(v.GetDouble());
}
if(v.IsUint64()) {
return boost::hash<uint64_t>()(v.GetUint64());
}
if(v.IsInt64()) {
return boost::hash<int64_t>()(v.GetInt64());
}
if(v.IsBool()) {
return boost::hash<bool>()(v.GetBool());
}
if(v.IsNull()) {
return boost::hash<uintptr_t>()(0);
}
if(v.IsArray()) {
std::size_t h = 0;
for (rapidjson::Value::ConstValueIterator
itr = v.Begin(); itr != v.End(); ++itr) {
h ^= hash_value(*itr);
}
return h;
}
if(v.IsObject()) {
std::size_t h = 0;
for (rapidjson::Value::ConstMemberIterator
itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) {
h ^= boost::hash<char const *>()(itr->name.GetString());
h ^= hash_value(itr->value);
}
return h;
}
if (v.IsString()) {
return boost::hash<std::string>()(std::string(v.GetString()));
}
assert(0);
return 0;
}
std::size_t hash_value(yajr::rpc::LocalId const & id) {
return
boost::hash<MethodName*>()(id.methodName_)
^
boost::hash<uint64_t>()(id.id_)
;
}
std::size_t hash_value(yajr::rpc::LocalIdentifier const & id) {
return boost::hash<yajr::rpc::LocalId>()(id.getLocalId());
}
std::size_t hash_value(yajr::rpc::RemoteIdentifier const & id) {
return hash_value(id.getRemoteId());
}
MethodName method::unknown("unknown");
MethodName method::echo("echo");
MethodName method::send_identity("send_identity");
MethodName method::policy_resolve("policy_resolve");
MethodName method::policy_unresolve("policy_unresolve");
MethodName method::policy_update("policy_update");
MethodName method::endpoint_declare("endpoint_declare");
MethodName method::endpoint_undeclare("endpoint_undeclare");
MethodName method::endpoint_resolve("endpoint_resolve");
MethodName method::endpoint_unresolve("endpoint_unresolve");
MethodName method::endpoint_update("endpoint_update");
MethodName method::state_report("state_report");
} /* yajr::rpc namespace */
} /* yajr namespace */
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "config.h"
#include "parse.hpp"
#include "ast.hpp"
#include "parse_op.hpp"
#include "peg.hpp"
#include "expand.hpp"
extern "C" {
//#include <gc_backptr.h>
void GC_dump();
extern unsigned GC_alloc_count;
}
//#include "symbol_table.hpp"
void parse_maps(ast::Environ & env) {
SourceFile * code = new_source_file(SOURCE_PREFIX "grammer.ins");
const char * s = code->begin();
try {
while (s != code->end()) {
parse_parse::Res r = parse_parse::parse(SourceStr(code, s, code->end()));
read_macro(r.parse, env);
s = r.end;
}
} catch (Error * err) {
fprintf(stderr, "%s\n", err->message().c_str());
exit(1);
}
}
int main(int argc, const char *argv[])
{
GC_disable();
//GC_free_space_divisor = 32;
assert(setvbuf(stdin, 0, _IOLBF, 0) == 0);
assert(setvbuf(stdout, 0, _IOLBF, 0) == 0);
parse_exp_->init();
ast::Environ env;
try {
parse_peg(SOURCE_PREFIX "grammer.in");
} catch (Error * err) {
fprintf(stderr, "%s\n", err->message().c_str());
exit(1);
}
SourceFile * prelude = new_source_file(SOURCE_PREFIX "prelude.zlh");
SourceFile * code = NULL;
try {
unsigned offset = 1;
bool debug_mode = false;
bool zls_mode = false;
bool for_ct = false;
bool load_prelude = true;
if (argc > offset && strcmp(argv[offset], "-d") == 0) {
debug_mode = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-s") == 0) {
zls_mode = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-C") == 0) {
for_ct = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-P") == 0) {
load_prelude = false;
offset++;
}
String base_name;
String output_fn;
if (argc > offset) {
code = new_source_file(argv[offset]);
const char * dot = strrchr(argv[offset], '.');
if (!dot) {
base_name = argv[offset];
output_fn = base_name;
} else {
StringBuf buf;
buf.append(argv[offset], dot);
base_name = buf.freeze(); // will also reset buf
if (strcmp(dot, ".zls") == 0)
buf.append(argv[offset]);
else
buf.append(argv[offset], dot);
buf.append(".zls");
output_fn = buf.freeze();
}
} else {
code = new_source_file(STDIN_FILENO);
output_fn = "a.out.zls";
}
//const Syntax * res = parse_str("TEST", SourceStr(code->entity(), code->begin(), code->end()));
//res->print();
//printf("\n");
//exit(0);
//printf("%d\n%s", ast::MACRO_PRELUDE_END - ast::MACRO_PRELUDE, ast::MACRO_PRELUDE);
if (zls_mode) {
printf("ZLS MODE\n");
parse_stmts_raw(SourceStr(code, code->begin(), code->end()), env);
} else {
parse_maps(env);
parse_stmts(parse_str("SLIST", SourceStr(prelude, prelude->begin(), prelude->end())),env);
if (debug_mode && load_prelude) {
SourceFile * prelude_body = new_source_file(SOURCE_PREFIX "prelude.zl");
parse_stmts(parse_str("SLIST", SourceStr(prelude_body, prelude_body->begin(), prelude_body->end())), env);
//SourceFile * class_body = new_source_file(SOURCE_PREFIX "class.zl");
//parse_stmts(parse_str("SLIST", SourceStr(class_body, class_body->begin(), class_body->end())), env);
} else if (load_prelude) {
load_macro_lib(SOURCE_PREFIX "prelude-fct.so", env);
}
//if (load_prelude && !for_ct)
//ast::import_file(SOURCE_PREFIX "test/class-new_abi.zl", env);
//ast::include_file(SOURCE_PREFIX "test/class-this_reg.zlh", env);
parse_stmts(parse_str("SLIST", SourceStr(code, code->begin(), code->end())),env);
}
ast::CompileWriter out;
out.open(output_fn, "w");
if (for_ct)
out.for_macro_sep_c = new ast::CompileWriter::ForMacroSepC;
//printf("FORCING COLLECTION\n");
//GC_gcollect();
//GC_dump();
ast::compile(env.top_level_symbols, out);
//ast::CompileWriter out2(ast::CompileWriter::ZLE);
//out2.open("a.out.zle", "w");
//ast::compile(env.top_level_symbols, out2);
//AST::ExecEnviron env;
//ast->eval(env);
if (for_ct) {
out.close();
StringBuf buf;
buf.printf("zls -g -fexceptions -shared -fpic -o %s-fct.so %s", ~base_name, ~output_fn);
String line = buf.freeze();
printf("%s\n", ~line);
int res = system(~line);
if (res == -1) {
perror("system(\"zls ...\")");
exit(2);
} else if (res != 0) {
exit(1);
}
}
out.for_macro_sep_c = NULL;
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
} catch (Error * err) {
//if (!err->source)
// err->source = code->entity();
fprintf(stderr, "%s\n", err->message().c_str());
exit(2);
}
//sleep(600);
}
// int main(int argc, const char *argv[])
// {
// printf("%u %u %u\n", sizeof(Syntax), sizeof(Syntax::D), sizeof(Syntax::Data));
// printf("XXX %u\n", sizeof(SymbolName));
// printf("XXX %u\n", sizeof(SourceStr));
// Syntax syn;
// int res = main2(argc,argv);
// printf("FORCING COLLECTION 2\n");
// GC_gcollect();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// return res;
// }
<commit_msg>Reenable GC.<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "config.h"
#include "parse.hpp"
#include "ast.hpp"
#include "parse_op.hpp"
#include "peg.hpp"
#include "expand.hpp"
extern "C" {
//#include <gc_backptr.h>
void GC_dump();
extern unsigned GC_alloc_count;
}
//#include "symbol_table.hpp"
void parse_maps(ast::Environ & env) {
SourceFile * code = new_source_file(SOURCE_PREFIX "grammer.ins");
const char * s = code->begin();
try {
while (s != code->end()) {
parse_parse::Res r = parse_parse::parse(SourceStr(code, s, code->end()));
read_macro(r.parse, env);
s = r.end;
}
} catch (Error * err) {
fprintf(stderr, "%s\n", err->message().c_str());
exit(1);
}
}
int main(int argc, const char *argv[])
{
//GC_disable();
//GC_free_space_divisor = 32;
assert(setvbuf(stdin, 0, _IOLBF, 0) == 0);
assert(setvbuf(stdout, 0, _IOLBF, 0) == 0);
parse_exp_->init();
ast::Environ env;
try {
parse_peg(SOURCE_PREFIX "grammer.in");
} catch (Error * err) {
fprintf(stderr, "%s\n", err->message().c_str());
exit(1);
}
SourceFile * prelude = new_source_file(SOURCE_PREFIX "prelude.zlh");
SourceFile * code = NULL;
try {
unsigned offset = 1;
bool debug_mode = false;
bool zls_mode = false;
bool for_ct = false;
bool load_prelude = true;
if (argc > offset && strcmp(argv[offset], "-d") == 0) {
debug_mode = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-s") == 0) {
zls_mode = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-C") == 0) {
for_ct = true;
offset++;
}
if (argc > offset && strcmp(argv[offset], "-P") == 0) {
load_prelude = false;
offset++;
}
String base_name;
String output_fn;
if (argc > offset) {
code = new_source_file(argv[offset]);
const char * dot = strrchr(argv[offset], '.');
if (!dot) {
base_name = argv[offset];
output_fn = base_name;
} else {
StringBuf buf;
buf.append(argv[offset], dot);
base_name = buf.freeze(); // will also reset buf
if (strcmp(dot, ".zls") == 0)
buf.append(argv[offset]);
else
buf.append(argv[offset], dot);
buf.append(".zls");
output_fn = buf.freeze();
}
} else {
code = new_source_file(STDIN_FILENO);
output_fn = "a.out.zls";
}
//const Syntax * res = parse_str("TEST", SourceStr(code->entity(), code->begin(), code->end()));
//res->print();
//printf("\n");
//exit(0);
//printf("%d\n%s", ast::MACRO_PRELUDE_END - ast::MACRO_PRELUDE, ast::MACRO_PRELUDE);
if (zls_mode) {
printf("ZLS MODE\n");
parse_stmts_raw(SourceStr(code, code->begin(), code->end()), env);
} else {
parse_maps(env);
parse_stmts(parse_str("SLIST", SourceStr(prelude, prelude->begin(), prelude->end())),env);
if (debug_mode && load_prelude) {
SourceFile * prelude_body = new_source_file(SOURCE_PREFIX "prelude.zl");
parse_stmts(parse_str("SLIST", SourceStr(prelude_body, prelude_body->begin(), prelude_body->end())), env);
//SourceFile * class_body = new_source_file(SOURCE_PREFIX "class.zl");
//parse_stmts(parse_str("SLIST", SourceStr(class_body, class_body->begin(), class_body->end())), env);
} else if (load_prelude) {
load_macro_lib(SOURCE_PREFIX "prelude-fct.so", env);
}
//if (load_prelude && !for_ct)
//ast::import_file(SOURCE_PREFIX "test/class-new_abi.zl", env);
//ast::include_file(SOURCE_PREFIX "test/class-this_reg.zlh", env);
parse_stmts(parse_str("SLIST", SourceStr(code, code->begin(), code->end())),env);
}
ast::CompileWriter out;
out.open(output_fn, "w");
if (for_ct)
out.for_macro_sep_c = new ast::CompileWriter::ForMacroSepC;
//printf("FORCING COLLECTION\n");
//GC_gcollect();
//GC_dump();
ast::compile(env.top_level_symbols, out);
//ast::CompileWriter out2(ast::CompileWriter::ZLE);
//out2.open("a.out.zle", "w");
//ast::compile(env.top_level_symbols, out2);
//AST::ExecEnviron env;
//ast->eval(env);
if (for_ct) {
out.close();
StringBuf buf;
buf.printf("zls -g -fexceptions -shared -fpic -o %s-fct.so %s", ~base_name, ~output_fn);
String line = buf.freeze();
printf("%s\n", ~line);
int res = system(~line);
if (res == -1) {
perror("system(\"zls ...\")");
exit(2);
} else if (res != 0) {
exit(1);
}
}
out.for_macro_sep_c = NULL;
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
//GC_generate_random_backtrace();
//fprintf(stderr, "---------------------------------------------\n");
} catch (Error * err) {
//if (!err->source)
// err->source = code->entity();
fprintf(stderr, "%s\n", err->message().c_str());
exit(2);
}
//sleep(600);
}
// int main(int argc, const char *argv[])
// {
// printf("%u %u %u\n", sizeof(Syntax), sizeof(Syntax::D), sizeof(Syntax::Data));
// printf("XXX %u\n", sizeof(SymbolName));
// printf("XXX %u\n", sizeof(SourceStr));
// Syntax syn;
// int res = main2(argc,argv);
// printf("FORCING COLLECTION 2\n");
// GC_gcollect();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// // GC_generate_random_backtrace();
// // fprintf(stderr, "---------------------------------------------\n");
// return res;
// }
<|endoftext|> |
<commit_before>b79b4a94-35ca-11e5-8f68-6c40088e03e4<commit_msg>b7a1f936-35ca-11e5-946a-6c40088e03e4<commit_after>b7a1f936-35ca-11e5-946a-6c40088e03e4<|endoftext|> |
<commit_before>9d7aeba3-4b02-11e5-bf4c-28cfe9171a43<commit_msg>Did ANOTHER thing<commit_after>9d8b2a33-4b02-11e5-b38b-28cfe9171a43<|endoftext|> |
<commit_before>809e9283-2d15-11e5-af21-0401358ea401<commit_msg>809e9284-2d15-11e5-af21-0401358ea401<commit_after>809e9284-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
void parse_data(std::ifstream &instream_data, std::vector <std::vector <std::string> >& vec_data,
std::map<std::string, std::vector <std::vector <std::string> > >& map_data){
int count=0;
while (instream_data){
std::string s;
if (!getline( instream_data, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
vec_data.push_back(record);
std::string full_name= vec_data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_data.insert(std::make_pair(modified_name, vec_data));
count++;
}
}
int main(){
std::vector <std::vector <std::string> > data;
std::map<std::string, std::vector <std::vector <std::string> > > map_player_salary;
std::vector <std::vector <std::string> > pitcher_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_pitcher_player;
std::vector <std::vector <std::string> > batter_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_batter_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
//parse_data for salary info
parse_data(infile, data, map_player_salary);
//test if player salary data works
for(int x=0; x<data.size(); x++){
if((data[x][21])!=""){
std::cout<<"Name: "<< data[x][1]<<" Salary: "<< data[x][21]<<std::endl;
}
}
if(map_player_salary.find("Clayton Kershaw")!=map_player_salary.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse data for pitcher info
parse_data(infile_pitcher, pitcher_data, map_pitcher_player);
//test if pitcher player data works
for(int x=0; x<pitcher_data.size(); x++){
if((pitcher_data[x][1])!="Name"){
std::cout<<"Name: "<< pitcher_data[x][1]<<" ERA: "<< pitcher_data[x][8]<<std::endl;
}
}
if(map_pitcher_player.find("Mike Wright")!=map_pitcher_player.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse data for batter info
parse_data(infile_batter, batter_data, map_batter_player);
//test if pitcher player data works
for(int x=0; x<pitcher_data.size(); x++){
if((pitcher_data[x][1])!="Name"){
std::cout<<"Name: "<< pitcher_data[x][1]<<" ERA: "<< pitcher_data[x][8]<<std::endl;
}
}
if(map_pitcher_player.find("Mike Wright")!=map_pitcher_player.end()){
std::cout<<"map works!!"<<std::endl;
}
return 0;
}
<commit_msg>Added batter testing info<commit_after>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
void parse_data(std::ifstream &instream_data, std::vector <std::vector <std::string> >& vec_data,
std::map<std::string, std::vector <std::vector <std::string> > >& map_data){
int count=0;
while (instream_data){
std::string s;
if (!getline( instream_data, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
vec_data.push_back(record);
std::string full_name= vec_data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_data.insert(std::make_pair(modified_name, vec_data));
count++;
}
}
int main(){
std::vector <std::vector <std::string> > data;
std::map<std::string, std::vector <std::vector <std::string> > > map_player_salary;
std::vector <std::vector <std::string> > pitcher_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_pitcher_player;
std::vector <std::vector <std::string> > batter_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_batter_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
//parse_data for salary info
parse_data(infile, data, map_player_salary);
//test if player salary data works
for(int x=0; x<data.size(); x++){
if((data[x][21])!=""){
std::cout<<"Name: "<< data[x][1]<<" Salary: "<< data[x][21]<<std::endl;
}
}
if(map_player_salary.find("Clayton Kershaw")!=map_player_salary.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse data for pitcher info
parse_data(infile_pitcher, pitcher_data, map_pitcher_player);
//test if pitcher player data works
for(int x=0; x<pitcher_data.size(); x++){
if((pitcher_data[x][1])!="Name"){
std::cout<<"Name: "<< pitcher_data[x][1]<<" ERA: "<< pitcher_data[x][8]<<std::endl;
}
}
if(map_pitcher_player.find("Mike Wright")!=map_pitcher_player.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse data for batter info
parse_data(infile_batter, batter_data, map_batter_player);
//test if pitcher player data works
for(int x=0; x<batter_data.size(); x++){
if((batter_data[x][1])!="Name"){
std::cout<<"Name: "<< batter_data[x][1]<<" BA: "<< batter_data[x][18]<<std::endl;
}
}
if(map_batter_player.find("Jose Abreu")!=map_batter_player.end()){
std::cout<<"map works!!"<<std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>9d468780-35ca-11e5-98e9-6c40088e03e4<commit_msg>9d4d0c5c-35ca-11e5-90b5-6c40088e03e4<commit_after>9d4d0c5c-35ca-11e5-90b5-6c40088e03e4<|endoftext|> |
<commit_before>31ba5052-2f67-11e5-9060-6c40088e03e4<commit_msg>31c0d45c-2f67-11e5-a23e-6c40088e03e4<commit_after>31c0d45c-2f67-11e5-a23e-6c40088e03e4<|endoftext|> |
<commit_before>baaac994-2e4f-11e5-b31a-28cfe91dbc4b<commit_msg>bab35a78-2e4f-11e5-af3f-28cfe91dbc4b<commit_after>bab35a78-2e4f-11e5-af3f-28cfe91dbc4b<|endoftext|> |
<commit_before>7619e6cc-2d53-11e5-baeb-247703a38240<commit_msg>761a69c6-2d53-11e5-baeb-247703a38240<commit_after>761a69c6-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>f052b87a-327f-11e5-98f1-9cf387a8033e<commit_msg>f059f7ab-327f-11e5-8c5e-9cf387a8033e<commit_after>f059f7ab-327f-11e5-8c5e-9cf387a8033e<|endoftext|> |
<commit_before>68c37ee4-2fa5-11e5-b8f3-00012e3d3f12<commit_msg>68c553a4-2fa5-11e5-ae85-00012e3d3f12<commit_after>68c553a4-2fa5-11e5-ae85-00012e3d3f12<|endoftext|> |
<commit_before>a3039c97-ad5b-11e7-9537-ac87a332f658<commit_msg>My Backup<commit_after>a373806b-ad5b-11e7-8bc3-ac87a332f658<|endoftext|> |
<commit_before>6bf6825c-2e4f-11e5-8798-28cfe91dbc4b<commit_msg>6c03e351-2e4f-11e5-b8f6-28cfe91dbc4b<commit_after>6c03e351-2e4f-11e5-b8f6-28cfe91dbc4b<|endoftext|> |
<commit_before>daafa505-ad58-11e7-9e65-ac87a332f658<commit_msg>The previous fix has been fixed<commit_after>db3bb94a-ad58-11e7-8b74-ac87a332f658<|endoftext|> |
<commit_before>697828e4-2fa5-11e5-8bcd-00012e3d3f12<commit_msg>6979d694-2fa5-11e5-82d3-00012e3d3f12<commit_after>6979d694-2fa5-11e5-82d3-00012e3d3f12<|endoftext|> |
<commit_before>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <exception>
#include <string>
#include <algorithm>
using namespace std;
using namespace cv;
RNG rng(12345);
typedef vector<Mat> MinecraftFont;
void printChar(const Mat& c)
{
cout << "CHAR!" << endl;
cout << c.rows << "/" << c.cols << endl;
for (int i = 0; i < c.rows; ++i) {
for (int j = 0; j < c.cols; ++j) {
cout << bool(int(c.at<uchar>(i, j))) << " ";
}
cout << endl;
}
}
char recognizeChar(const MinecraftFont& mf, const Mat& whiteOnBlacImg)
{
Mat candidate(whiteOnBlacImg.size(), whiteOnBlacImg.type());
cv::threshold(whiteOnBlacImg, candidate, 0.1, 255, CV_THRESH_BINARY_INV);
double similarity = 1.0/0.0;
char result = 0;
for (int f = 32; f < mf.size(); ++f) {
if ((candidate.rows > mf[f].rows) || (candidate.cols > mf[f].cols)) {
// TODO: resize here
continue;
}
for (int si = 0; si < mf[f].rows - candidate.rows + 1; si++) {
for (int sj = 0; sj < mf[f].cols - candidate.cols + 1; sj++) {
//cout << "ij " << si << " " << sj << endl;
Rect charRect = Rect(sj, si, candidate.cols, candidate.rows);
Mat windowNonBinary(mf[f], charRect);
//Mat window(windowNonBinary.size(), windowNonBinary.type());
Mat window = windowNonBinary;
/*if (f == '1') {
cout << si << " " << sj << endl;
printChar(window);
printChar(candidate);
//printChar(whiteOnBlacImg);
}*/
double current_similarity = norm(candidate, window);
//printChar(window);
if (current_similarity < similarity) {
//cout << current_similarity << " vs " << similarity << " " << int(f) << endl;
/*cout << "~~~~~~" << endl;
printChar(window);
cout << "------" << endl;
printChar(candidate);
cout << "~~~~~~" << endl;*/
result = f;
similarity = current_similarity;
}
}
}
}
return result;
}
struct contour_sorter // 'less' for contours
{
bool operator ()( const vector<Point>& a, const vector<Point> & b )
{
Rect ra(boundingRect(a));
Rect rb(boundingRect(b));
//return (ra.y < rb.y) || ((ra.y == rb.y) && (ra.x < rb.x));
return (ra.br().y < rb.br().y) || ((ra.br().y == rb.br().y) && (ra.br().x < ra.br().x));
}
};
void ScreenShotBB(const Mat& src, const Mat& processed_image, const MinecraftFont& mf)
{
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(processed_image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
sort(contours.begin(), contours.end(), contour_sorter());
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
// TODO: copy src to drawing
Mat drawing = src;
/*Mat drawing;
cvtColor(processed_image, drawing, CV_GRAY2RGB);*/
for( int i = 0; i < contours.size(); i++ ) {
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
//drawContours( drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 1, 1, 0 );
Mat c(processed_image, boundRect[i]);
printChar(c);
char rc = recognizeChar(mf, c);
//cout << "~~~~~~~~~~" << endl;
if (rc > 31) {
//cout << "OCR char: " << rc << " " << int(rc) << endl;
cout << rc;
} else {
cout << "Char not recognized!" << endl;
}
// cout << "~~~~~~~~~~" << endl;
cout << endl;
}
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
waitKey(0);
}
MinecraftFont LoadMinecraftFontImg(const std::string& imgName)
{
MinecraftFont font;
Mat src = imread(imgName, 1);
Mat srcGray;
cvtColor(src, srcGray, CV_BGR2GRAY);
Mat drawing = src;
for(int i = 4; i < src.cols - 16; i += 16) {
for (int j = 4; j < src.rows - 16; j += 16) {
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
Rect charRect = Rect(j, i, 16, 16);
rectangle(drawing, charRect.tl(), charRect.br(), color, 0, 0, 0);
Mat c(srcGray, charRect);
Mat cc;
c.copyTo(cc);
font.push_back(c);
}
}
namedWindow("Font", CV_WINDOW_AUTOSIZE);
imshow("Font", src);
//waitKey(0);
return font;
}
int main(int argc, const char** argv)
{
cout << "Hi!" << endl;
auto font = LoadMinecraftFontImg("minecraft_fixedwidth_font.png");
/*for (int f = 0; f < font.size(); ++f) {
cout << "NEW CHAR " << char(f) << endl;
printChar(font[f]);
}*/
if (argc != 3) {
cerr << "Bad args" << endl;
throw std::exception();
}
string input_image_name(argv[1]);
string output_image_name(argv[2]);
Mat image;
image = imread(input_image_name, 1);
if (!image.data) {
throw std::exception();
}
Mat processed_image;
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);
threshold(gray_image, processed_image, 222, -1, THRESH_TOZERO);
imwrite(output_image_name, processed_image);
ScreenShotBB(image, processed_image, font);
//namedWindow("Color image", CV_WINDOW_AUTOSIZE);
//namedWindow("Processed image", CV_WINDOW_AUTOSIZE);
//imshow("Color image", image);
//imshow("Processed image", processed_image);
}
<commit_msg>Now XYZ coordinates extraction almost works!<commit_after>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <exception>
#include <string>
#include <algorithm>
using namespace std;
using namespace cv;
RNG rng(12345);
typedef vector<Mat> MinecraftFont;
void printChar(const Mat& c)
{
cout << "CHAR!" << endl;
cout << c.rows << "/" << c.cols << endl;
for (int i = 0; i < c.rows; ++i) {
for (int j = 0; j < c.cols; ++j) {
cout << bool(int(c.at<uchar>(i, j))) << " ";
}
cout << endl;
}
}
char recognizeChar(const MinecraftFont& mf, const Mat& whiteOnBlacImg)
{
Mat candidate(whiteOnBlacImg.size(), whiteOnBlacImg.type());
cv::threshold(whiteOnBlacImg, candidate, 0.1, 255, CV_THRESH_BINARY_INV);
double similarity = 1.0/0.0;
char result = 0;
for (int f = 32; f < mf.size(); ++f) {
if ((candidate.rows > mf[f].rows) || (candidate.cols > mf[f].cols)) {
// TODO: resize here
continue;
}
for (int si = 0; si < mf[f].rows - candidate.rows + 1; si++) {
for (int sj = 0; sj < mf[f].cols - candidate.cols + 1; sj++) {
//cout << "ij " << si << " " << sj << endl;
Rect charRect = Rect(sj, si, candidate.cols, candidate.rows);
Mat windowNonBinary(mf[f], charRect);
//Mat window(windowNonBinary.size(), windowNonBinary.type());
Mat window = windowNonBinary;
/*if (f == '1') {
cout << si << " " << sj << endl;
printChar(window);
printChar(candidate);
//printChar(whiteOnBlacImg);
}*/
double current_similarity = norm(candidate, window);
//printChar(window);
if (current_similarity < similarity) {
//cout << current_similarity << " vs " << similarity << " " << int(f) << endl;
/*cout << "~~~~~~" << endl;
printChar(window);
cout << "------" << endl;
printChar(candidate);
cout << "~~~~~~" << endl;*/
result = f;
similarity = current_similarity;
}
}
}
}
return result;
}
struct contour_sorter // 'less' for contours
{
bool operator ()( const vector<Point>& a, const vector<Point> & b )
{
Rect ra(boundingRect(a));
Rect rb(boundingRect(b));
//return (ra.y < rb.y) || ((ra.y == rb.y) && (ra.x < rb.x));
return (ra.br().y < rb.br().y) || ((ra.br().y == rb.br().y) && (ra.br().x < ra.br().x));
}
};
bool yOverlap(const Rect& r1, const Rect& r2)
{
return (r1.y >= r2.y && r1.y <= r2.y + r2.height) || (r2.y >= r1.y && r2.y <= r1.y + r1.height);
}
void ScreenShotBB(const Mat& src, const Mat& processed_image, const MinecraftFont& mf)
{
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(processed_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
sort(contours.begin(), contours.end(), contour_sorter());
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
vector<Rect> firstCharsInLine( contours.size() );
// TODO: copy src to drawing
Mat drawing = src;
/*Mat drawing;
cvtColor(processed_image, drawing, CV_GRAY2RGB);*/
for( int i = 0; i < contours.size(); i++ ) {
approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
//drawContours( drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
}
vector<Rect> X;
vector<Rect> Y;
vector<Rect> Z;
vector<Rect> rectsToDraw;
for (int i = 0; i < boundRect.size(); i++) {
Mat c(processed_image, boundRect[i]);
//printChar(c);
char rc = recognizeChar(mf, c);
if (rc == 'X' || rc == 'Y' || rc == 'Z') {
cout << rc << endl;
rectsToDraw.push_back(boundRect[i]);
}
switch (rc) {
case 'X':
X.push_back(boundRect[i]);
break;
case 'Y':
Y.push_back(boundRect[i]);
break;
case 'Z':
Z.push_back(boundRect[i]);
break;
default:
break;
}
}
Rect XYZ_line;
for (int x = 0; x < X.size(); x++)
for (int y = 0; y < Y.size(); y++)
for (int z = 0; z < Z.size(); z++)
if (yOverlap(X[x], Y[y]) && yOverlap(X[x], Z[z]) && yOverlap(Y[y], Z[z])) {
cout << "FOUND!" << endl;
XYZ_line = Rect(0, X[x].tl().y, src.cols, X[x].height);
rectsToDraw.push_back(XYZ_line);
}
vector<Rect> chars_in_XYZ_line;
for (int i = 0; i < boundRect.size(); i++) {
if (yOverlap(boundRect[i], XYZ_line)) {
chars_in_XYZ_line.push_back(boundRect[i]);
rectsToDraw.push_back(boundRect[i]);
}
}
cout << "-----" << endl;
sort(chars_in_XYZ_line.begin(), chars_in_XYZ_line.end(), [](const Rect& r1, const Rect& r2){return r1.x < r2.x;});
for (int i = 0; i < chars_in_XYZ_line.size(); i++) {
Mat c(processed_image, chars_in_XYZ_line[i]);
char rc = recognizeChar(mf, c);
cout << rc;
}
cout << "-----" << endl;
rectsToDraw = chars_in_XYZ_line;
for (int i = 0; i < rectsToDraw.size(); i++) {
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
rectangle( drawing, rectsToDraw[i].tl(), rectsToDraw[i].br(), color, 1, 1, 0 );
}
cout << "Showing the window" << endl;
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
waitKey(0);
}
MinecraftFont LoadMinecraftFontImg(const std::string& imgName)
{
MinecraftFont font;
Mat src = imread(imgName, 1);
Mat srcGray;
cvtColor(src, srcGray, CV_BGR2GRAY);
Mat drawing = src;
for(int i = 4; i < src.cols - 16; i += 16) {
for (int j = 4; j < src.rows - 16; j += 16) {
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
Rect charRect = Rect(j, i, 16, 16);
rectangle(drawing, charRect.tl(), charRect.br(), color, 0, 0, 0);
Mat c(srcGray, charRect);
Mat cc;
c.copyTo(cc);
font.push_back(c);
}
}
namedWindow("Font", CV_WINDOW_AUTOSIZE);
imshow("Font", src);
//waitKey(0);
return font;
}
int main(int argc, const char** argv)
{
cout << "Hi!" << endl;
auto font = LoadMinecraftFontImg("minecraft_fixedwidth_font.png");
/*for (int f = 0; f < font.size(); ++f) {
cout << "NEW CHAR " << char(f) << endl;
printChar(font[f]);
}*/
if (argc != 3) {
cerr << "Bad args" << endl;
throw std::exception();
}
string input_image_name(argv[1]);
string output_image_name(argv[2]);
Mat image;
image = imread(input_image_name, 1);
if (!image.data) {
throw std::exception();
}
Mat processed_image;
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);
threshold(gray_image, processed_image, 222, -1, THRESH_TOZERO);
imwrite(output_image_name, processed_image);
ScreenShotBB(image, processed_image, font);
//namedWindow("Color image", CV_WINDOW_AUTOSIZE);
//namedWindow("Processed image", CV_WINDOW_AUTOSIZE);
//imshow("Color image", image);
//imshow("Processed image", processed_image);
}
<|endoftext|> |
<commit_before>ce8f2200-327f-11e5-9187-9cf387a8033e<commit_msg>ce957eca-327f-11e5-8028-9cf387a8033e<commit_after>ce957eca-327f-11e5-8028-9cf387a8033e<|endoftext|> |
<commit_before>78e830c0-2d53-11e5-baeb-247703a38240<commit_msg>78e8b3b0-2d53-11e5-baeb-247703a38240<commit_after>78e8b3b0-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>/*
PureBackup - human-readable backup output
Copyright (C) 2005 Ben Wilhelm
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; version 2 of the license only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
*/
#include "parse.h"
#include "debug.h"
#include "tree.h"
#include "state.h"
#include <string>
#include <fstream>
#include <set>
using namespace std;
// Makes sure everything up to this is virtual
MountTree *getMountpointLocation(const string &loc) {
const char *tpt = loc.c_str();
MountTree *cpos = getRoot();
while(*tpt) {
CHECK(*tpt == '/');
tpt++;
CHECK(*tpt);
CHECK(cpos->type == MTT_UNINITTED || cpos->type == MTT_VIRTUAL);
cpos->type = MTT_VIRTUAL;
// isolate the next path component
const char *tpn = strchr(tpt, '/');
if(!tpn)
tpn = tpt + strlen(tpt);
string linkage = string(tpt, tpn);
cpos = &cpos->virtual_links[linkage];
tpt = tpn;
}
return cpos;
}
void createMountpoint(const string &loc, const string &type, const string &source) {
MountTree *dpt =getMountpointLocation(loc);
CHECK(dpt);
CHECK(dpt->type == MTT_UNINITTED);
if(type == "file") {
dpt->type = MTT_FILE;
dpt->file_source = source;
dpt->file_scanned = false;
} else {
CHECK(0);
}
}
void printAll() {
printf("ROOT\n");
getRoot()->print(2);
}
void readConfig(const string &conffile) {
// First we init root
{
getRoot()->type = MTT_UNINITTED;
}
ifstream ifs(conffile.c_str());
kvData kvd;
while(getkvData(ifs, kvd)) {
if(kvd.category == "mountpoint") {
createMountpoint(kvd.consume("mount"), kvd.consume("type"), kvd.consume("source"));
} else {
CHECK(0);
}
}
CHECK(getRoot()->checkSanity());
printAll();
}
void scanPaths() {
getRoot()->scan();
CHECK(getRoot()->checkSanity());
//printAll();
}
enum { TYPE_CREATE, TYPE_DELETE, TYPE_COPY, TYPE_APPEND, TYPE_STORE, TYPE_END };
string type_strs[] = { "CREATE", "DELETE", "COPY", "APPEND", "STORE" };
class Instruction {
public:
vector<pair<bool, string> > depends;
vector<pair<bool, string> > removes;
vector<pair<bool, string> > creates;
int type;
string textout() const;
};
void dumpa(string *str, const string &txt, const vector<pair<bool, string> > &vek) {
*str += " " + txt + "\n";
for(int i = 0; i < vek.size(); i++)
*str += StringPrintf(" %d:%s\n", vek[i].first, vek[i].second.c_str());
}
string Instruction::textout() const {
string rvx;
CHECK(type >= 0 && type < TYPE_END);
rvx = type_strs[type] + "\n";
dumpa(&rvx, "Depends:", depends);
dumpa(&rvx, "Removes:", removes);
dumpa(&rvx, "Creates:", creates);
return rvx;
}
vector<Instruction> sortInst(const vector<Instruction> &oinst) {
vector<Instruction> buckets[TYPE_END];
map<pair<bool, string>, int> leftToUse;
for(int i = 0; i < oinst.size(); i++) {
CHECK(oinst[i].type >= 0 && oinst[i].type < TYPE_END);
buckets[oinst[i].type].push_back(oinst[i]);
for(int j = 0; j < oinst[i].depends.size(); j++)
leftToUse[oinst[i].depends[j]]++;
}
CHECK(buckets[0].size() == 1);
set<pair<bool, string> > live;
vector<Instruction> kinstr;
while(1) {
int tcl = 0;
for(int i = 0; i < TYPE_END; i++)
tcl += buckets[i].size();
if(!tcl)
break;
printf("Starting pass, %d instructions left\n", tcl);
for(int i = 0; i < TYPE_END; i++) {
for(int j = 0; j < buckets[i].size(); j++) {
bool good = true;
for(int k = 0; good && k < buckets[i][j].depends.size(); k++)
if(!live.count(buckets[i][j].depends[k]))
good = false;
for(int k = 0; good && k < buckets[i][j].removes.size(); k++)
if(!(leftToUse[buckets[i][j].removes[k]] == 0 || leftToUse[buckets[i][j].removes[k]] == 1 && count(buckets[i][j].depends.begin(), buckets[i][j].depends.end(), buckets[i][j].removes[k])))
good = false;
if(!good)
continue;
//dprintf("%s\n", buckets[i][j].textout().c_str());
for(int k = 0; k < buckets[i][j].depends.size(); k++)
leftToUse[buckets[i][j].depends[k]]--;
for(int k = 0; k < buckets[i][j].removes.size(); k++) {
CHECK(live.count(buckets[i][j].removes[k]));
live.erase(buckets[i][j].removes[k]);
}
for(int k = 0; k < buckets[i][j].creates.size(); k++) {
pair<bool, string> ite = buckets[i][j].creates[k];
CHECK(!live.count(ite));
live.insert(buckets[i][j].creates[k]);
}
kinstr.push_back(buckets[i][j]);
buckets[i].erase(buckets[i].begin() + j);
j--;
}
}
}
return kinstr;
}
int main() {
readConfig("purebackup.conf");
scanPaths();
map<string, Item> realitems;
getRoot()->dumpItems(&realitems, "");
dprintf("%d items found\n", realitems.size());
State origstate;
origstate.readFile("state0");
map<pair<bool, string>, Item> citem;
map<long long, vector<pair<bool, string> > > citemsizemap;
set<string> ftc;
Instruction fi;
fi.type = TYPE_CREATE;
vector<Instruction> inst;
for(map<string, Item>::iterator itr = realitems.begin(); itr != realitems.end(); itr++) {
CHECK(itr->second.size >= 0);
CHECK(itr->second.timestamp >= 0);
ftc.insert(itr->first);
}
for(map<string, Item>::const_iterator itr = origstate.getItemDb().begin(); itr != origstate.getItemDb().end(); itr++) {
CHECK(itr->second.size >= 0);
CHECK(itr->second.timestamp >= 0);
CHECK(citem.count(make_pair(false, itr->first)) == 0);
citem[make_pair(false, itr->first)] = itr->second;
citemsizemap[itr->second.size].push_back(make_pair(false, itr->first));
fi.creates.push_back(make_pair(false, itr->first));
ftc.insert(itr->first);
}
// FTC is the union of the files in realitems and origstate
// citem is the items that we can look at
// citemsizemap is the same, only organized by size
for(set<string>::iterator itr = ftc.begin(); itr != ftc.end(); itr++) {
if(realitems.count(*itr)) {
const Item &ite = realitems.find(*itr)->second;
bool got = false;
// First, we check to see if it's the same file as existed before
if(!got && citem.count(make_pair(false, *itr))) {
const Item &pite = citem.find(make_pair(false, *itr))->second;
if(ite.size == pite.size && ite.timestamp == pite.timestamp) {
// It's identical!
printf("Preserve file %s\n", itr->c_str());
fi.creates.push_back(make_pair(true, *itr));
got = true;
} else if(ite.size == pite.size && ite.checksum() == pite.checksum()) {
// It's touched! But we currently don't care!
printf("Preserve file %s\n", itr->c_str());
fi.creates.push_back(make_pair(true, *itr));
got = true;
} else if(ite.size > pite.size && ite.checksumPart(pite.size) == pite.checksum()) {
// It's appended!
printf("Appendination on %s, dude!\n", itr->c_str());
Instruction ti;
ti.type = TYPE_APPEND;
ti.creates.push_back(make_pair(true, *itr));
ti.depends.push_back(make_pair(false, *itr));
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
}
}
// Okay, now we see if it's been copied from somewhere
if(!got) {
const vector<pair<bool, string> > &sli = citemsizemap[ite.size];
printf("Trying %d originals\n", sli.size());
for(int k = 0; k < sli.size(); k++) {
CHECK(ite.size == citem[sli[k]].size);
printf("Comparing with %d:%s\n", sli[k].first, sli[k].second.c_str());
printf("%s vs %s\n", ite.checksum().toString().c_str(), citem[sli[k]].checksum().toString().c_str());
if(ite.checksum() == citem[sli[k]].checksum()) {
printf("Holy crapcock! Copying %s from %s:%d! MADNESS\n", itr->c_str(), sli[k].second.c_str(), sli[k].first);
Instruction ti;
ti.type = TYPE_COPY;
ti.creates.push_back(make_pair(true, *itr));
ti.depends.push_back(sli[k]);
if(citem.count(make_pair(false, *itr)))
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
break;
}
}
}
// And now we give up and just create it
if(!got) {
printf("Creating %s from GALACTIC ETHER\n", itr->c_str());
Instruction ti;
ti.type = TYPE_STORE;
ti.creates.push_back(make_pair(true, *itr));
if(citem.count(make_pair(false, *itr)))
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
}
CHECK(got);
citem[make_pair(true, *itr)] = ite;
citemsizemap[ite.size].push_back(make_pair(true, *itr));
} else {
CHECK(citem.count(make_pair(false, *itr)));
printf("Delete file %s\n", itr->c_str());
Instruction ti;
ti.type = TYPE_DELETE;
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
}
}
inst.push_back(fi);
inst = sortInst(inst);
for(int i = 0; i < inst.size(); i++)
printf("%s\n", inst[i].textout().c_str());
}
<commit_msg><commit_after>/*
PureBackup - human-readable backup output
Copyright (C) 2005 Ben Wilhelm
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; version 2 of the license only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
*/
#include "parse.h"
#include "debug.h"
#include "tree.h"
#include "state.h"
#include <string>
#include <fstream>
#include <set>
using namespace std;
// Makes sure everything up to this is virtual
MountTree *getMountpointLocation(const string &loc) {
const char *tpt = loc.c_str();
MountTree *cpos = getRoot();
while(*tpt) {
CHECK(*tpt == '/');
tpt++;
CHECK(*tpt);
CHECK(cpos->type == MTT_UNINITTED || cpos->type == MTT_VIRTUAL);
cpos->type = MTT_VIRTUAL;
// isolate the next path component
const char *tpn = strchr(tpt, '/');
if(!tpn)
tpn = tpt + strlen(tpt);
string linkage = string(tpt, tpn);
cpos = &cpos->virtual_links[linkage];
tpt = tpn;
}
return cpos;
}
void createMountpoint(const string &loc, const string &type, const string &source) {
MountTree *dpt =getMountpointLocation(loc);
CHECK(dpt);
CHECK(dpt->type == MTT_UNINITTED);
if(type == "file") {
dpt->type = MTT_FILE;
dpt->file_source = source;
dpt->file_scanned = false;
} else {
CHECK(0);
}
}
void printAll() {
printf("ROOT\n");
getRoot()->print(2);
}
void readConfig(const string &conffile) {
// First we init root
{
getRoot()->type = MTT_UNINITTED;
}
ifstream ifs(conffile.c_str());
kvData kvd;
while(getkvData(ifs, kvd)) {
if(kvd.category == "mountpoint") {
createMountpoint(kvd.consume("mount"), kvd.consume("type"), kvd.consume("source"));
} else {
CHECK(0);
}
}
CHECK(getRoot()->checkSanity());
printAll();
}
void scanPaths() {
getRoot()->scan();
CHECK(getRoot()->checkSanity());
//printAll();
}
enum { TYPE_CREATE, TYPE_ROTATE, TYPE_DELETE, TYPE_COPY, TYPE_APPEND, TYPE_STORE, TYPE_END };
string type_strs[] = { "CREATE", "ROTATE", "DELETE", "COPY", "APPEND", "STORE" };
class Instruction {
public:
vector<pair<bool, string> > depends;
vector<pair<bool, string> > removes;
vector<pair<bool, string> > creates;
int type;
string textout() const;
};
void dumpa(string *str, const string &txt, const vector<pair<bool, string> > &vek) {
*str += " " + txt + "\n";
for(int i = 0; i < vek.size(); i++)
*str += StringPrintf(" %d:%s\n", vek[i].first, vek[i].second.c_str());
}
string Instruction::textout() const {
string rvx;
CHECK(type >= 0 && type < TYPE_END);
rvx = type_strs[type] + "\n";
dumpa(&rvx, "Depends:", depends);
dumpa(&rvx, "Removes:", removes);
dumpa(&rvx, "Creates:", creates);
return rvx;
}
void loopprocess(int pos, vector<int> *loop, const vector<Instruction> &inst,
const map<pair<bool, string>, vector<int> > &depon,
const map<pair<bool, string>, int> &creates,
const set<pair<bool, string> > &removed,
vector<bool> *noprob) {
//printf("Entering loopprocess %d\n", pos);
//printf("%s\n", inst[pos].textout().c_str());
if((*noprob)[pos])
return;
if(loop->size() && loop->back() == pos)
return;
//printf("Pushback %d\n", pos);
loop->push_back(pos);
if(set<int>(loop->begin(), loop->end()).size() != loop->size()) {
//printf("LOOP!\n");
//for(int i = 0; i < loop->size(); i++)
//printf("%d\n", (*loop)[i]);
return;
}
//printf("Starting depends %d\n", pos);
vector<int> bku = *loop;
// Anything this depends on must exist
for(int i = 0; i < inst[pos].depends.size(); i++) {
CHECK(creates.count(inst[pos].depends[i]));
loopprocess(creates.find(inst[pos].depends[i])->second, loop, inst, depon, creates, removed, noprob);
if(*loop != bku)
return;
}
//printf("Starting removes %d\n", pos);
// Anything this removes must have its dependencies complete
for(int i = 0; i < inst[pos].removes.size(); i++) {
if(!depon.count(inst[pos].removes[i]))
continue;
const vector<int> &dpa = depon.find(inst[pos].removes[i])->second;
for(int j = 0; j < dpa.size(); j++) {
loopprocess(dpa[j], loop, inst, depon, creates, removed, noprob);
if(*loop != bku)
return;
}
}
//printf("Done %d\n", pos);
loop->pop_back();
(*noprob)[pos] = true;
}
vector<Instruction> deloop(const vector<Instruction> &inst) {
map<pair<bool, string>, vector<int> > depon;
map<pair<bool, string>, int> creates;
set<pair<bool, string> > removed;
vector<bool> noprob(inst.size());
for(int i = 0; i < inst.size(); i++) {
for(int j = 0; j < inst[i].depends.size(); j++)
depon[inst[i].depends[j]].push_back(i);
for(int j = 0; j < inst[i].creates.size(); j++) {
CHECK(!creates.count(inst[i].creates[j]));
creates[inst[i].creates[j]] = i;
}
for(int j = 0; j < inst[i].removes.size(); j++) {
CHECK(!removed.count(inst[i].removes[j]));
removed.insert(inst[i].removes[j]);
}
}
for(int i = 0; i < inst.size(); i++) {
vector<int> loop;
loopprocess(i, &loop, inst, depon, creates, removed, &noprob);
if(loop.size()) {
printf("Loop! %d\n", loop.size());
CHECK(loop.size() >= 3);
CHECK(loop.front() == loop.back());
set<int> lps(loop.begin(), loop.end());
CHECK(lps.size() == loop.size() - 1);
// TODO: preserve the actual rotation order
Instruction rotinstr;
rotinstr.type = TYPE_ROTATE;
for(set<int>::iterator it = lps.begin(); it != lps.end(); it++) {
CHECK(inst[*it].type == TYPE_COPY);
rotinstr.depends.insert(rotinstr.depends.end(), inst[*it].depends.begin(), inst[*it].depends.end());
rotinstr.removes.insert(rotinstr.removes.end(), inst[*it].removes.begin(), inst[*it].removes.end());
rotinstr.creates.insert(rotinstr.creates.end(), inst[*it].creates.begin(), inst[*it].creates.end());
}
CHECK((set<pair<bool, string> >(rotinstr.depends.begin(), rotinstr.depends.end()).size() == rotinstr.depends.size()));
CHECK((set<pair<bool, string> >(rotinstr.removes.begin(), rotinstr.removes.end()).size() == rotinstr.removes.size()));
CHECK((set<pair<bool, string> >(rotinstr.creates.begin(), rotinstr.creates.end()).size() == rotinstr.creates.size()));
vector<Instruction> nistr;
for(int i = 0; i < inst.size(); i++)
if(!lps.count(i))
nistr.push_back(inst[i]);
nistr.push_back(rotinstr);
return deloop(nistr);
}
}
return inst;
}
vector<Instruction> sortInst(vector<Instruction> oinst) {
oinst = deloop(oinst);
vector<Instruction> buckets[TYPE_END];
map<pair<bool, string>, int> leftToUse;
for(int i = 0; i < oinst.size(); i++) {
CHECK(oinst[i].type >= 0 && oinst[i].type < TYPE_END);
buckets[oinst[i].type].push_back(oinst[i]);
for(int j = 0; j < oinst[i].depends.size(); j++)
leftToUse[oinst[i].depends[j]]++;
}
CHECK(buckets[0].size() == 1);
set<pair<bool, string> > live;
vector<Instruction> kinstr;
while(1) {
int tcl = 0;
for(int i = 0; i < TYPE_END; i++)
tcl += buckets[i].size();
if(!tcl)
break;
printf("Starting pass, %d instructions left\n", tcl);
for(int i = 0; i < TYPE_END; i++) {
for(int j = 0; j < buckets[i].size(); j++) {
bool good = true;
for(int k = 0; good && k < buckets[i][j].depends.size(); k++)
if(!live.count(buckets[i][j].depends[k]))
good = false;
for(int k = 0; good && k < buckets[i][j].removes.size(); k++)
if(!(leftToUse[buckets[i][j].removes[k]] == 0 || leftToUse[buckets[i][j].removes[k]] == 1 && count(buckets[i][j].depends.begin(), buckets[i][j].depends.end(), buckets[i][j].removes[k])))
good = false;
if(!good)
continue;
//dprintf("%s\n", buckets[i][j].textout().c_str());
for(int k = 0; k < buckets[i][j].depends.size(); k++)
leftToUse[buckets[i][j].depends[k]]--;
for(int k = 0; k < buckets[i][j].removes.size(); k++) {
CHECK(live.count(buckets[i][j].removes[k]));
live.erase(buckets[i][j].removes[k]);
}
for(int k = 0; k < buckets[i][j].creates.size(); k++) {
pair<bool, string> ite = buckets[i][j].creates[k];
CHECK(!live.count(ite));
live.insert(buckets[i][j].creates[k]);
}
kinstr.push_back(buckets[i][j]);
buckets[i].erase(buckets[i].begin() + j);
j--;
}
}
for(int i = 0; i < TYPE_END; i++)
tcl -= buckets[i].size();
CHECK(tcl != 0);
}
return kinstr;
}
int main() {
readConfig("purebackup.conf");
scanPaths();
map<string, Item> realitems;
getRoot()->dumpItems(&realitems, "");
dprintf("%d items found\n", realitems.size());
State origstate;
origstate.readFile("state0");
map<pair<bool, string>, Item> citem;
map<long long, vector<pair<bool, string> > > citemsizemap;
set<string> ftc;
Instruction fi;
fi.type = TYPE_CREATE;
vector<Instruction> inst;
for(map<string, Item>::iterator itr = realitems.begin(); itr != realitems.end(); itr++) {
CHECK(itr->second.size >= 0);
CHECK(itr->second.timestamp >= 0);
ftc.insert(itr->first);
}
for(map<string, Item>::const_iterator itr = origstate.getItemDb().begin(); itr != origstate.getItemDb().end(); itr++) {
CHECK(itr->second.size >= 0);
CHECK(itr->second.timestamp >= 0);
CHECK(citem.count(make_pair(false, itr->first)) == 0);
citem[make_pair(false, itr->first)] = itr->second;
citemsizemap[itr->second.size].push_back(make_pair(false, itr->first));
fi.creates.push_back(make_pair(false, itr->first));
ftc.insert(itr->first);
}
// FTC is the union of the files in realitems and origstate
// citem is the items that we can look at
// citemsizemap is the same, only organized by size
for(set<string>::iterator itr = ftc.begin(); itr != ftc.end(); itr++) {
if(realitems.count(*itr)) {
const Item &ite = realitems.find(*itr)->second;
bool got = false;
// First, we check to see if it's the same file as existed before
if(!got && citem.count(make_pair(false, *itr))) {
const Item &pite = citem.find(make_pair(false, *itr))->second;
if(ite.size == pite.size && ite.timestamp == pite.timestamp) {
// It's identical!
printf("Preserve file %s\n", itr->c_str());
fi.creates.push_back(make_pair(true, *itr));
got = true;
} else if(ite.size == pite.size && ite.checksum() == pite.checksum()) {
// It's touched! But we currently don't care!
printf("Preserve file %s\n", itr->c_str());
fi.creates.push_back(make_pair(true, *itr));
got = true;
} else if(ite.size > pite.size && ite.checksumPart(pite.size) == pite.checksum()) {
// It's appended!
printf("Appendination on %s, dude!\n", itr->c_str());
Instruction ti;
ti.type = TYPE_APPEND;
ti.creates.push_back(make_pair(true, *itr));
ti.depends.push_back(make_pair(false, *itr));
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
}
}
// Okay, now we see if it's been copied from somewhere
if(!got) {
const vector<pair<bool, string> > &sli = citemsizemap[ite.size];
printf("Trying %d originals\n", sli.size());
for(int k = 0; k < sli.size(); k++) {
CHECK(ite.size == citem[sli[k]].size);
printf("Comparing with %d:%s\n", sli[k].first, sli[k].second.c_str());
printf("%s vs %s\n", ite.checksum().toString().c_str(), citem[sli[k]].checksum().toString().c_str());
if(ite.checksum() == citem[sli[k]].checksum()) {
printf("Holy crapcock! Copying %s from %s:%d! MADNESS\n", itr->c_str(), sli[k].second.c_str(), sli[k].first);
Instruction ti;
ti.type = TYPE_COPY;
ti.creates.push_back(make_pair(true, *itr));
ti.depends.push_back(sli[k]);
if(citem.count(make_pair(false, *itr)))
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
break;
}
}
}
// And now we give up and just create it
if(!got) {
printf("Creating %s from GALACTIC ETHER\n", itr->c_str());
Instruction ti;
ti.type = TYPE_STORE;
ti.creates.push_back(make_pair(true, *itr));
if(citem.count(make_pair(false, *itr)))
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
got = true;
}
CHECK(got);
citem[make_pair(true, *itr)] = ite;
citemsizemap[ite.size].push_back(make_pair(true, *itr));
} else {
CHECK(citem.count(make_pair(false, *itr)));
printf("Delete file %s\n", itr->c_str());
Instruction ti;
ti.type = TYPE_DELETE;
ti.removes.push_back(make_pair(false, *itr));
inst.push_back(ti);
}
}
inst.push_back(fi);
inst = sortInst(inst);
for(int i = 0; i < inst.size(); i++)
printf("%s\n", inst[i].textout().c_str());
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2001 Peter Dimov and Multi Media Ltd.
Copyright (c) 2016 Modified Work Barrett Adair
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY
*/
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS \
BOOST_CLBL_TRTS_ABOMINABLE_CONST
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS volatile
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS \
BOOST_CLBL_TRTS_ABOMINABLE_VOLATILE
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const volatile
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS \
BOOST_CLBL_TRTS_ABOMINABLE_CONST BOOST_CLBL_TRTS_ABOMINABLE_VOLATILE
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#ifndef BOOST_CLBL_TRTS_DISABLE_REFERENCE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS &
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS &
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS &&
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS &&
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const &
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS const &
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS volatile &
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS volatile &
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const volatile &
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS const volatile &
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const &&
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS const &&
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS volatile &&
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS volatile &&
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#define BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS const volatile &&
#define BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS const volatile &&
#include <boost/callable_traits/detail/unguarded/pmf_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
#undef BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
#endif // #ifndef BOOST_CLBL_TRTS_DISABLE_REFERENCE_QUALIFIERS
<commit_msg>Delete pmf.hpp<commit_after><|endoftext|> |
<commit_before>#include <cstdio>
#include <cmath>
#include <vector>
#include <random>
#include <chrono>
namespace NQueens
{
class Board
{
std::default_random_engine generator;
std::vector<int> rows;
int refillInterval;
int getConflictCount(int row, int col) const
{
int count = 0;
for (int i = 0; i < (int)rows.size(); ++i)
if (i != col && (rows[i] == row || abs(rows[i] - row) == abs(i - col)))
count++;
return count;
}
public:
Board(unsigned seed, int n, int interval): generator(seed), rows(n), refillInterval(interval)
{
Refill();
}
void Refill()
{
for (int i = 0; i < (int)rows.size(); ++i)
rows[i] = i;
for (int i = 0; i < (int)rows.size(); ++i)
std::swap(rows[i], rows[generator() % (int)rows.size()]);
}
void Solve()
{
int moveCount = 0;
while (true)
{
std::vector<int> candidates;
for (int i = 0; i < (int)rows.size(); ++i)
if (getConflictCount(rows[i], i) > 0)
candidates.push_back(i);
if (candidates.empty())
return;
int worstQueenColumn = candidates[generator() % candidates.size()];
candidates.clear();
int minConflictCount = (int)rows.size();
for (int i = 0; i < (int)rows.size(); ++i)
{
int conflictCount = getConflictCount(i, worstQueenColumn);
if (conflictCount < minConflictCount)
{
minConflictCount = conflictCount;
candidates.clear();
}
if (conflictCount == minConflictCount)
candidates.push_back(i);
}
if (!candidates.empty())
rows[worstQueenColumn] = candidates[generator() % candidates.size()];
++moveCount;
if (refillInterval == moveCount)
{
Refill();
moveCount = 0;
}
}
}
void Print() const
{
for (int i = 0; i < (int)rows.size(); ++i)
{
for (int j = 0; j < (int)rows.size(); ++j)
printf(rows[j] == i ? "*" : "_");
printf("\n");
}
}
};
}
int main()
{
int n;
scanf("%d", &n);
if (n < 0)
return 1;
NQueens::Board queens(std::chrono::system_clock::now().time_since_epoch().count(), n, 2 * n);
queens.Solve();
queens.Print();
return 0;
}
<commit_msg>nqueens: improved random index generation using `std::uniform_int_distribution` instead of calculating indexes using remainder<commit_after>#include <cstdio>
#include <cmath>
#include <vector>
#include <random>
#include <chrono>
namespace NQueens
{
class Board
{
std::default_random_engine generator;
std::vector<int> rows;
int refillInterval;
int getConflictCount(int row, int col) const
{
int count = 0;
for (int i = 0; i < (int)rows.size(); ++i)
if (i != col && (rows[i] == row || abs(rows[i] - row) == abs(i - col)))
count++;
return count;
}
public:
Board(unsigned seed, int n, int interval): generator(seed), rows(n), refillInterval(interval)
{
Refill();
}
void Refill()
{
for (int i = 0; i < (int)rows.size(); ++i)
rows[i] = i;
for (int i = 0; i < (int)rows.size(); ++i)
{
std::uniform_int_distribution<> distribution(0, (int)rows.size() - 1);
std::swap(rows[i], rows[distribution(generator)]);
}
}
void Solve()
{
int moveCount = 0;
while (true)
{
std::vector<int> candidates;
for (int i = 0; i < (int)rows.size(); ++i)
if (getConflictCount(rows[i], i) > 0)
candidates.push_back(i);
if (candidates.empty())
return;
std::uniform_int_distribution<> worstDistribution(0, (int)candidates.size() - 1);
int worstQueenColumn = candidates[worstDistribution(generator)];
candidates.clear();
int minConflictCount = (int)rows.size();
for (int i = 0; i < (int)rows.size(); ++i)
{
int conflictCount = getConflictCount(i, worstQueenColumn);
if (conflictCount < minConflictCount)
{
minConflictCount = conflictCount;
candidates.clear();
}
if (conflictCount == minConflictCount)
candidates.push_back(i);
}
if (!candidates.empty())
{
std::uniform_int_distribution<> bestDistribution(0, (int)candidates.size() - 1);
rows[worstQueenColumn] = candidates[bestDistribution(generator)];
}
++moveCount;
if (refillInterval == moveCount)
{
Refill();
moveCount = 0;
}
}
}
void Print() const
{
for (int i = 0; i < (int)rows.size(); ++i)
{
for (int j = 0; j < (int)rows.size(); ++j)
printf(rows[j] == i ? "*" : "_");
printf("\n");
}
}
};
}
int main()
{
int n;
scanf("%d", &n);
if (n < 0)
return 1;
NQueens::Board queens(std::chrono::system_clock::now().time_since_epoch().count(), n, 2 * n);
queens.Solve();
queens.Print();
return 0;
}
<|endoftext|> |
<commit_before>#include "httpd.h"
#include <stdio.h>
#include <string.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
int opterr = 1;
int optind = 1;
int optopt;
char *optarg;
static int getopt(int argc, char** argv, const char* opts) {
static int sp = 1;
register int c;
register char *cp;
if(sp == 1) {
if(optind >= argc ||
argv[optind][0] != '-' || argv[optind][1] == '\0')
return(EOF);
else if(strcmp(argv[optind], "--") == 0) {
optind++;
return(EOF);
}
}
optopt = c = argv[optind][sp];
if(c == ':' || (cp=strchr((char*)opts, c)) == NULL) {
if(argv[optind][++sp] == '\0') {
optind++;
sp = 1;
}
return('?');
}
if(*++cp == ':') {
if(argv[optind][sp+1] != '\0')
optarg = &argv[optind++][sp+1];
else if(++optind >= argc) {
sp = 1;
return('?');
} else
optarg = argv[optind++];
sp = 1;
} else {
if(argv[optind][++sp] == '\0') {
sp = 1;
optind++;
}
optarg = NULL;
}
return(c);
}
typedef std::map<std::string, std::string> Config;
typedef std::map<std::string, Config> ConfigList;
ConfigList loadConfigs(const char* filename) {
ConfigList configs;
Config config;
char buffer[BUFSIZ];
FILE* fp = fopen(filename, "r");
std::string profile = "global";
while(fp && fgets(buffer, sizeof(buffer), fp)) {
char* line = buffer;
char* ptr = strpbrk(line, "\r\n");
if (*line == '#') continue;
if (ptr) *ptr = 0;
ptr = strchr(line, ']');
if (*line == '[' && ptr) {
*ptr = 0;
if (config.size())
configs[profile] = config;
config.clear();
profile = line+1;
continue;
}
ptr = strchr(line, '=');
if (ptr && *line != ';') {
*ptr++ = 0;
config[line] = ptr;
}
}
configs[profile] = config;
if (fp) fclose(fp);
return configs;
}
bool loadAuthfile(const char* filename, std::vector<tthttpd::server::AuthInfo>& auths) {
char buffer[BUFSIZ];
auths.clear();
FILE* fp = fopen(filename, "r");
if (!fp) return false;
while(fp && fgets(buffer, sizeof(buffer), fp)) {
char* line = buffer;
char* ptr = strpbrk(line, "\r\n");
if (ptr) *ptr = 0;
ptr = strchr(line, ':');
if (ptr) *ptr++ = 0;
tthttpd::server::AuthInfo info;
info.user = line;
info.pass = ptr;
auths.push_back(info);
}
fclose(fp);
return true;
}
int main(int argc, char* argv[]) {
int c;
const char* root = ".";
const char* port = "www";
const char* cfg = NULL;
bool spawn_exec = false;
int verbose = 0;
int family = AF_UNSPEC;
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
opterr = 0;
while ((c = getopt(argc, (char**)argv, "46p:c:d:xvh") != -1)) {
switch (optopt) {
case '4': family = AF_INET; break;
case '6': family = AF_INET6; break;
case 'p': port = optarg; break;
case 'c': cfg = optarg; break;
case 'd': root = optarg; break;
case 'v': verbose++; break;
#ifdef PACKAGE_VERSION
case 'V':
printf("%s\n", PACKAGE_VERSION);
break;
#endif
case 'x': spawn_exec = true; break;
case 'h': argc = 0; break;
case '?': break;
default: argc = 0; break;
}
optarg = NULL;
}
if (argc == 0) {
const char* lines[] = {
#ifdef PACKAGE_VERSION
"tthttpd (tinytinyhttpd) " PACKAGE_VERSION<
#else
"tthttpd (tinytinyhttpd)",
#endif
" usage: tthttpd [-4|-6] [-p server-port] [-c config-file] [-d root-dir] [-v] [-x] [-h]",
" -4 : ipv4 only",
" -6 : ipv6 only",
" -p : server port (name or numeric)",
" -c : config file",
" -d : root directory",
" -v : verbose mode (-vvv mean level 3)",
" -x : spawn file as cgi if possible",
" -h : show this usage",
#ifdef PACKAGE_VERSION
" -V : show version",
#endif
NULL
};
for (const char** ptr = lines; *ptr; ptr++)
std::cerr << *ptr << std::endl;
exit(1);
}
tthttpd::server httpd(port);
httpd.bindRoot(root);
httpd.spawn_executable = spawn_exec;
httpd.verbose_mode = verbose;
httpd.family = family;
if (cfg) {
ConfigList configs = loadConfigs(cfg);
Config config;
Config::iterator it;
std::string val;
val = configs["global"]["path"];
#ifdef _WIN32
if (val.size()) {
std::string tmp = "PATH=";
tmp += val;
putenv(tmp.c_str());
}
#else
if (val.size()) setenv("PATH", val.c_str(), true);
#endif
val = configs["global"]["root"];
if (val.size()) httpd.bindRoot(val);
val = configs["global"]["ipv4_only"];
if (val == "on") httpd.family = AF_INET;
val = configs["global"]["ipv6_only"];
if (val == "on") httpd.family = AF_INET6;
val = configs["global"]["hostname"];
if (val.size()) httpd.hostname = val;
val = configs["global"]["port"];
if (val.size()) httpd.port = val;
val = configs["global"]["indexpages"];
if (val.size()) httpd.default_pages = tthttpd::split_string(val, ",");
val = configs["global"]["charset"];
if (val.size()) httpd.fs_charset = val;
val = configs["global"]["chroot"];
if (val.size()) httpd.chroot = val;
val = configs["global"]["user"];
if (val.size()) httpd.user = val;
val = configs["global"]["debug"];
if (val == "on") httpd.verbose_mode = 1;
else if (val.size()) httpd.verbose_mode = atol(val.c_str());
val = configs["global"]["spawnexec"];
if (val == "on") httpd.spawn_executable = true;
config = configs["request/aliases"];
for (it = config.begin(); it != config.end(); it++)
httpd.request_aliases[it->first] = it->second;
config = configs["mime/types"];
for (it = config.begin(); it != config.end(); it++)
httpd.mime_types[it->first] = it->second;
config = configs["request/environments"];
for (it = config.begin(); it != config.end(); it++)
httpd.request_environments[it->first] = it->second;
config = configs["authentication"];
for (it = config.begin(); it != config.end(); it++) {
tthttpd::server::BasicAuthInfo basic_auth_info;
basic_auth_info.target = it->first;
std::vector<std::string> infos = tthttpd::split_string(it->second, ",");
basic_auth_info.method = infos[0];
basic_auth_info.realm = infos[1];
std::vector<tthttpd::server::AuthInfo> auth_infos;
if (loadAuthfile(infos[2].c_str(), auth_infos))
basic_auth_info.auths = auth_infos;
httpd.basic_auths.push_back(basic_auth_info);
}
} else {
#ifdef _WIN32
httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe";
httpd.mime_types["php"] = "@c:/progra~1/php/php-cgi.exe";
httpd.mime_types["rb"] = "@c:/ruby/bin/ruby.exe";
httpd.mime_types["py"] = "@c:/python25/python.exe";
#else
httpd.mime_types["cgi"] = "@/usr/bin/perl";
httpd.mime_types["php"] = "@/usr/bin/php-cgi";
httpd.mime_types["rb"] = "@/usr/bin/ruby";
httpd.mime_types["py"] = "@/usr/bin/python";
#endif
}
httpd.start();
httpd.wait();
// Ctrl-C to break
return 0;
}
<commit_msg>< to ,<commit_after>#include "httpd.h"
#include <stdio.h>
#include <string.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
int opterr = 1;
int optind = 1;
int optopt;
char *optarg;
static int getopt(int argc, char** argv, const char* opts) {
static int sp = 1;
register int c;
register char *cp;
if(sp == 1) {
if(optind >= argc ||
argv[optind][0] != '-' || argv[optind][1] == '\0')
return(EOF);
else if(strcmp(argv[optind], "--") == 0) {
optind++;
return(EOF);
}
}
optopt = c = argv[optind][sp];
if(c == ':' || (cp=strchr((char*)opts, c)) == NULL) {
if(argv[optind][++sp] == '\0') {
optind++;
sp = 1;
}
return('?');
}
if(*++cp == ':') {
if(argv[optind][sp+1] != '\0')
optarg = &argv[optind++][sp+1];
else if(++optind >= argc) {
sp = 1;
return('?');
} else
optarg = argv[optind++];
sp = 1;
} else {
if(argv[optind][++sp] == '\0') {
sp = 1;
optind++;
}
optarg = NULL;
}
return(c);
}
typedef std::map<std::string, std::string> Config;
typedef std::map<std::string, Config> ConfigList;
ConfigList loadConfigs(const char* filename) {
ConfigList configs;
Config config;
char buffer[BUFSIZ];
FILE* fp = fopen(filename, "r");
std::string profile = "global";
while(fp && fgets(buffer, sizeof(buffer), fp)) {
char* line = buffer;
char* ptr = strpbrk(line, "\r\n");
if (*line == '#') continue;
if (ptr) *ptr = 0;
ptr = strchr(line, ']');
if (*line == '[' && ptr) {
*ptr = 0;
if (config.size())
configs[profile] = config;
config.clear();
profile = line+1;
continue;
}
ptr = strchr(line, '=');
if (ptr && *line != ';') {
*ptr++ = 0;
config[line] = ptr;
}
}
configs[profile] = config;
if (fp) fclose(fp);
return configs;
}
bool loadAuthfile(const char* filename, std::vector<tthttpd::server::AuthInfo>& auths) {
char buffer[BUFSIZ];
auths.clear();
FILE* fp = fopen(filename, "r");
if (!fp) return false;
while(fp && fgets(buffer, sizeof(buffer), fp)) {
char* line = buffer;
char* ptr = strpbrk(line, "\r\n");
if (ptr) *ptr = 0;
ptr = strchr(line, ':');
if (ptr) *ptr++ = 0;
tthttpd::server::AuthInfo info;
info.user = line;
info.pass = ptr;
auths.push_back(info);
}
fclose(fp);
return true;
}
int main(int argc, char* argv[]) {
int c;
const char* root = ".";
const char* port = "www";
const char* cfg = NULL;
bool spawn_exec = false;
int verbose = 0;
int family = AF_UNSPEC;
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
opterr = 0;
while ((c = getopt(argc, (char**)argv, "46p:c:d:xvh") != -1)) {
switch (optopt) {
case '4': family = AF_INET; break;
case '6': family = AF_INET6; break;
case 'p': port = optarg; break;
case 'c': cfg = optarg; break;
case 'd': root = optarg; break;
case 'v': verbose++; break;
#ifdef PACKAGE_VERSION
case 'V':
printf("%s\n", PACKAGE_VERSION);
break;
#endif
case 'x': spawn_exec = true; break;
case 'h': argc = 0; break;
case '?': break;
default: argc = 0; break;
}
optarg = NULL;
}
if (argc == 0) {
const char* lines[] = {
#ifdef PACKAGE_VERSION
"tthttpd (tinytinyhttpd) " PACKAGE_VERSION,
#else
"tthttpd (tinytinyhttpd)",
#endif
" usage: tthttpd [-4|-6] [-p server-port] [-c config-file] [-d root-dir] [-v] [-x] [-h]",
" -4 : ipv4 only",
" -6 : ipv6 only",
" -p : server port (name or numeric)",
" -c : config file",
" -d : root directory",
" -v : verbose mode (-vvv mean level 3)",
" -x : spawn file as cgi if possible",
" -h : show this usage",
#ifdef PACKAGE_VERSION
" -V : show version",
#endif
NULL
};
for (const char** ptr = lines; *ptr; ptr++)
std::cerr << *ptr << std::endl;
exit(1);
}
tthttpd::server httpd(port);
httpd.bindRoot(root);
httpd.spawn_executable = spawn_exec;
httpd.verbose_mode = verbose;
httpd.family = family;
if (cfg) {
ConfigList configs = loadConfigs(cfg);
Config config;
Config::iterator it;
std::string val;
val = configs["global"]["path"];
#ifdef _WIN32
if (val.size()) {
std::string tmp = "PATH=";
tmp += val;
putenv(tmp.c_str());
}
#else
if (val.size()) setenv("PATH", val.c_str(), true);
#endif
val = configs["global"]["root"];
if (val.size()) httpd.bindRoot(val);
val = configs["global"]["ipv4_only"];
if (val == "on") httpd.family = AF_INET;
val = configs["global"]["ipv6_only"];
if (val == "on") httpd.family = AF_INET6;
val = configs["global"]["hostname"];
if (val.size()) httpd.hostname = val;
val = configs["global"]["port"];
if (val.size()) httpd.port = val;
val = configs["global"]["indexpages"];
if (val.size()) httpd.default_pages = tthttpd::split_string(val, ",");
val = configs["global"]["charset"];
if (val.size()) httpd.fs_charset = val;
val = configs["global"]["chroot"];
if (val.size()) httpd.chroot = val;
val = configs["global"]["user"];
if (val.size()) httpd.user = val;
val = configs["global"]["debug"];
if (val == "on") httpd.verbose_mode = 1;
else if (val.size()) httpd.verbose_mode = atol(val.c_str());
val = configs["global"]["spawnexec"];
if (val == "on") httpd.spawn_executable = true;
config = configs["request/aliases"];
for (it = config.begin(); it != config.end(); it++)
httpd.request_aliases[it->first] = it->second;
config = configs["mime/types"];
for (it = config.begin(); it != config.end(); it++)
httpd.mime_types[it->first] = it->second;
config = configs["request/environments"];
for (it = config.begin(); it != config.end(); it++)
httpd.request_environments[it->first] = it->second;
config = configs["authentication"];
for (it = config.begin(); it != config.end(); it++) {
tthttpd::server::BasicAuthInfo basic_auth_info;
basic_auth_info.target = it->first;
std::vector<std::string> infos = tthttpd::split_string(it->second, ",");
basic_auth_info.method = infos[0];
basic_auth_info.realm = infos[1];
std::vector<tthttpd::server::AuthInfo> auth_infos;
if (loadAuthfile(infos[2].c_str(), auth_infos))
basic_auth_info.auths = auth_infos;
httpd.basic_auths.push_back(basic_auth_info);
}
} else {
#ifdef _WIN32
httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe";
httpd.mime_types["php"] = "@c:/progra~1/php/php-cgi.exe";
httpd.mime_types["rb"] = "@c:/ruby/bin/ruby.exe";
httpd.mime_types["py"] = "@c:/python25/python.exe";
#else
httpd.mime_types["cgi"] = "@/usr/bin/perl";
httpd.mime_types["php"] = "@/usr/bin/php-cgi";
httpd.mime_types["rb"] = "@/usr/bin/ruby";
httpd.mime_types["py"] = "@/usr/bin/python";
#endif
}
httpd.start();
httpd.wait();
// Ctrl-C to break
return 0;
}
<|endoftext|> |
<commit_before>#include "scope.h"
#include "details/ir/emit.h"
using namespace Yuni;
namespace ny {
namespace ir {
namespace Producer {
namespace {
bool extractParameterDetails(Scope& scope, AST::Node& node, uint32_t& lvid, AnyString& name) {
bool isRef = false;
bool isConst = false;
AST::Node* typeNode = nullptr;
for (auto& child: node.children) {
switch (child.rule) {
case AST::rgIdentifier: {
name = child.text;
break;
}
case AST::rgRef:
isRef = true;
break;
case AST::rgConst:
isConst = true;
break;
case AST::rgCref:
isRef = true;
isConst = true;
break;
case AST::rgVarType: {
for (auto& typeChild: child.children) {
switch (typeChild.rule) {
case AST::rgType: {
typeNode = &typeChild;
break;
}
default:
return unexpectedNode(child, "on/scope/fail/param/details/type");
}
}
break;
}
default:
return unexpectedNode(child, "on/scope/fail/param/details");
}
}
if (typeNode != nullptr) {
if (!scope.visitASTType(*typeNode, lvid))
return false;
switch (lvid) {
default: {
if (isRef)
ir::emit::type::qualifierRef(scope.ircode(), lvid, true);
if (isConst)
ir::emit::type::qualifierConst(scope.ircode(), lvid, true);
break;
}
case (uint32_t) -1: {
lvid = 0; // let's pretend no type was given
break;
}
case 0: // void
return error(*typeNode) << "void is not a valid parameter type";
}
}
return true;
}
bool findParameter(Scope& scope, AST::Node& node, uint32_t& lvid, AnyString& name) {
bool hasParameter = false;
for (auto& child: node.children) {
if (unlikely(child.rule != AST::rgFuncParams))
return unexpectedNode(child, "on/scope/fail");
for (auto& paramsChild: child.children) {
if (unlikely(paramsChild.rule != AST::rgFuncParam))
return unexpectedNode(paramsChild, "on/scope/fail/params");
if (unlikely(hasParameter))
return error(paramsChild) << "'on scope fail' accepts only one parameter";
hasParameter = true;
if (!extractParameterDetails(scope, paramsChild, lvid, name))
return false;
}
}
return true;
}
} // namespace
bool Scope::visitASTExprOnScopeFail(AST::Node& scopeNode, AST::Node& scopeFailNode) {
assert(scopeNode.rule == AST::rgScope);
assert(scopeFailNode.rule == AST::rgOnScopeFail);
uint32_t lvidType = 0;
AnyString name;
if (!findParameter(*this, scopeFailNode, lvidType, name))
return false;
auto& irout = ircode();
ir::emit::trace(irout, "begin 'on scope fail'");
// skip the entire block
uint32_t ignJmp = ir::emit::jmp(irout);
// label to trigger the error handler
uint32_t startLabel = ir::emit::label(irout, nextvar());
uint32_t var = [&]() -> uint32_t {
if (name.empty())
return 0;
// the error itself
uint32_t var = ir::emit::alloc(irout, nextvar());
if (lvidType != 0) {
auto& operands = irout.emit<isa::Op::follow>();
operands.follower = var;
operands.lvid = lvidType;
operands.symlink = 0;
}
return var;
}();
// register the 'on scope fail'
emitDebugpos(scopeFailNode);
ir::emit::on::scopefail(irout, var, startLabel);
{
if (not visitASTExprScope(scopeNode))
return false;
}
// jmp at the end of the original scope
uint32_t jmpOffset = ir::emit::jmp(irout);
onScopeFailExitLabels.emplace_back(scopeFailNode, jmpOffset, var);
// emit label to skip the entire block
irout.at<ir::isa::Op::jmp>(ignJmp).label = ir::emit::label(irout, nextvar());
ir::emit::trace(irout, "end 'on scope fail'");
return true;
}
} // namespace Producer
} // namespace ir
} // namespace ny
<commit_msg>semantic: on-scope-fail: register after code to avoid invalid reuse<commit_after>#include "scope.h"
#include "details/ir/emit.h"
using namespace Yuni;
namespace ny {
namespace ir {
namespace Producer {
namespace {
bool extractParameterDetails(Scope& scope, AST::Node& node, uint32_t& lvid, AnyString& name) {
bool isRef = false;
bool isConst = false;
AST::Node* typeNode = nullptr;
for (auto& child: node.children) {
switch (child.rule) {
case AST::rgIdentifier: {
name = child.text;
break;
}
case AST::rgRef:
isRef = true;
break;
case AST::rgConst:
isConst = true;
break;
case AST::rgCref:
isRef = true;
isConst = true;
break;
case AST::rgVarType: {
for (auto& typeChild: child.children) {
switch (typeChild.rule) {
case AST::rgType: {
typeNode = &typeChild;
break;
}
default:
return unexpectedNode(child, "on/scope/fail/param/details/type");
}
}
break;
}
default:
return unexpectedNode(child, "on/scope/fail/param/details");
}
}
if (typeNode != nullptr) {
if (!scope.visitASTType(*typeNode, lvid))
return false;
switch (lvid) {
default: {
if (isRef)
ir::emit::type::qualifierRef(scope.ircode(), lvid, true);
if (isConst)
ir::emit::type::qualifierConst(scope.ircode(), lvid, true);
break;
}
case (uint32_t) -1: {
lvid = 0; // let's pretend no type was given
break;
}
case 0: // void
return error(*typeNode) << "void is not a valid parameter type";
}
}
return true;
}
bool findParameter(Scope& scope, AST::Node& node, uint32_t& lvid, AnyString& name) {
bool hasParameter = false;
for (auto& child: node.children) {
if (unlikely(child.rule != AST::rgFuncParams))
return unexpectedNode(child, "on/scope/fail");
for (auto& paramsChild: child.children) {
if (unlikely(paramsChild.rule != AST::rgFuncParam))
return unexpectedNode(paramsChild, "on/scope/fail/params");
if (unlikely(hasParameter))
return error(paramsChild) << "'on scope fail' accepts only one parameter";
hasParameter = true;
if (!extractParameterDetails(scope, paramsChild, lvid, name))
return false;
}
}
return true;
}
} // namespace
bool Scope::visitASTExprOnScopeFail(AST::Node& scopeNode, AST::Node& scopeFailNode) {
assert(scopeNode.rule == AST::rgScope);
assert(scopeFailNode.rule == AST::rgOnScopeFail);
uint32_t lvidType = 0;
AnyString name;
if (!findParameter(*this, scopeFailNode, lvidType, name))
return false;
auto& irout = ircode();
ir::emit::trace(irout, "begin 'on scope fail'");
// skip the entire block
uint32_t ignJmp = ir::emit::jmp(irout);
// label to trigger the error handler
uint32_t startLabel = ir::emit::label(irout, nextvar());
uint32_t var = [&]() -> uint32_t {
if (name.empty())
return 0;
// the error itself
uint32_t var = ir::emit::alloc(irout, nextvar());
if (lvidType != 0) {
auto& operands = irout.emit<isa::Op::follow>();
operands.follower = var;
operands.lvid = lvidType;
operands.symlink = 0;
}
return var;
}();
if (not visitASTExprScope(scopeNode))
return false;
// register the 'on scope fail' after the code for the error handler to not be reused
emitDebugpos(scopeFailNode);
ir::emit::on::scopefail(irout, var, startLabel);
// jmp at the end of the original scope
uint32_t jmpOffset = ir::emit::jmp(irout);
onScopeFailExitLabels.emplace_back(scopeFailNode, jmpOffset, var);
// emit label to skip the entire block
irout.at<ir::isa::Op::jmp>(ignJmp).label = ir::emit::label(irout, nextvar());
ir::emit::trace(irout, "end 'on scope fail'");
return true;
}
} // namespace Producer
} // namespace ir
} // namespace ny
<|endoftext|> |
<commit_before>// File: decoder.hh
// Decodes the names and types encoded by OCC
#ifndef H_SYNOPSIS_CPP_DECODER
#define H_SYNOPSIS_CPP_DECODER
#include <string>
#include <vector>
// Forward decl of Types::Type
namespace Types { class Type; }
// bad duplicate typedef.. hmm
typedef std::vector<std::string> ScopedName;
// Forward decl of Builder
class Builder;
class Lookup;
namespace std {
//. A specialization of the char_traits for unsigned char
template<>
struct char_traits<unsigned char>
{
typedef unsigned char char_type;
typedef int int_type;
typedef streampos pos_type;
typedef streamoff off_type;
typedef mbstate_t state_type;
static void
assign(char_type& __c1, const char_type& __c2)
{ __c1 = __c2; }
static bool
eq(const char_type& __c1, const char_type& __c2)
{ return __c1 == __c2; }
static bool
lt(const char_type& __c1, const char_type& __c2)
{ return __c1 < __c2; }
static int
compare(const char_type* __s1, const char_type* __s2, size_t __n)
{ return memcmp(__s1, __s2, __n); }
static size_t
length(const char_type* __s)
{ return strlen(reinterpret_cast<const char*>(__s)); }
static const char_type*
find(const char_type* __s, size_t __n, const char_type& __a)
{ return static_cast<const char_type*>(memchr(__s, __a, __n)); }
static char_type*
move(char_type* __s1, const char_type* __s2, size_t __n)
{ return static_cast<char_type*>(memmove(__s1, __s2, __n)); }
static char_type*
copy(char_type* __s1, const char_type* __s2, size_t __n)
{ return static_cast<char_type*>(memcpy(__s1, __s2, __n)); }
static char_type*
assign(char_type* __s, size_t __n, char_type __a)
{ return static_cast<char_type*>(memset(__s, __a, __n)); }
static char_type
to_char_type(const int_type& __c)
{ return static_cast<char_type>(__c); }
// To keep both the byte 0xff and the eof symbol 0xffffffff
// from ending up as 0xffffffff.
static int_type
to_int_type(const char_type& __c)
{ return static_cast<int_type>(static_cast<unsigned char>(__c)); }
static bool
eq_int_type(const int_type& __c1, const int_type& __c2)
{ return __c1 == __c2; }
static int_type
eof() { return static_cast<int_type>(EOF); }
static int_type
not_eof(const int_type& __c)
{ return (__c == eof()) ? 0 : __c; }
};
};
//. A string type for the encoded names and types
typedef std::basic_string<unsigned char> code;
//. A string iterator type for the encoded names and types
typedef code::iterator code_iter;
//. Insertion operator for encoded names and types
std::ostream& operator <<(std::ostream& o, const code& s);
//. Decoder for OCC encodings. This class can be used to decode the names and
//. types encoded by OCC for function and variable types and names.
class Decoder {
public:
//. Constructor
Decoder(Builder*);
//. Convert a char* to a 'code' type
static code toCode(char*);
//. Initialise the type decoder
void init(char*);
//. Returns the iterator used in decoding
code_iter& iter() { return m_iter; }
//. Return a Type object from the encoded type.
//. @preconditions You must call init() first.
Types::Type* decodeType();
//. Decodes a Qualified type. iter must be just after the Q
Types::Type* decodeQualType();
//. Decodes a Template type. iter must be just after the T
Types::Type* decodeTemplate();
//. Decodes a FuncPtr type. iter must be just after the F
Types::Type* decodeFuncPtr();
//. Decode a name
std::string decodeName();
//. Decode a qualified name
ScopedName decodeQualified();
//. Decode a name starting from the given iterator.
//. Note the iterator passed need not be from the currently decoding
//. string since this is a simple method.
std::string decodeName(code_iter);
//. Decode a name starting from the given char*
std::string decodeName(char*);
//. Decode a qualified name with only names in it
void decodeQualName(ScopedName& names);
//. Returns true if the char* is pointing to a name (that starts with a
//. length). This is needed since char can be signed or unsigned, and
//. explicitly casting to one or the other is ugly
bool isName(char* ptr);
private:
//. The encoded type string currently being decoded
code m_string;
//. The current position in m_enc_iter
code_iter m_iter;
//. The builder
Builder* m_builder;
//. The lookup
Lookup* m_lookup;
};
inline bool Decoder::isName(char* ptr)
{
code::value_type* iter = reinterpret_cast<code::value_type*>(ptr);
return iter && iter[0] > 0x80;
}
#endif // header guard
<commit_msg>Wrap the char_traits in a check for G++ 3.2 or higher<commit_after>// File: decoder.hh
// Decodes the names and types encoded by OCC
#ifndef H_SYNOPSIS_CPP_DECODER
#define H_SYNOPSIS_CPP_DECODER
#include <string>
#include <vector>
// Forward decl of Types::Type
namespace Types { class Type; }
// bad duplicate typedef.. hmm
typedef std::vector<std::string> ScopedName;
// Forward decl of Builder
class Builder;
class Lookup;
#if defined(__GNUC__) && __GNUC__ >= 3 && __GNUC_MINOR__ >= 2
namespace std {
//. A specialization of the char_traits for unsigned char
template<>
struct char_traits<unsigned char>
{
typedef unsigned char char_type;
typedef int int_type;
typedef streampos pos_type;
typedef streamoff off_type;
typedef mbstate_t state_type;
static void
assign(char_type& __c1, const char_type& __c2)
{ __c1 = __c2; }
static bool
eq(const char_type& __c1, const char_type& __c2)
{ return __c1 == __c2; }
static bool
lt(const char_type& __c1, const char_type& __c2)
{ return __c1 < __c2; }
static int
compare(const char_type* __s1, const char_type* __s2, size_t __n)
{ return memcmp(__s1, __s2, __n); }
static size_t
length(const char_type* __s)
{ return strlen(reinterpret_cast<const char*>(__s)); }
static const char_type*
find(const char_type* __s, size_t __n, const char_type& __a)
{ return static_cast<const char_type*>(memchr(__s, __a, __n)); }
static char_type*
move(char_type* __s1, const char_type* __s2, size_t __n)
{ return static_cast<char_type*>(memmove(__s1, __s2, __n)); }
static char_type*
copy(char_type* __s1, const char_type* __s2, size_t __n)
{ return static_cast<char_type*>(memcpy(__s1, __s2, __n)); }
static char_type*
assign(char_type* __s, size_t __n, char_type __a)
{ return static_cast<char_type*>(memset(__s, __a, __n)); }
static char_type
to_char_type(const int_type& __c)
{ return static_cast<char_type>(__c); }
// To keep both the byte 0xff and the eof symbol 0xffffffff
// from ending up as 0xffffffff.
static int_type
to_int_type(const char_type& __c)
{ return static_cast<int_type>(static_cast<unsigned char>(__c)); }
static bool
eq_int_type(const int_type& __c1, const int_type& __c2)
{ return __c1 == __c2; }
static int_type
eof() { return static_cast<int_type>(EOF); }
static int_type
not_eof(const int_type& __c)
{ return (__c == eof()) ? 0 : __c; }
};
};
#endif
//. A string type for the encoded names and types
typedef std::basic_string<unsigned char> code;
//. A string iterator type for the encoded names and types
typedef code::iterator code_iter;
//. Insertion operator for encoded names and types
std::ostream& operator <<(std::ostream& o, const code& s);
//. Decoder for OCC encodings. This class can be used to decode the names and
//. types encoded by OCC for function and variable types and names.
class Decoder {
public:
//. Constructor
Decoder(Builder*);
//. Convert a char* to a 'code' type
static code toCode(char*);
//. Initialise the type decoder
void init(char*);
//. Returns the iterator used in decoding
code_iter& iter() { return m_iter; }
//. Return a Type object from the encoded type.
//. @preconditions You must call init() first.
Types::Type* decodeType();
//. Decodes a Qualified type. iter must be just after the Q
Types::Type* decodeQualType();
//. Decodes a Template type. iter must be just after the T
Types::Type* decodeTemplate();
//. Decodes a FuncPtr type. iter must be just after the F
Types::Type* decodeFuncPtr();
//. Decode a name
std::string decodeName();
//. Decode a qualified name
ScopedName decodeQualified();
//. Decode a name starting from the given iterator.
//. Note the iterator passed need not be from the currently decoding
//. string since this is a simple method.
std::string decodeName(code_iter);
//. Decode a name starting from the given char*
std::string decodeName(char*);
//. Decode a qualified name with only names in it
void decodeQualName(ScopedName& names);
//. Returns true if the char* is pointing to a name (that starts with a
//. length). This is needed since char can be signed or unsigned, and
//. explicitly casting to one or the other is ugly
bool isName(char* ptr);
private:
//. The encoded type string currently being decoded
code m_string;
//. The current position in m_enc_iter
code_iter m_iter;
//. The builder
Builder* m_builder;
//. The lookup
Lookup* m_lookup;
};
inline bool Decoder::isName(char* ptr)
{
code::value_type* iter = reinterpret_cast<code::value_type*>(ptr);
return iter && iter[0] > 0x80;
}
#endif // header guard
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salframe.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 18:06:15 $
*
* 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 _SV_SALFRAME_HXX
#define _SV_SALFRAME_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifdef __cplusplus
#ifndef _SV_PTRSTYLE_HXX
#include <vcl/ptrstyle.hxx>
#endif
#ifndef _SV_SNDSTYLE_HXX
#include <vcl/sndstyle.hxx>
#endif
#endif // __cplusplus
#ifndef _SV_SALWTYPE_HXX
#include <vcl/salwtype.hxx>
#endif
#ifndef _SV_SALGEOM_HXX
#include <vcl/salgeom.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SV_REGION_HXX
#include <vcl/region.hxx>
#endif
#ifndef _VCL_IMPDEL_HXX
#include <vcl/impdel.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SV_KEYCODE_HXX
#include <vcl/keycod.hxx>
#endif
#ifdef __cplusplus
class AllSettings;
class SalGraphics;
class SalBitmap;
class SalMenu;
#else
#define AllSettings void
#define SalGraphics void
#endif // __cplusplus
struct SalFrameState;
struct SalInputContext;
struct SystemEnvData;
// -----------------
// - SalFrameTypes -
// -----------------
#define SAL_FRAME_TOTOP_RESTOREWHENMIN ((USHORT)0x0001)
#define SAL_FRAME_TOTOP_FOREGROUNDTASK ((USHORT)0x0002)
#define SAL_FRAME_TOTOP_GRABFOCUS ((USHORT)0x0004)
#define SAL_FRAME_TOTOP_GRABFOCUS_ONLY ((USHORT)0x0008)
#define SAL_FRAME_ENDEXTTEXTINPUT_COMPLETE ((USHORT)0x0001)
#define SAL_FRAME_ENDEXTTEXTINPUT_CANCEL ((USHORT)0x0002)
// -----------------
// - SalFrameStyle -
// -----------------
#define SAL_FRAME_STYLE_DEFAULT ((ULONG)0x00000001)
#define SAL_FRAME_STYLE_MOVEABLE ((ULONG)0x00000002)
#define SAL_FRAME_STYLE_SIZEABLE ((ULONG)0x00000004)
#define SAL_FRAME_STYLE_CLOSEABLE ((ULONG)0x00000008)
// no shadow effect on WindowsXP
#define SAL_FRAME_STYLE_NOSHADOW ((ULONG)0x00000010)
// indicate tooltip windows, so they can always be topmost
#define SAL_FRAME_STYLE_TOOLTIP ((ULONG)0x00000020)
// windows without windowmanager decoration, this typically only applies to floating windows
#define SAL_FRAME_STYLE_OWNERDRAWDECORATION ((ULONG)0x00000040)
// dialogs
#define SAL_FRAME_STYLE_DIALOG ((ULONG)0x00000080)
// partial fullscreen: fullscreen on one monitor of a multimonitor display
#define SAL_FRAME_STYLE_PARTIAL_FULLSCREEN ((ULONG)0x08000000)
// system child window
#define SAL_FRAME_STYLE_CHILD ((ULONG)0x10000000)
// floating window
#define SAL_FRAME_STYLE_FLOAT ((ULONG)0x20000000)
// toolwindows should be painted with a smaller decoration
#define SAL_FRAME_STYLE_TOOLWINDOW ((ULONG)0x40000000)
// the window containing the intro bitmap, aka splashscreen
#define SAL_FRAME_STYLE_INTRO ((ULONG)0x80000000)
/*
#define SAL_FRAME_STYLE_MINABLE ((ULONG)0x00000008)
#define SAL_FRAME_STYLE_MAXABLE ((ULONG)0x00000010)
#define SAL_FRAME_STYLE_BORDER ((ULONG)0x00000040)
#define SAL_FRAME_STYLE_DOC ((ULONG)0x00004000)
#define SAL_FRAME_STYLE_DIALOG ((ULONG)0x00008000)
#define SAL_FRAME_STYLE_TOOL ((ULONG)0x00010000)
#define SAL_FRAME_STYLE_FULLSIZE ((ULONG)0x00020000)
*/
// ----------------------------------------
// - extended frame style -
// - (sal equivalent to extended WinBits) -
// ----------------------------------------
typedef sal_uInt64 SalExtStyle;
#define SAL_FRAME_EXT_STYLE_DOCUMENT SalExtStyle(0x00000001)
// ------------------------
// - Flags for SetPosSize -
// ------------------------
#define SAL_FRAME_POSSIZE_X ((USHORT)0x0001)
#define SAL_FRAME_POSSIZE_Y ((USHORT)0x0002)
#define SAL_FRAME_POSSIZE_WIDTH ((USHORT)0x0004)
#define SAL_FRAME_POSSIZE_HEIGHT ((USHORT)0x0008)
#ifdef __cplusplus
using namespace rtl;
// ------------
// - SalFrame -
// ------------
struct SystemParentData;
class VCL_DLLPUBLIC SalFrame : public vcl::DeletionNotifier
{
void* m_pInst;
SALFRAMEPROC m_pProc;
public: // public for Sal Implementation
SalFrame() : m_pInst( NULL ), m_pProc( NULL ) {}
virtual ~SalFrame();
public: // public for Sal Implementation
SalFrameGeometry maGeometry;
public:
// SalGraphics or NULL, but two Graphics for all SalFrames
// must be returned
virtual SalGraphics* GetGraphics() = 0;
virtual void ReleaseGraphics( SalGraphics* pGraphics ) = 0;
// Event must be destroyed, when Frame is destroyed
// When Event is called, SalInstance::Yield() must be returned
virtual BOOL PostEvent( void* pData ) = 0;
virtual void SetTitle( const XubString& rTitle ) = 0;
virtual void SetIcon( USHORT nIcon ) = 0;
virtual void SetMenu( SalMenu *pSalMenu ) = 0;
virtual void DrawMenuBar() = 0;
virtual void SetExtendedFrameStyle( SalExtStyle nExtStyle ) = 0;
// Before the window is visible, a resize event
// must be sent with the correct size
virtual void Show( BOOL bVisible, BOOL bNoActivate = FALSE ) = 0;
virtual void Enable( BOOL bEnable ) = 0;
// Set ClientSize and Center the Window to the desktop
// and send/post a resize message
virtual void SetMinClientSize( long nWidth, long nHeight ) = 0;
virtual void SetMaxClientSize( long nWidth, long nHeight ) = 0;
virtual void SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags ) = 0;
virtual void GetClientSize( long& rWidth, long& rHeight ) = 0;
virtual void GetWorkArea( Rectangle& rRect ) = 0;
virtual SalFrame* GetParent() const = 0;
// Note: x will be mirrored at parent if UI mirroring is active
SalFrameGeometry GetGeometry();
const SalFrameGeometry& GetUnmirroredGeometry() const { return maGeometry; }
virtual void SetWindowState( const SalFrameState* pState ) = 0;
virtual BOOL GetWindowState( SalFrameState* pState ) = 0;
virtual void ShowFullScreen( BOOL bFullScreen, sal_Int32 nDisplay ) = 0;
// Enable/Disable ScreenSaver, SystemAgents, ...
virtual void StartPresentation( BOOL bStart ) = 0;
// Show Window over all other Windows
virtual void SetAlwaysOnTop( BOOL bOnTop ) = 0;
// Window to top and grab focus
virtual void ToTop( USHORT nFlags ) = 0;
// this function can call with the same
// pointer style
virtual void SetPointer( PointerStyle ePointerStyle ) = 0;
virtual void CaptureMouse( BOOL bMouse ) = 0;
virtual void SetPointerPos( long nX, long nY ) = 0;
// flush output buffer
virtual void Flush() = 0;
// flush output buffer, wait till outstanding operations are done
virtual void Sync() = 0;
virtual void SetInputContext( SalInputContext* pContext ) = 0;
virtual void EndExtTextInput( USHORT nFlags ) = 0;
virtual String GetKeyName( USHORT nKeyCode ) = 0;
virtual String GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode ) = 0;
// returns in 'rKeyCode' the single keycode that translates to the given unicode when using a keyboard layout of language 'aLangType'
// returns FALSE if no mapping exists or function not supported
// this is required for advanced menu support
virtual BOOL MapUnicodeToKeyCode( sal_Unicode aUnicode, LanguageType aLangType, KeyCode& rKeyCode ) = 0;
// returns the input language used for the last key stroke
// may be LANGUAGE_DONTKNOW if not supported by the OS
virtual LanguageType GetInputLanguage() = 0;
virtual SalBitmap* SnapShot() = 0;
virtual void UpdateSettings( AllSettings& rSettings ) = 0;
virtual void Beep( SoundType eSoundType ) = 0;
// returns system data (most prominent: window handle)
virtual const SystemEnvData* GetSystemData() const = 0;
// sets a background bitmap on the frame; the implementation
// must not make assumptions about the lifetime of the passed SalBitmap
// but should copy its contents to an own buffer
virtual void SetBackgroundBitmap( SalBitmap* ) = 0;
// get current modifier, button mask and mouse position
struct SalPointerState
{
ULONG mnState;
Point maPos; // in frame coordinates
};
virtual SalPointerState GetPointerState() = 0;
// set new parent window
virtual void SetParent( SalFrame* pNewParent ) = 0;
// reparent window to act as a plugin; implementation
// may choose to use a new system window inetrnally
// return false to indicate failure
virtual bool SetPluginParent( SystemParentData* pNewParent ) = 0;
// shaped system windows
// set clip region to none (-> rectangular windows, normal state)
virtual void ResetClipRegion() = 0;
// start setting the clipregion consisting of nRects rectangles
virtual void BeginSetClipRegion( ULONG nRects ) = 0;
// add a rectangle to the clip region
virtual void UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) = 0;
// done setting up the clipregion
virtual void EndSetClipRegion() = 0;
// Callbacks (indepent part in vcl/source/window/winproc.cxx)
// for default message handling return 0
void SetCallback( void* pInst, SALFRAMEPROC pProc )
{ m_pInst = pInst; m_pProc = pProc; }
// returns the instance set
void* GetInstance() const { return m_pInst; }
// Call the callback set; this sometimes necessary for implementation classes
// that should not now more than necessary about the SalFrame implementation
// (e.g. input methods, printer update handlers).
long CallCallback( USHORT nEvent, const void* pEvent ) const
{ return m_pProc ? m_pProc( m_pInst, const_cast<SalFrame*>(this), nEvent, pEvent ) : 0; }
};
#endif // __cplusplus
#endif // _SV_SALFRAME_HXX
<commit_msg>INTEGRATION: CWS aquavcl03 (1.2.106); FILE MERGED 2007/09/06 15:42:39 pl 1.2.106.1: #i80230# make instance pointer of SalFrameProc a Window ptr explicitly<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salframe.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:17:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_SALFRAME_HXX
#define _SV_SALFRAME_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifdef __cplusplus
#ifndef _SV_PTRSTYLE_HXX
#include <vcl/ptrstyle.hxx>
#endif
#ifndef _SV_SNDSTYLE_HXX
#include <vcl/sndstyle.hxx>
#endif
#endif // __cplusplus
#ifndef _SV_SALWTYPE_HXX
#include <vcl/salwtype.hxx>
#endif
#ifndef _SV_SALGEOM_HXX
#include <vcl/salgeom.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SV_REGION_HXX
#include <vcl/region.hxx>
#endif
#ifndef _VCL_IMPDEL_HXX
#include <vcl/impdel.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SV_KEYCODE_HXX
#include <vcl/keycod.hxx>
#endif
class AllSettings;
class SalGraphics;
class SalBitmap;
class SalMenu;
class Window;
struct SalFrameState;
struct SalInputContext;
struct SystemEnvData;
// -----------------
// - SalFrameTypes -
// -----------------
#define SAL_FRAME_TOTOP_RESTOREWHENMIN ((USHORT)0x0001)
#define SAL_FRAME_TOTOP_FOREGROUNDTASK ((USHORT)0x0002)
#define SAL_FRAME_TOTOP_GRABFOCUS ((USHORT)0x0004)
#define SAL_FRAME_TOTOP_GRABFOCUS_ONLY ((USHORT)0x0008)
#define SAL_FRAME_ENDEXTTEXTINPUT_COMPLETE ((USHORT)0x0001)
#define SAL_FRAME_ENDEXTTEXTINPUT_CANCEL ((USHORT)0x0002)
// -----------------
// - SalFrameStyle -
// -----------------
#define SAL_FRAME_STYLE_DEFAULT ((ULONG)0x00000001)
#define SAL_FRAME_STYLE_MOVEABLE ((ULONG)0x00000002)
#define SAL_FRAME_STYLE_SIZEABLE ((ULONG)0x00000004)
#define SAL_FRAME_STYLE_CLOSEABLE ((ULONG)0x00000008)
// no shadow effect on WindowsXP
#define SAL_FRAME_STYLE_NOSHADOW ((ULONG)0x00000010)
// indicate tooltip windows, so they can always be topmost
#define SAL_FRAME_STYLE_TOOLTIP ((ULONG)0x00000020)
// windows without windowmanager decoration, this typically only applies to floating windows
#define SAL_FRAME_STYLE_OWNERDRAWDECORATION ((ULONG)0x00000040)
// dialogs
#define SAL_FRAME_STYLE_DIALOG ((ULONG)0x00000080)
// partial fullscreen: fullscreen on one monitor of a multimonitor display
#define SAL_FRAME_STYLE_PARTIAL_FULLSCREEN ((ULONG)0x08000000)
// system child window
#define SAL_FRAME_STYLE_CHILD ((ULONG)0x10000000)
// floating window
#define SAL_FRAME_STYLE_FLOAT ((ULONG)0x20000000)
// toolwindows should be painted with a smaller decoration
#define SAL_FRAME_STYLE_TOOLWINDOW ((ULONG)0x40000000)
// the window containing the intro bitmap, aka splashscreen
#define SAL_FRAME_STYLE_INTRO ((ULONG)0x80000000)
/*
#define SAL_FRAME_STYLE_MINABLE ((ULONG)0x00000008)
#define SAL_FRAME_STYLE_MAXABLE ((ULONG)0x00000010)
#define SAL_FRAME_STYLE_BORDER ((ULONG)0x00000040)
#define SAL_FRAME_STYLE_DOC ((ULONG)0x00004000)
#define SAL_FRAME_STYLE_DIALOG ((ULONG)0x00008000)
#define SAL_FRAME_STYLE_TOOL ((ULONG)0x00010000)
#define SAL_FRAME_STYLE_FULLSIZE ((ULONG)0x00020000)
*/
// ----------------------------------------
// - extended frame style -
// - (sal equivalent to extended WinBits) -
// ----------------------------------------
typedef sal_uInt64 SalExtStyle;
#define SAL_FRAME_EXT_STYLE_DOCUMENT SalExtStyle(0x00000001)
// ------------------------
// - Flags for SetPosSize -
// ------------------------
#define SAL_FRAME_POSSIZE_X ((USHORT)0x0001)
#define SAL_FRAME_POSSIZE_Y ((USHORT)0x0002)
#define SAL_FRAME_POSSIZE_WIDTH ((USHORT)0x0004)
#define SAL_FRAME_POSSIZE_HEIGHT ((USHORT)0x0008)
#ifdef __cplusplus
using namespace rtl;
// ------------
// - SalFrame -
// ------------
struct SystemParentData;
class VCL_DLLPUBLIC SalFrame : public vcl::DeletionNotifier
{
// the VCL window corresponding to this frame
Window* m_pWindow;
SALFRAMEPROC m_pProc;
public: // public for Sal Implementation
SalFrame() : m_pWindow( NULL ), m_pProc( NULL ) {}
virtual ~SalFrame();
public: // public for Sal Implementation
SalFrameGeometry maGeometry;
public:
// SalGraphics or NULL, but two Graphics for all SalFrames
// must be returned
virtual SalGraphics* GetGraphics() = 0;
virtual void ReleaseGraphics( SalGraphics* pGraphics ) = 0;
// Event must be destroyed, when Frame is destroyed
// When Event is called, SalInstance::Yield() must be returned
virtual BOOL PostEvent( void* pData ) = 0;
virtual void SetTitle( const XubString& rTitle ) = 0;
virtual void SetIcon( USHORT nIcon ) = 0;
virtual void SetMenu( SalMenu *pSalMenu ) = 0;
virtual void DrawMenuBar() = 0;
virtual void SetExtendedFrameStyle( SalExtStyle nExtStyle ) = 0;
// Before the window is visible, a resize event
// must be sent with the correct size
virtual void Show( BOOL bVisible, BOOL bNoActivate = FALSE ) = 0;
virtual void Enable( BOOL bEnable ) = 0;
// Set ClientSize and Center the Window to the desktop
// and send/post a resize message
virtual void SetMinClientSize( long nWidth, long nHeight ) = 0;
virtual void SetMaxClientSize( long nWidth, long nHeight ) = 0;
virtual void SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags ) = 0;
virtual void GetClientSize( long& rWidth, long& rHeight ) = 0;
virtual void GetWorkArea( Rectangle& rRect ) = 0;
virtual SalFrame* GetParent() const = 0;
// Note: x will be mirrored at parent if UI mirroring is active
SalFrameGeometry GetGeometry();
const SalFrameGeometry& GetUnmirroredGeometry() const { return maGeometry; }
virtual void SetWindowState( const SalFrameState* pState ) = 0;
virtual BOOL GetWindowState( SalFrameState* pState ) = 0;
virtual void ShowFullScreen( BOOL bFullScreen, sal_Int32 nDisplay ) = 0;
// Enable/Disable ScreenSaver, SystemAgents, ...
virtual void StartPresentation( BOOL bStart ) = 0;
// Show Window over all other Windows
virtual void SetAlwaysOnTop( BOOL bOnTop ) = 0;
// Window to top and grab focus
virtual void ToTop( USHORT nFlags ) = 0;
// this function can call with the same
// pointer style
virtual void SetPointer( PointerStyle ePointerStyle ) = 0;
virtual void CaptureMouse( BOOL bMouse ) = 0;
virtual void SetPointerPos( long nX, long nY ) = 0;
// flush output buffer
virtual void Flush() = 0;
// flush output buffer, wait till outstanding operations are done
virtual void Sync() = 0;
virtual void SetInputContext( SalInputContext* pContext ) = 0;
virtual void EndExtTextInput( USHORT nFlags ) = 0;
virtual String GetKeyName( USHORT nKeyCode ) = 0;
virtual String GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode ) = 0;
// returns in 'rKeyCode' the single keycode that translates to the given unicode when using a keyboard layout of language 'aLangType'
// returns FALSE if no mapping exists or function not supported
// this is required for advanced menu support
virtual BOOL MapUnicodeToKeyCode( sal_Unicode aUnicode, LanguageType aLangType, KeyCode& rKeyCode ) = 0;
// returns the input language used for the last key stroke
// may be LANGUAGE_DONTKNOW if not supported by the OS
virtual LanguageType GetInputLanguage() = 0;
virtual SalBitmap* SnapShot() = 0;
virtual void UpdateSettings( AllSettings& rSettings ) = 0;
virtual void Beep( SoundType eSoundType ) = 0;
// returns system data (most prominent: window handle)
virtual const SystemEnvData* GetSystemData() const = 0;
// sets a background bitmap on the frame; the implementation
// must not make assumptions about the lifetime of the passed SalBitmap
// but should copy its contents to an own buffer
virtual void SetBackgroundBitmap( SalBitmap* ) = 0;
// get current modifier, button mask and mouse position
struct SalPointerState
{
ULONG mnState;
Point maPos; // in frame coordinates
};
virtual SalPointerState GetPointerState() = 0;
// set new parent window
virtual void SetParent( SalFrame* pNewParent ) = 0;
// reparent window to act as a plugin; implementation
// may choose to use a new system window inetrnally
// return false to indicate failure
virtual bool SetPluginParent( SystemParentData* pNewParent ) = 0;
// shaped system windows
// set clip region to none (-> rectangular windows, normal state)
virtual void ResetClipRegion() = 0;
// start setting the clipregion consisting of nRects rectangles
virtual void BeginSetClipRegion( ULONG nRects ) = 0;
// add a rectangle to the clip region
virtual void UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) = 0;
// done setting up the clipregion
virtual void EndSetClipRegion() = 0;
// Callbacks (indepent part in vcl/source/window/winproc.cxx)
// for default message handling return 0
void SetCallback( Window* pWindow, SALFRAMEPROC pProc )
{ m_pWindow = pWindow; m_pProc = pProc; }
// returns the instance set
Window* GetWindow() const { return m_pWindow; }
// Call the callback set; this sometimes necessary for implementation classes
// that should not now more than necessary about the SalFrame implementation
// (e.g. input methods, printer update handlers).
long CallCallback( USHORT nEvent, const void* pEvent ) const
{ return m_pProc ? m_pProc( m_pWindow, const_cast<SalFrame*>(this), nEvent, pEvent ) : 0; }
};
#endif // __cplusplus
#endif // _SV_SALFRAME_HXX
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "VCLKDEApplication.hxx"
#define Region QtXRegion
#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qabstracteventdispatcher.h>
#include <qclipboard.h>
#include <qthread.h>
#undef Region
#include "KDEXLib.hxx"
#include <i18n_im.hxx>
#include <i18n_xkb.hxx>
#include <saldata.hxx>
#include <vos/process.hxx>
#include "KDESalDisplay.hxx"
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
#include <stdio.h>
#ifdef KDE_HAVE_GLIB
#if QT_VERSION >= QT_VERSION_CHECK( 4, 8, 0 )
#if 0 // wait until fixed in Qt
#define GLIB_EVENT_LOOP_SUPPORT
#endif
#endif
#endif
#ifdef GLIB_EVENT_LOOP_SUPPORT
#include <glib-2.0/glib.h>
#endif
KDEXLib::KDEXLib() :
SalXLib(), m_bStartupDone(false), m_pApplication(0),
m_pFreeCmdLineArgs(0), m_pAppCmdLineArgs(0), m_nFakeCmdLineArgs( 0 ),
eventLoopType( LibreOfficeEventLoop )
{
// the timers created here means they belong to the main thread
connect( &timeoutTimer, SIGNAL( timeout()), this, SLOT( timeoutActivated()));
connect( &userEventTimer, SIGNAL( timeout()), this, SLOT( userEventActivated()));
// QTimer::start() can be called only in its (here main) thread, so this will
// forward between threads if needed
connect( this, SIGNAL( startTimeoutTimerSignal()), this, SLOT( startTimeoutTimer()), Qt::QueuedConnection );
connect( this, SIGNAL( startUserEventTimerSignal()), this, SLOT( startUserEventTimer()), Qt::QueuedConnection );
// this one needs to be blocking, so that the handling in main thread is processed before
// the thread emitting the signal continues
connect( this, SIGNAL( processYieldSignal( bool, bool )), this, SLOT( processYield( bool, bool )),
Qt::BlockingQueuedConnection );
}
KDEXLib::~KDEXLib()
{
delete m_pApplication;
// free the faked cmdline arguments no longer needed by KApplication
for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
{
free( m_pFreeCmdLineArgs[i] );
}
delete [] m_pFreeCmdLineArgs;
delete [] m_pAppCmdLineArgs;
}
void KDEXLib::Init()
{
SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
pInputMethod->SetLocale();
XrmInitialize();
KAboutData *kAboutData = new KAboutData("OpenOffice.org",
"kdelibs4",
ki18n( "OpenOffice.org" ),
"3.0.0",
ki18n( "OpenOffice.org with KDE Native Widget Support." ),
KAboutData::License_LGPL,
ki18n( "Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Novell, Inc"),
ki18n( "OpenOffice.org is an office suite.\n" ),
"http://kde.openoffice.org/index.html",
"dev@kde.openoffice.org" );
kAboutData->addAuthor( ki18n( "Jan Holesovsky" ),
ki18n( "Original author and maintainer of the KDE NWF." ),
"kendy@artax.karlin.mff.cuni.cz",
"http://artax.karlin.mff.cuni.cz/~kendy" );
kAboutData->addAuthor( ki18n("Roman Shtylman"),
ki18n( "Porting to KDE 4." ),
"shtylman@gmail.com", "http://shtylman.com" );
kAboutData->addAuthor( ki18n("Eric Bischoff"),
ki18n( "Accessibility fixes, porting to KDE 4." ),
"bischoff@kde.org" );
//kAboutData->setProgramIconName("OpenOffice");
m_nFakeCmdLineArgs = 1;
USHORT nIdx;
vos::OExtCommandLine aCommandLine;
int nParams = aCommandLine.getCommandArgCount();
rtl::OString aDisplay;
rtl::OUString aParam, aBin;
for ( nIdx = 0; nIdx < nParams; ++nIdx )
{
aCommandLine.getCommandArg( nIdx, aParam );
if ( !m_pFreeCmdLineArgs && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
{
aCommandLine.getCommandArg( nIdx + 1, aParam );
aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );
m_nFakeCmdLineArgs = 3;
m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
m_pFreeCmdLineArgs[ 1 ] = strdup( "-display" );
m_pFreeCmdLineArgs[ 2 ] = strdup( aDisplay.getStr() );
}
}
if ( !m_pFreeCmdLineArgs )
m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
osl_getExecutableFile( &aParam.pData );
osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
rtl::OString aExec = rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() );
m_pFreeCmdLineArgs[0] = strdup( aExec.getStr() );
// make a copy of the string list for freeing it since
// KApplication manipulates the pointers inside the argument vector
// note: KApplication bad !
m_pAppCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
m_pAppCmdLineArgs[i] = m_pFreeCmdLineArgs[i];
KCmdLineArgs::init( m_nFakeCmdLineArgs, m_pAppCmdLineArgs, kAboutData );
m_pApplication = new VCLKDEApplication();
kapp->disableSessionManagement();
KApplication::setQuitOnLastWindowClosed(false);
setupEventLoop();
Display* pDisp = QX11Info::display();
SalKDEDisplay *pSalDisplay = new SalKDEDisplay(pDisp);
pInputMethod->CreateMethod( pDisp );
pInputMethod->AddConnectionWatch( pDisp, (void*)this );
pSalDisplay->SetInputMethod( pInputMethod );
PushXErrorLevel( true );
SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
XSync( pDisp, False );
pKbdExtension->UseExtension( ! HasXErrorOccured() );
PopXErrorLevel();
pSalDisplay->SetKbdExtension( pKbdExtension );
}
// When we use Qt event loop, it can actually use its own event loop handling, or wrap
// the Glib event loop (the latter is the default is Qt is built with Glib support
// and $QT_NO_GLIB is not set). We mostly do not care which one it is, as QSocketNotifier's
// and QTimer's can handle it transparently, but it matters for the SolarMutex, which
// needs to be unlocked shortly before entering the main sleep (e.g. select()) and locked
// immediatelly after. So we need to know which event loop implementation is used and
// hook accordingly.
#ifdef GLIB_EVENT_LOOP_SUPPORT
static GPollFunc old_gpoll = NULL;
static gint gpoll_wrapper( GPollFD*, guint, gint );
#endif
void KDEXLib::setupEventLoop()
{
#ifdef GLIB_EVENT_LOOP_SUPPORT
// Glib is simple, it has g_main_context_set_poll_func() for wrapping the sleep call.
// The catch is that Qt has a bug that allows triggering timers even when they should
// not be, leading to crashes caused by QClipboard re-entering the event loop.
// (http://bugreports.qt.nokia.com/browse/QTBUG-14461), so enable only with Qt>=4.8.0,
// where it is(?) fixed.
if( QAbstractEventDispatcher::instance()->inherits( "QEventDispatcherGlib" ))
{
eventLoopType = GlibEventLoop;
old_gpoll = g_main_context_get_poll_func( NULL );
g_main_context_set_poll_func( NULL, gpoll_wrapper );
// set QClipboard to use event loop, otherwise the main thread will hold
// SolarMutex locked, which will prevent the clipboard thread from answering
m_pApplication->clipboard()->setProperty( "useEventLoopWhenWaiting", true );
return;
}
#endif
// TODO handle also Qt's own event loop (requires fixing Qt too)
}
#ifdef GLIB_EVENT_LOOP_SUPPORT
gint gpoll_wrapper( GPollFD* ufds, guint nfds, gint timeout )
{
YieldMutexReleaser release; // release YieldMutex (and re-acquire at block end)
return old_gpoll( ufds, nfds, timeout );
}
#endif
void KDEXLib::Insert( int fd, void* data, YieldFunc pending, YieldFunc queued, YieldFunc handle )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Insert( fd, data, pending, queued, handle );
SocketData sdata;
sdata.data = data;
sdata.pending = pending;
sdata.queued = queued;
sdata.handle = handle;
// qApp as parent to make sure it uses the main thread event loop
sdata.notifier = new QSocketNotifier( fd, QSocketNotifier::Read, qApp );
connect( sdata.notifier, SIGNAL( activated( int )), this, SLOT( socketNotifierActivated( int )));
socketData[ fd ] = sdata;
}
void KDEXLib::Remove( int fd )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Remove( fd );
SocketData sdata = socketData.take( fd );// according to SalXLib::Remove() this should be safe
delete sdata.notifier;
}
void KDEXLib::socketNotifierActivated( int fd )
{
const SocketData& sdata = socketData[ fd ];
sdata.handle( fd, sdata.data );
}
void KDEXLib::Yield( bool bWait, bool bHandleAllCurrentEvents )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Yield( bWait, bHandleAllCurrentEvents );
// if we are the main thread (which is where the event processing is done),
// good, just do it
if( qApp->thread() == QThread::currentThread())
processYield( bWait, bHandleAllCurrentEvents );
else
{ // if this deadlocks, event processing needs to go into a separate thread
// or some other solution needs to be found
emit processYieldSignal( bWait, bHandleAllCurrentEvents );
}
}
void KDEXLib::processYield( bool bWait, bool bHandleAllCurrentEvents )
{
QAbstractEventDispatcher* dispatcher = QAbstractEventDispatcher::instance( qApp->thread());
bool wasEvent = false;
for( int cnt = bHandleAllCurrentEvents ? 100 : 1;
cnt > 0;
--cnt )
{
if( !dispatcher->processEvents( QEventLoop::AllEvents ))
break;
wasEvent = true;
}
if( bWait && !wasEvent )
dispatcher->processEvents( QEventLoop::WaitForMoreEvents );
}
void KDEXLib::StartTimer( ULONG nMS )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::StartTimer( nMS );
timeoutTimer.setInterval( nMS );
// QTimer's can be started only in their thread (main thread here)
if( qApp->thread() == QThread::currentThread())
startTimeoutTimer();
else
emit startTimeoutTimerSignal();
}
void KDEXLib::startTimeoutTimer()
{
timeoutTimer.start();
}
void KDEXLib::StopTimer()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::StopTimer();
timeoutTimer.stop();
}
void KDEXLib::timeoutActivated()
{
GetX11SalData()->Timeout();
// QTimer is not single shot, so will be restarted immediatelly
}
void KDEXLib::Wakeup()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Wakeup();
QAbstractEventDispatcher::instance( qApp->thread())->wakeUp(); // main thread event loop
}
void KDEXLib::PostUserEvent()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::PostUserEvent();
if( qApp->thread() == QThread::currentThread())
startUserEventTimer();
else
emit startUserEventTimerSignal();
}
void KDEXLib::startUserEventTimer()
{
userEventTimer.start( 0 );
}
void KDEXLib::userEventActivated()
{
SalKDEDisplay::self()->EventGuardAcquire();
if( SalKDEDisplay::self()->userEventsCount() <= 1 )
userEventTimer.stop();
SalKDEDisplay::self()->EventGuardRelease();
SalKDEDisplay::self()->DispatchInternalEvent();
// QTimer is not single shot, so will be restarted immediatelly
}
void KDEXLib::doStartup()
{
if( ! m_bStartupDone )
{
KStartupInfo::appStarted();
m_bStartupDone = true;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "called KStartupInfo::appStarted()\n" );
#endif
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>disable KDE's crash handler<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "VCLKDEApplication.hxx"
#define Region QtXRegion
#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qabstracteventdispatcher.h>
#include <qclipboard.h>
#include <qthread.h>
#undef Region
#include "KDEXLib.hxx"
#include <i18n_im.hxx>
#include <i18n_xkb.hxx>
#include <saldata.hxx>
#include <vos/process.hxx>
#include "KDESalDisplay.hxx"
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
#include <stdio.h>
#ifdef KDE_HAVE_GLIB
#if QT_VERSION >= QT_VERSION_CHECK( 4, 8, 0 )
#if 0 // wait until fixed in Qt
#define GLIB_EVENT_LOOP_SUPPORT
#endif
#endif
#endif
#ifdef GLIB_EVENT_LOOP_SUPPORT
#include <glib-2.0/glib.h>
#endif
KDEXLib::KDEXLib() :
SalXLib(), m_bStartupDone(false), m_pApplication(0),
m_pFreeCmdLineArgs(0), m_pAppCmdLineArgs(0), m_nFakeCmdLineArgs( 0 ),
eventLoopType( LibreOfficeEventLoop )
{
// the timers created here means they belong to the main thread
connect( &timeoutTimer, SIGNAL( timeout()), this, SLOT( timeoutActivated()));
connect( &userEventTimer, SIGNAL( timeout()), this, SLOT( userEventActivated()));
// QTimer::start() can be called only in its (here main) thread, so this will
// forward between threads if needed
connect( this, SIGNAL( startTimeoutTimerSignal()), this, SLOT( startTimeoutTimer()), Qt::QueuedConnection );
connect( this, SIGNAL( startUserEventTimerSignal()), this, SLOT( startUserEventTimer()), Qt::QueuedConnection );
// this one needs to be blocking, so that the handling in main thread is processed before
// the thread emitting the signal continues
connect( this, SIGNAL( processYieldSignal( bool, bool )), this, SLOT( processYield( bool, bool )),
Qt::BlockingQueuedConnection );
}
KDEXLib::~KDEXLib()
{
delete m_pApplication;
// free the faked cmdline arguments no longer needed by KApplication
for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
{
free( m_pFreeCmdLineArgs[i] );
}
delete [] m_pFreeCmdLineArgs;
delete [] m_pAppCmdLineArgs;
}
void KDEXLib::Init()
{
SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
pInputMethod->SetLocale();
XrmInitialize();
KAboutData *kAboutData = new KAboutData("OpenOffice.org",
"kdelibs4",
ki18n( "OpenOffice.org" ),
"3.0.0",
ki18n( "OpenOffice.org with KDE Native Widget Support." ),
KAboutData::License_LGPL,
ki18n( "Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Novell, Inc"),
ki18n( "OpenOffice.org is an office suite.\n" ),
"http://kde.openoffice.org/index.html",
"dev@kde.openoffice.org" );
kAboutData->addAuthor( ki18n( "Jan Holesovsky" ),
ki18n( "Original author and maintainer of the KDE NWF." ),
"kendy@artax.karlin.mff.cuni.cz",
"http://artax.karlin.mff.cuni.cz/~kendy" );
kAboutData->addAuthor( ki18n("Roman Shtylman"),
ki18n( "Porting to KDE 4." ),
"shtylman@gmail.com", "http://shtylman.com" );
kAboutData->addAuthor( ki18n("Eric Bischoff"),
ki18n( "Accessibility fixes, porting to KDE 4." ),
"bischoff@kde.org" );
//kAboutData->setProgramIconName("OpenOffice");
m_nFakeCmdLineArgs = 2;
USHORT nIdx;
vos::OExtCommandLine aCommandLine;
int nParams = aCommandLine.getCommandArgCount();
rtl::OString aDisplay;
rtl::OUString aParam, aBin;
for ( nIdx = 0; nIdx < nParams; ++nIdx )
{
aCommandLine.getCommandArg( nIdx, aParam );
if ( !m_pFreeCmdLineArgs && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
{
aCommandLine.getCommandArg( nIdx + 1, aParam );
aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );
m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs + 2 ];
m_pFreeCmdLineArgs[ m_nFakeCmdLineArgs + 0 ] = strdup( "-display" );
m_pFreeCmdLineArgs[ m_nFakeCmdLineArgs + 1 ] = strdup( aDisplay.getStr() );
m_nFakeCmdLineArgs += 2;
}
}
if ( !m_pFreeCmdLineArgs )
m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
osl_getExecutableFile( &aParam.pData );
osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
rtl::OString aExec = rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() );
m_pFreeCmdLineArgs[0] = strdup( aExec.getStr() );
m_pFreeCmdLineArgs[1] = strdup( "--nocrashhandler" );
// make a copy of the string list for freeing it since
// KApplication manipulates the pointers inside the argument vector
// note: KApplication bad !
m_pAppCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
m_pAppCmdLineArgs[i] = m_pFreeCmdLineArgs[i];
KCmdLineArgs::init( m_nFakeCmdLineArgs, m_pAppCmdLineArgs, kAboutData );
m_pApplication = new VCLKDEApplication();
kapp->disableSessionManagement();
KApplication::setQuitOnLastWindowClosed(false);
setupEventLoop();
Display* pDisp = QX11Info::display();
SalKDEDisplay *pSalDisplay = new SalKDEDisplay(pDisp);
pInputMethod->CreateMethod( pDisp );
pInputMethod->AddConnectionWatch( pDisp, (void*)this );
pSalDisplay->SetInputMethod( pInputMethod );
PushXErrorLevel( true );
SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
XSync( pDisp, False );
pKbdExtension->UseExtension( ! HasXErrorOccured() );
PopXErrorLevel();
pSalDisplay->SetKbdExtension( pKbdExtension );
}
// When we use Qt event loop, it can actually use its own event loop handling, or wrap
// the Glib event loop (the latter is the default is Qt is built with Glib support
// and $QT_NO_GLIB is not set). We mostly do not care which one it is, as QSocketNotifier's
// and QTimer's can handle it transparently, but it matters for the SolarMutex, which
// needs to be unlocked shortly before entering the main sleep (e.g. select()) and locked
// immediatelly after. So we need to know which event loop implementation is used and
// hook accordingly.
#ifdef GLIB_EVENT_LOOP_SUPPORT
static GPollFunc old_gpoll = NULL;
static gint gpoll_wrapper( GPollFD*, guint, gint );
#endif
void KDEXLib::setupEventLoop()
{
#ifdef GLIB_EVENT_LOOP_SUPPORT
// Glib is simple, it has g_main_context_set_poll_func() for wrapping the sleep call.
// The catch is that Qt has a bug that allows triggering timers even when they should
// not be, leading to crashes caused by QClipboard re-entering the event loop.
// (http://bugreports.qt.nokia.com/browse/QTBUG-14461), so enable only with Qt>=4.8.0,
// where it is(?) fixed.
if( QAbstractEventDispatcher::instance()->inherits( "QEventDispatcherGlib" ))
{
eventLoopType = GlibEventLoop;
old_gpoll = g_main_context_get_poll_func( NULL );
g_main_context_set_poll_func( NULL, gpoll_wrapper );
// set QClipboard to use event loop, otherwise the main thread will hold
// SolarMutex locked, which will prevent the clipboard thread from answering
m_pApplication->clipboard()->setProperty( "useEventLoopWhenWaiting", true );
return;
}
#endif
// TODO handle also Qt's own event loop (requires fixing Qt too)
}
#ifdef GLIB_EVENT_LOOP_SUPPORT
gint gpoll_wrapper( GPollFD* ufds, guint nfds, gint timeout )
{
YieldMutexReleaser release; // release YieldMutex (and re-acquire at block end)
return old_gpoll( ufds, nfds, timeout );
}
#endif
void KDEXLib::Insert( int fd, void* data, YieldFunc pending, YieldFunc queued, YieldFunc handle )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Insert( fd, data, pending, queued, handle );
SocketData sdata;
sdata.data = data;
sdata.pending = pending;
sdata.queued = queued;
sdata.handle = handle;
// qApp as parent to make sure it uses the main thread event loop
sdata.notifier = new QSocketNotifier( fd, QSocketNotifier::Read, qApp );
connect( sdata.notifier, SIGNAL( activated( int )), this, SLOT( socketNotifierActivated( int )));
socketData[ fd ] = sdata;
}
void KDEXLib::Remove( int fd )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Remove( fd );
SocketData sdata = socketData.take( fd );// according to SalXLib::Remove() this should be safe
delete sdata.notifier;
}
void KDEXLib::socketNotifierActivated( int fd )
{
const SocketData& sdata = socketData[ fd ];
sdata.handle( fd, sdata.data );
}
void KDEXLib::Yield( bool bWait, bool bHandleAllCurrentEvents )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Yield( bWait, bHandleAllCurrentEvents );
// if we are the main thread (which is where the event processing is done),
// good, just do it
if( qApp->thread() == QThread::currentThread())
processYield( bWait, bHandleAllCurrentEvents );
else
{ // if this deadlocks, event processing needs to go into a separate thread
// or some other solution needs to be found
emit processYieldSignal( bWait, bHandleAllCurrentEvents );
}
}
void KDEXLib::processYield( bool bWait, bool bHandleAllCurrentEvents )
{
QAbstractEventDispatcher* dispatcher = QAbstractEventDispatcher::instance( qApp->thread());
bool wasEvent = false;
for( int cnt = bHandleAllCurrentEvents ? 100 : 1;
cnt > 0;
--cnt )
{
if( !dispatcher->processEvents( QEventLoop::AllEvents ))
break;
wasEvent = true;
}
if( bWait && !wasEvent )
dispatcher->processEvents( QEventLoop::WaitForMoreEvents );
}
void KDEXLib::StartTimer( ULONG nMS )
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::StartTimer( nMS );
timeoutTimer.setInterval( nMS );
// QTimer's can be started only in their thread (main thread here)
if( qApp->thread() == QThread::currentThread())
startTimeoutTimer();
else
emit startTimeoutTimerSignal();
}
void KDEXLib::startTimeoutTimer()
{
timeoutTimer.start();
}
void KDEXLib::StopTimer()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::StopTimer();
timeoutTimer.stop();
}
void KDEXLib::timeoutActivated()
{
GetX11SalData()->Timeout();
// QTimer is not single shot, so will be restarted immediatelly
}
void KDEXLib::Wakeup()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::Wakeup();
QAbstractEventDispatcher::instance( qApp->thread())->wakeUp(); // main thread event loop
}
void KDEXLib::PostUserEvent()
{
if( eventLoopType == LibreOfficeEventLoop )
return SalXLib::PostUserEvent();
if( qApp->thread() == QThread::currentThread())
startUserEventTimer();
else
emit startUserEventTimerSignal();
}
void KDEXLib::startUserEventTimer()
{
userEventTimer.start( 0 );
}
void KDEXLib::userEventActivated()
{
SalKDEDisplay::self()->EventGuardAcquire();
if( SalKDEDisplay::self()->userEventsCount() <= 1 )
userEventTimer.stop();
SalKDEDisplay::self()->EventGuardRelease();
SalKDEDisplay::self()->DispatchInternalEvent();
// QTimer is not single shot, so will be restarted immediatelly
}
void KDEXLib::doStartup()
{
if( ! m_bStartupDone )
{
KStartupInfo::appStarted();
m_bStartupDone = true;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "called KStartupInfo::appStarted()\n" );
#endif
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TObjArray.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliT0CalibOffsetChannelsTask.h"
//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"
// Task should calculate channels offset
// Authors: Alla
ClassImp(AliT0CalibOffsetChannelsTask)
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask()
: AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
fRunNumber(0)
{
// Constructor
for( int ip=0; ip < 24; ip++){
fTimeDiff[ip] = 0;
fCFD[ip] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
// DefineInput(0, TChain::Class());
// DefineOutput(1, TObjArray::Class());
}
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name)
: AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
fRunNumber(0)
{
// Constructor
for( int ip=0; ip < 24; ip++){
fTimeDiff[ip] = 0;
fCFD[ip] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
DefineOutput(1, TObjArray::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
}
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask()
{
// Destructor
// printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
delete fTzeroORA;
delete fTzeroORC;
delete fResolution;
delete fTzeroORAplusORC;
for( Int_t ip=0; ip < 24; ip++){
delete fTimeDiff[ip];
delete fCFD[ip];
}
delete fTzeroObject;
}
//________________________________________________________________________
/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
printf ("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
printf ("*** CONNECTED NEW EVENT ****");
}
}
}
*/
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()
{
// Create histograms
for (Int_t i=0; i<24; i++) {
fTimeDiff[i] = new TH1F (Form("CFD1minCFD%d",i+1),"fTimeDiff",300, -300, 300);
fCFD[i] = new TH1F(Form("CFD%d",i+1),"CFD",500, 2000, 3000);//6000, 7000);
// fCFD[i] = new TH1F(Form("CFD%d",i+1),"CFD",500, -1000, 1000);//6000, 7000);
}
fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",400,-2000,2000); //or A plus or C
fResolution = new TH1F("fResolution","fResolution",400,-2000,2000);// or A minus or C spectrum
fTzeroORA = new TH1F("fTzeroORA","fTzeroORA",400,-2000,2000);// or A spectrum
fTzeroORC = new TH1F("fTzeroORC","fTzeroORC",400,-2000,2000);// or C spectrum
fTzeroObject = new TObjArray(0);
fTzeroObject->SetOwner(kTRUE);
for (Int_t i=0; i<24; i++)
fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);
for (Int_t i=0; i<24; i++)
fTzeroObject->AddAtAndExpand(fCFD[i],i+24); //24 - 48
fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);
fTzeroObject->AddAtAndExpand(fResolution, 49);
fTzeroObject->AddAtAndExpand(fTzeroORA, 50);
fTzeroObject->AddAtAndExpand(fTzeroORC, 51);
PostData(1, fTzeroObject);
// Called once
}
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserExec(Option_t *)
{
// Main loop
// Called for each event
// Post output data.
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESD) {
printf("ERROR: fESD not available\n");
return;
}
fRunNumber = fESD->GetRunNumber() ;
const Double32_t* time = fESD->GetT0time();
for (Int_t i=0; i<12; i++) {
if( time[i] != 0 ){
printf(" %i time %f \n", i, time[i] );
fCFD[i]->Fill( time[i]);
if( time[0] != 0 )
fTimeDiff[i]->Fill( time[i]-time[0]);
}
}
for (Int_t i=12; i<24; i++) {
if( time[i] != 0) {
fCFD[i]->Fill( time[i]);
if( time[12] != 0 )
fTimeDiff[i]->Fill( time[i]-time[12]);
}
}
const Double32_t* mean = fESD->GetT0TOF();
Double32_t meanTOF = mean[0] ;
Double32_t orA = mean[1] ;
Double32_t orC = mean[2];
if(orA<99999) fTzeroORA->Fill(orA);
if(orC<99999) fTzeroORC->Fill(orC);
if(orA<99999 && orC<99999) fResolution->Fill((orA-orC)/2.);
if(orA<99999 && orC<99999) fTzeroORAplusORC->Fill(meanTOF);
// printf("%f %f %f\n",orA,orC,meanTOF);
PostData(1, fTzeroObject);
}
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::Terminate(Option_t *)
{
// Called once at the end of the query
}
<commit_msg> printout removed<commit_after>#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TObjArray.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliT0CalibOffsetChannelsTask.h"
//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"
// Task should calculate channels offset
// Authors: Alla
ClassImp(AliT0CalibOffsetChannelsTask)
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask()
: AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
fRunNumber(0)
{
// Constructor
for( int ip=0; ip < 24; ip++){
fTimeDiff[ip] = 0;
fCFD[ip] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
// DefineInput(0, TChain::Class());
// DefineOutput(1, TObjArray::Class());
}
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name)
: AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),
fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
fRunNumber(0)
{
// Constructor
for( int ip=0; ip < 24; ip++){
fTimeDiff[ip] = 0;
fCFD[ip] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
DefineOutput(1, TObjArray::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
}
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask()
{
// Destructor
// printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
delete fTzeroORA;
delete fTzeroORC;
delete fResolution;
delete fTzeroORAplusORC;
for( Int_t ip=0; ip < 24; ip++){
delete fTimeDiff[ip];
delete fCFD[ip];
}
delete fTzeroObject;
}
//________________________________________________________________________
/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
printf ("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
printf ("*** CONNECTED NEW EVENT ****");
}
}
}
*/
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()
{
// Create histograms
for (Int_t i=0; i<24; i++) {
fTimeDiff[i] = new TH1F (Form("CFD1minCFD%d",i+1),"fTimeDiff",300, -300, 300);
fCFD[i] = new TH1F(Form("CFD%d",i+1),"CFD",500, 2000, 3000);//6000, 7000);
// fCFD[i] = new TH1F(Form("CFD%d",i+1),"CFD",500, -1000, 1000);//6000, 7000);
}
fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",400,-2000,2000); //or A plus or C
fResolution = new TH1F("fResolution","fResolution",400,-2000,2000);// or A minus or C spectrum
fTzeroORA = new TH1F("fTzeroORA","fTzeroORA",400,-2000,2000);// or A spectrum
fTzeroORC = new TH1F("fTzeroORC","fTzeroORC",400,-2000,2000);// or C spectrum
fTzeroObject = new TObjArray(0);
fTzeroObject->SetOwner(kTRUE);
for (Int_t i=0; i<24; i++)
fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);
for (Int_t i=0; i<24; i++)
fTzeroObject->AddAtAndExpand(fCFD[i],i+24); //24 - 48
fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);
fTzeroObject->AddAtAndExpand(fResolution, 49);
fTzeroObject->AddAtAndExpand(fTzeroORA, 50);
fTzeroObject->AddAtAndExpand(fTzeroORC, 51);
PostData(1, fTzeroObject);
// Called once
}
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserExec(Option_t *)
{
// Main loop
// Called for each event
// Post output data.
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESD) {
printf("ERROR: fESD not available\n");
return;
}
fRunNumber = fESD->GetRunNumber() ;
const Double32_t* time = fESD->GetT0time();
for (Int_t i=0; i<12; i++) {
if( time[i] != 0 ){
fCFD[i]->Fill( time[i]);
if( time[0] != 0 )
fTimeDiff[i]->Fill( time[i]-time[0]);
}
}
for (Int_t i=12; i<24; i++) {
if( time[i] != 0) {
fCFD[i]->Fill( time[i]);
if( time[12] != 0 )
fTimeDiff[i]->Fill( time[i]-time[12]);
}
}
const Double32_t* mean = fESD->GetT0TOF();
Double32_t meanTOF = mean[0] ;
Double32_t orA = mean[1] ;
Double32_t orC = mean[2];
if(orA<99999) fTzeroORA->Fill(orA);
if(orC<99999) fTzeroORC->Fill(orC);
if(orA<99999 && orC<99999) fResolution->Fill((orA-orC)/2.);
if(orA<99999 && orC<99999) fTzeroORAplusORC->Fill(meanTOF);
// printf("%f %f %f\n",orA,orC,meanTOF);
PostData(1, fTzeroObject);
}
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::Terminate(Option_t *)
{
// Called once at the end of the query
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/bookmarks/recently_used_folders_combo_model.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model_observer.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using content::BrowserThread;
// Implementation of ComboboxModelObserver that records when
// OnComboboxModelChanged() is invoked.
class TestComboboxModelObserver : public ui::ComboboxModelObserver {
public:
TestComboboxModelObserver() : changed_(false) {}
~TestComboboxModelObserver() override {}
// Returns whether the model changed and clears changed state.
bool GetAndClearChanged() {
const bool changed = changed_;
changed_ = false;
return changed;
}
// ui::ComboboxModelObserver:
void OnComboboxModelChanged(ui::ComboboxModel* model) override {
changed_ = true;
}
private:
bool changed_;
DISALLOW_COPY_AND_ASSIGN(TestComboboxModelObserver);
};
class RecentlyUsedFoldersComboModelTest : public testing::Test {
public:
RecentlyUsedFoldersComboModelTest();
void SetUp() override;
void TearDown() override;
protected:
BookmarkModel* GetModel();
private:
base::MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
scoped_ptr<TestingProfile> profile_;
DISALLOW_COPY_AND_ASSIGN(RecentlyUsedFoldersComboModelTest);
};
RecentlyUsedFoldersComboModelTest::RecentlyUsedFoldersComboModelTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_) {
}
void RecentlyUsedFoldersComboModelTest::SetUp() {
profile_.reset(new TestingProfile());
profile_->CreateBookmarkModel(true);
bookmarks::test::WaitForBookmarkModelToLoad(GetModel());
}
void RecentlyUsedFoldersComboModelTest::TearDown() {
// Flush the message loop to make application verifiers happy.
message_loop_.RunUntilIdle();
}
BookmarkModel* RecentlyUsedFoldersComboModelTest::GetModel() {
return BookmarkModelFactory::GetForProfile(profile_.get());
}
// Verifies there are no duplicate nodes in the model.
TEST_F(RecentlyUsedFoldersComboModelTest, NoDups) {
const BookmarkNode* new_node = GetModel()->AddURL(
GetModel()->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"),
GURL("http://a"));
RecentlyUsedFoldersComboModel model(GetModel(), new_node);
std::set<base::string16> items;
for (int i = 0; i < model.GetItemCount(); ++i) {
if (!model.IsItemSeparatorAt(i))
EXPECT_EQ(0u, items.count(model.GetItemAt(i)));
}
}
// Verifies that observers are notified on changes.
TEST_F(RecentlyUsedFoldersComboModelTest, NotifyObserver) {
const BookmarkNode* folder = GetModel()->AddFolder(
GetModel()->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"));
const BookmarkNode* sub_folder = GetModel()->AddFolder(
folder, 0, base::ASCIIToUTF16("b"));
const BookmarkNode* new_node = GetModel()->AddURL(
sub_folder, 0, base::ASCIIToUTF16("a"), GURL("http://a"));
RecentlyUsedFoldersComboModel model(GetModel(), new_node);
TestComboboxModelObserver observer;
model.AddObserver(&observer);
const int initial_count = model.GetItemCount();
// Remove a folder, it should remove an item from the model too.
GetModel()->Remove(sub_folder);
EXPECT_TRUE(observer.GetAndClearChanged());
const int updated_count = model.GetItemCount();
EXPECT_LT(updated_count, initial_count);
// Remove all, which should remove a folder too.
GetModel()->RemoveAllUserBookmarks();
EXPECT_TRUE(observer.GetAndClearChanged());
EXPECT_LT(model.GetItemCount(), updated_count);
model.RemoveObserver(&observer);
}
<commit_msg>chrome: Simplify the initialization of BookmarkModel in RecentlyUsedFoldersComboModelTest.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/bookmarks/recently_used_folders_combo_model.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/bookmarks/test/test_bookmark_client.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model_observer.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks::TestBookmarkClient;
using content::BrowserThread;
// Implementation of ComboboxModelObserver that records when
// OnComboboxModelChanged() is invoked.
class TestComboboxModelObserver : public ui::ComboboxModelObserver {
public:
TestComboboxModelObserver() : changed_(false) {}
~TestComboboxModelObserver() override {}
// Returns whether the model changed and clears changed state.
bool GetAndClearChanged() {
const bool changed = changed_;
changed_ = false;
return changed;
}
// ui::ComboboxModelObserver:
void OnComboboxModelChanged(ui::ComboboxModel* model) override {
changed_ = true;
}
private:
bool changed_;
DISALLOW_COPY_AND_ASSIGN(TestComboboxModelObserver);
};
class RecentlyUsedFoldersComboModelTest : public testing::Test {
public:
RecentlyUsedFoldersComboModelTest();
private:
base::MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
DISALLOW_COPY_AND_ASSIGN(RecentlyUsedFoldersComboModelTest);
};
RecentlyUsedFoldersComboModelTest::RecentlyUsedFoldersComboModelTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_) {
}
// Verifies there are no duplicate nodes in the model.
TEST_F(RecentlyUsedFoldersComboModelTest, NoDups) {
TestBookmarkClient client;
scoped_ptr<BookmarkModel> bookmark_model(client.CreateModel());
const BookmarkNode* new_node = bookmark_model->AddURL(
bookmark_model->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"),
GURL("http://a"));
RecentlyUsedFoldersComboModel model(bookmark_model.get(), new_node);
std::set<base::string16> items;
for (int i = 0; i < model.GetItemCount(); ++i) {
if (!model.IsItemSeparatorAt(i))
EXPECT_EQ(0u, items.count(model.GetItemAt(i)));
}
}
// Verifies that observers are notified on changes.
TEST_F(RecentlyUsedFoldersComboModelTest, NotifyObserver) {
TestBookmarkClient client;
scoped_ptr<BookmarkModel> bookmark_model(client.CreateModel());
const BookmarkNode* folder = bookmark_model->AddFolder(
bookmark_model->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"));
const BookmarkNode* sub_folder = bookmark_model->AddFolder(
folder, 0, base::ASCIIToUTF16("b"));
const BookmarkNode* new_node = bookmark_model->AddURL(
sub_folder, 0, base::ASCIIToUTF16("a"), GURL("http://a"));
RecentlyUsedFoldersComboModel model(bookmark_model.get(), new_node);
TestComboboxModelObserver observer;
model.AddObserver(&observer);
const int initial_count = model.GetItemCount();
// Remove a folder, it should remove an item from the model too.
bookmark_model->Remove(sub_folder);
EXPECT_TRUE(observer.GetAndClearChanged());
const int updated_count = model.GetItemCount();
EXPECT_LT(updated_count, initial_count);
// Remove all, which should remove a folder too.
bookmark_model->RemoveAllUserBookmarks();
EXPECT_TRUE(observer.GetAndClearChanged());
EXPECT_LT(model.GetItemCount(), updated_count);
model.RemoveObserver(&observer);
}
<|endoftext|> |
<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h"
namespace {
const int kTwoHoursInMinutes = 120;
} // namespace
namespace feature_engagement {
NewTabTracker::NewTabTracker(Profile* profile,
SessionDurationUpdater* session_duration_updater)
: FeatureTracker(profile, session_duration_updater) {}
NewTabTracker::~NewTabTracker() = default;
void NewTabTracker::OnNewTabOpened() {}
void NewTabTracker::OnSessionTimeMet() {}
int NewTabTracker::GetSessionTimeRequiredToShowInMinutes() {
NOTREACHED();
return kTwoHoursInMinutes;
}
} // namespace feature_engagement
<commit_msg>Changes on the FeatureTracker constructor<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h"
#include "components/feature_engagement/public/feature_constants.h"
namespace {
const int kDefaultPromoShowTimeInHours = 2;
} // namespace
namespace feature_engagement {
NewTabTracker::NewTabTracker(Profile* profile,
SessionDurationUpdater* session_duration_updater)
: FeatureTracker(profile,
session_duration_updater,
&kIPHNewTabFeature,
base::TimeDelta::FromHours(kDefaultPromoShowTimeInHours)) {
}
NewTabTracker::~NewTabTracker() = default;
void NewTabTracker::OnNewTabOpened() {}
void NewTabTracker::OnSessionTimeMet() {}
} // namespace feature_engagement
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stgole.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 16:10:14 $
*
* 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_sot.hxx"
#include "rtl/string.h"
#include "rtl/string.h"
#include "stgole.hxx"
#include "storinfo.hxx" // Read/WriteClipboardFormat()
#include <tools/debug.hxx>
///////////////////////// class StgInternalStream ////////////////////////
StgInternalStream::StgInternalStream
( BaseStorage& rStg, const String& rName, BOOL bWr )
{
bIsWritable = TRUE;
USHORT nMode = bWr
? STREAM_WRITE | STREAM_SHARE_DENYALL
: STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;
pStrm = rStg.OpenStream( rName, nMode );
// set the error code right here in the stream
SetError( rStg.GetError() );
SetBufferSize( 1024 );
}
StgInternalStream::~StgInternalStream()
{
delete pStrm;
}
ULONG StgInternalStream::GetData( void* pData, ULONG nSize )
{
if( pStrm )
{
nSize = pStrm->Read( pData, nSize );
SetError( pStrm->GetError() );
return nSize;
}
else
return 0;
}
ULONG StgInternalStream::PutData( const void* pData, ULONG nSize )
{
if( pStrm )
{
nSize = pStrm->Write( pData, nSize );
SetError( pStrm->GetError() );
return nSize;
}
else
return 0;
}
ULONG StgInternalStream::SeekPos( ULONG nPos )
{
return pStrm ? pStrm->Seek( nPos ) : 0;
}
void StgInternalStream::FlushData()
{
if( pStrm )
{
pStrm->Flush();
SetError( pStrm->GetError() );
}
}
void StgInternalStream::Commit()
{
Flush();
pStrm->Commit();
}
///////////////////////// class StgCompObjStream /////////////////////////
StgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )
: StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1CompObj" ) ), bWr )
{
memset( &aClsId, 0, sizeof( ClsId ) );
nCbFormat = 0;
}
BOOL StgCompObjStream::Load()
{
memset( &aClsId, 0, sizeof( ClsId ) );
nCbFormat = 0;
aUserName.Erase();
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 8L ); // skip the first part
INT32 nMarker = 0;
*this >> nMarker;
if( nMarker == -1L )
{
*this >> aClsId;
INT32 nLen1 = 0;
*this >> nLen1;
// higher bits are ignored
nLen1 &= 0xFFFF;
sal_Char* p = new sal_Char[ (USHORT) nLen1 ];
if( Read( p, nLen1 ) == (ULONG) nLen1 )
{
aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();
/* // Now we can read the CB format
INT32 nLen2 = 0;
*this >> nLen2;
if( nLen2 > 0 )
{
// get a string name
if( nLen2 > nLen1 )
delete p, p = new char[ nLen2 ];
if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )
nCbFormat = Exchange::RegisterFormatName( String( p ) );
else
SetError( SVSTREAM_GENERALERROR );
}
else if( nLen2 == -1L )
// Windows clipboard format
*this >> nCbFormat;
else
// unknown identifier
SetError( SVSTREAM_GENERALERROR );
*/
nCbFormat = ReadClipboardFormat( *this );
}
else
SetError( SVSTREAM_GENERALERROR );
delete [] p;
}
return BOOL( GetError() == SVSTREAM_OK );
}
BOOL StgCompObjStream::Store()
{
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 0L );
ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );
*this << (INT16) 1 // Version?
<< (INT16) -2 // 0xFFFE = Byte Order Indicator
<< (INT32) 0x0A03 // Windows 3.10
<< (INT32) -1L
<< aClsId // Class ID
<< (INT32) (aAsciiUserName.Len() + 1)
<< (const char *)aAsciiUserName.GetBuffer()
<< (UINT8) 0; // string terminator
/* // determine the clipboard format string
String aCbFmt;
if( nCbFormat > FORMAT_GDIMETAFILE )
aCbFmt = Exchange::GetFormatName( nCbFormat );
if( aCbFmt.Len() )
*this << (INT32) aCbFmt.Len() + 1
<< (const char*) aCbFmt
<< (UINT8) 0;
else if( nCbFormat )
*this << (INT32) -1 // for Windows
<< (INT32) nCbFormat;
else
*this << (INT32) 0; // no clipboard format
*/
WriteClipboardFormat( *this, nCbFormat );
*this << (INT32) 0; // terminator
Commit();
return BOOL( GetError() == SVSTREAM_OK );
}
/////////////////////////// class StgOleStream ///////////////////////////
StgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )
: StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1Ole" ) ), bWr )
{
nFlags = 0;
}
BOOL StgOleStream::Load()
{
nFlags = 0;
if( GetError() != SVSTREAM_OK )
return FALSE;
INT32 version = 0;
Seek( 0L );
*this >> version >> nFlags;
return BOOL( GetError() == SVSTREAM_OK );
}
BOOL StgOleStream::Store()
{
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 0L );
*this << (INT32) 0x02000001 // OLE version, format
<< (INT32) nFlags // Object flags
<< (INT32) 0 // Update Options
<< (INT32) 0 // reserved
<< (INT32) 0; // Moniker 1
Commit();
return BOOL( GetError() == SVSTREAM_OK );
}
<commit_msg>INTEGRATION: CWS obo05 (1.8.4); FILE MERGED 2006/09/08 09:23:54 obo 1.8.4.2: pragma only for .net 2005 2006/07/03 15:43:10 obo 1.8.4.1: #i53611# disable warning C4342<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stgole.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2006-09-25 13:35:41 $
*
* 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_sot.hxx"
#include "rtl/string.h"
#include "rtl/string.h"
#include "stgole.hxx"
#include "storinfo.hxx" // Read/WriteClipboardFormat()
#include <tools/debug.hxx>
#if defined(_MSC_VER) && (_MSC_VER>=1400)
#pragma warning(disable: 4342)
#endif
///////////////////////// class StgInternalStream ////////////////////////
StgInternalStream::StgInternalStream
( BaseStorage& rStg, const String& rName, BOOL bWr )
{
bIsWritable = TRUE;
USHORT nMode = bWr
? STREAM_WRITE | STREAM_SHARE_DENYALL
: STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;
pStrm = rStg.OpenStream( rName, nMode );
// set the error code right here in the stream
SetError( rStg.GetError() );
SetBufferSize( 1024 );
}
StgInternalStream::~StgInternalStream()
{
delete pStrm;
}
ULONG StgInternalStream::GetData( void* pData, ULONG nSize )
{
if( pStrm )
{
nSize = pStrm->Read( pData, nSize );
SetError( pStrm->GetError() );
return nSize;
}
else
return 0;
}
ULONG StgInternalStream::PutData( const void* pData, ULONG nSize )
{
if( pStrm )
{
nSize = pStrm->Write( pData, nSize );
SetError( pStrm->GetError() );
return nSize;
}
else
return 0;
}
ULONG StgInternalStream::SeekPos( ULONG nPos )
{
return pStrm ? pStrm->Seek( nPos ) : 0;
}
void StgInternalStream::FlushData()
{
if( pStrm )
{
pStrm->Flush();
SetError( pStrm->GetError() );
}
}
void StgInternalStream::Commit()
{
Flush();
pStrm->Commit();
}
///////////////////////// class StgCompObjStream /////////////////////////
StgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )
: StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1CompObj" ) ), bWr )
{
memset( &aClsId, 0, sizeof( ClsId ) );
nCbFormat = 0;
}
BOOL StgCompObjStream::Load()
{
memset( &aClsId, 0, sizeof( ClsId ) );
nCbFormat = 0;
aUserName.Erase();
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 8L ); // skip the first part
INT32 nMarker = 0;
*this >> nMarker;
if( nMarker == -1L )
{
*this >> aClsId;
INT32 nLen1 = 0;
*this >> nLen1;
// higher bits are ignored
nLen1 &= 0xFFFF;
sal_Char* p = new sal_Char[ (USHORT) nLen1 ];
if( Read( p, nLen1 ) == (ULONG) nLen1 )
{
aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();
/* // Now we can read the CB format
INT32 nLen2 = 0;
*this >> nLen2;
if( nLen2 > 0 )
{
// get a string name
if( nLen2 > nLen1 )
delete p, p = new char[ nLen2 ];
if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )
nCbFormat = Exchange::RegisterFormatName( String( p ) );
else
SetError( SVSTREAM_GENERALERROR );
}
else if( nLen2 == -1L )
// Windows clipboard format
*this >> nCbFormat;
else
// unknown identifier
SetError( SVSTREAM_GENERALERROR );
*/
nCbFormat = ReadClipboardFormat( *this );
}
else
SetError( SVSTREAM_GENERALERROR );
delete [] p;
}
return BOOL( GetError() == SVSTREAM_OK );
}
BOOL StgCompObjStream::Store()
{
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 0L );
ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );
*this << (INT16) 1 // Version?
<< (INT16) -2 // 0xFFFE = Byte Order Indicator
<< (INT32) 0x0A03 // Windows 3.10
<< (INT32) -1L
<< aClsId // Class ID
<< (INT32) (aAsciiUserName.Len() + 1)
<< (const char *)aAsciiUserName.GetBuffer()
<< (UINT8) 0; // string terminator
/* // determine the clipboard format string
String aCbFmt;
if( nCbFormat > FORMAT_GDIMETAFILE )
aCbFmt = Exchange::GetFormatName( nCbFormat );
if( aCbFmt.Len() )
*this << (INT32) aCbFmt.Len() + 1
<< (const char*) aCbFmt
<< (UINT8) 0;
else if( nCbFormat )
*this << (INT32) -1 // for Windows
<< (INT32) nCbFormat;
else
*this << (INT32) 0; // no clipboard format
*/
WriteClipboardFormat( *this, nCbFormat );
*this << (INT32) 0; // terminator
Commit();
return BOOL( GetError() == SVSTREAM_OK );
}
/////////////////////////// class StgOleStream ///////////////////////////
StgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )
: StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1Ole" ) ), bWr )
{
nFlags = 0;
}
BOOL StgOleStream::Load()
{
nFlags = 0;
if( GetError() != SVSTREAM_OK )
return FALSE;
INT32 version = 0;
Seek( 0L );
*this >> version >> nFlags;
return BOOL( GetError() == SVSTREAM_OK );
}
BOOL StgOleStream::Store()
{
if( GetError() != SVSTREAM_OK )
return FALSE;
Seek( 0L );
*this << (INT32) 0x02000001 // OLE version, format
<< (INT32) nFlags // Object flags
<< (INT32) 0 // Update Options
<< (INT32) 0 // reserved
<< (INT32) 0; // Moniker 1
Commit();
return BOOL( GetError() == SVSTREAM_OK );
}
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 <unordered_map>
#include <Python.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#if PY_MAJOR_VERSION >= 3
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob)? \
((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
namespace protobuf {
namespace python {
namespace message_factory {
PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
PyType_GenericAlloc(type, 0));
if (factory == NULL) {
return NULL;
}
DynamicMessageFactory* message_factory = new DynamicMessageFactory();
// This option might be the default some day.
message_factory->SetDelegateToGeneratedFactory(true);
factory->message_factory = message_factory;
factory->pool = pool;
// TODO(amauryfa): When the MessageFactory is not created from the
// DescriptorPool this reference should be owned, not borrowed.
// Py_INCREF(pool);
factory->classes_by_descriptor = new PyMessageFactory::ClassesByMessageMap();
return factory;
}
PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {"pool", 0};
PyObject* pool = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &pool)) {
return NULL;
}
ScopedPyObjectPtr owned_pool;
if (pool == NULL || pool == Py_None) {
owned_pool.reset(PyObject_CallFunction(
reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
if (owned_pool == NULL) {
return NULL;
}
pool = owned_pool.get();
} else {
if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
pool->ob_type->tp_name);
return NULL;
}
}
return reinterpret_cast<PyObject*>(
NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
}
static void Dealloc(PyObject* pself) {
PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
// TODO(amauryfa): When the MessageFactory is not created from the
// DescriptorPool this reference should be owned, not borrowed.
// Py_CLEAR(self->pool);
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
for (iterator it = self->classes_by_descriptor->begin();
it != self->classes_by_descriptor->end(); ++it) {
Py_DECREF(it->second);
}
delete self->classes_by_descriptor;
delete self->message_factory;
Py_TYPE(self)->tp_free(pself);
}
// Add a message class to our database.
int RegisterMessageClass(PyMessageFactory* self,
const Descriptor* message_descriptor,
CMessageClass* message_class) {
Py_INCREF(message_class);
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
std::make_pair(message_descriptor, message_class));
if (!ret.second) {
// Update case: DECREF the previous value.
Py_DECREF(ret.first->second);
ret.first->second = message_class;
}
return 0;
}
CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
const Descriptor* descriptor) {
// This is the same implementation as MessageFactory.GetPrototype().
// Do not create a MessageClass that already exists.
std::unordered_map<const Descriptor*, CMessageClass*>::iterator it =
self->classes_by_descriptor->find(descriptor);
if (it != self->classes_by_descriptor->end()) {
Py_INCREF(it->second);
return it->second;
}
ScopedPyObjectPtr py_descriptor(
PyMessageDescriptor_FromDescriptor(descriptor));
if (py_descriptor == NULL) {
return NULL;
}
// Create a new message class.
ScopedPyObjectPtr args(Py_BuildValue(
"s(){sOsOsO}", descriptor->name().c_str(),
"DESCRIPTOR", py_descriptor.get(),
"__module__", Py_None,
"message_factory", self));
if (args == NULL) {
return NULL;
}
ScopedPyObjectPtr message_class(PyObject_CallObject(
reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
if (message_class == NULL) {
return NULL;
}
// Create messages class for the messages used by the fields, and registers
// all extensions for these messages during the recursion.
for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
const Descriptor* sub_descriptor =
descriptor->field(field_idx)->message_type();
// It is NULL if the field type is not a message.
if (sub_descriptor != NULL) {
CMessageClass* result = GetOrCreateMessageClass(self, sub_descriptor);
if (result == NULL) {
return NULL;
}
Py_DECREF(result);
}
}
// Register extensions defined in this message.
for (int ext_idx = 0 ; ext_idx < descriptor->extension_count() ; ext_idx++) {
const FieldDescriptor* extension = descriptor->extension(ext_idx);
ScopedPyObjectPtr py_extended_class(
GetOrCreateMessageClass(self, extension->containing_type())
->AsPyObject());
if (py_extended_class == NULL) {
return NULL;
}
ScopedPyObjectPtr py_extension(PyFieldDescriptor_FromDescriptor(extension));
if (py_extension == NULL) {
return NULL;
}
ScopedPyObjectPtr result(cmessage::RegisterExtension(
py_extended_class.get(), py_extension.get()));
if (result == NULL) {
return NULL;
}
}
return reinterpret_cast<CMessageClass*>(message_class.release());
}
// Retrieve the message class added to our database.
CMessageClass* GetMessageClass(PyMessageFactory* self,
const Descriptor* message_descriptor) {
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
iterator ret = self->classes_by_descriptor->find(message_descriptor);
if (ret == self->classes_by_descriptor->end()) {
PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
message_descriptor->full_name().c_str());
return NULL;
} else {
return ret->second;
}
}
static PyMethodDef Methods[] = {
{NULL}};
static PyObject* GetPool(PyMessageFactory* self, void* closure) {
Py_INCREF(self->pool);
return reinterpret_cast<PyObject*>(self->pool);
}
static PyGetSetDef Getters[] = {
{"pool", (getter)GetPool, NULL, "DescriptorPool"},
{NULL}
};
} // namespace message_factory
PyTypeObject PyMessageFactory_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".MessageFactory", // tp_name
sizeof(PyMessageFactory), // tp_basicsize
0, // tp_itemsize
message_factory::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
"A static Message Factory", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
message_factory::Methods, // tp_methods
0, // tp_members
message_factory::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
message_factory::New, // tp_new
PyObject_Del, // tp_free
};
bool InitMessageFactory() {
if (PyType_Ready(&PyMessageFactory_Type) < 0) {
return false;
}
return true;
}
} // namespace python
} // namespace protobuf
} // namespace google
<commit_msg>pyext: missing cast to constant char* (#5713)<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 <unordered_map>
#include <Python.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#if PY_MAJOR_VERSION >= 3
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
namespace protobuf {
namespace python {
namespace message_factory {
PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
PyType_GenericAlloc(type, 0));
if (factory == NULL) {
return NULL;
}
DynamicMessageFactory* message_factory = new DynamicMessageFactory();
// This option might be the default some day.
message_factory->SetDelegateToGeneratedFactory(true);
factory->message_factory = message_factory;
factory->pool = pool;
// TODO(amauryfa): When the MessageFactory is not created from the
// DescriptorPool this reference should be owned, not borrowed.
// Py_INCREF(pool);
factory->classes_by_descriptor = new PyMessageFactory::ClassesByMessageMap();
return factory;
}
PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {"pool", 0};
PyObject* pool = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &pool)) {
return NULL;
}
ScopedPyObjectPtr owned_pool;
if (pool == NULL || pool == Py_None) {
owned_pool.reset(PyObject_CallFunction(
reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
if (owned_pool == NULL) {
return NULL;
}
pool = owned_pool.get();
} else {
if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
pool->ob_type->tp_name);
return NULL;
}
}
return reinterpret_cast<PyObject*>(
NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
}
static void Dealloc(PyObject* pself) {
PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
// TODO(amauryfa): When the MessageFactory is not created from the
// DescriptorPool this reference should be owned, not borrowed.
// Py_CLEAR(self->pool);
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
for (iterator it = self->classes_by_descriptor->begin();
it != self->classes_by_descriptor->end(); ++it) {
Py_DECREF(it->second);
}
delete self->classes_by_descriptor;
delete self->message_factory;
Py_TYPE(self)->tp_free(pself);
}
// Add a message class to our database.
int RegisterMessageClass(PyMessageFactory* self,
const Descriptor* message_descriptor,
CMessageClass* message_class) {
Py_INCREF(message_class);
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
std::make_pair(message_descriptor, message_class));
if (!ret.second) {
// Update case: DECREF the previous value.
Py_DECREF(ret.first->second);
ret.first->second = message_class;
}
return 0;
}
CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
const Descriptor* descriptor) {
// This is the same implementation as MessageFactory.GetPrototype().
// Do not create a MessageClass that already exists.
std::unordered_map<const Descriptor*, CMessageClass*>::iterator it =
self->classes_by_descriptor->find(descriptor);
if (it != self->classes_by_descriptor->end()) {
Py_INCREF(it->second);
return it->second;
}
ScopedPyObjectPtr py_descriptor(
PyMessageDescriptor_FromDescriptor(descriptor));
if (py_descriptor == NULL) {
return NULL;
}
// Create a new message class.
ScopedPyObjectPtr args(Py_BuildValue(
"s(){sOsOsO}", descriptor->name().c_str(),
"DESCRIPTOR", py_descriptor.get(),
"__module__", Py_None,
"message_factory", self));
if (args == NULL) {
return NULL;
}
ScopedPyObjectPtr message_class(PyObject_CallObject(
reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
if (message_class == NULL) {
return NULL;
}
// Create messages class for the messages used by the fields, and registers
// all extensions for these messages during the recursion.
for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
const Descriptor* sub_descriptor =
descriptor->field(field_idx)->message_type();
// It is NULL if the field type is not a message.
if (sub_descriptor != NULL) {
CMessageClass* result = GetOrCreateMessageClass(self, sub_descriptor);
if (result == NULL) {
return NULL;
}
Py_DECREF(result);
}
}
// Register extensions defined in this message.
for (int ext_idx = 0 ; ext_idx < descriptor->extension_count() ; ext_idx++) {
const FieldDescriptor* extension = descriptor->extension(ext_idx);
ScopedPyObjectPtr py_extended_class(
GetOrCreateMessageClass(self, extension->containing_type())
->AsPyObject());
if (py_extended_class == NULL) {
return NULL;
}
ScopedPyObjectPtr py_extension(PyFieldDescriptor_FromDescriptor(extension));
if (py_extension == NULL) {
return NULL;
}
ScopedPyObjectPtr result(cmessage::RegisterExtension(
py_extended_class.get(), py_extension.get()));
if (result == NULL) {
return NULL;
}
}
return reinterpret_cast<CMessageClass*>(message_class.release());
}
// Retrieve the message class added to our database.
CMessageClass* GetMessageClass(PyMessageFactory* self,
const Descriptor* message_descriptor) {
typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
iterator ret = self->classes_by_descriptor->find(message_descriptor);
if (ret == self->classes_by_descriptor->end()) {
PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
message_descriptor->full_name().c_str());
return NULL;
} else {
return ret->second;
}
}
static PyMethodDef Methods[] = {
{NULL}};
static PyObject* GetPool(PyMessageFactory* self, void* closure) {
Py_INCREF(self->pool);
return reinterpret_cast<PyObject*>(self->pool);
}
static PyGetSetDef Getters[] = {
{"pool", (getter)GetPool, NULL, "DescriptorPool"},
{NULL}
};
} // namespace message_factory
PyTypeObject PyMessageFactory_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".MessageFactory", // tp_name
sizeof(PyMessageFactory), // tp_basicsize
0, // tp_itemsize
message_factory::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
"A static Message Factory", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
message_factory::Methods, // tp_methods
0, // tp_members
message_factory::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
message_factory::New, // tp_new
PyObject_Del, // tp_free
};
bool InitMessageFactory() {
if (PyType_Ready(&PyMessageFactory_Type) < 0) {
return false;
}
return true;
}
} // namespace python
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: testFunctions.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Christopher Dembia *
* *
* 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 <OpenSim/Common/Sine.h>
#include <OpenSim/Common/SignalGenerator.h>
#include <OpenSim/Common/Reporter.h>
#include "ComponentsForTesting.h"
using namespace OpenSim;
using namespace SimTK;
void testSignalGenerator() {
// Feed a SignalGenerator's output into a TableReporter, and make sure the
// reported value is correct.
// Build the model.
RootComponent world;
auto* signalGen = new SignalGenerator();
signalGen->setName("sinusoid");
const double amplitude = 1.5;
const double omega = 3.1;
const double phase = 0.3;
signalGen->set_function(Sine(amplitude, omega, phase));
world.addComponent(signalGen);
auto* reporter = new TableReporter();
reporter->addToReport(signalGen->getOutput("signal"));
world.addComponent(reporter);
// Build the system.
MultibodySystem system;
world.buildUpSystem(system);
State s = system.realizeTopology();
system.realize(s, Stage::Model);
// "Simulate."
const int numTimePoints = 5;
for (int i = 0; i < numTimePoints; ++i) {
s.setTime(0.1 * i);
system.realize(s, Stage::Report);
}
// Check that the SignalGenerator produced the correct values.
const TimeSeriesTable_<Real>& results = reporter->getTable();
SimTK_TEST_EQ((int)results.getNumRows(), numTimePoints);
for (int i = 0; i < numTimePoints; ++i) {
const double time = 0.1 * i;
system.realize(s, Stage::Report);
SimTK_TEST_EQ(results.getRowAtIndex(i)[0],
amplitude * std::sin(omega * time + phase));
}
}
int main() {
SimTK_START_TEST("testSignalGenerator");
SimTK_SUBTEST(testSignalGenerator);
SimTK_END_TEST();
}
<commit_msg>Add offset to Sine function case.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: testFunctions.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Christopher Dembia *
* *
* 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 <OpenSim/Common/Sine.h>
#include <OpenSim/Common/SignalGenerator.h>
#include <OpenSim/Common/Reporter.h>
#include "ComponentsForTesting.h"
using namespace OpenSim;
using namespace SimTK;
void testSignalGenerator() {
// Feed a SignalGenerator's output into a TableReporter, and make sure the
// reported value is correct.
// Build the model.
RootComponent world;
auto* signalGen = new SignalGenerator();
signalGen->setName("sinusoid");
const double amplitude = 1.5;
const double omega = 3.1;
const double phase = 0.3;
const double offset = 0.12345;
signalGen->set_function(Sine(amplitude, omega, phase, offset));
world.addComponent(signalGen);
auto* reporter = new TableReporter();
reporter->addToReport(signalGen->getOutput("signal"));
world.addComponent(reporter);
// Build the system.
MultibodySystem system;
world.buildUpSystem(system);
State s = system.realizeTopology();
system.realize(s, Stage::Model);
// "Simulate."
const int numTimePoints = 5;
for (int i = 0; i < numTimePoints; ++i) {
s.setTime(0.1 * i);
system.realize(s, Stage::Report);
}
// Check that the SignalGenerator produced the correct values.
const TimeSeriesTable_<Real>& results = reporter->getTable();
SimTK_TEST_EQ((int)results.getNumRows(), numTimePoints);
for (int i = 0; i < numTimePoints; ++i) {
const double time = 0.1 * i;
system.realize(s, Stage::Report);
SimTK_TEST_EQ(results.getRowAtIndex(i)[0],
amplitude * std::sin(omega * time + phase) + offset);
}
}
int main() {
SimTK_START_TEST("testSignalGenerator");
SimTK_SUBTEST(testSignalGenerator);
SimTK_END_TEST();
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: ForceSet.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2018 Stanford University and the Authors *
* Author(s): Ajay Seth, Jack Middleton *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "ForceSet.h"
using namespace std;
using namespace OpenSim;
void ForceSet::extendConnectToModel(Model& aModel)
{
// BASE CLASS
Super::extendConnectToModel(aModel);
_actuators.setMemoryOwner(false);
_muscles.setMemoryOwner(false);
updateActuators();
updateMuscles();
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// ACTUATOR
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Remove an actuator from the actuator set.
*
* @param aIndex Index of the actuator to be removed.
* @return True if the remove was successful; false otherwise.
*/
bool ForceSet::remove(int aIndex)
{
bool success = Super::remove(aIndex);
updateActuators();
updateMuscles();
return(success);
}
//_____________________________________________________________________________
/**
* Append an actuator on to the set. A copy of the specified actuator
* is not made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aActuator Pointer to the actuator to be appended.
* @return True if successful; false otherwise.
*/
bool ForceSet::append(Force *aForce)
{
bool success = Super::adoptAndAppend(aForce);
if (success && hasModel()) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Append an actuator on to the set. A copy of the specified actuator
* is made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aActuator reference to the actuator to be appended.
* @return True if successful; false otherwise.
*/
bool ForceSet::
append(Force &aForce)
{
bool success = Super::cloneAndAppend(aForce);
if (success && hasModel()) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Append actuators from an actuator set to this set. Copies of the actuators are not made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aForceSet The set of actuators to be appended.
* @param aAllowDuplicateNames If true, all actuators will be appended; If false, don't append actuators whose
* name already exists in this model's actuator set.
* @return True if successful; false otherwise.
*/
bool ForceSet::append(ForceSet &aForceSet, bool aAllowDuplicateNames)
{
bool success = true;
for(int i=0;i<aForceSet.getSize() && success;i++) {
bool nameExists = false;
if(!aAllowDuplicateNames) {
std::string name = aForceSet.get(i).getName();
for(int j=0;j<getSize();j++) {
if(get(j).getName() == name) {
nameExists = true;
break;
}
}
}
if(!nameExists) {
if(!Super::adoptAndAppend(&aForceSet.get(i)))
success = false;
}
}
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Set the actuator at an index. A copy of the specified actuator is NOT made.
* The actuator previously set at the index is removed (and deleted).
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aIndex Array index where the actuator is to be stored. aIndex
* should be in the range 0 <= aIndex <= getSize();
* @param aActuator Pointer to the actuator to be set.
* @return True if successful; false otherwise.
*/
bool ForceSet::set(int aIndex,Force *aActuator, bool preserveGroups)
{
bool success = Super::set(aIndex, aActuator, preserveGroups);
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
bool ForceSet::insert(int aIndex, Force *aForce)
{
bool success = Super::insert(aIndex, aForce);
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Get the list of Actuators.
*/
const Set<Actuator>& ForceSet::getActuators() const
{
return _actuators;
}
Set<Actuator>& ForceSet::updActuators()
{
updateActuators();
return _actuators;
}
//_____________________________________________________________________________
/**
* Rebuild the list of Actuators.
*/
void ForceSet::updateActuators()
{
_actuators.setMemoryOwner(false);
_actuators.setSize(0);
for (int i = 0; i < getSize(); ++i) {
Actuator* act = dynamic_cast<Actuator*>(&get(i));
if (act) _actuators.adoptAndAppend(act);
}
}
//=============================================================================
//_____________________________________________________________________________
/**
* Get the list of Muscles.
*/
const Set<Muscle>& ForceSet::getMuscles() const
{
if (_muscles.getSize() == 0)
const_cast<ForceSet*>(this)->updateMuscles();
return _muscles;
}
Set<Muscle>& ForceSet::updMuscles()
{
if (_muscles.getSize() == 0)
updateMuscles();
return _muscles;
}
//_____________________________________________________________________________
/**
* Rebuild the list of Muscles.
*/
void ForceSet::updateMuscles()
{
_muscles.setMemoryOwner(false);
_muscles.setSize(0);
for (int i = 0; i < getSize(); ++i) {
Muscle* m = dynamic_cast<Muscle*>(&get(i));
if (m) _muscles.adoptAndAppend(m);
}
}
//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
//_____________________________________________________________________________
/**
* Get the names of the states of the actuators.
*
* @param rNames Array of names.
*/
void ForceSet::
getStateVariableNames(OpenSim::Array<std::string> &rNames) const
{
for(int i=0;i<getSize();i++) {
ScalarActuator *act = dynamic_cast<ScalarActuator*>(&get(i));
if(act) {
rNames.append(act->getStateVariableNames());
}
}
}
//=============================================================================
// CHECK
//=============================================================================
//_____________________________________________________________________________
/**
* Check that all actuators are valid.
*/
bool ForceSet::
check() const
{
bool status=true;
// LOOP THROUGH ACTUATORS
ScalarActuator *act;
int size = getSize();
for(int i=0;i<size;i++) {
act = dynamic_cast<ScalarActuator *>(&get(i));
if(!act) continue;
}
return(status);
}
<commit_msg>Revert ForceSet to its previous behavior where the Muscles list is NOT updated upon getMuscles<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: ForceSet.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2018 Stanford University and the Authors *
* Author(s): Ajay Seth, Jack Middleton *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "ForceSet.h"
using namespace std;
using namespace OpenSim;
void ForceSet::extendConnectToModel(Model& aModel)
{
// BASE CLASS
Super::extendConnectToModel(aModel);
_actuators.setMemoryOwner(false);
_muscles.setMemoryOwner(false);
updateActuators();
updateMuscles();
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// ACTUATOR
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Remove an actuator from the actuator set.
*
* @param aIndex Index of the actuator to be removed.
* @return True if the remove was successful; false otherwise.
*/
bool ForceSet::remove(int aIndex)
{
bool success = Super::remove(aIndex);
updateActuators();
updateMuscles();
return(success);
}
//_____________________________________________________________________________
/**
* Append an actuator on to the set. A copy of the specified actuator
* is not made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aActuator Pointer to the actuator to be appended.
* @return True if successful; false otherwise.
*/
bool ForceSet::append(Force *aForce)
{
bool success = Super::adoptAndAppend(aForce);
if (success && hasModel()) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Append an actuator on to the set. A copy of the specified actuator
* is made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aActuator reference to the actuator to be appended.
* @return True if successful; false otherwise.
*/
bool ForceSet::
append(Force &aForce)
{
bool success = Super::cloneAndAppend(aForce);
if (success && hasModel()) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Append actuators from an actuator set to this set. Copies of the actuators are not made.
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aForceSet The set of actuators to be appended.
* @param aAllowDuplicateNames If true, all actuators will be appended; If false, don't append actuators whose
* name already exists in this model's actuator set.
* @return True if successful; false otherwise.
*/
bool ForceSet::append(ForceSet &aForceSet, bool aAllowDuplicateNames)
{
bool success = true;
for(int i=0;i<aForceSet.getSize() && success;i++) {
bool nameExists = false;
if(!aAllowDuplicateNames) {
std::string name = aForceSet.get(i).getName();
for(int j=0;j<getSize();j++) {
if(get(j).getName() == name) {
nameExists = true;
break;
}
}
}
if(!nameExists) {
if(!Super::adoptAndAppend(&aForceSet.get(i)))
success = false;
}
}
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Set the actuator at an index. A copy of the specified actuator is NOT made.
* The actuator previously set at the index is removed (and deleted).
*
* This method overrides the method in Set<Force> so that several
* internal variables of the actuator set can be updated.
*
* @param aIndex Array index where the actuator is to be stored. aIndex
* should be in the range 0 <= aIndex <= getSize();
* @param aActuator Pointer to the actuator to be set.
* @return True if successful; false otherwise.
*/
bool ForceSet::set(int aIndex,Force *aActuator, bool preserveGroups)
{
bool success = Super::set(aIndex, aActuator, preserveGroups);
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
bool ForceSet::insert(int aIndex, Force *aForce)
{
bool success = Super::insert(aIndex, aForce);
if(success) {
updateActuators();
updateMuscles();
}
return(success);
}
//_____________________________________________________________________________
/**
* Get the list of Actuators.
*/
const Set<Actuator>& ForceSet::getActuators() const
{
return _actuators;
}
Set<Actuator>& ForceSet::updActuators()
{
updateActuators();
return _actuators;
}
//_____________________________________________________________________________
/**
* Rebuild the list of Actuators.
*/
void ForceSet::updateActuators()
{
_actuators.setMemoryOwner(false);
_actuators.setSize(0);
for (int i = 0; i < getSize(); ++i) {
Actuator* act = dynamic_cast<Actuator*>(&get(i));
if (act) _actuators.adoptAndAppend(act);
}
}
//=============================================================================
//_____________________________________________________________________________
/**
* Get the list of Muscles.
*/
const Set<Muscle>& ForceSet::getMuscles() const
{
return _muscles;
}
Set<Muscle>& ForceSet::updMuscles()
{
if (_muscles.getSize() == 0)
updateMuscles();
return _muscles;
}
//_____________________________________________________________________________
/**
* Rebuild the list of Muscles.
*/
void ForceSet::updateMuscles()
{
_muscles.setMemoryOwner(false);
_muscles.setSize(0);
for (int i = 0; i < getSize(); ++i) {
Muscle* m = dynamic_cast<Muscle*>(&get(i));
if (m) _muscles.adoptAndAppend(m);
}
}
//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
//_____________________________________________________________________________
/**
* Get the names of the states of the actuators.
*
* @param rNames Array of names.
*/
void ForceSet::
getStateVariableNames(OpenSim::Array<std::string> &rNames) const
{
for(int i=0;i<getSize();i++) {
ScalarActuator *act = dynamic_cast<ScalarActuator*>(&get(i));
if(act) {
rNames.append(act->getStateVariableNames());
}
}
}
//=============================================================================
// CHECK
//=============================================================================
//_____________________________________________________________________________
/**
* Check that all actuators are valid.
*/
bool ForceSet::
check() const
{
bool status=true;
// LOOP THROUGH ACTUATORS
ScalarActuator *act;
int size = getSize();
for(int i=0;i<size;i++) {
act = dynamic_cast<ScalarActuator *>(&get(i));
if(!act) continue;
}
return(status);
}
<|endoftext|> |
<commit_before>#ifndef GCL_TYPE_INFO__
# define GCL_TYPE_INFO__
#include <gcl_cpp/preprocessor.hpp>
#include <tuple>
#include <memory>
#include <functional>
#include <cassert>
#include <vector>
#include <typeindex>
#include <gcl_cpp/mp.hpp>
#include <gcl_cpp/tuple_utils.hpp>
namespace gcl::type_info
{
namespace id
{
using type = std::type_index;
#if defined(__cpp_rtti)
template <typename T>
static const type value = typeid(T);
#endif
template <typename T>
static constexpr auto type_name = experimental::type_name<T>();
}
template<typename ... Ts>
static constexpr std::vector<id::type> make_ids_vector() { return { id<Ts>::value... }; }
template<typename ... Ts>
static constexpr std::array<id::type, sizeof...(Ts)> make_ids_array() { return { id<T>::value... }; }
template <typename ... Ts>
struct variadic_template
{ // wrapper to gcl::mp::<function_name>
using std_type = std::tuple<Ts...>;
inline static constexpr auto size = sizeof...(Ts); // or std::tuple_size_v<tuple_type>
template <size_t N>
using type_at = gcl::mp::type_at<N, Ts...>;
template <typename T>
static constexpr inline size_t index_of = gcl::mp::index_of<T, Ts...>;
template <typename T>
static constexpr inline bool contains = gcl::mp::contains<T, Ts...>;
auto to_std()
{
return std_type{};
}
};
template <typename ... Ts>
using pack = variadic_template<Ts...>;
namespace experimental
{
template <typename T>
constexpr std::string_view type_name(/*no parameters allowed*/)
{
#ifdef _MSC_VER
std::string_view str_view = __FUNCSIG__;
str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__));
str_view.remove_suffix(str_view.length() - str_view.rfind('>'));
#elif defined (__GNUC__)
std::string_view str_view = __PRETTY_FUNCTION__;
str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__));
const char prefix[] = " [with T = ";
str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1);
str_view.remove_suffix(str_view.length() - str_view.find(';'));
#else
static_assert(false, "not supported compiler");
#endif
return str_view;
}
struct holder final
{ // hold a value anonymously
// /!\ cost much more than std::any
struct interface_t
{ // as interface, for safe y-shaped inheritance tree (type erasure)
interface_t() = default;
interface_t(const interface_t &) = delete;
interface_t(interface_t &&) = delete;
virtual ~interface_t() = default;
};
using value_type = std::unique_ptr<interface_t>;
template <typename T>
struct type_eraser : interface_t, std::decay_t<T>
{
using target_type = std::decay_t<T>;
explicit type_eraser(target_type && value)
: target_type{ std::forward<target_type>(value) }
{}
};
holder() = delete;
holder(holder &) = delete;
holder(holder &&) = default;
template <typename concret_t>
explicit holder(concret_t && elem)
: value(std::unique_ptr<interface_t>(new type_eraser<concret_t>{ std::forward<concret_t>(elem) }))
, id(type_info::id::value<concret_t>)
{}
template <typename T>
T & cast() const
{
using target_type = std::decay_t<T>;
if (id != gcl::type_info::id::value<target_type>)
throw std::bad_cast();
auto * as_type_eraser_ptr = static_cast<type_eraser<target_type&>*>(value.get());
return static_cast<target_type&>(*as_type_eraser_ptr);
}
const gcl::type_info::id::type id;
const value_type value;
};
}
}
inline std::ostream & operator<<(std::ostream & os, const std::type_index & index)
{
return os << "type_id=[(" << index.hash_code() << ')' << index.name() << ']';
}
#include <memory>
namespace gcl::deprecated::type_info
{ // C++11
template <typename ... Ts>
struct variadic_template
{
using tuple_type = std::tuple<Ts...>;
inline static constexpr auto size = sizeof...(Ts); // or std::tuple_size_v<tuple_type>
template <size_t N>
using type_at = typename std::tuple_element<N, tuple_type>::type;
template <typename T>
static constexpr inline size_t index_of(void)
{
return index_of_impl<T, 0, Ts...>();
}
auto to_std()
{
return tuple_type{};
}
private:
template <typename needle_t, size_t it_n, typename iterated_t, typename ... haystack_t>
static constexpr inline size_t index_of_impl(void)
{
return (std::is_same<needle_t, iterated_t>::value ? it_n : index_of_impl<needle_t, it_n + 1, haystack_t...>());
}
template <typename needle_t, size_t iterated_t>
static constexpr inline size_t index_of_impl(void)
{
throw std::out_of_range("variadic_template::index_of_impl : Not found");
}
};
#if (defined _DEBUG && defined GCL_UNSAFE_CODE)
using id_type = uint64_t;
template <typename T>
struct id
{
// Warning : Values change per program instance
// Error : compiler optimization may set the same value per instance
static const id_type value; // [todo]::[C++14] : MS compiler (VS2015) do not support variable-template
// [todo]::[C++17] : seems to no be able to self-reference a template variable
};
#pragma warning (disable : 4311 4302)
template <typename T>
const gcl::deprecated::type_info::id_type gcl::deprecated::type_info::id<T>::value
= reinterpret_cast<gcl::deprecated::type_info::id_type>(&(gcl::deprecated::type_info::id<T>::value));
#pragma warning (default : 4311 4302)
#else
using id_type = std::type_index;
template <typename T>
struct id
{
static inline const id_type value = typeid(T);
};
#endif
template <typename interface_t>
struct holder final
{
using typeid_type = id_type;
using value_type = std::unique_ptr<interface_t>;
holder() = delete;
holder(holder &) = default;
holder(holder &&) = default;
holder(id_type _id, value_type && ptr)
: value(std::move(ptr))
, id(_id)
{}
template <typename concret_t>
explicit holder(std::unique_ptr<concret_t> && ptr)
: value(std::forward<std::unique_ptr<concret_t>>(ptr))
, id(gcl::deprecated::type_info::id<concret_t>::value)
{
check_<concret_t>();
}
template <typename concret_t>
explicit holder(concret_t * ptr)
: value(std::move(ptr))
, id(gcl::deprecated::type_info::id<concret_t>::value)
{
check_<concret_t>();
}
const id_type id;
const value_type value;
private:
template <typename concret_t>
static constexpr void check_()
{
static_assert(!std::is_same<interface_t, concret_t>::value, "interface and concrete types are the same");
static_assert(std::is_base_of<interface_t, concret_t>::value, "interface_t is not base of concrete_t");
}
};
namespace experimental
{
struct any
{
any(const any &) = delete;
any(const any &&) = delete;
virtual inline ~any() = 0 {}
virtual inline const gcl::deprecated::type_info::id_type id() const = 0;
inline bool operator==(const any & other)
{
return other.id() == id() && compare_impl(other);
}
protected:
virtual inline const bool compare_impl(const any &) const = 0;
any() = default;
};
template <typename T>
struct any_impl : public any, public T
{
friend any;
using type_t = any_impl<T>;
template <typename ... Args>
explicit any_impl(Args... args)
: any()
, T(std::forward<std::decay<Args...>::type>(args...))
{}
~any_impl() override {}
operator T()
{
return static_cast<T&>(*this);
}
inline const gcl::deprecated::type_info::id_type id() const override
{
return gcl::deprecated::type_info::id<T>::value;
}
inline const bool compare_impl(const any & other) const override
{
assert(id() == other.id());
return (dynamic_cast<const T &>(dynamic_cast<const type_t &>(other)) == dynamic_cast<const T&>(*this));
}
};
}
}
#endif // GCL_TYPE_INFO__
<commit_msg>gcl::type_info : fix compilation issues for few compilers / compile-options. e.g template keyword use and member-function declaration order<commit_after>#ifndef GCL_TYPE_INFO__
# define GCL_TYPE_INFO__
#include <gcl_cpp/preprocessor.hpp>
#include <tuple>
#include <memory>
#include <functional>
#include <cassert>
#include <vector>
#include <typeindex>
#include <gcl_cpp/mp.hpp>
#include <gcl_cpp/tuple_utils.hpp>
namespace gcl::type_info
{
namespace id
{
using type = std::type_index;
#if defined(__cpp_rtti)
template <typename T>
static const type value = typeid(T);
#endif
template <typename T>
static constexpr auto type_name = experimental::template type_name<T>();
}
template <typename ... Ts>
static constexpr std::vector<id::type> make_ids_vector() { return { id<Ts>::value... }; }
template <typename ... Ts>
static constexpr std::array<id::type, sizeof...(Ts)> make_ids_array() { return { id<Ts>::value... }; }
template <typename ... Ts>
struct variadic_template
{ // wrapper to gcl::mp::<function_name>
using std_type = std::tuple<Ts...>;
inline static constexpr auto size = sizeof...(Ts); // or std::tuple_size_v<tuple_type>
template <size_t N>
using type_at = gcl::mp::type_at<N, Ts...>;
template <typename T>
static constexpr inline size_t index_of = gcl::mp::index_of<T, Ts...>;
template <typename T>
static constexpr inline bool contains = gcl::mp::contains<T, Ts...>;
auto to_std()
{
return std_type{};
}
};
template <typename ... Ts>
using pack = variadic_template<Ts...>;
namespace experimental
{
template <typename T>
constexpr std::string_view type_name(/*no parameters allowed*/)
{
#ifdef _MSC_VER
std::string_view str_view = __FUNCSIG__;
str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__));
str_view.remove_suffix(str_view.length() - str_view.rfind('>'));
#elif defined (__GNUC__)
std::string_view str_view = __PRETTY_FUNCTION__;
str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__));
const char prefix[] = " [with T = ";
str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1);
str_view.remove_suffix(str_view.length() - str_view.find(';'));
#else
static_assert(false, "not supported compiler");
#endif
return str_view;
}
struct holder final
{ // hold a value anonymously
// /!\ cost much more than std::any
struct interface_t
{ // as interface, for safe y-shaped inheritance tree (type erasure)
interface_t() = default;
interface_t(const interface_t &) = delete;
interface_t(interface_t &&) = delete;
virtual ~interface_t() = default;
};
using value_type = std::unique_ptr<interface_t>;
template <typename T>
struct type_eraser : interface_t, std::decay_t<T>
{
using target_type = std::decay_t<T>;
explicit type_eraser(target_type && value)
: target_type{ std::forward<target_type>(value) }
{}
};
holder() = delete;
holder(holder &) = delete;
holder(holder &&) = default;
template <typename concret_t>
explicit holder(concret_t && elem)
: value(std::unique_ptr<interface_t>(new type_eraser<concret_t>{ std::forward<concret_t>(elem) }))
, id(type_info::id::value<concret_t>)
{}
template <typename T>
T & cast() const
{
using target_type = std::decay_t<T>;
if (id != gcl::type_info::id::value<target_type>)
throw std::bad_cast();
auto * as_type_eraser_ptr = static_cast<type_eraser<target_type&>*>(value.get());
return static_cast<target_type&>(*as_type_eraser_ptr);
}
const gcl::type_info::id::type id;
const value_type value;
};
}
}
inline std::ostream & operator<<(std::ostream & os, const std::type_index & index)
{
return os << "type_id=[(" << index.hash_code() << ')' << index.name() << ']';
}
#include <memory>
namespace gcl::deprecated::type_info
{ // C++11
template <typename ... Ts>
struct variadic_template
{
using tuple_type = std::tuple<Ts...>;
inline static constexpr auto size = sizeof...(Ts); // or std::tuple_size_v<tuple_type>
template <size_t N>
using type_at = typename std::tuple_element<N, tuple_type>::type;
template <typename T>
static constexpr inline size_t index_of(void)
{
return index_of_impl<T, 0, Ts...>();
}
auto to_std()
{
return tuple_type{};
}
private:
template <typename needle_t, size_t it_n, typename iterated_t, typename ... haystack_t>
static constexpr inline size_t index_of_impl(void)
{
return (std::is_same<needle_t, iterated_t>::value ? it_n : index_of_impl<needle_t, it_n + 1, haystack_t...>());
}
template <typename needle_t, size_t iterated_t>
static constexpr inline size_t index_of_impl(void)
{
throw std::out_of_range("variadic_template::index_of_impl : Not found");
}
};
#if (defined _DEBUG && defined GCL_UNSAFE_CODE)
using id_type = uint64_t;
template <typename T>
struct id
{
// Warning : Values change per program instance
// Error : compiler optimization may set the same value per instance
static const id_type value; // [todo]::[C++14] : MS compiler (VS2015) do not support variable-template
// [todo]::[C++17] : seems to no be able to self-reference a template variable
};
#pragma warning (disable : 4311 4302)
template <typename T>
const gcl::deprecated::type_info::id_type gcl::deprecated::type_info::id<T>::value
= reinterpret_cast<gcl::deprecated::type_info::id_type>(&(gcl::deprecated::type_info::id<T>::value));
#pragma warning (default : 4311 4302)
#else
using id_type = std::type_index;
template <typename T>
struct id
{
static inline const id_type value = typeid(T);
};
#endif
template <typename interface_t>
struct holder final
{
using typeid_type = id_type;
using value_type = std::unique_ptr<interface_t>;
holder() = delete;
holder(holder &) = default;
holder(holder &&) = default;
holder(id_type _id, value_type && ptr)
: value(std::move(ptr))
, id(_id)
{}
template <typename concret_t>
explicit holder(std::unique_ptr<concret_t> && ptr)
: value(std::forward<std::unique_ptr<concret_t>>(ptr))
, id(gcl::deprecated::type_info::id<concret_t>::value)
{
check_<concret_t>();
}
template <typename concret_t>
explicit holder(concret_t * ptr)
: value(std::move(ptr))
, id(gcl::deprecated::type_info::id<concret_t>::value)
{
check_<concret_t>();
}
const id_type id;
const value_type value;
private:
template <typename concret_t>
static constexpr void check_()
{
static_assert(!std::is_same<interface_t, concret_t>::value, "interface and concrete types are the same");
static_assert(std::is_base_of<interface_t, concret_t>::value, "interface_t is not base of concrete_t");
}
};
namespace experimental
{
struct any
{
any(const any &) = delete;
any(const any &&) = delete;
virtual inline ~any() = 0 {}
virtual inline const gcl::deprecated::type_info::id_type id() const = 0;
inline bool operator==(const any & other)
{
return other.id() == id() && compare_impl(other);
}
protected:
virtual inline const bool compare_impl(const any &) const = 0;
any() = default;
};
template <typename T>
struct any_impl : public any, public T
{
friend any;
using type_t = any_impl<T>;
template <typename ... Args>
explicit any_impl(Args... args)
: any()
, T(std::forward<std::decay<Args...>::type>(args...))
{}
~any_impl() override {}
operator T()
{
return static_cast<T&>(*this);
}
inline const gcl::deprecated::type_info::id_type id() const override
{
return gcl::deprecated::type_info::id<T>::value;
}
inline const bool compare_impl(const any & other) const override
{
assert(id() == other.id());
return (dynamic_cast<const T &>(dynamic_cast<const type_t &>(other)) == dynamic_cast<const T&>(*this));
}
};
}
}
#endif // GCL_TYPE_INFO__
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlComponent.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ihi $ $Date: 2007-11-20 19:00:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#ifndef RPT_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef RPT_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef RPT_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef RPT_XMLHELPER_HXX
#include "xmlHelper.hxx"
#endif
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef RPT_XMLSTYLEIMPORT_HXX
#include "xmlStyleImport.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_NAMECONTAINER_HXX_
#include <comphelper/namecontainer.hxx>
#endif
#ifndef _COMPHELPER_GENERICPROPERTYSET_HXX_
#include <comphelper/genericpropertyset.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_REPORT_XREPORTCONTROLMODEL_HPP_
#include <com/sun/star/report/XReportControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HXX_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
namespace rptxml
{
using namespace ::comphelper;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::report;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLComponent )
OXMLComponent::OXMLComponent( ORptFilter& _rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const Reference< XReportComponent > & _xComponent
) :
SvXMLImportContext( _rImport, nPrfx, _sLocalName )
,m_xComponent(_xComponent)
{
DBG_CTOR( rpt_OXMLComponent,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
OSL_ENSURE(m_xComponent.is(),"Component is NULL!");
const SvXMLNamespaceMap& rMap = _rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = _rImport.GetComponentElemTokenMap();
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
for(sal_Int16 i = 0; i < nLength; ++i)
{
try
{
::rtl::OUString sLocalName;
const ::rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const ::rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_NAME:
m_xComponent->setName(sValue);
break;
case XML_TOK_TEXT_STYLE_NAME:
m_sTextStyleName = sValue;
break;
case XML_TOK_TRANSFORM:
break;
default:
break;
}
}
catch(const Exception&)
{
OSL_ENSURE(0,"Exception catched while putting props into report component!");
}
}
}
// -----------------------------------------------------------------------------
OXMLComponent::~OXMLComponent()
{
DBG_DTOR( rpt_OXMLComponent,NULL);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ORptFilter& OXMLComponent::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.3.56); FILE MERGED 2008/04/01 15:23:37 thb 1.3.56.3: #i85898# Stripping all external header guards 2008/04/01 12:33:08 thb 1.3.56.2: #i85898# Stripping all external header guards 2008/03/31 13:32:06 rt 1.3.56.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: xmlComponent.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlComponent.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/xmluconv.hxx>
#include <xmloff/nmspmap.hxx>
#include "xmlEnums.hxx"
#include "xmlHelper.hxx"
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include "xmlStyleImport.hxx"
#include <ucbhelper/content.hxx>
#include <tools/debug.hxx>
#include <comphelper/namecontainer.hxx>
#include <comphelper/genericpropertyset.hxx>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/report/XReportControlModel.hpp>
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HXX_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#include <tools/debug.hxx>
namespace rptxml
{
using namespace ::comphelper;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::report;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLComponent )
OXMLComponent::OXMLComponent( ORptFilter& _rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const Reference< XReportComponent > & _xComponent
) :
SvXMLImportContext( _rImport, nPrfx, _sLocalName )
,m_xComponent(_xComponent)
{
DBG_CTOR( rpt_OXMLComponent,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
OSL_ENSURE(m_xComponent.is(),"Component is NULL!");
const SvXMLNamespaceMap& rMap = _rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = _rImport.GetComponentElemTokenMap();
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
for(sal_Int16 i = 0; i < nLength; ++i)
{
try
{
::rtl::OUString sLocalName;
const ::rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const ::rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_NAME:
m_xComponent->setName(sValue);
break;
case XML_TOK_TEXT_STYLE_NAME:
m_sTextStyleName = sValue;
break;
case XML_TOK_TRANSFORM:
break;
default:
break;
}
}
catch(const Exception&)
{
OSL_ENSURE(0,"Exception catched while putting props into report component!");
}
}
}
// -----------------------------------------------------------------------------
OXMLComponent::~OXMLComponent()
{
DBG_DTOR( rpt_OXMLComponent,NULL);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ORptFilter& OXMLComponent::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>//
// Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch
// PHOS Yuri.Kharlov@cern.ch
//
AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE)
{
// Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPartCorr", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskPartCorr", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;
// Configure analysis
//===========================================================================
//Reader
//For this particular analysis few things done by the reader.
//Nothing else needs to be set.
AliCaloTrackReader * reader = 0x0;
if (data=="AOD") reader = new AliCaloTrackAODReader();
else if(data=="ESD") reader = new AliCaloTrackESDReader();
//reader->SetDebug(10);//10 for lots of messages
reader->SwitchOnEMCALCells();
reader->SwitchOnPHOSCells();
reader->SwitchOnEMCAL();
reader->SwitchOnPHOS();
reader->SwitchOnCTS();
reader->SetEMCALPtMin(0.);
reader->SetPHOSPtMin (0.);
reader->SetCTSPtMin (0.);
reader->SetZvertexCut(10.);
if(kUseKinematics){
if(inputDataType == "ESD"){
reader->SwitchOnStack();
reader->SwitchOffAODMCParticles();
}
else if(inputDataType == "AOD"){
reader->SwitchOffStack();
reader->SwitchOnAODMCParticles();
}
}
//if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL");
reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches.
reader->SwitchOffWriteDeltaAOD() ;
if(oldAOD) reader->SwitchOnOldAODs();
if(kPrintSettings) reader->Print("");
// *** Calorimeters Utils ***
AliCalorimeterUtils *cu = new AliCalorimeterUtils;
// Remove clusters close to borders, at least max energy cell is 1 cell away
cu->SetNumberOfCellsFromEMCALBorder(1);
cu->SetNumberOfCellsFromPHOSBorder(2);
cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");
// Remove EMCAL hottest channels for first LHC10 periods
//cu->SwitchOnBadChannelsRemoval();
// SM0
//cu->SetEMCALChannelStatus(0,3,13); cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13);
//cu->SetEMCALChannelStatus(0,20,7); cu->SetEMCALChannelStatus(0,38,2);
// SM1
//cu->SetEMCALChannelStatus(1,4,7); cu->SetEMCALChannelStatus(1,4,13); cu->SetEMCALChannelStatus(1,9,20);
//cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23);
//cu->SetEMCALChannelStatus(1,37,5); cu->SetEMCALChannelStatus(1,40,1); cu->SetEMCALChannelStatus(1,40,2);
//cu->SetEMCALChannelStatus(1,40,5); cu->SetEMCALChannelStatus(1,41,0); cu->SetEMCALChannelStatus(1,41,1);
//cu->SetEMCALChannelStatus(1,41,2); cu->SetEMCALChannelStatus(1,41,4);
// SM2
//cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17);
//cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21);
//cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17);
//cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21);
//cu->SetEMCALChannelStatus(2,19,22);
//SM3
//cu->SetEMCALChannelStatus(3,4,7);
//Recalibration
//cu->SwitchOnRecalibration();
//TFile * f = new TFile("RecalibrationFactors.root","read");
//cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0"));
//cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1"));
//cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2"));
//cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3"));
cu->SetDebug(-1);
if(kPrintSettings) cu->Print("");
// ##### Analysis algorithm settings ####
//AliFiducialCut * fidCut = new AliFiducialCut();
//fidCut->DoCTSFiducialCut(kFALSE) ;
//fidCut->DoEMCALFiducialCut(kTRUE) ;
//fidCut->DoPHOSFiducialCut(kTRUE) ;
AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA();
//emcalQA->SetDebug(2); //10 for lots of messages
emcalQA->SetCalorimeter("EMCAL");
if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
else emcalQA->SwitchOffDataMC() ;
emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name
//emcalQA->SetFiducialCut(fidCut);
emcalQA->SwitchOffFiducialCut();
emcalQA->SwitchOffPlotsMaking();
emcalQA->SwitchOnCorrelation();
if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment
//Set Histrograms bins and ranges
emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 181*TMath::DegToRad(), 200) ;
emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ;
emcalQA->SetNumberOfModules(10);
emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ;
emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 );
emcalQA->SetHistoPOverERangeAndNBins(0,10.,100);
emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200);
emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
emcalQA->SetHistoTimeRangeAndNBins(300.,900,300);
emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100);
emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
emcalQA->SetHistoXRangeAndNBins(-230,90,120);
emcalQA->SetHistoYRangeAndNBins(370,450,40);
emcalQA->SetHistoZRangeAndNBins(-400,400,200);
emcalQA->SetHistoRRangeAndNBins(400,450,25);
emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
//emcalQA->GetMCAnalysisUtils()->SetDebug(10);
if(kPrintSettings) emcalQA->Print("");
AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA();
//phosQA->SetDebug(2); //10 for lots of messages
phosQA->SetCalorimeter("PHOS");
if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
else phosQA->SwitchOffDataMC() ;
phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name
//phosQA->SetFiducialCut(fidCut);
phosQA->SwitchOffFiducialCut();
//phosQA->GetMCAnalysisUtils()->SetDebug(10);
phosQA->SwitchOffPlotsMaking();
//Set Histrograms bins and ranges
phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ;
phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ;
phosQA->SetNumberOfModules(3); //PHOS first year
phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ;
phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ;
phosQA->SetHistoPOverERangeAndNBins(0,10.,100);
phosQA->SetHistodEdxRangeAndNBins(0.,200.,200);
phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
phosQA->SetHistoTimeRangeAndNBins(0.,300,300);
phosQA->SetHistoRatioRangeAndNBins(0.,2.,100);
phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
phosQA->SetHistoXRangeAndNBins(-100,400,100);
phosQA->SetHistoYRangeAndNBins(-490,-290,100);
phosQA->SetHistoZRangeAndNBins(-80,80,100);
phosQA->SetHistoRRangeAndNBins(440,480,80);
phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
// #### Configure Maker ####
AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();
maker->SetReader(reader);//pointer to reader
maker->SetCaloUtils(cu); //pointer to calorimeter utils
maker->AddAnalysis(emcalQA,0);
maker->AddAnalysis(phosQA,1);
maker->SetAnaDebug(-1) ; // 0 to at least print the event number
maker->SwitchOnHistogramsMaker() ;
maker->SwitchOffAODsMaker() ;
if(kPrintSettings) maker->Print("");
printf("======================== \n");
printf(" End Configuration of Calorimeter QA \n");
printf("======================== \n");
// Create task
//===========================================================================
AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance");
task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
//task->SetDebugLevel(-1);
task->SelectCollisionCandidates();
task->SetAnalysisMaker(maker);
mgr->AddTask(task);
//Create containers
// AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(),
// AliAnalysisManager::kOutputContainer, "Calo.Performance.root");
if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("CaloQA", TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CaloQA",outputFile.Data()));
AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(),
AliAnalysisManager::kParamContainer,
Form("%s:CaloQACuts",outputFile.Data()));
//Form("%s:PartCorrCuts",outputfile.Data()));
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task, 1, cout_pc);
mgr->ConnectOutput (task, 2, cout_cuts);
return task;
}
<commit_msg>trick to fill missing histograms<commit_after>//
// Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch
// PHOS Yuri.Kharlov@cern.ch
//
AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE)
{
// Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPartCorr", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskPartCorr", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;
// Configure analysis
//===========================================================================
//Reader
//For this particular analysis few things done by the reader.
//Nothing else needs to be set.
AliCaloTrackReader * reader = 0x0;
if (data=="AOD") reader = new AliCaloTrackAODReader();
else if(data=="ESD") reader = new AliCaloTrackESDReader();
//reader->SetDebug(10);//10 for lots of messages
reader->SwitchOnEMCALCells();
reader->SwitchOnPHOSCells();
reader->SwitchOnEMCAL();
reader->SwitchOnPHOS();
reader->SwitchOnCTS();
reader->SetEMCALPtMin(0.);
reader->SetPHOSPtMin (0.);
reader->SetCTSPtMin (0.);
reader->SetZvertexCut(10.);
if(kUseKinematics){
if(inputDataType == "ESD"){
reader->SwitchOnStack();
reader->SwitchOffAODMCParticles();
}
else if(inputDataType == "AOD"){
reader->SwitchOffStack();
reader->SwitchOnAODMCParticles();
}
}
//if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL");
reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches.
reader->SwitchOffWriteDeltaAOD() ;
if(oldAOD) reader->SwitchOnOldAODs();
if(kPrintSettings) reader->Print("");
// *** Calorimeters Utils ***
AliCalorimeterUtils *cu = new AliCalorimeterUtils;
// Remove clusters close to borders, at least max energy cell is 1 cell away
cu->SetNumberOfCellsFromEMCALBorder(1);
cu->SetNumberOfCellsFromPHOSBorder(2);
cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");
// Remove EMCAL hottest channels for first LHC10 periods
cu->SwitchOnBadChannelsRemoval();
// SM0
//cu->SetEMCALChannelStatus(0,3,13); cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13);
//cu->SetEMCALChannelStatus(0,20,7); cu->SetEMCALChannelStatus(0,38,2);
// SM1
//cu->SetEMCALChannelStatus(1,4,7); cu->SetEMCALChannelStatus(1,4,13); cu->SetEMCALChannelStatus(1,9,20);
//cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23);
//cu->SetEMCALChannelStatus(1,37,5); cu->SetEMCALChannelStatus(1,40,1); cu->SetEMCALChannelStatus(1,40,2);
//cu->SetEMCALChannelStatus(1,40,5); cu->SetEMCALChannelStatus(1,41,0); cu->SetEMCALChannelStatus(1,41,1);
//cu->SetEMCALChannelStatus(1,41,2); cu->SetEMCALChannelStatus(1,41,4);
// SM2
//cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17);
//cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21);
//cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17);
//cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21);
//cu->SetEMCALChannelStatus(2,19,22);
//SM3
//cu->SetEMCALChannelStatus(3,4,7);
//Recalibration
//cu->SwitchOnRecalibration();
//TFile * f = new TFile("RecalibrationFactors.root","read");
//cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0"));
//cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1"));
//cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2"));
//cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3"));
cu->SetDebug(-1);
if(kPrintSettings) cu->Print("");
// ##### Analysis algorithm settings ####
//AliFiducialCut * fidCut = new AliFiducialCut();
//fidCut->DoCTSFiducialCut(kFALSE) ;
//fidCut->DoEMCALFiducialCut(kTRUE) ;
//fidCut->DoPHOSFiducialCut(kTRUE) ;
AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA();
//emcalQA->SetDebug(10); //10 for lots of messages
emcalQA->SetCalorimeter("EMCAL");
if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
else emcalQA->SwitchOffDataMC() ;
emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name
//emcalQA->SetFiducialCut(fidCut);
emcalQA->SwitchOffFiducialCut();
emcalQA->SwitchOffPlotsMaking();
emcalQA->SwitchOnCorrelation();
// if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment
//Set Histrograms bins and ranges
emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 181*TMath::DegToRad(), 200) ;
emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ;
emcalQA->SetNumberOfModules(10);
emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ;
emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 );
emcalQA->SetHistoPOverERangeAndNBins(0,10.,100);
emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200);
emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
emcalQA->SetHistoTimeRangeAndNBins(300.,900,300);
emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100);
emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
emcalQA->SetHistoXRangeAndNBins(-230,90,120);
emcalQA->SetHistoYRangeAndNBins(370,450,40);
emcalQA->SetHistoZRangeAndNBins(-400,400,200);
emcalQA->SetHistoRRangeAndNBins(400,450,25);
emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
//emcalQA->GetMCAnalysisUtils()->SetDebug(10);
if(kPrintSettings) emcalQA->Print("");
AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA();
//phosQA->SetDebug(2); //10 for lots of messages
phosQA->SetCalorimeter("PHOS");
if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
else phosQA->SwitchOffDataMC() ;
phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name
//phosQA->SetFiducialCut(fidCut);
phosQA->SwitchOffFiducialCut();
//phosQA->GetMCAnalysisUtils()->SetDebug(10);
phosQA->SwitchOffPlotsMaking();
//Set Histrograms bins and ranges
phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ;
phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ;
phosQA->SetNumberOfModules(3); //PHOS first year
phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ;
phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ;
phosQA->SetHistoPOverERangeAndNBins(0,10.,100);
phosQA->SetHistodEdxRangeAndNBins(0.,200.,200);
phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
phosQA->SetHistoTimeRangeAndNBins(0.,300,300);
phosQA->SetHistoRatioRangeAndNBins(0.,2.,100);
phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
phosQA->SetHistoXRangeAndNBins(-100,400,100);
phosQA->SetHistoYRangeAndNBins(-490,-290,100);
phosQA->SetHistoZRangeAndNBins(-80,80,100);
phosQA->SetHistoRRangeAndNBins(440,480,80);
phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
// #### Configure Maker ####
AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();
maker->SetReader(reader);//pointer to reader
maker->SetCaloUtils(cu); //pointer to calorimeter utils
maker->AddAnalysis(emcalQA,0);
maker->AddAnalysis(phosQA,1);
maker->SetAnaDebug(-1) ; // 0 to at least print the event number
maker->SwitchOnHistogramsMaker() ;
maker->SwitchOffAODsMaker() ;
if(kPrintSettings) maker->Print("");
printf("======================== \n");
printf(" End Configuration of Calorimeter QA \n");
printf("======================== \n");
// Create task
//===========================================================================
AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance");
task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
//task->SetDebugLevel(-1);
task->SelectCollisionCandidates();
task->SetAnalysisMaker(maker);
mgr->AddTask(task);
//Create containers
// AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(),
// AliAnalysisManager::kOutputContainer, "Calo.Performance.root");
if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("CaloQA", TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CaloQA",outputFile.Data()));
AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(),
AliAnalysisManager::kParamContainer,
Form("%s:CaloQACuts",outputFile.Data()));
//Form("%s:PartCorrCuts",outputfile.Data()));
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task, 1, cout_pc);
mgr->ConnectOutput (task, 2, cout_cuts);
return task;
}
<|endoftext|> |
<commit_before><commit_msg>add get_logger_debug to disable logging by default<commit_after><|endoftext|> |
<commit_before>#include <ContentForgeTool.h>
#include <ShaderCompiler.h>
#include <Utils.h>
#include <CLI11.hpp>
#include <iostream>
#include <thread>
#include <filesystem>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/shaders/hlsl_usm/CEGUI.hlsl.meta
// -s src/shaders/hlsl_usm/CEGUI.hlsl
// -s src/shaders
class CLog : public DEMShaderCompiler::ILogDelegate
{
private:
std::string Prefix;
public:
CLog(const std::string& TaskID)
{
Prefix = "[DLL " + TaskID + "] ";
}
virtual void Log(const char* pMessage) override
{
// FIXME: not thread safe, just for testing
std::cout << Prefix << pMessage << std::endl;
}
};
class CHLSLTool : public CContentForgeTool
{
public:
std::string _DBPath;
std::string _InputSignaturesDir;
CHLSLTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual void ProcessCommandLine(CLI::App& CLIApp) override
{
CContentForgeTool::ProcessCommandLine(CLIApp);
CLIApp.add_option("--db", _DBPath, "Shader DB file path");
CLIApp.add_option("--is,--inputsig", _InputSignaturesDir, "Folder where input signature binaries will be saved");
}
virtual int Init() override
{
if (_DBPath.empty())
_DBPath = (fs::path(_RootDir) / fs::path("src/shaders/shaders.db3")).string();
if (_InputSignaturesDir.empty())
_InputSignaturesDir = (fs::path(_RootDir) / fs::path("shaders/sig")).string();
if (!DEMShaderCompiler::Init(_DBPath.c_str())) return 1;
return 0;
}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
if (_LogVerbosity >= EVerbosity::Debug)
{
std::cout << "Source: " << Task.SrcFilePath.generic_string() << std::endl;
std::cout << "Task: " << Task.TaskID.CStr() << std::endl;
std::cout << "Thread: " << std::this_thread::get_id() << std::endl;
}
const std::string EntryPoint = GetParam<std::string>(Task.Params, "Entry", std::string{});
if (EntryPoint.empty()) return false;
const std::string Output = GetParam<std::string>(Task.Params, "Output", std::string{});
const int Target = GetParam<int>(Task.Params, "Target", 0);
const std::string Defines = GetParam<std::string>(Task.Params, "Defines", std::string{});
const bool Debug = GetParam<bool>(Task.Params, "Debug", false);
EShaderType ShaderType;
const CStrID Type = GetParam<CStrID>(Task.Params, "Type", CStrID::Empty);
if (Type == "Vertex") ShaderType = ShaderType_Vertex;
else if (Type == "Pixel") ShaderType = ShaderType_Pixel;
else if (Type == "Geometry") ShaderType = ShaderType_Geometry;
else if (Type == "Hull") ShaderType = ShaderType_Hull;
else if (Type == "Domain") ShaderType = ShaderType_Domain;
else return false;
const std::string TaskID(Task.TaskID.CStr());
const auto DestPath = fs::path(_RootDir) / fs::path(Output) / (TaskID + ".bin");
CLog Log(TaskID);
const auto Code = DEMShaderCompiler::CompileShader(
Task.SrcFilePath.string().c_str(), DestPath.string().c_str(), _InputSignaturesDir.c_str(),
ShaderType, Target, EntryPoint.c_str(), Defines.c_str(), Debug, Task.SrcFileData->data(), Task.SrcFileData->size(), &Log);
return Code == DEM_SHADER_COMPILER_SUCCESS;
}
};
int main(int argc, const char** argv)
{
CHLSLTool Tool("cf-hlsl", "HLSL to DeusExMachina resource converter", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
/*
"Command line args:\n"
"------------------\n"
"-db [filepath] path to persistent shader DB,\n"
" default: 'Shaders:ShaderDB.db3'\n"
"-d build shaders with debug info\n"
"-sm3 build only old sm3.0 techs, else only\n"
" Unified Shader Model techs will be built\n"
"-r rebuild shaders even if not changed\n"
int ExitApp(int Code, bool WaitKey);
int CompileEffect(const char* pInFilePath, const char* pOutFilePath, bool Debug, EShaderModel ShaderModel);
int CompileRenderPath(const char* pInFilePath, const char* pOutFilePath, EShaderModel ShaderModel);
int main(int argc, const char** argv)
{
std::string DB(Args.GetStringArg("-db"));
bool Debug = Args.GetBoolArg("-d");
bool Rebuild = Args.GetBoolArg("-r"); //!!!or if tool / DLL version changed (store in DB)!
EShaderModel ShaderModel = Args.GetBoolArg("-sm3") ? ShaderModel_30 : ShaderModel_USM;
if (DB.IsEmpty()) DB = "Shaders:ShaderDB.db3";
if (Rebuild) IOSrv->DeleteFile(DB); //???!!!pass the Rebuild flag inside instead!
#ifdef _DEBUG
std::string DLLPath = IOSrv->ResolveAssigns("Home:../DEMShaderCompiler/DEMShaderCompiler_d.dll");
#else
std::string DLLPath = IOSrv->ResolveAssigns("Home:../DEMShaderCompiler/DEMShaderCompiler.dll");
#endif
std::string OutputDir = PathUtils::GetAbsolutePath(IOSrv->ResolveAssigns("Home:"), IOSrv->ResolveAssigns("Shaders:Bin/"));
if (!InitDEMShaderCompilerDLL(DLLPath.CStr(), DB.CStr(), OutputDir.CStr())) return ExitApp(ERR_MAIN_FAILED, WaitKey);
for (size_t i = 0; i < InList.GetCount(); ++i)
{
const std::string& InRec = InList[i];
const std::string& OutRec = OutList[i];
n_msg(VL_INFO, "Compiling pair %d: '%s' -> '%s'\n", i, InRec.CStr(), OutRec.CStr());
bool Dir = IOSrv->DirectoryExists(InRec);
if (!Dir && IOSrv->DirectoryExists(OutRec)) return ExitApp(ERR_IN_OUT_TYPES_DONT_MATCH, WaitKey);
if (Dir)
{
n_msg(VL_ERROR, "Whole directory compilation is not supported yet\n");
return ExitApp(ERR_NOT_IMPLEMENTED_YET, WaitKey);
}
else
{
if (!IOSrv->FileExists(InRec)) return ExitApp(ERR_IN_NOT_FOUND, WaitKey);
int Code = RenderPathes ? CompileRenderPath(InRec, OutRec, ShaderModel) : CompileEffect(InRec, OutRec, Debug, ShaderModel);
if (Code != 0) return ExitApp(Code, WaitKey);
}
}
return ExitApp(SUCCESS, WaitKey);
}
//---------------------------------------------------------------------
int ExitApp(int Code, bool WaitKey)
{
if (!TermDEMShaderCompilerDLL())
{
n_msg(VL_ERROR, "DEM shader compiler was not unloaded cleanly\n");
Code = ERR_MAIN_FAILED;
}
if (Code != SUCCESS) n_msg(VL_ERROR, TOOL_NAME" v"VERSION": Error occurred with code %d\n", Code);
if (WaitKey)
{
Sys::Log("\nPress any key to exit...\n");
_getch();
}
return Code;
}
//---------------------------------------------------------------------
*/<commit_msg>Dead code removed<commit_after>#include <ContentForgeTool.h>
#include <ShaderCompiler.h>
#include <Utils.h>
#include <CLI11.hpp>
#include <thread>
#include <filesystem>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/shaders/hlsl_usm/CEGUI.hlsl.meta
// -s src/shaders/hlsl_usm/CEGUI.hlsl
// -s src/shaders
class CLog : public DEMShaderCompiler::ILogDelegate
{
private:
std::string Prefix;
public:
CLog(const std::string& TaskID)
{
Prefix = "[DLL " + TaskID + "] ";
}
virtual void Log(const char* pMessage) override
{
// FIXME: not thread safe, just for testing
std::cout << Prefix << pMessage << std::endl;
}
};
class CHLSLTool : public CContentForgeTool
{
public:
std::string _DBPath;
std::string _InputSignaturesDir;
CHLSLTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual void ProcessCommandLine(CLI::App& CLIApp) override
{
CContentForgeTool::ProcessCommandLine(CLIApp);
CLIApp.add_option("--db", _DBPath, "Shader DB file path");
CLIApp.add_option("--is,--inputsig", _InputSignaturesDir, "Folder where input signature binaries will be saved");
}
virtual int Init() override
{
if (_DBPath.empty())
_DBPath = (fs::path(_RootDir) / fs::path("src/shaders/shaders.db3")).string();
if (_InputSignaturesDir.empty())
_InputSignaturesDir = (fs::path(_RootDir) / fs::path("shaders/sig")).string();
if (!DEMShaderCompiler::Init(_DBPath.c_str())) return 1;
return 0;
}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
if (_LogVerbosity >= EVerbosity::Debug)
{
std::cout << "Source: " << Task.SrcFilePath.generic_string() << std::endl;
std::cout << "Task: " << Task.TaskID.CStr() << std::endl;
std::cout << "Thread: " << std::this_thread::get_id() << std::endl;
}
const std::string EntryPoint = GetParam<std::string>(Task.Params, "Entry", std::string{});
if (EntryPoint.empty()) return false;
const std::string Output = GetParam<std::string>(Task.Params, "Output", std::string{});
const int Target = GetParam<int>(Task.Params, "Target", 0);
const std::string Defines = GetParam<std::string>(Task.Params, "Defines", std::string{});
const bool Debug = GetParam<bool>(Task.Params, "Debug", false);
EShaderType ShaderType;
const CStrID Type = GetParam<CStrID>(Task.Params, "Type", CStrID::Empty);
if (Type == "Vertex") ShaderType = ShaderType_Vertex;
else if (Type == "Pixel") ShaderType = ShaderType_Pixel;
else if (Type == "Geometry") ShaderType = ShaderType_Geometry;
else if (Type == "Hull") ShaderType = ShaderType_Hull;
else if (Type == "Domain") ShaderType = ShaderType_Domain;
else return false;
const std::string TaskID(Task.TaskID.CStr());
const auto DestPath = fs::path(_RootDir) / fs::path(Output) / (TaskID + ".bin");
CLog Log(TaskID);
const auto Code = DEMShaderCompiler::CompileShader(
Task.SrcFilePath.string().c_str(), DestPath.string().c_str(), _InputSignaturesDir.c_str(),
ShaderType, Target, EntryPoint.c_str(), Defines.c_str(), Debug, Task.SrcFileData->data(), Task.SrcFileData->size(), &Log);
return Code == DEM_SHADER_COMPILER_SUCCESS;
}
};
int main(int argc, const char** argv)
{
CHLSLTool Tool("cf-hlsl", "HLSL to DeusExMachina resource converter", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
<|endoftext|> |
<commit_before><commit_msg>10161 - Ant on a Chessboard<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SchedulerFeature.h"
#ifdef _WIN32
#include <stdio.h>
#include <windows.h>
#endif
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/ArangoGlobalContext.h"
#include "Basics/WorkMonitor.h"
#include "Logger/LogAppender.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/ServerFeature.h"
#include "Scheduler/Scheduler.h"
#include "V8Server/V8DealerFeature.h"
#include "V8Server/v8-dispatcher.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
Scheduler* SchedulerFeature::SCHEDULER = nullptr;
SchedulerFeature::SchedulerFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Scheduler"), _scheduler(nullptr) {
setOptional(true);
requiresElevatedPrivileges(false);
//startsAfter("Database");
startsAfter("FileDescriptors");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
SchedulerFeature::~SchedulerFeature() {}
void SchedulerFeature::collectOptions(
std::shared_ptr<options::ProgramOptions> options) {
options->addSection("scheduler", "Configure the I/O scheduler");
options->addOption("--server.threads", "number of threads",
new UInt64Parameter(&_nrServerThreads));
options->addHiddenOption("--server.minimal-threads",
"minimal number of threads",
new UInt64Parameter(&_nrMinimalThreads));
options->addHiddenOption("--server.maximal-threads",
"maximal number of threads",
new UInt64Parameter(&_nrMaximalThreads));
options->addOption("--server.maximal-queue-size",
"maximum queue length for asynchronous operations",
new UInt64Parameter(&_queueSize));
options->addOldOption("scheduler.threads", "server.threads");
}
void SchedulerFeature::validateOptions(
std::shared_ptr<options::ProgramOptions>) {
if (_nrServerThreads == 0) {
_nrServerThreads = TRI_numberProcessors();
LOG_TOPIC(DEBUG, arangodb::Logger::FIXME) << "Detected number of processors: " << _nrServerThreads;
}
if (_queueSize < 128) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
<< "invalid value for `--server.maximal-queue-size', need at least 128";
FATAL_ERROR_EXIT();
}
if (_nrMinimalThreads < 2) {
_nrMinimalThreads = 2;
}
if (_nrServerThreads <= _nrMinimalThreads) {
_nrServerThreads = _nrMinimalThreads;
}
if (_nrMaximalThreads == 0) {
_nrMaximalThreads = 4 * _nrServerThreads;
}
if (_nrMaximalThreads < 64) {
_nrMaximalThreads = 64;
}
if (_nrMinimalThreads > _nrMaximalThreads) {
_nrMaximalThreads = _nrMinimalThreads;
}
TRI_ASSERT(0 < _nrMinimalThreads);
TRI_ASSERT(_nrMinimalThreads <= _nrServerThreads);
TRI_ASSERT(_nrServerThreads <= _nrMaximalThreads);
}
void SchedulerFeature::start() {
ArangoGlobalContext::CONTEXT->maskAllSignals();
buildScheduler();
bool ok = _scheduler->start(nullptr);
if (!ok) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "the scheduler cannot be started";
FATAL_ERROR_EXIT();
}
buildHangupHandler();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "scheduler has started";
V8DealerFeature* dealer =
ApplicationServer::getFeature<V8DealerFeature>("V8Dealer");
dealer->defineContextUpdate(
[](v8::Isolate* isolate, v8::Handle<v8::Context> context, size_t) {
TRI_InitV8Dispatcher(isolate, context);
},
nullptr);
}
void SchedulerFeature::beginShutdown() {
// shut-down scheduler
if (_scheduler != nullptr) {
_scheduler->stopRebalancer();
}
}
void SchedulerFeature::stop() {
static size_t const MAX_TRIES = 100;
// shutdown user jobs (needs the scheduler)
TRI_ShutdownV8Dispatcher();
// cancel signals
if (_exitSignals != nullptr) {
_exitSignals->cancel();
_exitSignals.reset();
}
#ifndef WIN32
if (_hangupSignals != nullptr) {
_hangupSignals->cancel();
_hangupSignals.reset();
}
#endif
// clear the handlers stuck in the WorkMonitor
WorkMonitor::clearHandlers();
// shut-down scheduler
_scheduler->beginShutdown();
for (size_t count = 0; count < MAX_TRIES && _scheduler->isRunning();
++count) {
LOG_TOPIC(TRACE, Logger::STARTUP) << "waiting for scheduler to stop";
usleep(100000);
}
}
void SchedulerFeature::unprepare() {
if (_scheduler != nullptr) {
_scheduler->shutdown();
}
SCHEDULER = nullptr;
}
#ifdef _WIN32
bool CtrlHandler(DWORD eventType) {
bool shutdown = false;
std::string shutdownMessage;
switch (eventType) {
case CTRL_BREAK_EVENT: {
shutdown = true;
shutdownMessage = "control-break received";
break;
}
case CTRL_C_EVENT: {
shutdown = true;
shutdownMessage = "control-c received";
break;
}
case CTRL_CLOSE_EVENT: {
shutdown = true;
shutdownMessage = "window-close received";
break;
}
case CTRL_LOGOFF_EVENT: {
shutdown = true;
shutdownMessage = "user-logoff received";
break;
}
case CTRL_SHUTDOWN_EVENT: {
shutdown = true;
shutdownMessage = "system-shutdown received";
break;
}
default: {
shutdown = false;
break;
}
}
if (shutdown == false) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "Invalid CTRL HANDLER event received - ignoring event";
return true;
}
static bool seen = false;
if (!seen) {
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "" << shutdownMessage << ", beginning shut down sequence";
if (application_features::ApplicationServer::server != nullptr) {
application_features::ApplicationServer::server->beginShutdown();
}
seen = true;
return true;
}
// ........................................................................
// user is desperate to kill the server!
// ........................................................................
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "" << shutdownMessage << ", terminating";
_exit(EXIT_FAILURE); // quick exit for windows
return true;
}
#endif
void SchedulerFeature::buildScheduler() {
_scheduler =
std::make_unique<Scheduler>(static_cast<uint64_t>(_nrMinimalThreads),
static_cast<uint64_t>(_nrServerThreads),
static_cast<uint64_t>(_nrMaximalThreads),
static_cast<uint64_t>(_queueSize));
SCHEDULER = _scheduler.get();
}
void SchedulerFeature::buildControlCHandler() {
#ifdef WIN32
{
int result = SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, true);
if (result == 0) {
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "unable to install control-c handler";
}
}
#else
auto ioService = _scheduler->managerService();
_exitSignals = std::make_shared<boost::asio::signal_set>(*ioService, SIGINT,
SIGTERM, SIGQUIT);
_signalHandler = [this](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "control-c received, beginning shut down sequence";
server()->beginShutdown();
_exitSignals->async_wait(_exitHandler);
};
_exitHandler = [](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "control-c received (again!), terminating";
FATAL_ERROR_EXIT();
};
_exitSignals->async_wait(_signalHandler);
#endif
}
void SchedulerFeature::buildHangupHandler() {
#ifndef WIN32
auto ioService = _scheduler->managerService();
_hangupSignals =
std::make_shared<boost::asio::signal_set>(*ioService, SIGHUP);
_hangupHandler = [this](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "hangup received, about to reopen logfile";
LogAppender::reopen();
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "hangup received, reopened logfile";
_hangupSignals->async_wait(_hangupHandler);
};
_hangupSignals->async_wait(_hangupHandler);
#endif
}
<commit_msg>fix a shutdown error<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SchedulerFeature.h"
#ifdef _WIN32
#include <stdio.h>
#include <windows.h>
#endif
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/ArangoGlobalContext.h"
#include "Basics/WorkMonitor.h"
#include "Logger/LogAppender.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/ServerFeature.h"
#include "Scheduler/Scheduler.h"
#include "V8Server/V8DealerFeature.h"
#include "V8Server/v8-dispatcher.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
Scheduler* SchedulerFeature::SCHEDULER = nullptr;
SchedulerFeature::SchedulerFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Scheduler"), _scheduler(nullptr) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Database");
startsAfter("FileDescriptors");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
SchedulerFeature::~SchedulerFeature() {}
void SchedulerFeature::collectOptions(
std::shared_ptr<options::ProgramOptions> options) {
options->addSection("scheduler", "Configure the I/O scheduler");
options->addOption("--server.threads", "number of threads",
new UInt64Parameter(&_nrServerThreads));
options->addHiddenOption("--server.minimal-threads",
"minimal number of threads",
new UInt64Parameter(&_nrMinimalThreads));
options->addHiddenOption("--server.maximal-threads",
"maximal number of threads",
new UInt64Parameter(&_nrMaximalThreads));
options->addOption("--server.maximal-queue-size",
"maximum queue length for asynchronous operations",
new UInt64Parameter(&_queueSize));
options->addOldOption("scheduler.threads", "server.threads");
}
void SchedulerFeature::validateOptions(
std::shared_ptr<options::ProgramOptions>) {
if (_nrServerThreads == 0) {
_nrServerThreads = TRI_numberProcessors();
LOG_TOPIC(DEBUG, arangodb::Logger::FIXME) << "Detected number of processors: " << _nrServerThreads;
}
if (_queueSize < 128) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
<< "invalid value for `--server.maximal-queue-size', need at least 128";
FATAL_ERROR_EXIT();
}
if (_nrMinimalThreads < 2) {
_nrMinimalThreads = 2;
}
if (_nrServerThreads <= _nrMinimalThreads) {
_nrServerThreads = _nrMinimalThreads;
}
if (_nrMaximalThreads == 0) {
_nrMaximalThreads = 4 * _nrServerThreads;
}
if (_nrMaximalThreads < 64) {
_nrMaximalThreads = 64;
}
if (_nrMinimalThreads > _nrMaximalThreads) {
_nrMaximalThreads = _nrMinimalThreads;
}
TRI_ASSERT(0 < _nrMinimalThreads);
TRI_ASSERT(_nrMinimalThreads <= _nrServerThreads);
TRI_ASSERT(_nrServerThreads <= _nrMaximalThreads);
}
void SchedulerFeature::start() {
ArangoGlobalContext::CONTEXT->maskAllSignals();
buildScheduler();
bool ok = _scheduler->start(nullptr);
if (!ok) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "the scheduler cannot be started";
FATAL_ERROR_EXIT();
}
buildHangupHandler();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "scheduler has started";
V8DealerFeature* dealer =
ApplicationServer::getFeature<V8DealerFeature>("V8Dealer");
dealer->defineContextUpdate(
[](v8::Isolate* isolate, v8::Handle<v8::Context> context, size_t) {
TRI_InitV8Dispatcher(isolate, context);
},
nullptr);
}
void SchedulerFeature::beginShutdown() {
// shut-down scheduler
if (_scheduler != nullptr) {
_scheduler->stopRebalancer();
}
}
void SchedulerFeature::stop() {
static size_t const MAX_TRIES = 100;
// shutdown user jobs (needs the scheduler)
TRI_ShutdownV8Dispatcher();
// cancel signals
if (_exitSignals != nullptr) {
_exitSignals->cancel();
_exitSignals.reset();
}
#ifndef WIN32
if (_hangupSignals != nullptr) {
_hangupSignals->cancel();
_hangupSignals.reset();
}
#endif
// clear the handlers stuck in the WorkMonitor
WorkMonitor::clearHandlers();
// shut-down scheduler
_scheduler->beginShutdown();
for (size_t count = 0; count < MAX_TRIES && _scheduler->isRunning();
++count) {
LOG_TOPIC(TRACE, Logger::STARTUP) << "waiting for scheduler to stop";
usleep(100000);
}
}
void SchedulerFeature::unprepare() {
if (_scheduler != nullptr) {
_scheduler->shutdown();
}
SCHEDULER = nullptr;
}
#ifdef _WIN32
bool CtrlHandler(DWORD eventType) {
bool shutdown = false;
std::string shutdownMessage;
switch (eventType) {
case CTRL_BREAK_EVENT: {
shutdown = true;
shutdownMessage = "control-break received";
break;
}
case CTRL_C_EVENT: {
shutdown = true;
shutdownMessage = "control-c received";
break;
}
case CTRL_CLOSE_EVENT: {
shutdown = true;
shutdownMessage = "window-close received";
break;
}
case CTRL_LOGOFF_EVENT: {
shutdown = true;
shutdownMessage = "user-logoff received";
break;
}
case CTRL_SHUTDOWN_EVENT: {
shutdown = true;
shutdownMessage = "system-shutdown received";
break;
}
default: {
shutdown = false;
break;
}
}
if (shutdown == false) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "Invalid CTRL HANDLER event received - ignoring event";
return true;
}
static bool seen = false;
if (!seen) {
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "" << shutdownMessage << ", beginning shut down sequence";
if (application_features::ApplicationServer::server != nullptr) {
application_features::ApplicationServer::server->beginShutdown();
}
seen = true;
return true;
}
// ........................................................................
// user is desperate to kill the server!
// ........................................................................
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "" << shutdownMessage << ", terminating";
_exit(EXIT_FAILURE); // quick exit for windows
return true;
}
#endif
void SchedulerFeature::buildScheduler() {
_scheduler =
std::make_unique<Scheduler>(static_cast<uint64_t>(_nrMinimalThreads),
static_cast<uint64_t>(_nrServerThreads),
static_cast<uint64_t>(_nrMaximalThreads),
static_cast<uint64_t>(_queueSize));
SCHEDULER = _scheduler.get();
}
void SchedulerFeature::buildControlCHandler() {
#ifdef WIN32
{
int result = SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, true);
if (result == 0) {
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "unable to install control-c handler";
}
}
#else
auto ioService = _scheduler->managerService();
_exitSignals = std::make_shared<boost::asio::signal_set>(*ioService, SIGINT,
SIGTERM, SIGQUIT);
_signalHandler = [this](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "control-c received, beginning shut down sequence";
server()->beginShutdown();
_exitSignals->async_wait(_exitHandler);
};
_exitHandler = [](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "control-c received (again!), terminating";
FATAL_ERROR_EXIT();
};
_exitSignals->async_wait(_signalHandler);
#endif
}
void SchedulerFeature::buildHangupHandler() {
#ifndef WIN32
auto ioService = _scheduler->managerService();
_hangupSignals =
std::make_shared<boost::asio::signal_set>(*ioService, SIGHUP);
_hangupHandler = [this](const boost::system::error_code& error, int number) {
if (error) {
return;
}
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "hangup received, about to reopen logfile";
LogAppender::reopen();
LOG_TOPIC(INFO, arangodb::Logger::FIXME) << "hangup received, reopened logfile";
_hangupSignals->async_wait(_hangupHandler);
};
_hangupSignals->async_wait(_hangupHandler);
#endif
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2016 CNRS
// Author: NMansard
//
//
// This file is part of hpp-pinocchio
// hpp-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.
//
// hpp-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
// hpp-pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE tdevice
#include <boost/test/unit_test.hpp>
#include <hpp/model/device.hh>
#include <hpp/model/urdf/util.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
#include "../tests/utils.hh"
static bool verbose = false;
// virtual ~Device() ;
//NOTCHECKED DevicePtr_t clone()
//NOTCHECKED DevicePtr_t cloneConst() const
//NOTCHECKED const std::string& name () const
// static DevicePtr_t create (const std::string & name);
//NOTCHECKED static DevicePtr_t createCopy (const DevicePtr_t& device);
//NOTCHECKED static DevicePtr_t createCopyConst (const DeviceConstPtr_t& device);
// void model( ModelPtr_t modelPtr )
// ModelConstPtr_t model() const
// ModelPtr_t model()
// void data( DataPtr_t dataPtr )
// DataConstPtr_t data() const
// DataPtr_t data()
// void createData();
// const JointVector_t& getJointVector () const;
// JointPtr_t rootJoint () const;
// JointPtr_t getJointAtConfigRank (const size_type& r) const;
// JointPtr_t getJointAtVelocityRank (const size_type& r) const;
// JointPtr_t getJointByName (const std::string& name) const;
//NOTCHECKED JointPtr_t getJointByBodyName (const std::string& name) const;
// size_type configSize () const;
// size_type numberDof () const;
//NOTCHECKED ExtraConfigSpace& extraConfigSpace ()
//NOTCHECKED const ExtraConfigSpace& extraConfigSpace () const
//NOTCHECKED virtual void setDimensionExtraConfigSpace (const size_type& dimension)
// const Configuration_t& currentConfiguration () const
// virtual bool currentConfiguration (ConfigurationIn_t configuration);
//NOTCHECKED Configuration_t neutralConfiguration () const;
// const vector_t& currentVelocity () const
// void currentVelocity (vectorIn_t velocity)
// const vector_t& currentAcceleration () const
// void currentAcceleration (vectorIn_t acceleration)
// const value_type& mass () const;
// vector3_t positionCenterOfMass () const;
// const ComJacobian_t& jacobianCenterOfMass () const;
//NOTCHECKED void addGripper (const GripperPtr_t& gripper)
//NOTCHECKED Grippers_t& grippers ()
//NOTCHECKED const Grippers_t& grippers () const
//NOTCHECKED const ObjectVector_t& obstacles (Request_t type) const;
//NOTCHECKED virtual void addCollisionPairs ;
//NOTCHECKED virtual void removeCollisionPairs;
//NOTCHECKED const CollisionPairs_t& collisionPairs (Request_t type) const;
//NOTCHECKED ObjectIterator objectIterator (Request_t type);
//NOTCHECKED bool collisionTest () const;
//NOTCHECKED void computeDistances ();
//NOTCHECKED const DistanceResults_t& distanceResults () const ;
//NOTCHECKED void controlComputation (const Computation_t& flag)
//NOTCHECKED Computation_t computationFlag () const
//NOTCHECKED virtual void computeForwardKinematics ();
//NOTCHECKED virtual std::ostream& print (std::ostream& os) const;
// protected:
// Device(const std::string& name);
//NOTCHECKED void updateDistances ();
//NOTCHECKED Device(const Device& device);
// void resizeState ();
//NOTCHECKED void resizeJacobians ();
// protected:
//NOTCHECKED ModelPtr_t model_;
//NOTCHECKED DataPtr_t data_;
//NOTCHECKED std::string name_;
//NOTCHECKED DistanceResults_t distances_;
//NOTCHECKED Configuration_t currentConfiguration_;
//NOTCHECKED vector_t currentVelocity_;
//NOTCHECKED vector_t currentAcceleration_;
//NOTCHECKED bool upToDate_;
//NOTCHECKED Computation_t computationFlag_;
//NOTCHECKED CollisionPairs_t collisionPairs_;
//NOTCHECKED CollisionPairs_t distancePairs_;
//NOTCHECKED Grippers_t grippers_;
//NOTCHECKED ExtraConfigSpace extraConfigSpace_;
//NOTCHECKED DeviceWkPtr_t weakPtr_;
/* --- UNIT TESTS ----------------------------------------------------------- */
/* --- UNIT TESTS ----------------------------------------------------------- */
/* --- UNIT TESTS ----------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (create)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
std::ofstream log ("./tdevice.log");
log << *(model.get ()) << std::endl;
}
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (easyGetter)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
model->setDimensionExtraConfigSpace(2);
pinocchio->setDimensionExtraConfigSpace(2);
/* --- Check NQ NV */
if(verbose)
{
std::cout << "nq = " << model->configSize() << " vs " << pinocchio->configSize() << std::endl;
std::cout << "nq = " << model->numberDof() << " vs " << pinocchio->numberDof() << std::endl;
}
BOOST_CHECK ( model->configSize()==pinocchio->configSize() );
BOOST_CHECK ( model->numberDof() ==pinocchio->numberDof() );
/* --- Check configuration */
{
BOOST_CHECK ( model ->currentConfiguration().size()==model ->configSize() );
BOOST_CHECK ( pinocchio->currentConfiguration().size()==pinocchio->configSize() );
Eigen::VectorXd q = Eigen::VectorXd::Random( model->configSize() );
const Eigen::VectorXd qcopy = q;
model->currentConfiguration(q);
BOOST_CHECK( model->currentConfiguration() == qcopy );
q = qcopy;
pinocchio->currentConfiguration(q);
BOOST_CHECK( pinocchio->currentConfiguration() == qcopy );
}
/* --- Check vel acc */
{
BOOST_CHECK ( model ->currentVelocity().size()==model ->numberDof() );
BOOST_CHECK ( pinocchio->currentVelocity().size()==pinocchio->numberDof() );
BOOST_CHECK ( model ->currentAcceleration().size()==model ->numberDof() );
BOOST_CHECK ( pinocchio->currentAcceleration().size()==pinocchio->numberDof() );
Eigen::VectorXd q = Eigen::VectorXd::Random( model->numberDof() );
const Eigen::VectorXd qcopy = q;
model->currentVelocity(q);
BOOST_CHECK( model->currentVelocity() == qcopy );
q = qcopy;
pinocchio->currentVelocity(q);
BOOST_CHECK( pinocchio->currentVelocity() == qcopy );
q = qcopy;
model->currentAcceleration(q);
BOOST_CHECK( model->currentAcceleration() == qcopy );
q = qcopy;
pinocchio->currentAcceleration(q);
BOOST_CHECK( pinocchio->currentAcceleration() == qcopy );
}
}
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (compute)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
Eigen::VectorXd q = Eigen::VectorXd::Random( model->configSize() );
q[3] += 1.0;
q.segment<4>(3) /= q.segment<4>(3).norm();
model->currentConfiguration(q);
model->controlComputation (hpp::model::Device::ALL);
model->computeForwardKinematics();
pinocchio->currentConfiguration(m2p::q(q));
pinocchio->controlComputation (hpp::pinocchio::Device::ALL);
pinocchio->computeForwardKinematics();
if( verbose )
{
std::cout << "com_model = " << model ->positionCenterOfMass() << std::endl;
std::cout << "com_pinocchio = " << pinocchio->positionCenterOfMass() << std::endl;
std::cout << model ->jacobianCenterOfMass().leftCols<9>() << std::endl;
std::cout << pinocchio->jacobianCenterOfMass().leftCols<9>() << std::endl;
}
BOOST_CHECK( model->mass() == pinocchio->mass() );
BOOST_CHECK( model->positionCenterOfMass().isApprox
(pinocchio->positionCenterOfMass()) );
Eigen::MatrixXd Jmodel = model ->jacobianCenterOfMass();
Eigen::MatrixXd Jpinocchio = pinocchio->jacobianCenterOfMass();
Eigen::MatrixXd oRb = Jpinocchio.leftCols<3>();
BOOST_CHECK( (Jmodel *p2m::Xq(oRb)).isApprox(Jpinocchio) );
BOOST_CHECK( (Jpinocchio*m2p::Xq(oRb)).isApprox(Jmodel) );
}
void checkJointBound(const hpp::model::JointPtr_t& jm, const hpp::pinocchio::JointPtr_t& jp)
{
BOOST_CHECK(jp->configSize() == jm->configSize());
for (int rk = 0; rk < jm->configSize(); ++rk) {
BOOST_CHECK(jp->isBounded(rk) == jm->isBounded(rk));
if (jm->isBounded(rk)) {
BOOST_CHECK(jp->lowerBound(rk) == jm->lowerBound(rk));
BOOST_CHECK(jp->upperBound(rk) == jm->upperBound(rk));
}
}
}
BOOST_AUTO_TEST_CASE(jointAccess)
{
static bool verbose = true;
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
BOOST_CHECK (pinocchio->rootJoint()->rankInConfiguration() == 0);
if(verbose)
std::cout << pinocchio->getJointAtConfigRank(0)->name() << " -- "
<< pinocchio->rootJoint()->name() <<std::endl;
BOOST_CHECK (pinocchio->getJointAtConfigRank(0)->name() == pinocchio->rootJoint()->name());
BOOST_CHECK (pinocchio->getJointAtVelocityRank(0)->name() == pinocchio->rootJoint()->name());
for (int i=1;i<pinocchio->model()->njoint;++i)
{
BOOST_CHECK( pinocchio->getJointAtConfigRank(pinocchio->model()->joints[i].idx_q())->name()
== pinocchio->model()->names[i] );
BOOST_CHECK( pinocchio->getJointAtVelocityRank(pinocchio->model()->joints[i].idx_v())->name()
== pinocchio->model()->names[i] );
}
hpp::model::JointPtr_t jm = model->getJointVector()[5];
BOOST_CHECK( pinocchio->getJointByName (jm->name())->name() == jm->name() );
// Compare the joint vector
if (verbose)
std::cout << "\n\nComparing joint vectors\n\n";
hpp::model::size_type idM = 0;
hpp::model ::JointVector_t jvm = model ->getJointVector();
hpp::pinocchio::JointVector_t jvp = pinocchio->getJointVector();
for (int idP=0;idP<jvp.size();++idP)
{
// Skip anchor joints for hpp-model
while(idM < jvm.size() &&
dynamic_cast<hpp::model::JointAnchor*>(jvm[idM]) != NULL) {
idM++;
}
if(verbose)
std::cout
<< jvp[idP]->name() << " -- "
<< jvm[idM]->name() << std::endl;
se3::JointIndex jidP = jvp[idP]->index();
BOOST_CHECK(jidP == idP + 1);
if (verbose)
std::cout << pinocchio->model()->joints[jidP].shortname() << std::endl;
if (pinocchio->model()->joints[jidP].shortname() == "JointModelFreeFlyer") {
// The root joint have different names in model and pinocchio
if (idP == 0) { idM += 2; continue; }
// Joint is a freeflyer
std::string nameP = jvp[idP]->name();
BOOST_CHECK( jvm[idM]->name().compare(0, nameP.length(), nameP) == 0);
idM++;
BOOST_CHECK( jvm[idM]->name().compare(0, nameP.length(), nameP) == 0);
idM++;
} else {
// Joint is a neither an anchor nor a freeflyer
BOOST_CHECK(jvp[idP]->name() == jvm[idM]->name());
// Check joint bound
checkJointBound (jvm[idM], jvp[idP]);
idM++;
}
}
// Check that all the remainings joint of hpp-model are anchor joints.
while(idM != jvm.size()) {
BOOST_CHECK(dynamic_cast<hpp::model::JointAnchor*>(jvm[idM]) != NULL);
idM++;
}
}
<commit_msg>Add uncomplete check of Joint::currentTransformation<commit_after>//
// Copyright (c) 2016 CNRS
// Author: NMansard
//
//
// This file is part of hpp-pinocchio
// hpp-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.
//
// hpp-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
// hpp-pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE tdevice
#include <boost/test/unit_test.hpp>
#include <hpp/model/device.hh>
#include <hpp/model/urdf/util.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
#include "../tests/utils.hh"
static bool verbose = false;
// virtual ~Device() ;
//NOTCHECKED DevicePtr_t clone()
//NOTCHECKED DevicePtr_t cloneConst() const
//NOTCHECKED const std::string& name () const
// static DevicePtr_t create (const std::string & name);
//NOTCHECKED static DevicePtr_t createCopy (const DevicePtr_t& device);
//NOTCHECKED static DevicePtr_t createCopyConst (const DeviceConstPtr_t& device);
// void model( ModelPtr_t modelPtr )
// ModelConstPtr_t model() const
// ModelPtr_t model()
// void data( DataPtr_t dataPtr )
// DataConstPtr_t data() const
// DataPtr_t data()
// void createData();
// const JointVector_t& getJointVector () const;
// JointPtr_t rootJoint () const;
// JointPtr_t getJointAtConfigRank (const size_type& r) const;
// JointPtr_t getJointAtVelocityRank (const size_type& r) const;
// JointPtr_t getJointByName (const std::string& name) const;
//NOTCHECKED JointPtr_t getJointByBodyName (const std::string& name) const;
// size_type configSize () const;
// size_type numberDof () const;
//NOTCHECKED ExtraConfigSpace& extraConfigSpace ()
//NOTCHECKED const ExtraConfigSpace& extraConfigSpace () const
//NOTCHECKED virtual void setDimensionExtraConfigSpace (const size_type& dimension)
// const Configuration_t& currentConfiguration () const
// virtual bool currentConfiguration (ConfigurationIn_t configuration);
//NOTCHECKED Configuration_t neutralConfiguration () const;
// const vector_t& currentVelocity () const
// void currentVelocity (vectorIn_t velocity)
// const vector_t& currentAcceleration () const
// void currentAcceleration (vectorIn_t acceleration)
// const value_type& mass () const;
// vector3_t positionCenterOfMass () const;
// const ComJacobian_t& jacobianCenterOfMass () const;
//NOTCHECKED void addGripper (const GripperPtr_t& gripper)
//NOTCHECKED Grippers_t& grippers ()
//NOTCHECKED const Grippers_t& grippers () const
//NOTCHECKED const ObjectVector_t& obstacles (Request_t type) const;
//NOTCHECKED virtual void addCollisionPairs ;
//NOTCHECKED virtual void removeCollisionPairs;
//NOTCHECKED const CollisionPairs_t& collisionPairs (Request_t type) const;
//NOTCHECKED ObjectIterator objectIterator (Request_t type);
//NOTCHECKED bool collisionTest () const;
//NOTCHECKED void computeDistances ();
//NOTCHECKED const DistanceResults_t& distanceResults () const ;
//NOTCHECKED void controlComputation (const Computation_t& flag)
//NOTCHECKED Computation_t computationFlag () const
//NOTCHECKED virtual void computeForwardKinematics ();
//NOTCHECKED virtual std::ostream& print (std::ostream& os) const;
// protected:
// Device(const std::string& name);
//NOTCHECKED void updateDistances ();
//NOTCHECKED Device(const Device& device);
// void resizeState ();
//NOTCHECKED void resizeJacobians ();
// protected:
//NOTCHECKED ModelPtr_t model_;
//NOTCHECKED DataPtr_t data_;
//NOTCHECKED std::string name_;
//NOTCHECKED DistanceResults_t distances_;
//NOTCHECKED Configuration_t currentConfiguration_;
//NOTCHECKED vector_t currentVelocity_;
//NOTCHECKED vector_t currentAcceleration_;
//NOTCHECKED bool upToDate_;
//NOTCHECKED Computation_t computationFlag_;
//NOTCHECKED CollisionPairs_t collisionPairs_;
//NOTCHECKED CollisionPairs_t distancePairs_;
//NOTCHECKED Grippers_t grippers_;
//NOTCHECKED ExtraConfigSpace extraConfigSpace_;
//NOTCHECKED DeviceWkPtr_t weakPtr_;
/* --- UNIT TESTS ----------------------------------------------------------- */
/* --- UNIT TESTS ----------------------------------------------------------- */
/* --- UNIT TESTS ----------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (create)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
std::ofstream log ("./tdevice.log");
log << *(model.get ()) << std::endl;
}
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (easyGetter)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
model->setDimensionExtraConfigSpace(2);
pinocchio->setDimensionExtraConfigSpace(2);
/* --- Check NQ NV */
if(verbose)
{
std::cout << "nq = " << model->configSize() << " vs " << pinocchio->configSize() << std::endl;
std::cout << "nq = " << model->numberDof() << " vs " << pinocchio->numberDof() << std::endl;
}
BOOST_CHECK ( model->configSize()==pinocchio->configSize() );
BOOST_CHECK ( model->numberDof() ==pinocchio->numberDof() );
/* --- Check configuration */
{
BOOST_CHECK ( model ->currentConfiguration().size()==model ->configSize() );
BOOST_CHECK ( pinocchio->currentConfiguration().size()==pinocchio->configSize() );
Eigen::VectorXd q = Eigen::VectorXd::Random( model->configSize() );
const Eigen::VectorXd qcopy = q;
model->currentConfiguration(q);
BOOST_CHECK( model->currentConfiguration() == qcopy );
q = qcopy;
pinocchio->currentConfiguration(q);
BOOST_CHECK( pinocchio->currentConfiguration() == qcopy );
}
/* --- Check vel acc */
{
BOOST_CHECK ( model ->currentVelocity().size()==model ->numberDof() );
BOOST_CHECK ( pinocchio->currentVelocity().size()==pinocchio->numberDof() );
BOOST_CHECK ( model ->currentAcceleration().size()==model ->numberDof() );
BOOST_CHECK ( pinocchio->currentAcceleration().size()==pinocchio->numberDof() );
Eigen::VectorXd q = Eigen::VectorXd::Random( model->numberDof() );
const Eigen::VectorXd qcopy = q;
model->currentVelocity(q);
BOOST_CHECK( model->currentVelocity() == qcopy );
q = qcopy;
pinocchio->currentVelocity(q);
BOOST_CHECK( pinocchio->currentVelocity() == qcopy );
q = qcopy;
model->currentAcceleration(q);
BOOST_CHECK( model->currentAcceleration() == qcopy );
q = qcopy;
pinocchio->currentAcceleration(q);
BOOST_CHECK( pinocchio->currentAcceleration() == qcopy );
}
}
/* -------------------------------------------------------------------------- */
BOOST_AUTO_TEST_CASE (compute)
{
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
Eigen::VectorXd q = Eigen::VectorXd::Random( model->configSize() );
q[3] += 1.0;
q.segment<4>(3) /= q.segment<4>(3).norm();
model->currentConfiguration(q);
model->controlComputation (hpp::model::Device::ALL);
model->computeForwardKinematics();
pinocchio->currentConfiguration(m2p::q(q));
pinocchio->controlComputation (hpp::pinocchio::Device::ALL);
pinocchio->computeForwardKinematics();
// Skip root joint because the name is not the same.
for (int i=2;i<pinocchio->model()->njoint;++i)
{
const std::string& name = pinocchio->model()->names[i];
hpp::model ::JointPtr_t jm = model ->getJointByName (name);
hpp::pinocchio::JointPtr_t jp = pinocchio->getJointByName (name);
hpp::model ::Transform3f tfm = jm->currentTransformation();
hpp::pinocchio::Transform3f tfp = jp->currentTransformation();
// The center of the joint frames should be the same.
BOOST_CHECK( tfm.getTranslation().isApprox(tfp.translation()) );
// The rotations may be permuted because HPP only has a rotation around X.
// To be checked using urdf link position (see hpp-constraints/pmdiff/tvalue.cc
}
if( verbose )
{
std::cout << "com_model = " << model ->positionCenterOfMass() << std::endl;
std::cout << "com_pinocchio = " << pinocchio->positionCenterOfMass() << std::endl;
std::cout << model ->jacobianCenterOfMass().leftCols<9>() << std::endl;
std::cout << pinocchio->jacobianCenterOfMass().leftCols<9>() << std::endl;
}
BOOST_CHECK( model->mass() == pinocchio->mass() );
BOOST_CHECK( model->positionCenterOfMass().isApprox
(pinocchio->positionCenterOfMass()) );
Eigen::MatrixXd Jmodel = model ->jacobianCenterOfMass();
Eigen::MatrixXd Jpinocchio = pinocchio->jacobianCenterOfMass();
Eigen::MatrixXd oRb = Jpinocchio.leftCols<3>();
BOOST_CHECK( (Jmodel *p2m::Xq(oRb)).isApprox(Jpinocchio) );
BOOST_CHECK( (Jpinocchio*m2p::Xq(oRb)).isApprox(Jmodel) );
}
void checkJointBound(const hpp::model::JointPtr_t& jm, const hpp::pinocchio::JointPtr_t& jp)
{
BOOST_CHECK(jp->configSize() == jm->configSize());
for (int rk = 0; rk < jm->configSize(); ++rk) {
BOOST_CHECK(jp->isBounded(rk) == jm->isBounded(rk));
if (jm->isBounded(rk)) {
BOOST_CHECK(jp->lowerBound(rk) == jm->lowerBound(rk));
BOOST_CHECK(jp->upperBound(rk) == jm->upperBound(rk));
}
}
}
BOOST_AUTO_TEST_CASE(jointAccess)
{
static bool verbose = true;
hpp::model::DevicePtr_t model = hppModel();
hpp::pinocchio::DevicePtr_t pinocchio = hppPinocchio();
BOOST_CHECK (pinocchio->rootJoint()->rankInConfiguration() == 0);
if(verbose)
std::cout << pinocchio->getJointAtConfigRank(0)->name() << " -- "
<< pinocchio->rootJoint()->name() <<std::endl;
BOOST_CHECK (pinocchio->getJointAtConfigRank(0)->name() == pinocchio->rootJoint()->name());
BOOST_CHECK (pinocchio->getJointAtVelocityRank(0)->name() == pinocchio->rootJoint()->name());
for (int i=1;i<pinocchio->model()->njoint;++i)
{
BOOST_CHECK( pinocchio->getJointAtConfigRank(pinocchio->model()->joints[i].idx_q())->name()
== pinocchio->model()->names[i] );
BOOST_CHECK( pinocchio->getJointAtVelocityRank(pinocchio->model()->joints[i].idx_v())->name()
== pinocchio->model()->names[i] );
}
hpp::model::JointPtr_t jm = model->getJointVector()[5];
BOOST_CHECK( pinocchio->getJointByName (jm->name())->name() == jm->name() );
// Compare the joint vector
if (verbose)
std::cout << "\n\nComparing joint vectors\n\n";
hpp::model::size_type idM = 0;
hpp::model ::JointVector_t jvm = model ->getJointVector();
hpp::pinocchio::JointVector_t jvp = pinocchio->getJointVector();
for (int idP=0;idP<jvp.size();++idP)
{
// Skip anchor joints for hpp-model
while(idM < jvm.size() &&
dynamic_cast<hpp::model::JointAnchor*>(jvm[idM]) != NULL) {
idM++;
}
if(verbose)
std::cout
<< jvp[idP]->name() << " -- "
<< jvm[idM]->name() << std::endl;
se3::JointIndex jidP = jvp[idP]->index();
BOOST_CHECK(jidP == idP + 1);
if (verbose)
std::cout << pinocchio->model()->joints[jidP].shortname() << std::endl;
if (pinocchio->model()->joints[jidP].shortname() == "JointModelFreeFlyer") {
// The root joint have different names in model and pinocchio
if (idP == 0) { idM += 2; continue; }
// Joint is a freeflyer
std::string nameP = jvp[idP]->name();
BOOST_CHECK( jvm[idM]->name().compare(0, nameP.length(), nameP) == 0);
idM++;
BOOST_CHECK( jvm[idM]->name().compare(0, nameP.length(), nameP) == 0);
idM++;
} else {
// Joint is a neither an anchor nor a freeflyer
BOOST_CHECK(jvp[idP]->name() == jvm[idM]->name());
// Check joint bound
checkJointBound (jvm[idM], jvp[idP]);
idM++;
}
}
// Check that all the remainings joint of hpp-model are anchor joints.
while(idM != jvm.size()) {
BOOST_CHECK(dynamic_cast<hpp::model::JointAnchor*>(jvm[idM]) != NULL);
idM++;
}
}
<|endoftext|> |
<commit_before><commit_msg>do not add deprecated limits<commit_after><|endoftext|> |
<commit_before>// template impl (included from header)
// #include "hheap.h"
template<typename V>
Node<V>::Node(int32_t _id, V _value) :
id(_id), value(_value), rank(0), is_hollow(false), is_root(true), next_sibling(
nullptr), head_childs(nullptr) {
}
template<typename V, typename C>
inline std::vector<Node<V>*>& HollowHeap<V, C>::RootsAtRank(uint32_t rank) {
if (roots_of_rank_.size() <= rank) {
uint32_t old_size = roots_of_rank_.size();
roots_of_rank_.resize(rank + 1, nullptr);
for (uint32_t i = old_size; i <= rank; ++i) {
roots_of_rank_[i] = new std::vector<Node<V>*>();
}
}
return *roots_of_rank_[rank];
}
template<typename V, typename C>
HollowHeap<V, C>::HollowHeap() :
size_(0), comparator_(), min_node_(nullptr), roots_of_rank_(), node_map_(), n_ids_(
0), node_map_arr_(nullptr) {
}
template<typename V, typename C>
HollowHeap<V, C>::HollowHeap(uint32_t n_ids) :
size_(0), comparator_(), min_node_(nullptr), roots_of_rank_(), node_map_(), n_ids_(
n_ids), node_map_arr_(new Node<V>*[n_ids_]) {
Node<V> **arr = node_map_arr_.get();
std::fill(arr, arr + n_ids_, nullptr);
}
// return false if id is already inserted
template<typename V, typename C>
bool HollowHeap<V, C>::Push(uint32_t id, V value) {
if (n_ids_) {
if (node_map_arr_[id] != nullptr) {
return false;
}
} else {
if (node_map_.find(id) != node_map_.end()) {
return false;
}
}
Node<V> *new_node = new Node<V>(id, value);
if (n_ids_) {
node_map_arr_[id] = new_node;
} else {
node_map_[id] = new_node;
}
RootsAtRank(0).emplace_back(new_node);
++size_;
if (min_node_ == nullptr || comparator_(value, min_node_->value)) {
min_node_ = new_node;
}
return true;
}
template<typename V, typename C>
void HollowHeap<V, C>::Push(V value) {
Node<V> *new_node = new Node<V>(-1, value);
RootsAtRank(0).emplace_back(new_node);
++size_;
if (min_node_ == nullptr || comparator_(value, min_node_->value)) {
min_node_ = new_node;
}
}
template<typename V, typename C>
std::pair<int32_t, V> HollowHeap<V, C>::Top() const {
return std::make_pair(min_node_->id, min_node_->value);
}
template<typename V, typename C>
inline Node<V>* HollowHeap<V, C>::link(Node<V> *r1, Node<V> *r2) {
Node<V> *temp;
if (comparator_(r1->value, r2->value)) {
temp = r1->head_childs;
r1->head_childs = r2;
r2->next_sibling = temp;
r2->is_root = false;
++r1->rank;
return r1;
} else {
temp = r2->head_childs;
r2->head_childs = r1;
r1->next_sibling = temp;
r1->is_root = false;
++r2->rank;
return r2;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::Pop() {
Node<V> *temp, *temp_2;
// remove id & make top hollow
if (min_node_->id >= 0) {
if (n_ids_) {
node_map_arr_[min_node_->id] = nullptr;
} else {
node_map_.erase(min_node_->id);
}
}
min_node_->is_hollow = true;
// recursively remove hollow roots
for (auto it = roots_of_rank_.rbegin(); it != roots_of_rank_.rend(); ++it) {
std::vector<Node<V>*> &l = **it;
uint32_t non_hollow = 0;
for (uint32_t i = 0; i < l.size(); ++i) {
if (l[i]->is_hollow) { // hollow node
Node<V> *current = l[i]->head_childs;
while (current) {
roots_of_rank_[current->rank]->emplace_back(current);
current->is_root = true;
temp = current;
current = current->next_sibling;
temp->next_sibling = nullptr;
}
delete l[i];
} else {
l[non_hollow++] = l[i];
}
}
l.resize(non_hollow);
}
// re-link roots and shrink roots vector
int32_t max_rank = -1;
for (uint32_t i = 0; i < roots_of_rank_.size(); ++i) {
std::vector<Node<V>*> &l = *roots_of_rank_[i];
if (l.size()) {
max_rank = l.front()->rank;
}
uint32_t num_links = l.size() >> 1;
while (num_links--) {
temp = l.back();
l.pop_back();
temp_2 = l.back();
l.pop_back();
temp = link(temp, temp_2);
RootsAtRank(temp->rank).emplace_back(temp);
}
}
// shrink roots vector
for (uint32_t i = max_rank + 1; i < roots_of_rank_.size(); ++i) {
delete roots_of_rank_[i];
}
roots_of_rank_.resize(max_rank + 1);
// update min-id
min_node_ = nullptr;
for (auto it = roots_of_rank_.begin(); it != roots_of_rank_.end(); ++it) {
std::vector<Node<V>*> &l = **it;
if (l.size()) {
if (min_node_ == nullptr || comparator_(l[0]->value, min_node_->value)) {
min_node_ = l[0];
}
}
}
// reduce size;
--size_;
}
// return false if id is not inserted yet, or updating value is invalid
template<typename V, typename C>
bool HollowHeap<V, C>::Update(uint32_t id, V value) {
Node<V> *current_node;
if (n_ids_) {
current_node = node_map_arr_[id];
if (current_node == nullptr || !comparator_(value, current_node->value)) {
return false;
}
} else {
auto i = node_map_.find(id);
if (i == node_map_.end() || !comparator_(value, i->second->value)) {
return false;
}
current_node = i->second;
}
// if id is root
if (current_node->is_root) {
current_node->value = value;
if (comparator_(current_node->value, min_node_->value)) {
min_node_ = current_node;
}
return true;
}
// make current node hollow
current_node->is_hollow = true;
// build new node
Node<V> *new_node = new Node<V>(id, value);
if (current_node->rank > 2) {
new_node->rank = current_node->rank - 2;
Node<V> *second_child = current_node->head_childs->next_sibling;
new_node->head_childs = second_child->next_sibling;
second_child->next_sibling = nullptr;
}
if (n_ids_) {
node_map_arr_[id] = new_node;
} else {
node_map_[id] = new_node;
}
RootsAtRank(new_node->rank).emplace_back(new_node);
// update min-id
if (comparator_(new_node->value, min_node_->value)) {
min_node_ = new_node;
}
return true;
}
template<typename V, typename C>
uint32_t HollowHeap<V, C>::size() const {
return size_;
}
template<typename V, typename C>
bool HollowHeap<V, C>::empty() const {
return size_ == 0;
}
template<typename V, typename C>
bool HollowHeap<V, C>::ContainsId(uint32_t id) const {
if (n_ids_) {
return node_map_arr_[id] != nullptr;
} else {
return node_map_.find(id) != node_map_.end();
}
}
template<typename V, typename C>
V HollowHeap<V, C>::Get(uint32_t id) const {
if (n_ids_) {
return node_map_arr_[id]->value;
} else {
return node_map_[id]->value;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::PopId(uint32_t id) {
Node<V> *node;
// find node corresponding to id
if (n_ids_) {
node = node_map_arr_[id];
} else {
node = node_map_[id];
}
// pop
if (node == min_node_) {
Pop();
} else {
node->is_hollow = true;
if (n_ids_) {
node_map_arr_[id] = nullptr;
} else {
node_map_.erase(id);
}
// reduce size;
--size_;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::DeleteNodeRecursively(Node<V> *node) {
Node<V> *temp;
while (node->head_childs != nullptr) {
temp = node->head_childs->next_sibling;
DeleteNodeRecursively(node->head_childs);
node->head_childs = temp;
}
delete node;
}
template<typename V, typename C>
HollowHeap<V, C>::~HollowHeap() {
for (auto it = roots_of_rank_.begin(); it != roots_of_rank_.end(); ++it) {
std::vector<Node<V>*> &l = **it;
for (const auto &n : l) {
DeleteNodeRecursively(n);
}
delete *it;
}
}
<commit_msg>minor fix<commit_after>// template impl (included from header)
// #include "hheap.h"
template<typename V>
Node<V>::Node(int32_t _id, V _value) :
id(_id), value(_value), rank(0), is_hollow(false), is_root(true), next_sibling(
nullptr), head_childs(nullptr) {
}
template<typename V, typename C>
inline std::vector<Node<V>*>& HollowHeap<V, C>::RootsAtRank(uint32_t rank) {
if (roots_of_rank_.size() <= rank) {
uint32_t old_size = roots_of_rank_.size();
roots_of_rank_.resize(rank + 1, nullptr);
for (uint32_t i = old_size; i <= rank; ++i) {
roots_of_rank_[i] = new std::vector<Node<V>*>();
}
}
return *roots_of_rank_[rank];
}
template<typename V, typename C>
HollowHeap<V, C>::HollowHeap() :
size_(0), comparator_(), min_node_(nullptr), roots_of_rank_(), node_map_(), n_ids_(
0), node_map_arr_(nullptr) {
}
template<typename V, typename C>
HollowHeap<V, C>::HollowHeap(uint32_t n_ids) :
size_(0), comparator_(), min_node_(nullptr), roots_of_rank_(), node_map_(), n_ids_(
n_ids), node_map_arr_(new Node<V>*[n_ids_]) {
Node<V> **arr = node_map_arr_.get();
std::fill(arr, arr + n_ids_, nullptr);
}
// return false if id is already inserted
template<typename V, typename C>
bool HollowHeap<V, C>::Push(uint32_t id, V value) {
if (n_ids_) {
if (node_map_arr_[id] != nullptr) {
return false;
}
} else {
if (node_map_.find(id) != node_map_.end()) {
return false;
}
}
Node<V> *new_node = new Node<V>(id, value);
if (n_ids_) {
node_map_arr_[id] = new_node;
} else {
node_map_[id] = new_node;
}
RootsAtRank(0).emplace_back(new_node);
++size_;
if (min_node_ == nullptr || comparator_(value, min_node_->value)) {
min_node_ = new_node;
}
return true;
}
template<typename V, typename C>
void HollowHeap<V, C>::Push(V value) {
Node<V> *new_node = new Node<V>(-1, value);
RootsAtRank(0).emplace_back(new_node);
++size_;
if (min_node_ == nullptr || comparator_(value, min_node_->value)) {
min_node_ = new_node;
}
}
template<typename V, typename C>
std::pair<int32_t, V> HollowHeap<V, C>::Top() const {
return std::make_pair(min_node_->id, min_node_->value);
}
template<typename V, typename C>
inline Node<V>* HollowHeap<V, C>::link(Node<V> *r1, Node<V> *r2) {
Node<V> *temp;
if (comparator_(r1->value, r2->value)) {
temp = r1->head_childs;
r1->head_childs = r2;
r2->next_sibling = temp;
r2->is_root = false;
++r1->rank;
return r1;
} else {
temp = r2->head_childs;
r2->head_childs = r1;
r1->next_sibling = temp;
r1->is_root = false;
++r2->rank;
return r2;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::Pop() {
Node<V> *temp, *temp_2;
// remove id & make top hollow
if (min_node_->id >= 0) {
if (n_ids_) {
node_map_arr_[min_node_->id] = nullptr;
} else {
node_map_.erase(min_node_->id);
}
}
min_node_->is_hollow = true;
// recursively remove hollow roots
for (auto it = roots_of_rank_.rbegin(); it != roots_of_rank_.rend(); ++it) {
std::vector<Node<V>*> &l = **it;
uint32_t non_hollow = 0;
for (uint32_t i = 0; i < l.size(); ++i) {
if (l[i]->is_hollow) { // hollow node
Node<V> *current = l[i]->head_childs;
while (current) {
roots_of_rank_[current->rank]->emplace_back(current);
current->is_root = true;
temp = current;
current = current->next_sibling;
temp->next_sibling = nullptr;
}
delete l[i];
} else {
l[non_hollow++] = l[i];
}
}
l.resize(non_hollow);
}
// re-link roots and shrink roots vector
int32_t max_rank = -1;
for (uint32_t i = 0; i < roots_of_rank_.size(); ++i) {
std::vector<Node<V>*> &l = *roots_of_rank_[i];
if (l.size()) {
max_rank = l.front()->rank;
}
uint32_t num_links = l.size() >> 1;
while (num_links--) {
temp = l.back();
l.pop_back();
temp_2 = l.back();
l.pop_back();
temp = link(temp, temp_2);
RootsAtRank(temp->rank).emplace_back(temp);
}
}
// shrink roots vector
for (uint32_t i = max_rank + 1; i < roots_of_rank_.size(); ++i) {
delete roots_of_rank_[i];
}
roots_of_rank_.resize(max_rank + 1);
// update min-id
min_node_ = nullptr;
for (auto it = roots_of_rank_.begin(); it != roots_of_rank_.end(); ++it) {
std::vector<Node<V>*> &l = **it;
if (l.size()) {
if (min_node_ == nullptr || comparator_(l[0]->value, min_node_->value)) {
min_node_ = l[0];
}
}
}
// reduce size;
--size_;
}
// return false if id is not inserted yet, or updating value is invalid
template<typename V, typename C>
bool HollowHeap<V, C>::Update(uint32_t id, V value) {
Node<V> *current_node;
if (n_ids_) {
current_node = node_map_arr_[id];
if (current_node == nullptr || !comparator_(value, current_node->value)) {
return false;
}
} else {
auto i = node_map_.find(id);
if (i == node_map_.end() || !comparator_(value, i->second->value)) {
return false;
}
current_node = i->second;
}
// if id is root
if (current_node->is_root) {
current_node->value = value;
if (comparator_(current_node->value, min_node_->value)) {
min_node_ = current_node;
}
return true;
}
// make current node hollow
current_node->is_hollow = true;
// build new node
Node<V> *new_node = new Node<V>(id, value);
if (current_node->rank > 2) {
new_node->rank = current_node->rank - 2;
Node<V> *second_child = current_node->head_childs->next_sibling;
new_node->head_childs = second_child->next_sibling;
second_child->next_sibling = nullptr;
}
if (n_ids_) {
node_map_arr_[id] = new_node;
} else {
node_map_[id] = new_node;
}
RootsAtRank(new_node->rank).emplace_back(new_node);
// update min-id
if (comparator_(new_node->value, min_node_->value)) {
min_node_ = new_node;
}
return true;
}
template<typename V, typename C>
uint32_t HollowHeap<V, C>::size() const {
return size_;
}
template<typename V, typename C>
bool HollowHeap<V, C>::empty() const {
return size_ == 0;
}
template<typename V, typename C>
bool HollowHeap<V, C>::ContainsId(uint32_t id) const {
if (n_ids_) {
return node_map_arr_[id] != nullptr;
} else {
return node_map_.find(id) != node_map_.end();
}
}
template<typename V, typename C>
V HollowHeap<V, C>::Get(uint32_t id) const {
if (n_ids_) {
return node_map_arr_[id]->value;
} else {
return node_map_.find(id)->second->value;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::PopId(uint32_t id) {
Node<V> *node;
// find node corresponding to id
if (n_ids_) {
node = node_map_arr_[id];
} else {
node = node_map_[id];
}
// pop
if (node == min_node_) {
Pop();
} else {
node->is_hollow = true;
if (n_ids_) {
node_map_arr_[id] = nullptr;
} else {
node_map_.erase(id);
}
// reduce size;
--size_;
}
}
template<typename V, typename C>
void HollowHeap<V, C>::DeleteNodeRecursively(Node<V> *node) {
Node<V> *temp;
while (node->head_childs != nullptr) {
temp = node->head_childs->next_sibling;
DeleteNodeRecursively(node->head_childs);
node->head_childs = temp;
}
delete node;
}
template<typename V, typename C>
HollowHeap<V, C>::~HollowHeap() {
for (auto it = roots_of_rank_.begin(); it != roots_of_rank_.end(); ++it) {
std::vector<Node<V>*> &l = **it;
for (const auto &n : l) {
DeleteNodeRecursively(n);
}
delete *it;
}
}
<|endoftext|> |
<commit_before>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <string>
#include <iostream>
#include <map>
using namespace std;
using namespace cv;
//================================================================================
template<typename M>
inline typename M::mapped_type getValue(const M &dict, const typename M::key_type &key, const string & errorMessage)
{
typename M::const_iterator it = dict.find(key);
if (it == dict.end())
{
CV_Error(Error::StsBadArg, errorMessage);
}
return it->second;
}
inline map<string, Size> sizeByResolution()
{
map<string, Size> res;
res["720p"] = Size(1280, 720);
res["1080p"] = Size(1920, 1080);
res["4k"] = Size(3840, 2160);
return res;
}
inline map<string, int> fourccByCodec()
{
map<string, int> res;
res["h264"] = VideoWriter::fourcc('H','2','6','4');
res["h265"] = VideoWriter::fourcc('H','E','V','C');
res["mpeg2"] = VideoWriter::fourcc('M','P','E','G');
res["mpeg4"] = VideoWriter::fourcc('M','P','4','2');
res["mjpeg"] = VideoWriter::fourcc('M','J','P','G');
res["vp8"] = VideoWriter::fourcc('V','P','8','0');
return res;
}
inline map<string, string> defaultEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "x264enc";
res["h265"] = "x265enc";
res["mpeg2"] = "mpeg2enc";
res["mjpeg"] = "jpegenc";
res["vp8"] = "vp8enc";
return res;
}
inline map<string, string> VAAPIEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! vaapih264enc";
res["h265"] = "parsebin ! vaapih265enc";
res["mpeg2"] = "parsebin ! vaapimpeg2enc";
res["mjpeg"] = "parsebin ! vaapijpegenc";
res["vp8"] = "parsebin ! vaapivp8enc";
return res;
}
inline map<string, string> mfxDecodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! mfxh264dec";
res["h265"] = "parsebin ! mfxhevcdec";
res["mpeg2"] = "parsebin ! mfxmpeg2dec";
res["mjpeg"] = "parsebin ! mfxjpegdec";
return res;
}
inline map<string, string> mfxEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "mfxh264enc";
res["h265"] = "mfxhevcenc";
res["mpeg2"] = "mfxmpeg2enc";
res["mjpeg"] = "mfxjpegenc";
return res;
}
inline map<string, string> libavDecodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! avdec_h264";
res["h265"] = "parsebin ! avdec_h265";
res["mpeg2"] = "parsebin ! avdec_mpeg2video";
res["mpeg4"] = "parsebin ! avdec_mpeg4";
res["mjpeg"] = "parsebin ! avdec_mjpeg";
res["vp8"] = "parsebin ! avdec_vp8";
return res;
}
inline map<string, string> libavEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "avenc_h264";
res["h265"] = "avenc_h265";
res["mpeg2"] = "avenc_mpeg2video";
res["mpeg4"] = "avenc_mpeg4";
res["mjpeg"] = "avenc_mjpeg";
res["vp8"] = "avenc_vp8";
return res;
}
inline map<string, string> demuxPluginByContainer()
{
map<string, string> res;
res["avi"] = "avidemux";
res["mp4"] = "qtdemux";
res["mov"] = "qtdemux";
res["mkv"] = "matroskademux";
return res;
}
inline map<string, string> muxPluginByContainer()
{
map<string, string> res;
res["avi"] = "avimux";
res["mp4"] = "qtmux";
res["mov"] = "qtmux";
res["mkv"] = "matroskamux";
return res;
}
//================================================================================
inline string containerByName(const string &name)
{
size_t found = name.rfind(".");
if (found != string::npos)
{
return name.substr(found + 1); // container type
}
return string();
}
//================================================================================
inline Ptr<VideoCapture> createCapture(const string &backend, const string &file_name, const string &codec)
{
if (backend == "gst-default")
{
cout << "Created GStreamer capture ( " << file_name << " )" << endl;
return makePtr<VideoCapture>(file_name, CAP_GSTREAMER);
}
else if (backend.find("gst") == 0)
{
ostringstream line;
line << "filesrc location=\"" << file_name << "\"";
line << " ! ";
line << getValue(demuxPluginByContainer(), containerByName(file_name), "Invalid container");
line << " ! ";
if (backend.find("basic") == 4)
line << "decodebin";
else if (backend.find("vaapi") == 4)
line << "vaapidecodebin";
else if (backend.find("libav") == 4)
line << getValue(libavDecodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("mfx") == 4)
line << getValue(mfxDecodeElementByCodec(), codec, "Invalid or unsupported codec");
else
return Ptr<VideoCapture>();
line << " ! videoconvert n-threads=" << getNumThreads();
line << " ! appsink sync=false";
cout << "Created GStreamer capture ( " << line.str() << " )" << endl;
return makePtr<VideoCapture>(line.str(), CAP_GSTREAMER);
}
else if (backend == "ffmpeg")
{
cout << "Created FFmpeg capture ( " << file_name << " )" << endl;
return makePtr<VideoCapture>(file_name, CAP_FFMPEG);
}
return Ptr<VideoCapture>();
}
inline Ptr<VideoCapture> createSynthSource(Size sz, unsigned fps)
{
ostringstream line;
line << "videotestsrc pattern=smpte";
line << " ! video/x-raw";
line << ",width=" << sz.width << ",height=" << sz.height;
if (fps > 0)
line << ",framerate=" << fps << "/1";
line << " ! appsink sync=false";
cout << "Created synthetic video source ( " << line.str() << " )" << endl;
return makePtr<VideoCapture>(line.str(), CAP_GSTREAMER);
}
inline Ptr<VideoWriter> createWriter(const string &backend, const string &file_name, const string &codec, Size sz, unsigned fps)
{
if (backend == "gst-default")
{
cout << "Created GStreamer writer ( " << file_name << ", FPS=" << fps << ", Size=" << sz << ")" << endl;
return makePtr<VideoWriter>(file_name, CAP_GSTREAMER, getValue(fourccByCodec(), codec, "Invalid codec"), fps, sz, true);
}
else if (backend.find("gst") == 0)
{
ostringstream line;
line << "appsrc ! videoconvert n-threads=" << getNumThreads() << " ! ";
if (backend.find("basic") == 4)
line << getValue(defaultEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("vaapi") == 4)
line << getValue(VAAPIEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("libav") == 4)
line << getValue(libavEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("mfx") == 4)
line << getValue(mfxEncodeElementByCodec(), codec, "Invalid codec");
else
return Ptr<VideoWriter>();
line << " ! ";
line << getValue(muxPluginByContainer(), containerByName(file_name), "Invalid container");
line << " ! ";
line << "filesink location=\"" << file_name << "\"";
cout << "Created GStreamer writer ( " << line.str() << " )" << endl;
return makePtr<VideoWriter>(line.str(), CAP_GSTREAMER, 0, fps, sz, true);
}
else if (backend == "ffmpeg")
{
cout << "Created FFMpeg writer ( " << file_name << ", FPS=" << fps << ", Size=" << sz << " )" << endl;
return makePtr<VideoWriter>(file_name, CAP_FFMPEG, getValue(fourccByCodec(), codec, "Invalid codec"), fps, sz, true);
}
return Ptr<VideoWriter>();
}
//================================================================================
int main(int argc, char *argv[])
{
const string keys =
"{h help usage ? | | print help messages }"
"{m mode |decode | coding mode (supported: encode, decode) }"
"{b backend |default | video backend (supported: 'gst-default', 'gst-basic', 'gst-vaapi', 'gst-libav', 'gst-mfx', 'ffmpeg') }"
"{c codec |h264 | codec name (supported: 'h264', 'h265', 'mpeg2', 'mpeg4', 'mjpeg', 'vp8') }"
"{f file path | | path to file }"
"{r resolution |720p | video resolution for encoding (supported: '720p', '1080p', '4k') }"
"{fps |30 | fix frame per second for encoding (supported: fps > 0) }"
"{fast | | fast measure fps }";
CommandLineParser cmd_parser(argc, argv, keys);
cmd_parser.about("This program measures performance of video encoding and decoding using different backends OpenCV.");
if (cmd_parser.has("help"))
{
cmd_parser.printMessage();
return 0;
}
bool fast_measure = cmd_parser.has("fast"); // fast measure fps
unsigned fix_fps = cmd_parser.get<unsigned>("fps"); // fixed frame per second
string backend = cmd_parser.get<string>("backend"); // video backend
string mode = cmd_parser.get<string>("mode"); // coding mode
string codec = cmd_parser.get<string>("codec"); // codec type
string file_name = cmd_parser.get<string>("file"); // path to videofile
string resolution = cmd_parser.get<string>("resolution"); // video resolution
if (!cmd_parser.check())
{
cmd_parser.printErrors();
return -1;
}
if (mode != "encode" && mode != "decode")
{
cout << "Unsupported mode: " << mode << endl;
return -1;
}
file_name = samples::findFile(file_name);
cout << "Mode: " << mode << ", Backend: " << backend << ", File: " << file_name << ", Codec: " << codec << endl;
TickMeter total;
Ptr<VideoCapture> cap;
Ptr<VideoWriter> wrt;
try
{
if (mode == "decode")
{
cap = createCapture(backend, file_name, codec);
if (!cap)
{
cout << "Failed to create video capture" << endl;
return -3;
}
if (!cap->isOpened())
{
cout << "Capture is not opened" << endl;
return -4;
}
}
else if (mode == "encode")
{
Size sz = getValue(sizeByResolution(), resolution, "Invalid resolution");
cout << "FPS: " << fix_fps << ", Frame size: " << sz << endl;
cap = createSynthSource(sz, fix_fps);
wrt = createWriter(backend, file_name, codec, sz, fix_fps);
if (!cap || !wrt)
{
cout << "Failed to create synthetic video source or video writer" << endl;
return -3;
}
if (!cap->isOpened() || !wrt->isOpened())
{
cout << "Synthetic video source or video writer is not opened" << endl;
return -4;
}
}
}
catch (...)
{
cout << "Unsupported parameters" << endl;
return -2;
}
TickMeter tick;
Mat frame;
Mat element;
total.start();
while(true)
{
if (mode == "decode")
{
tick.start();
if (!cap->grab())
{
cout << "No more frames - break" << endl;
break;
}
if (!cap->retrieve(frame))
{
cout << "Failed to retrieve frame - break" << endl;
break;
}
if (frame.empty())
{
cout << "Empty frame received - break" << endl;
break;
}
tick.stop();
}
else if (mode == "encode")
{
int limit = 100;
while (!cap->grab() && --limit != 0)
{
cout << "Skipping empty input frame - " << limit << endl;
}
cap->retrieve(element);
tick.start();
*wrt << element;
tick.stop();
}
if (fast_measure && tick.getCounter() >= 1000)
{
cout << "Fast mode frame limit reached - break" << endl;
break;
}
if (mode == "encode" && tick.getCounter() >= 1000)
{
cout << "Encode frame limit reached - break" << endl;
break;
}
}
total.stop();
if (tick.getCounter() == 0)
{
cout << "No frames have been processed" << endl;
return -10;
}
else
{
double res_fps = tick.getCounter() / tick.getTimeSec();
cout << tick.getCounter() << " frames in " << tick.getTimeSec() << " sec ~ " << res_fps << " FPS" << " (total time: " << total.getTimeSec() << " sec)" << endl;
}
return 0;
}
<commit_msg>samples: skip findFile() in encoding mode<commit_after>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <string>
#include <iostream>
#include <map>
using namespace std;
using namespace cv;
//================================================================================
template<typename M>
inline typename M::mapped_type getValue(const M &dict, const typename M::key_type &key, const string & errorMessage)
{
typename M::const_iterator it = dict.find(key);
if (it == dict.end())
{
CV_Error(Error::StsBadArg, errorMessage);
}
return it->second;
}
inline map<string, Size> sizeByResolution()
{
map<string, Size> res;
res["720p"] = Size(1280, 720);
res["1080p"] = Size(1920, 1080);
res["4k"] = Size(3840, 2160);
return res;
}
inline map<string, int> fourccByCodec()
{
map<string, int> res;
res["h264"] = VideoWriter::fourcc('H','2','6','4');
res["h265"] = VideoWriter::fourcc('H','E','V','C');
res["mpeg2"] = VideoWriter::fourcc('M','P','E','G');
res["mpeg4"] = VideoWriter::fourcc('M','P','4','2');
res["mjpeg"] = VideoWriter::fourcc('M','J','P','G');
res["vp8"] = VideoWriter::fourcc('V','P','8','0');
return res;
}
inline map<string, string> defaultEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "x264enc";
res["h265"] = "x265enc";
res["mpeg2"] = "mpeg2enc";
res["mjpeg"] = "jpegenc";
res["vp8"] = "vp8enc";
return res;
}
inline map<string, string> VAAPIEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! vaapih264enc";
res["h265"] = "parsebin ! vaapih265enc";
res["mpeg2"] = "parsebin ! vaapimpeg2enc";
res["mjpeg"] = "parsebin ! vaapijpegenc";
res["vp8"] = "parsebin ! vaapivp8enc";
return res;
}
inline map<string, string> mfxDecodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! mfxh264dec";
res["h265"] = "parsebin ! mfxhevcdec";
res["mpeg2"] = "parsebin ! mfxmpeg2dec";
res["mjpeg"] = "parsebin ! mfxjpegdec";
return res;
}
inline map<string, string> mfxEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "mfxh264enc";
res["h265"] = "mfxhevcenc";
res["mpeg2"] = "mfxmpeg2enc";
res["mjpeg"] = "mfxjpegenc";
return res;
}
inline map<string, string> libavDecodeElementByCodec()
{
map<string, string> res;
res["h264"] = "parsebin ! avdec_h264";
res["h265"] = "parsebin ! avdec_h265";
res["mpeg2"] = "parsebin ! avdec_mpeg2video";
res["mpeg4"] = "parsebin ! avdec_mpeg4";
res["mjpeg"] = "parsebin ! avdec_mjpeg";
res["vp8"] = "parsebin ! avdec_vp8";
return res;
}
inline map<string, string> libavEncodeElementByCodec()
{
map<string, string> res;
res["h264"] = "avenc_h264";
res["h265"] = "avenc_h265";
res["mpeg2"] = "avenc_mpeg2video";
res["mpeg4"] = "avenc_mpeg4";
res["mjpeg"] = "avenc_mjpeg";
res["vp8"] = "avenc_vp8";
return res;
}
inline map<string, string> demuxPluginByContainer()
{
map<string, string> res;
res["avi"] = "avidemux";
res["mp4"] = "qtdemux";
res["mov"] = "qtdemux";
res["mkv"] = "matroskademux";
return res;
}
inline map<string, string> muxPluginByContainer()
{
map<string, string> res;
res["avi"] = "avimux";
res["mp4"] = "qtmux";
res["mov"] = "qtmux";
res["mkv"] = "matroskamux";
return res;
}
//================================================================================
inline string containerByName(const string &name)
{
size_t found = name.rfind(".");
if (found != string::npos)
{
return name.substr(found + 1); // container type
}
return string();
}
//================================================================================
inline Ptr<VideoCapture> createCapture(const string &backend, const string &file_name, const string &codec)
{
if (backend == "gst-default")
{
cout << "Created GStreamer capture ( " << file_name << " )" << endl;
return makePtr<VideoCapture>(file_name, CAP_GSTREAMER);
}
else if (backend.find("gst") == 0)
{
ostringstream line;
line << "filesrc location=\"" << file_name << "\"";
line << " ! ";
line << getValue(demuxPluginByContainer(), containerByName(file_name), "Invalid container");
line << " ! ";
if (backend.find("basic") == 4)
line << "decodebin";
else if (backend.find("vaapi") == 4)
line << "vaapidecodebin";
else if (backend.find("libav") == 4)
line << getValue(libavDecodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("mfx") == 4)
line << getValue(mfxDecodeElementByCodec(), codec, "Invalid or unsupported codec");
else
return Ptr<VideoCapture>();
line << " ! videoconvert n-threads=" << getNumThreads();
line << " ! appsink sync=false";
cout << "Created GStreamer capture ( " << line.str() << " )" << endl;
return makePtr<VideoCapture>(line.str(), CAP_GSTREAMER);
}
else if (backend == "ffmpeg")
{
cout << "Created FFmpeg capture ( " << file_name << " )" << endl;
return makePtr<VideoCapture>(file_name, CAP_FFMPEG);
}
return Ptr<VideoCapture>();
}
inline Ptr<VideoCapture> createSynthSource(Size sz, unsigned fps)
{
ostringstream line;
line << "videotestsrc pattern=smpte";
line << " ! video/x-raw";
line << ",width=" << sz.width << ",height=" << sz.height;
if (fps > 0)
line << ",framerate=" << fps << "/1";
line << " ! appsink sync=false";
cout << "Created synthetic video source ( " << line.str() << " )" << endl;
return makePtr<VideoCapture>(line.str(), CAP_GSTREAMER);
}
inline Ptr<VideoWriter> createWriter(const string &backend, const string &file_name, const string &codec, Size sz, unsigned fps)
{
if (backend == "gst-default")
{
cout << "Created GStreamer writer ( " << file_name << ", FPS=" << fps << ", Size=" << sz << ")" << endl;
return makePtr<VideoWriter>(file_name, CAP_GSTREAMER, getValue(fourccByCodec(), codec, "Invalid codec"), fps, sz, true);
}
else if (backend.find("gst") == 0)
{
ostringstream line;
line << "appsrc ! videoconvert n-threads=" << getNumThreads() << " ! ";
if (backend.find("basic") == 4)
line << getValue(defaultEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("vaapi") == 4)
line << getValue(VAAPIEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("libav") == 4)
line << getValue(libavEncodeElementByCodec(), codec, "Invalid codec");
else if (backend.find("mfx") == 4)
line << getValue(mfxEncodeElementByCodec(), codec, "Invalid codec");
else
return Ptr<VideoWriter>();
line << " ! ";
line << getValue(muxPluginByContainer(), containerByName(file_name), "Invalid container");
line << " ! ";
line << "filesink location=\"" << file_name << "\"";
cout << "Created GStreamer writer ( " << line.str() << " )" << endl;
return makePtr<VideoWriter>(line.str(), CAP_GSTREAMER, 0, fps, sz, true);
}
else if (backend == "ffmpeg")
{
cout << "Created FFMpeg writer ( " << file_name << ", FPS=" << fps << ", Size=" << sz << " )" << endl;
return makePtr<VideoWriter>(file_name, CAP_FFMPEG, getValue(fourccByCodec(), codec, "Invalid codec"), fps, sz, true);
}
return Ptr<VideoWriter>();
}
//================================================================================
int main(int argc, char *argv[])
{
const string keys =
"{h help usage ? | | print help messages }"
"{m mode |decode | coding mode (supported: encode, decode) }"
"{b backend |default | video backend (supported: 'gst-default', 'gst-basic', 'gst-vaapi', 'gst-libav', 'gst-mfx', 'ffmpeg') }"
"{c codec |h264 | codec name (supported: 'h264', 'h265', 'mpeg2', 'mpeg4', 'mjpeg', 'vp8') }"
"{f file path | | path to file }"
"{r resolution |720p | video resolution for encoding (supported: '720p', '1080p', '4k') }"
"{fps |30 | fix frame per second for encoding (supported: fps > 0) }"
"{fast | | fast measure fps }";
CommandLineParser cmd_parser(argc, argv, keys);
cmd_parser.about("This program measures performance of video encoding and decoding using different backends OpenCV.");
if (cmd_parser.has("help"))
{
cmd_parser.printMessage();
return 0;
}
bool fast_measure = cmd_parser.has("fast"); // fast measure fps
unsigned fix_fps = cmd_parser.get<unsigned>("fps"); // fixed frame per second
string backend = cmd_parser.get<string>("backend"); // video backend
string mode = cmd_parser.get<string>("mode"); // coding mode
string codec = cmd_parser.get<string>("codec"); // codec type
string file_name = cmd_parser.get<string>("file"); // path to videofile
string resolution = cmd_parser.get<string>("resolution"); // video resolution
if (!cmd_parser.check())
{
cmd_parser.printErrors();
return -1;
}
if (mode != "encode" && mode != "decode")
{
cout << "Unsupported mode: " << mode << endl;
return -1;
}
if (mode == "decode")
{
file_name = samples::findFile(file_name);
}
cout << "Mode: " << mode << ", Backend: " << backend << ", File: " << file_name << ", Codec: " << codec << endl;
TickMeter total;
Ptr<VideoCapture> cap;
Ptr<VideoWriter> wrt;
try
{
if (mode == "decode")
{
cap = createCapture(backend, file_name, codec);
if (!cap)
{
cout << "Failed to create video capture" << endl;
return -3;
}
if (!cap->isOpened())
{
cout << "Capture is not opened" << endl;
return -4;
}
}
else if (mode == "encode")
{
Size sz = getValue(sizeByResolution(), resolution, "Invalid resolution");
cout << "FPS: " << fix_fps << ", Frame size: " << sz << endl;
cap = createSynthSource(sz, fix_fps);
wrt = createWriter(backend, file_name, codec, sz, fix_fps);
if (!cap || !wrt)
{
cout << "Failed to create synthetic video source or video writer" << endl;
return -3;
}
if (!cap->isOpened() || !wrt->isOpened())
{
cout << "Synthetic video source or video writer is not opened" << endl;
return -4;
}
}
}
catch (...)
{
cout << "Unsupported parameters" << endl;
return -2;
}
TickMeter tick;
Mat frame;
Mat element;
total.start();
while(true)
{
if (mode == "decode")
{
tick.start();
if (!cap->grab())
{
cout << "No more frames - break" << endl;
break;
}
if (!cap->retrieve(frame))
{
cout << "Failed to retrieve frame - break" << endl;
break;
}
if (frame.empty())
{
cout << "Empty frame received - break" << endl;
break;
}
tick.stop();
}
else if (mode == "encode")
{
int limit = 100;
while (!cap->grab() && --limit != 0)
{
cout << "Skipping empty input frame - " << limit << endl;
}
cap->retrieve(element);
tick.start();
*wrt << element;
tick.stop();
}
if (fast_measure && tick.getCounter() >= 1000)
{
cout << "Fast mode frame limit reached - break" << endl;
break;
}
if (mode == "encode" && tick.getCounter() >= 1000)
{
cout << "Encode frame limit reached - break" << endl;
break;
}
}
total.stop();
if (tick.getCounter() == 0)
{
cout << "No frames have been processed" << endl;
return -10;
}
else
{
double res_fps = tick.getCounter() / tick.getTimeSec();
cout << tick.getCounter() << " frames in " << tick.getTimeSec() << " sec ~ " << res_fps << " FPS" << " (total time: " << total.getTimeSec() << " sec)" << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* BloomFilter.cpp
*
* Created on: 08.08.2015
* Author: Henning
*/
#include "BloomFilter.h"
#include "Random.h"
namespace Aux {
BloomFilter::BloomFilter(count numHashes, count size): numHashes(numHashes), size(size) {
membership.resize(numHashes);
salts.resize(numHashes);
for (index i = 0; i < numHashes; ++i) {
membership[i].resize(size, false);
salts[i] = Aux::Random::integer();
}
}
void BloomFilter::insert(index key) {
for (index func = 0; func < numHashes; ++func) {
membership[func][hash(key, func)] = true;
}
}
bool BloomFilter::isMember(index key) const {
bool result = true;
for (index func = 0; func < numHashes; ++func) {
result = result && membership[func][hash(key, func)];
}
return result;
}
index BloomFilter::hash(index key, index hfunc) const {
index result = 0;
std::hash<index> myhash;
result = myhash(key ^ salts[hfunc]);
return (result % size);
}
}
<commit_msg>Bloom filter doc, max clique computes clique as well (not only size)<commit_after>/*
* BloomFilter.cpp
*
* Created on: 08.08.2015
* Author: Henning
*/
#include "BloomFilter.h"
#include "Random.h"
namespace Aux {
BloomFilter::BloomFilter(count numHashes, count size): numHashes(numHashes), size(size),
membership(numHashes), salts(numHashes)
{
for (index i = 0; i < numHashes; ++i) {
membership[i].resize(size, false);
salts[i] = Aux::Random::integer();
}
}
void BloomFilter::insert(index key) {
// set hashed positions of key in each array to true
for (index func = 0; func < numHashes; ++func) {
membership[func][hash(key, func)] = true;
}
}
bool BloomFilter::isMember(index key) const {
bool result = true;
// find out if all hashed positions of key are true
for (index func = 0; (func < numHashes) && result; ++func) {
result = result && membership[func][hash(key, func)];
}
return result;
}
index BloomFilter::hash(index key, index hfunc) const {
index result = 0;
std::hash<index> myhash;
// instead of using different hash functions: salt key with different (but fixed) random salt
result = myhash(key ^ salts[hfunc]);
return (result % size);
}
}
<|endoftext|> |
<commit_before>//
// Vehicles.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "TerrainSceneWP.h"
#include "Engines.h"
#include "Hawaii.h"
///////////////////////////////
// helpers
void ConvertPurpleToColor(vtGroup *pModel, RGBf replace)
{
#if 0
RGBf color;
int i;
vtGeom *pShape;
vtMaterialArray *pApps;
vtMaterial *pApp;
// TODO
// walk down through a part of the scene graph, converting
// any geometry encountered
if (pModel->m_pModel->IsClass(vtGeom))
{
pShape = (vtGeom *)pModel;
bool has_purple = false;
pApps = pShape->GetMaterials();
if (!pApps)
return;
for (i = 0; i < pApps->GetSize(); i++)
{
pApp = pApps->GetAt(i);
// is purple?
color = pApp->GetDiffuse();
if (color.r == 1.0f && color.g == 0.0f && color.b == 1.0f)
{
has_purple = true;
break;
}
}
if (has_purple)
{
vtMaterialArray *pApps2 = new vtMaterialArray();
pApps2->CopyFrom(pApps);
pShape->SetMaterials(pApps2);
for (i = 0; i < pApps2->GetSize(); i++)
{
pApp = pApps2->GetAt(i);
if (!pApp) continue;
color = pApp->GetDiffuse();
if (color.r == 1.0f && color.g == 0.0f && color.b == 1.0f)
{
vtMaterial *pApp2 = new vtMaterial();
pApp2->Copy(pApp);
pApps2->SetAt(i, pApp2);
pApp2->SetDiffuse2(replace);
pApp2->SetAmbient2(replace*0.6f);
}
}
}
}
for (i = 0; i < pModel->GetNumChildren(); i++)
{
vtTransform *pChild = (vtTransform *) pModel->GetChild(i);
ConvertPurpleToColor(pChild, replace);
}
#endif
}
/////////////////////////////////////////
void IslandTerrain::create_road_vehicles()
{
// must have roads for them to drive on
if (!m_pRoadMap)
return;
}
void PTerrain::create_ground_vehicles(float fSize, float fSpeed)
{
FPoint3 vNormal, center;
FPoint3 start_point;
//add some cars!
if (m_pRoadMap)
{
NodeGeom *n = (NodeGeom*) m_pRoadMap->GetFirstNode();
vtTransform *car;
int num, col;
RGBf color;
for (int i = 0; i < m_Params.m_iNumCars; i++)
{
if (n == NULL) {
n = (NodeGeom*) m_pRoadMap->GetFirstNode();
}
num = i % 3;
col = i % 5;
switch (col) {
case 0:
color.Set(1.0f, 1.0f, 1.0f);
break;
case 1:
color.Set(1.0f, 1.0f, 0.0f);
break;
case 2:
color.Set(0.0f, 0.0f, .5f);
break;
case 3:
color.Set(1.0f, 0.0f, 0.0f);
break;
case 4:
color.Set(0.0f, .5f, 0.0f);
break;
}
switch (num) {
case 0:
car = CreateVehicle("discovery", color, fSize);
break;
case 1:
car = CreateVehicle("bronco", color, fSize);
break;
case 2:
car = CreateVehicle("bus", color, fSize);
break;
}
AddNode(car);
PlantModelAtPoint(car, n->m_p);
// AddCarEngine(car, 60.0f, n);
n = (NodeGeom*) n->m_pNext;
}
}
/* // try loading a car
CarEngine *cEng;
vtTransform *car;
car = LoadModel("Vehicles/bronco_v2.DSM");
float fAltitude;
convert_meters_to_local_xz(192200, 2157700, start_point.x, start_point.z);
m_pLocalGrid->FindAltitudeAtPoint(start_point, fAltitude, vNormal);
if (car != NULL)
{
car->Size(.01f*sc,.01f*sc,.01f*sc);
car->RotateLocal(YAXIS, PID2f); //adjust for MAX model
#if CAR_VIEW
FollowerEngine* follower = new FollowerEngine(car, pScene->GetCamera());
follower->SetName2("Follower Engine");
AddEngine(follower, pScene);
#endif
if (m_Params.m_bDoSound)
{
// sound
vtSound3D* carnoise = new vtSound3D("Data/Vehicles/loud01.wav");
carnoise->Initialize();
carnoise->SetName2("Corvette Sound");
carnoise->SetModel(1,1,30,30); //set limit of how far away sound can be heard
carnoise->SetTarget(car); //set target
carnoise->SetMute(true); //mute the sound until later
carnoise->Play(0, 0.0f); //play the sound (muted)
AddEngine(carnoise, pScene);
}
AddNode(car);
if (m_pRoadMap != NULL) {
//follow a road
cEng = new CarEngine(start_point, m_pLocalGrid, 60.0f*fSize, .25f*fSize, m_pRoadMap->GetFirstNode(), 1, m_Params.m_fRoadHeight);
cEng->SetName2("Car Engine");
// cEng->GetPath("Data/test2.pf", m_pRoadMap);
} else {
//simple test: drive in a circle
center = start_point;
//for moving in a circle
center.z -=4;
cEng = new CarEngine(start_point, m_pLocalGrid, 60.0f*fSize, .25f*fSize, center);
cEng->SetName2("Car Engine");
//or drive in a straight line
//cEng = new CarEngine(start_point, pLocalGrid, 60*fSize, .25*fSize);
}
cEng->SetTarget(car);
if (cEng->SetTires()) {
AddEngine(cEng, pScene);
} else {
//uh oh!
delete cEng;
}
}
*/
}
VehicleType::VehicleType(const char *szName)
{
m_strTypeName = szName;
m_pNext = NULL;
m_bAttemptedLoaded = false;
m_iLods = 0;
}
//
// set filename and swap-out distance (in meters) for each LOD
//
void VehicleType::SetModelLod(int lod, const char *filename, float fDistance)
{
if (lod > MAX_VEHICLE_LODS)
return;
m_strFilename[lod] = filename;
if (m_iLods <= lod)
m_iLods = lod+1;
m_fDistance.SetAt(lod, fDistance * WORLD_SCALE);
}
void VehicleType::AttemptModelLoad()
{
m_bAttemptedLoaded = true;
if (m_iLods < 1)
return;
#if 0
// TODO
for (int i = 0; i < m_iLods; i++)
{
if (vtModel *pMod = vtLoadModel(m_strFilename[i])) // can read file?
m_pModels.SetAt(i, pMod);
}
#endif
}
Vehicle *VehicleType::CreateVehicle(RGBf &cColor, float fSize)
{
// check if it's loaded yet
if (!m_bAttemptedLoaded)
AttemptModelLoad();
if (m_pModels.GetSize() == 0)
return NULL;
Vehicle *pNewVehicle = new Vehicle();
pNewVehicle->SetName2("VehicleLOD-" + m_strTypeName);
float distances[10];
// there is no distance at which the object should vanish for being too close
distances[0] = 0.0f;
#if 0
for (int i = 0; i < m_iLods; i++)
{
vtTransform *pNewModel = (Vehicle *)m_pModels.GetAt(i)->CreateClone();
pNewVehicle->AddChild(pNewModel);
distances[i+1] = m_fDistance.GetAt(i) * fSize;
}
pNewVehicle->SetRanges(distances, m_iLods+1);
float scale = 0.01f * WORLD_SCALE; // models are in cm
pNewVehicle->m_fSize = fSize * scale;
ConvertPurpleToColor(pNewVehicle, cColor);
return pNewVehicle;
#else
return NULL;
#endif
}
<commit_msg>removed big chunk of obsolete code<commit_after>//
// Vehicles.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "TerrainSceneWP.h"
#include "Engines.h"
#include "Hawaii.h"
///////////////////////////////
// helpers
void ConvertPurpleToColor(vtGroup *pModel, RGBf replace)
{
#if 0
RGBf color;
int i;
vtGeom *pShape;
vtMaterialArray *pApps;
vtMaterial *pApp;
// TODO
// walk down through a part of the scene graph, converting
// any geometry encountered
if (pModel->m_pModel->IsClass(vtGeom))
{
pShape = (vtGeom *)pModel;
bool has_purple = false;
pApps = pShape->GetMaterials();
if (!pApps)
return;
for (i = 0; i < pApps->GetSize(); i++)
{
pApp = pApps->GetAt(i);
// is purple?
color = pApp->GetDiffuse();
if (color.r == 1.0f && color.g == 0.0f && color.b == 1.0f)
{
has_purple = true;
break;
}
}
if (has_purple)
{
vtMaterialArray *pApps2 = new vtMaterialArray();
pApps2->CopyFrom(pApps);
pShape->SetMaterials(pApps2);
for (i = 0; i < pApps2->GetSize(); i++)
{
pApp = pApps2->GetAt(i);
if (!pApp) continue;
color = pApp->GetDiffuse();
if (color.r == 1.0f && color.g == 0.0f && color.b == 1.0f)
{
vtMaterial *pApp2 = new vtMaterial();
pApp2->Copy(pApp);
pApps2->SetAt(i, pApp2);
pApp2->SetDiffuse2(replace);
pApp2->SetAmbient2(replace*0.6f);
}
}
}
}
for (i = 0; i < pModel->GetNumChildren(); i++)
{
vtTransform *pChild = (vtTransform *) pModel->GetChild(i);
ConvertPurpleToColor(pChild, replace);
}
#endif
}
/////////////////////////////////////////
void IslandTerrain::create_road_vehicles()
{
// must have roads for them to drive on
if (!m_pRoadMap)
return;
}
void PTerrain::create_ground_vehicles(float fSize, float fSpeed)
{
FPoint3 vNormal, center;
FPoint3 start_point;
//add some cars!
if (m_pRoadMap)
{
NodeGeom *n = (NodeGeom*) m_pRoadMap->GetFirstNode();
vtTransform *car;
int num, col;
RGBf color;
for (int i = 0; i < m_Params.m_iNumCars; i++)
{
if (n == NULL) {
n = (NodeGeom*) m_pRoadMap->GetFirstNode();
}
num = i % 3;
col = i % 5;
switch (col) {
case 0:
color.Set(1.0f, 1.0f, 1.0f);
break;
case 1:
color.Set(1.0f, 1.0f, 0.0f);
break;
case 2:
color.Set(0.0f, 0.0f, .5f);
break;
case 3:
color.Set(1.0f, 0.0f, 0.0f);
break;
case 4:
color.Set(0.0f, .5f, 0.0f);
break;
}
switch (num) {
case 0:
car = CreateVehicle("discovery", color, fSize);
break;
case 1:
car = CreateVehicle("bronco", color, fSize);
break;
case 2:
car = CreateVehicle("bus", color, fSize);
break;
}
AddNode(car);
PlantModelAtPoint(car, n->m_p);
// AddCarEngine(car, 60.0f, n);
n = (NodeGeom*) n->m_pNext;
}
}
}
VehicleType::VehicleType(const char *szName)
{
m_strTypeName = szName;
m_pNext = NULL;
m_bAttemptedLoaded = false;
m_iLods = 0;
}
//
// set filename and swap-out distance (in meters) for each LOD
//
void VehicleType::SetModelLod(int lod, const char *filename, float fDistance)
{
if (lod > MAX_VEHICLE_LODS)
return;
m_strFilename[lod] = filename;
if (m_iLods <= lod)
m_iLods = lod+1;
m_fDistance.SetAt(lod, fDistance * WORLD_SCALE);
}
void VehicleType::AttemptModelLoad()
{
m_bAttemptedLoaded = true;
if (m_iLods < 1)
return;
#if 0
// TODO
for (int i = 0; i < m_iLods; i++)
{
if (vtModel *pMod = vtLoadModel(m_strFilename[i])) // can read file?
m_pModels.SetAt(i, pMod);
}
#endif
}
Vehicle *VehicleType::CreateVehicle(RGBf &cColor, float fSize)
{
// check if it's loaded yet
if (!m_bAttemptedLoaded)
AttemptModelLoad();
if (m_pModels.GetSize() == 0)
return NULL;
Vehicle *pNewVehicle = new Vehicle();
pNewVehicle->SetName2("VehicleLOD-" + m_strTypeName);
float distances[10];
// there is no distance at which the object should vanish for being too close
distances[0] = 0.0f;
#if 0
for (int i = 0; i < m_iLods; i++)
{
vtTransform *pNewModel = (Vehicle *)m_pModels.GetAt(i)->CreateClone();
pNewVehicle->AddChild(pNewModel);
distances[i+1] = m_fDistance.GetAt(i) * fSize;
}
pNewVehicle->SetRanges(distances, m_iLods+1);
float scale = 0.01f * WORLD_SCALE; // models are in cm
pNewVehicle->m_fSize = fSize * scale;
ConvertPurpleToColor(pNewVehicle, cColor);
return pNewVehicle;
#else
return NULL;
#endif
}
<|endoftext|> |
<commit_before>#include <UnitTest++/src/UnitTest++.h>
#include "rdestl/intrusive_slist.h"
namespace
{
struct MyNode : public rde::intrusive_slist_node
{
explicit MyNode(int i = 0): data(i) {}
int data;
};
TEST(DefaultCtorConstructsEmptyList)
{
rde::intrusive_slist<MyNode> l;
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(PushFront)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
CHECK_EQUAL(1ul, l.size());
MyNode node2;
node2.data = 10;
l.push_front(&node2);
CHECK_EQUAL(2ul, l.size());
CHECK_EQUAL(10, l.front()->data);
}
TEST(PopFront)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
MyNode node2;
node2.data = 10;
l.push_front(&node2);
MyNode node3;
node3.data = 15;
l.push_front(&node3);
CHECK_EQUAL(3ul, l.size());
l.pop_front();
CHECK_EQUAL(2ul, l.size());
CHECK_EQUAL(10, l.front()->data);
l.pop_front();
CHECK_EQUAL(1ul, l.size());
CHECK_EQUAL(5, l.front()->data);
l.pop_front();
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(Previous)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
MyNode node2;
node2.data = 10;
l.push_front(&node2);
rde::intrusive_slist<MyNode>::iterator it = l.begin();
++it;
rde::intrusive_slist<MyNode>::iterator itPrev = l.previous(it);
CHECK(itPrev == l.begin());
}
TEST(Clear)
{
rde::intrusive_slist<MyNode> l;
l.push_front(new MyNode(5));
l.push_front(new MyNode(6));
l.push_front(new MyNode(7));
l.push_front(new MyNode(8));
CHECK_EQUAL(4ul, l.size());
l.clear();
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(GetIterator)
{
rde::intrusive_slist<MyNode> l;
l.push_front(new MyNode(5));
l.push_front(new MyNode(6));
MyNode* n(new MyNode(7));
l.push_front(n);
l.push_front(new MyNode(8));
rde::intrusive_slist<MyNode>::iterator it = l.get_iterator(n);
CHECK_EQUAL(7, it->data);
}
}
<commit_msg>Bugfixes - memory leaks<commit_after>#include <UnitTest++/src/UnitTest++.h>
#include "rdestl/intrusive_slist.h"
namespace
{
struct MyNode : public rde::intrusive_slist_node
{
explicit MyNode(int i = 0): data(i) {}
int data;
};
TEST(DefaultCtorConstructsEmptyList)
{
rde::intrusive_slist<MyNode> l;
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(PushFront)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
CHECK_EQUAL(1ul, l.size());
MyNode node2;
node2.data = 10;
l.push_front(&node2);
CHECK_EQUAL(2ul, l.size());
CHECK_EQUAL(10, l.front()->data);
}
TEST(PopFront)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
MyNode node2;
node2.data = 10;
l.push_front(&node2);
MyNode node3;
node3.data = 15;
l.push_front(&node3);
CHECK_EQUAL(3ul, l.size());
l.pop_front();
CHECK_EQUAL(2ul, l.size());
CHECK_EQUAL(10, l.front()->data);
l.pop_front();
CHECK_EQUAL(1ul, l.size());
CHECK_EQUAL(5, l.front()->data);
l.pop_front();
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(Previous)
{
rde::intrusive_slist<MyNode> l;
MyNode node;
node.data = 5;
l.push_front(&node);
MyNode node2;
node2.data = 10;
l.push_front(&node2);
rde::intrusive_slist<MyNode>::iterator it = l.begin();
++it;
rde::intrusive_slist<MyNode>::iterator itPrev = l.previous(it);
CHECK(itPrev == l.begin());
}
TEST(Clear)
{
rde::intrusive_slist<MyNode> l;
MyNode n0(5); l.push_front(&n0);
MyNode n1(6); l.push_front(&n1);
MyNode n2(7); l.push_front(&n2);
MyNode n3(8); l.push_front(&n3);
CHECK_EQUAL(4ul, l.size());
l.clear();
CHECK(l.empty());
CHECK_EQUAL(0ul, l.size());
}
TEST(GetIterator)
{
rde::intrusive_slist<MyNode> l;
MyNode n0(5); l.push_front(&n0);
MyNode n1(6); l.push_front(&n1);
MyNode* n(new MyNode(7));
l.push_front(n);
MyNode n2(8); l.push_front(&n2);
rde::intrusive_slist<MyNode>::iterator it = l.get_iterator(n);
CHECK_EQUAL(7, it->data);
delete n;
}
}
<|endoftext|> |
<commit_before>#include "eventgenerator.h"
#include "parse.h"
#include "eventgeneratorfactory.h"
#include <thread.h>
#include <vector>
using namespace std;
EventGenerator*
EventGenerator::parse(char *filename)
{
ifstream in(filename);
if(!in) {
cerr << "no such file " << filename << endl;
threadexitsall(0);
}
string line;
EventGenerator *gen = 0;
while(getline(in,line)) {
vector<string> words = split(line);
// skip empty lines and commented lines
if(words.empty() || words[0][0] == '#')
continue;
// read generator string
if(words[0] != "generator") {
cerr << "first line in event file should be ``generator [G]''" << endl;
exit(-1);
}
words.erase(words.begin());
string generator = words[0];
words.erase(words.begin());
gen = EventGeneratorFactory::Instance()->create(generator, &words);
break;
}
if(!gen) {
cerr << "the generator you specified is unknown" << endl;
exit(-1);
}
// leave the rest of the file to the specific generator
gen->parse(in);
return gen;
}
<commit_msg>fix strib's compiler error<commit_after>#include "eventgenerator.h"
#include "parse.h"
#include "eventgeneratorfactory.h"
#include <lib9.h>
#include <thread.h>
#include <vector>
using namespace std;
EventGenerator*
EventGenerator::parse(char *filename)
{
ifstream in(filename);
if(!in) {
cerr << "no such file " << filename << endl;
threadexitsall(0);
}
string line;
EventGenerator *gen = 0;
while(getline(in,line)) {
vector<string> words = split(line);
// skip empty lines and commented lines
if(words.empty() || words[0][0] == '#')
continue;
// read generator string
if(words[0] != "generator") {
cerr << "first line in event file should be ``generator [G]''" << endl;
exit(-1);
}
words.erase(words.begin());
string generator = words[0];
words.erase(words.begin());
gen = EventGeneratorFactory::Instance()->create(generator, &words);
break;
}
if(!gen) {
cerr << "the generator you specified is unknown" << endl;
exit(-1);
}
// leave the rest of the file to the specific generator
gen->parse(in);
return gen;
}
<|endoftext|> |
<commit_before>#include "FanDefinition.h"
#include "ui/UIWebView.h"
#include "../compiler.h"
#include "../TilesImage.h"
#include "../mahjong-algorithm/stringify.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../widget/LoadingView.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_PLATFORM_OS_TVOS)
#define HAS_WEBVIEW 1
#else
#define HAS_WEBVIEW 0
#endif
USING_NS_CC;
static std::vector<std::string> g_principles;
static std::vector<std::string> g_definitions;
static void replaceTilesToImage(std::string &text, float scale) {
char tilesStr[128];
mahjong::tile_t tiles[14];
long tilesCnt;
char imgStr[1024];
std::string::size_type pos = text.find('[');
while (pos != std::string::npos) {
const char *str = text.c_str();
int readLen;
if (sscanf(str + pos + 1, "%[^]]%n", tilesStr, &readLen) != EOF
&& str[pos + readLen + 1] == ']'
&& (tilesCnt = mahjong::parse_tiles(tilesStr, tiles, 14)) >= 0) {
size_t totalWriteLen = 0;
for (long i = 0; i < tilesCnt; ++i) {
int writeLen = snprintf(imgStr + totalWriteLen, sizeof(imgStr) - totalWriteLen,
"<img src=\"%s\" width=\"%d\" height=\"%d\"/>",
tilesImageName[tiles[i]], (int)(TILE_WIDTH * scale), (int)(TILE_HEIGHT * scale));
totalWriteLen += writeLen;
}
text.replace(pos, readLen + 2, imgStr);
pos = text.find('[', pos + totalWriteLen);
}
else {
pos = text.find('[', pos + 1);
}
}
}
Scene *FanDefinitionScene::create(size_t idx) {
auto scene = new (std::nothrow) FanDefinitionScene();
scene->initWithIndex(idx);
scene->autorelease();
return scene;
}
bool FanDefinitionScene::initWithIndex(size_t idx) {
const char *title = idx < 100 ? mahjong::fan_name[idx] : principle_title[idx - 100];
if (UNLIKELY(!BaseScene::initWithTitle(title))) {
return false;
}
if (LIKELY(!g_definitions.empty() && !g_principles.empty())) {
createContentView(idx);
return true;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
LoadingView *loadingView = LoadingView::create();
this->addChild(loadingView);
loadingView->setPosition(origin);
#if HAS_WEBVIEW
float scale = 1.0f;
float maxWidth = (visibleSize.width - 10) / 18;
if (maxWidth < 25) {
scale = maxWidth / TILE_WIDTH;
}
#else
float scale = 1.0f / Director::getInstance()->getContentScaleFactor();
#endif
auto thiz = makeRef(this); // 保证线程回来之前不析构
std::thread([thiz, idx, scale, loadingView]() {
// 读文件
if (g_definitions.empty()) {
ValueVector valueVec = FileUtils::getInstance()->getValueVectorFromFile("text/score_definition.xml");
g_definitions.reserve(valueVec.size());
std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(g_definitions), [scale](const Value &value) {
std::string ret = value.asString();
replaceTilesToImage(ret, scale);
return std::move(ret);
});
}
if (g_principles.empty()) {
ValueVector valueVec = FileUtils::getInstance()->getValueVectorFromFile("text/score_principles.xml");
g_principles.reserve(valueVec.size());
std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(g_principles), [scale](const Value &value) {
std::string ret = value.asString();
replaceTilesToImage(ret, scale);
return std::move(ret);
});
}
// 切换到cocos线程
Director::getInstance()->getScheduler()->performFunctionInCocosThread([thiz, idx, loadingView]() {
if (LIKELY(thiz->isRunning())) {
loadingView->removeFromParent();
thiz->createContentView(idx);
}
});
}).detach();
return true;
}
void FanDefinitionScene::createContentView(size_t idx) {
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
const std::string &text = idx < 100 ? g_definitions[idx] : g_principles[idx - 100];
#if HAS_WEBVIEW
experimental::ui::WebView *webView = experimental::ui::WebView::create();
webView->setContentSize(Size(visibleSize.width, visibleSize.height - 35));
webView->setOnEnterCallback(std::bind(&experimental::ui::WebView::loadHTMLString, webView, std::ref(text), ""));
this->addChild(webView);
webView->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f - 15.0f));
#else
ui::RichText *richText = ui::RichText::createWithXML("<font face=\"Verdana\" size=\"12\" color=\"#000000\">" + text + "</font>");
richText->setContentSize(Size(visibleSize.width - 10, 0));
richText->ignoreContentAdaptWithSize(false);
richText->setVerticalSpace(2);
richText->formatText();
this->addChild(richText);
richText->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 40.0f));
#endif
}
<commit_msg>可能潜在线程问题<commit_after>#include "FanDefinition.h"
#include "ui/UIWebView.h"
#include "../compiler.h"
#include "../TilesImage.h"
#include "../mahjong-algorithm/stringify.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../widget/LoadingView.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_PLATFORM_OS_TVOS)
#define HAS_WEBVIEW 1
#else
#define HAS_WEBVIEW 0
#endif
USING_NS_CC;
static std::vector<std::string> g_principles;
static std::vector<std::string> g_definitions;
static void replaceTilesToImage(std::string &text, float scale) {
char tilesStr[128];
mahjong::tile_t tiles[14];
long tilesCnt;
char imgStr[1024];
std::string::size_type pos = text.find('[');
while (pos != std::string::npos) {
const char *str = text.c_str();
int readLen;
if (sscanf(str + pos + 1, "%[^]]%n", tilesStr, &readLen) != EOF
&& str[pos + readLen + 1] == ']'
&& (tilesCnt = mahjong::parse_tiles(tilesStr, tiles, 14)) >= 0) {
size_t totalWriteLen = 0;
for (long i = 0; i < tilesCnt; ++i) {
int writeLen = snprintf(imgStr + totalWriteLen, sizeof(imgStr) - totalWriteLen,
"<img src=\"%s\" width=\"%d\" height=\"%d\"/>",
tilesImageName[tiles[i]], (int)(TILE_WIDTH * scale), (int)(TILE_HEIGHT * scale));
totalWriteLen += writeLen;
}
text.replace(pos, readLen + 2, imgStr);
pos = text.find('[', pos + totalWriteLen);
}
else {
pos = text.find('[', pos + 1);
}
}
}
Scene *FanDefinitionScene::create(size_t idx) {
auto scene = new (std::nothrow) FanDefinitionScene();
scene->initWithIndex(idx);
scene->autorelease();
return scene;
}
bool FanDefinitionScene::initWithIndex(size_t idx) {
const char *title = idx < 100 ? mahjong::fan_name[idx] : principle_title[idx - 100];
if (UNLIKELY(!BaseScene::initWithTitle(title))) {
return false;
}
if (LIKELY(g_definitions.size() == 82 && g_principles.size() == 5)) {
createContentView(idx);
return true;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
LoadingView *loadingView = LoadingView::create();
this->addChild(loadingView);
loadingView->setPosition(origin);
#if HAS_WEBVIEW
float scale = 1.0f;
float maxWidth = (visibleSize.width - 10) / 18;
if (maxWidth < 25) {
scale = maxWidth / TILE_WIDTH;
}
#else
float scale = 1.0f / Director::getInstance()->getContentScaleFactor();
#endif
auto thiz = makeRef(this); // 保证线程回来之前不析构
std::thread([thiz, idx, scale, loadingView]() {
// 读文件
std::vector<std::string> definitions;
ValueVector valueVec = FileUtils::getInstance()->getValueVectorFromFile("text/score_definition.xml");
if (valueVec.size() == 82) {
definitions.reserve(82);
std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(definitions), [scale](const Value &value) {
std::string ret = value.asString();
replaceTilesToImage(ret, scale);
return std::move(ret);
});
}
std::vector<std::string> principles;
valueVec = FileUtils::getInstance()->getValueVectorFromFile("text/score_principles.xml");
if (valueVec.size() == 5) {
principles.reserve(5);
std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(principles), [scale](const Value &value) {
std::string ret = value.asString();
replaceTilesToImage(ret, scale);
return std::move(ret);
});
}
// 切换到cocos线程
Director::getInstance()->getScheduler()->performFunctionInCocosThread([thiz, idx, loadingView, definitions, principles]() mutable {
g_definitions.swap(definitions);
g_principles.swap(principles);
if (LIKELY(thiz->isRunning())) {
loadingView->removeFromParent();
thiz->createContentView(idx);
}
});
}).detach();
return true;
}
void FanDefinitionScene::createContentView(size_t idx) {
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
const std::string &text = idx < 100 ? g_definitions[idx] : g_principles[idx - 100];
#if HAS_WEBVIEW
experimental::ui::WebView *webView = experimental::ui::WebView::create();
webView->setContentSize(Size(visibleSize.width, visibleSize.height - 35));
webView->setOnEnterCallback(std::bind(&experimental::ui::WebView::loadHTMLString, webView, std::ref(text), ""));
this->addChild(webView);
webView->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f - 15.0f));
#else
ui::RichText *richText = ui::RichText::createWithXML("<font face=\"Verdana\" size=\"12\" color=\"#000000\">" + text + "</font>");
richText->setContentSize(Size(visibleSize.width - 10, 0));
richText->ignoreContentAdaptWithSize(false);
richText->setVerticalSpace(2);
richText->formatText();
this->addChild(richText);
richText->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 40.0f));
#endif
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, 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 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.
*
* $Id: organized.hpp 3220 2011-11-21 15:50:53Z koenbuys $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
typename pcl::search::FlannSearch<PointT>::IndexPtr
pcl::search::FlannSearch<PointT>::KdTreeIndexCreator::createIndex (const flann::Matrix<float> &data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<flann::L2<float> > (data,flann::KDTreeSingleIndexParams (15))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::FlannSearch(FlannIndexCreator *creator)
:creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_.ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists)
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
indices.resize (k,-1);
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances)
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof(PointT)/sizeof(float) : dim_ );
flann::SearchParams p;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,radius*radius, p);
delete [] data;
indices=i [0];
distances=d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, int max_nn)
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof(PointT)/sizeof(float) : dim_ );
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
index_->radiusSearch (m,k_indices,k_sqr_distances,radius*radius, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
index_->radiusSearch (m, k_indices, k_sqr_distances, radius * radius, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::convertInputToFlannMatrix ()
{
int original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_.ptr();
input_copied_for_flann_ = true;
identity_mapping_ = true;
input_flann_ = flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ());
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = input_flann_.ptr();
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
/// TODO: implement "no NaN check" option that just re-uses the cloud data in the flann matrix
for (int i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (i); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
else
{
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (indices_index); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
input_flann_.rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<commit_msg> * FlannSearch: adapted use of flann::Matrix to new semantics of the 'stride' parameter, fixing incorrect results and a crash<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, 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 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.
*
* $Id: organized.hpp 3220 2011-11-21 15:50:53Z koenbuys $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
typename pcl::search::FlannSearch<PointT>::IndexPtr
pcl::search::FlannSearch<PointT>::KdTreeIndexCreator::createIndex (const flann::Matrix<float> &data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<flann::L2<float> > (data,flann::KDTreeSingleIndexParams (15))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::FlannSearch(FlannIndexCreator *creator)
:creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_.ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists)
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
indices.resize (k,-1);
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances)
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float) );
flann::SearchParams p;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,radius*radius, p);
delete [] data;
indices=i [0];
distances=d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, int max_nn)
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
index_->radiusSearch (m,k_indices,k_sqr_distances,radius*radius, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.eps = eps_;
p.max_neighbors = max_nn;
index_->radiusSearch (m, k_indices, k_sqr_distances, radius * radius, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::convertInputToFlannMatrix ()
{
int original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_.ptr();
input_copied_for_flann_ = true;
identity_mapping_ = true;
input_flann_ = flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ());
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = input_flann_.ptr();
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
/// TODO: implement "no NaN check" option that just re-uses the cloud data in the flann matrix
for (int i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (i); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
else
{
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (indices_index); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
input_flann_.rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConnectionPageSetup.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2007-04-26 07:56:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_CONNECTIONPAGESETUP_HXX
#include "ConnectionPageSetup.hxx"
#endif
#ifndef _DBAUI_AUTOCONTROLS_HRC_
#include "AutoControls.hrc"
#endif
#ifndef _DBAUI_DBADMINSETUP_HRC_
#include "dbadminsetup.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _DBAUI_DBADMIN_HXX_
#include "dbadmin.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HRC_
#include "dbadmin.hrc"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif
#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
// #106016# ------------------------------------
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XPROGRESSHANDLER_HPP_
#include <com/sun/star/ucb/XProgressHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _UCBHELPER_COMMANDENVIRONMENT_HXX
#include <ucbhelper/commandenvironment.hxx>
#endif
#ifndef DBAUI_FILEPICKER_INTERACTION_HXX
#include "finteraction.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SV_MNEMONIC_HXX
#include <vcl/mnemonic.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
using namespace ::svt;
OGenericAdministrationPage* OConnectionTabPageSetup::CreateDbaseTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_DBASE, _rAttrSet, STR_DBASE_HELPTEXT, STR_DBASE_HEADERTEXT, STR_DBASE_PATH_OR_FILE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateMSAccessTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_MSACCESS, _rAttrSet, STR_MSACCESS_HELPTEXT, STR_MSACCESS_HEADERTEXT, STR_MSACCESS_MDB_FILE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateAdabasTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADABAS, _rAttrSet, STR_ADABAS_HELPTEXT, STR_ADABAS_HEADERTEXT, STR_ADABAS_DATABASE_NAME);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateADOTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADO, _rAttrSet, STR_ADO_HELPTEXT, STR_ADO_HEADERTEXT, STR_COMMONURL);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateODBCTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ODBC, _rAttrSet, STR_ODBC_HELPTEXT, STR_ODBC_HEADERTEXT, STR_NAME_OF_ODBC_DATASOURCE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateUserDefinedTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_USERDEFINED, _rAttrSet, USHRT_MAX, USHRT_MAX, STR_COMMONURL);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
//========================================================================
//= OConnectionTabPageSetup
//========================================================================
DBG_NAME(OConnectionTabPageSetup)
OConnectionTabPageSetup::OConnectionTabPageSetup(Window* pParent, USHORT _rId, const SfxItemSet& _rCoreAttrs, USHORT _nHelpTextResId, USHORT _nHeaderResId, USHORT _nUrlResId)
:OConnectionHelper(pParent, ModuleRes(_rId), _rCoreAttrs)
,m_bUserGrabFocus(sal_True)
,m_aFT_HelpText(this, ModuleRes(FT_AUTOWIZARDHELPTEXT))
{
DBG_CTOR(OConnectionTabPageSetup, NULL);
if ( USHRT_MAX != _nHelpTextResId )
{
String sHelpText = String(ModuleRes(_nHelpTextResId));
m_aFT_HelpText.SetText(sHelpText);
}
else
m_aFT_HelpText.Hide();
if ( USHRT_MAX != _nHeaderResId )
SetHeaderText(this, FT_AUTOWIZARDHEADER, _nHeaderResId);
if ( USHRT_MAX != _nUrlResId )
{
String sLabelText = String(ModuleRes(_nUrlResId));
m_aFT_Connection.SetText(sLabelText);
if ( USHRT_MAX == _nHelpTextResId )
{
Point aPos = m_aFT_HelpText.GetPosPixel();
Point aFTPos = m_aFT_Connection.GetPosPixel();
Point aEDPos = m_aET_Connection.GetPosPixel();
Point aPBPos = m_aPB_Connection.GetPosPixel();
aEDPos.Y() = aPos.Y() + aEDPos.Y() - aFTPos.Y();
aPBPos.Y() = aPos.Y() + aPBPos.Y() - aFTPos.Y();
aFTPos.Y() = aPos.Y();
m_aFT_Connection.SetPosPixel(aFTPos);
m_aET_Connection.SetPosPixel(aEDPos);
m_aPB_Connection.SetPosPixel(aPBPos);
}
}
else
m_aFT_Connection.Hide();
m_aET_Connection.SetModifyHdl(LINK(this, OConnectionTabPageSetup, OnEditModified));
SetRoadmapStateValue(sal_False);
}
// -----------------------------------------------------------------------
OConnectionTabPageSetup::~OConnectionTabPageSetup()
{
DBG_DTOR(OConnectionTabPageSetup,NULL);
}
// -----------------------------------------------------------------------
void OConnectionTabPageSetup::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue)
{
m_eType = m_pAdminDialog->getDatasourceType(_rSet);
// special handling for oracle, this can only happen
// if the user enters the same url as used for Oracle and we are on the JDBC path
if ( DST_ORACLE_JDBC == m_eType )
m_eType = DST_JDBC;
OConnectionHelper::implInitControls(_rSet, _bSaveValue);
if ( m_eType >= DST_USERDEFINE1 )
{
String sDisplayName = m_pCollection->getTypeDisplayName(m_eType);
FixedText* ppTextControls[] ={&m_aFT_Connection};
for (size_t i = 0; i < sizeof(ppTextControls)/sizeof(ppTextControls[0]); ++i)
{
ppTextControls[i]->SetText(sDisplayName);
}
}
callModifiedHdl();
}
// -----------------------------------------------------------------------
sal_Bool OConnectionTabPageSetup::commitPage(COMMIT_REASON /*_eReason*/)
{
return commitURL();
}
// -----------------------------------------------------------------------
sal_Bool OConnectionTabPageSetup::FillItemSet(SfxItemSet& _rSet)
{
sal_Bool bChangedSomething = sal_False;
fillString(_rSet,&m_aET_Connection, DSID_CONNECTURL, bChangedSomething);
return bChangedSomething;
}
// -----------------------------------------------------------------------
bool OConnectionTabPageSetup::checkTestConnection()
{
return !m_aET_Connection.IsVisible() || (m_aET_Connection.GetTextNoPrefix().Len() != 0);
}
// -----------------------------------------------------------------------
IMPL_LINK(OConnectionTabPageSetup, OnEditModified, Edit*, /*_pEdit*/)
{
SetRoadmapStateValue(checkTestConnection());
callModifiedHdl();
return 0L;
}
// -----------------------------------------------------------------------
void OConnectionTabPageSetup::toggleURLControlGroup(BOOL _bEnable)
{
m_aET_Connection.Enable(_bEnable);
m_aPB_Connection.Enable(_bEnable);
m_aFT_Connection.Enable(_bEnable);
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS dba23a (1.7.72); FILE MERGED 2007/03/13 08:42:12 fs 1.7.72.2: some slight re-factoring (class/method renaming), plus some rudimentary fix for #b6532894# 2007/02/26 10:34:00 fs 1.7.72.1: remove unused code Issue number: #i74776# Submitted by: jnavrati@openoffice.org Reviewed by: frank.schoenheit@sun.com<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConnectionPageSetup.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:22:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_CONNECTIONPAGESETUP_HXX
#include "ConnectionPageSetup.hxx"
#endif
#ifndef _DBAUI_AUTOCONTROLS_HRC_
#include "AutoControls.hrc"
#endif
#ifndef _DBAUI_DBADMINSETUP_HRC_
#include "dbadminsetup.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _DBAUI_DBADMIN_HXX_
#include "dbadmin.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HRC_
#include "dbadmin.hrc"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif
#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
// #106016# ------------------------------------
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XPROGRESSHANDLER_HPP_
#include <com/sun/star/ucb/XProgressHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _UCBHELPER_COMMANDENVIRONMENT_HXX
#include <ucbhelper/commandenvironment.hxx>
#endif
#ifndef DBAUI_FILEPICKER_INTERACTION_HXX
#include "finteraction.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SV_MNEMONIC_HXX
#include <vcl/mnemonic.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
using namespace ::svt;
OGenericAdministrationPage* OConnectionTabPageSetup::CreateDbaseTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_DBASE, _rAttrSet, STR_DBASE_HELPTEXT, STR_DBASE_HEADERTEXT, STR_DBASE_PATH_OR_FILE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateMSAccessTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_MSACCESS, _rAttrSet, STR_MSACCESS_HELPTEXT, STR_MSACCESS_HEADERTEXT, STR_MSACCESS_MDB_FILE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateAdabasTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADABAS, _rAttrSet, STR_ADABAS_HELPTEXT, STR_ADABAS_HEADERTEXT, STR_ADABAS_DATABASE_NAME);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateADOTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADO, _rAttrSet, STR_ADO_HELPTEXT, STR_ADO_HEADERTEXT, STR_COMMONURL);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateODBCTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ODBC, _rAttrSet, STR_ODBC_HELPTEXT, STR_ODBC_HEADERTEXT, STR_NAME_OF_ODBC_DATASOURCE);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
OGenericAdministrationPage* OConnectionTabPageSetup::CreateUserDefinedTabPage( Window* pParent, const SfxItemSet& _rAttrSet )
{
OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_USERDEFINED, _rAttrSet, USHRT_MAX, USHRT_MAX, STR_COMMONURL);
oDBWizardPage->FreeResource();
return oDBWizardPage;
}
//========================================================================
//= OConnectionTabPageSetup
//========================================================================
DBG_NAME(OConnectionTabPageSetup)
OConnectionTabPageSetup::OConnectionTabPageSetup(Window* pParent, USHORT _rId, const SfxItemSet& _rCoreAttrs, USHORT _nHelpTextResId, USHORT _nHeaderResId, USHORT _nUrlResId)
:OConnectionHelper(pParent, ModuleRes(_rId), _rCoreAttrs)
,m_bUserGrabFocus(sal_True)
,m_aFT_HelpText(this, ModuleRes(FT_AUTOWIZARDHELPTEXT))
{
DBG_CTOR(OConnectionTabPageSetup, NULL);
if ( USHRT_MAX != _nHelpTextResId )
{
String sHelpText = String(ModuleRes(_nHelpTextResId));
m_aFT_HelpText.SetText(sHelpText);
}
else
m_aFT_HelpText.Hide();
if ( USHRT_MAX != _nHeaderResId )
SetHeaderText(FT_AUTOWIZARDHEADER, _nHeaderResId);
if ( USHRT_MAX != _nUrlResId )
{
String sLabelText = String(ModuleRes(_nUrlResId));
m_aFT_Connection.SetText(sLabelText);
if ( USHRT_MAX == _nHelpTextResId )
{
Point aPos = m_aFT_HelpText.GetPosPixel();
Point aFTPos = m_aFT_Connection.GetPosPixel();
Point aEDPos = m_aET_Connection.GetPosPixel();
Point aPBPos = m_aPB_Connection.GetPosPixel();
aEDPos.Y() = aPos.Y() + aEDPos.Y() - aFTPos.Y();
aPBPos.Y() = aPos.Y() + aPBPos.Y() - aFTPos.Y();
aFTPos.Y() = aPos.Y();
m_aFT_Connection.SetPosPixel(aFTPos);
m_aET_Connection.SetPosPixel(aEDPos);
m_aPB_Connection.SetPosPixel(aPBPos);
}
}
else
m_aFT_Connection.Hide();
m_aET_Connection.SetModifyHdl(LINK(this, OConnectionTabPageSetup, OnEditModified));
SetRoadmapStateValue(sal_False);
}
// -----------------------------------------------------------------------
OConnectionTabPageSetup::~OConnectionTabPageSetup()
{
DBG_DTOR(OConnectionTabPageSetup,NULL);
}
// -----------------------------------------------------------------------
void OConnectionTabPageSetup::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue)
{
m_eType = m_pAdminDialog->getDatasourceType(_rSet);
// special handling for oracle, this can only happen
// if the user enters the same url as used for Oracle and we are on the JDBC path
if ( DST_ORACLE_JDBC == m_eType )
m_eType = DST_JDBC;
OConnectionHelper::implInitControls(_rSet, _bSaveValue);
if ( m_eType >= DST_USERDEFINE1 )
{
String sDisplayName = m_pCollection->getTypeDisplayName(m_eType);
FixedText* ppTextControls[] ={&m_aFT_Connection};
for (size_t i = 0; i < sizeof(ppTextControls)/sizeof(ppTextControls[0]); ++i)
{
ppTextControls[i]->SetText(sDisplayName);
}
}
callModifiedHdl();
}
// -----------------------------------------------------------------------
sal_Bool OConnectionTabPageSetup::commitPage(COMMIT_REASON /*_eReason*/)
{
return commitURL();
}
// -----------------------------------------------------------------------
sal_Bool OConnectionTabPageSetup::FillItemSet(SfxItemSet& _rSet)
{
sal_Bool bChangedSomething = sal_False;
fillString(_rSet,&m_aET_Connection, DSID_CONNECTURL, bChangedSomething);
return bChangedSomething;
}
// -----------------------------------------------------------------------
bool OConnectionTabPageSetup::checkTestConnection()
{
return !m_aET_Connection.IsVisible() || (m_aET_Connection.GetTextNoPrefix().Len() != 0);
}
// -----------------------------------------------------------------------
IMPL_LINK(OConnectionTabPageSetup, OnEditModified, Edit*, /*_pEdit*/)
{
SetRoadmapStateValue(checkTestConnection());
callModifiedHdl();
return 0L;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMandelbrotSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMandelbrotSource.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkImageMandelbrotSource, "1.30");
vtkStandardNewMacro(vtkImageMandelbrotSource);
//----------------------------------------------------------------------------
vtkImageMandelbrotSource::vtkImageMandelbrotSource()
{
this->MaximumNumberOfIterations = 100;
this->WholeExtent[0] = 0;
this->WholeExtent[1] = 250;
this->WholeExtent[2] = 0;
this->WholeExtent[3] = 250;
this->WholeExtent[4] = 0;
this->WholeExtent[5] = 0;
this->SampleCX[0] = 0.01;
this->SampleCX[1] = 0.01;
this->SampleCX[2] = 0.01;
this->SampleCX[3] = 0.01;
this->OriginCX[0] = -1.75;
this->OriginCX[1] = -1.25;
this->OriginCX[2] = 0.0;
this->OriginCX[3] = 0.0;
this->ProjectionAxes[0] = 0;
this->ProjectionAxes[1] = 1;
this->ProjectionAxes[2] = 2;
}
//----------------------------------------------------------------------------
vtkImageMandelbrotSource::~vtkImageMandelbrotSource()
{
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "OriginC: (" << this->OriginCX[0] << ", "
<< this->OriginCX[1] << ")\n";
os << indent << "OriginX: (" << this->OriginCX[2] << ", "
<< this->OriginCX[3] << ")\n";
os << indent << "SampleC: (" << this->SampleCX[0] << ", "
<< this->SampleCX[1] << ")\n";
os << indent << "SampleX: (" << this->SampleCX[2] << ", "
<< this->SampleCX[3] << ")\n";
os << indent << "WholeExtent: (" << this->WholeExtent[0] << ", "
<< this->WholeExtent[1] << ", " << this->WholeExtent[2] << ", "
<< this->WholeExtent[3] << ", " << this->WholeExtent[4] << ", "
<< this->WholeExtent[5] << ")\n";
os << "MaximumNumberOfIterations: " << this->MaximumNumberOfIterations << endl;
os << indent << "ProjectionAxes: (" << this->ProjectionAxes[0] << ", "
<< this->ProjectionAxes[1] << this->ProjectionAxes[2] << ")\n";
}
//----------------------------------------------------------------------------
/*
void vtkImageMandelbrotSource::SetOriginCX(double cReal, double cImag,
double xReal, double xImag)
{
int modified = 0;
if (cReal != this->OriginCX[0])
{
this->OriginCX[0] = cReal;
modified = 1;
}
if (cImag != this->OriginCX[1])
{
this->OriginCX[1] = cImag;
modified = 1;
}
if (xReal != this->OriginCX[2])
{
this->OriginCX[2] = xReal;
modified = 1;
}
if (xImag != this->OriginCX[3])
{
this->OriginCX[3] = xImag;
modified = 1;
}
if (modified)
{
this->Modified();
}
}
*/
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::SetWholeExtent(int extent[6])
{
int idx, modified = 0;
for (idx = 0; idx < 6; ++idx)
{
if (this->WholeExtent[idx] != extent[idx])
{
this->WholeExtent[idx] = extent[idx];
this->Modified();
}
}
if (modified)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::SetWholeExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetWholeExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::ExecuteInformation()
{
int idx, axis;
float origin[3];
float spacing[3];
vtkImageData *output = this->GetOutput();
output->SetWholeExtent(this->WholeExtent);
for (idx = 0; idx < 3; ++idx)
{
axis = this->ProjectionAxes[idx];
if (axis >= 0 && axis < 4)
{
origin[idx] = this->OriginCX[axis];
spacing[idx] = this->SampleCX[axis];
}
else
{
vtkErrorMacro("Bad projection axis.");
origin[idx] = 0.0;
spacing[idx] = 1.0;
}
}
output->SetSpacing(spacing);
output->SetOrigin(origin);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_FLOAT);
}
//----------------------------------------------------------------------------
// We may want separate zooms for mandelbrot and julia.
void vtkImageMandelbrotSource::Zoom(double factor)
{
if (factor == 1.0)
{
return;
}
this->Modified();
this->SampleCX[0] *= factor;
this->SampleCX[1] *= factor;
this->SampleCX[2] *= factor;
this->SampleCX[3] *= factor;
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::Pan(double x, double y, double z)
{
int idx, axis;
double pan[3];
if (x == 0.0 && y == 0.0 && z == 0.0)
{
return;
}
this->Modified();
pan[0]=x; pan[1]=y; pan[2]=z;
for (idx = 0; idx < 3; ++idx)
{
axis = this->ProjectionAxes[idx];
if (axis >= 0 && axis < 4)
{
this->OriginCX[axis] += this->SampleCX[axis] * pan[idx];
}
}
}
//----------------------------------------------------------------------------
void
vtkImageMandelbrotSource::CopyOriginAndSample(vtkImageMandelbrotSource *source)
{
int idx;
for (idx = 0; idx < 4; ++idx)
{
this->OriginCX[idx] = source->OriginCX[idx];
this->SampleCX[idx] = source->SampleCX[idx];
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
int *ext, a0, a1, a2;
float *ptr;
int min0, max0;
int idx0, idx1, idx2;
int inc0, inc1, inc2;
double *origin, *sample;
double p[4];
unsigned long count = 0;
unsigned long target;
// Copy origin into pixel
for (idx0 = 0; idx0 < 4; ++idx0)
{
p[idx0] = this->OriginCX[idx0];
}
ext = data->GetUpdateExtent();
ptr = (float *)(data->GetScalarPointerForExtent(ext));
vtkDebugMacro("Generating Extent: " << ext[0] << " -> " << ext[1] << ", "
<< ext[2] << " -> " << ext[3]);
// Get min and max of axis 0 because it is the innermost loop.
min0 = ext[0];
max0 = ext[1];
data->GetContinuousIncrements(ext, inc0, inc1, inc2);
target = (unsigned long)((ext[5]-ext[4]+1)*(ext[3]-ext[2]+1)/50.0);
target++;
a0 = this->ProjectionAxes[0];
a1 = this->ProjectionAxes[1];
a2 = this->ProjectionAxes[2];
origin = this->OriginCX;
sample = this->SampleCX;
if (a0<0 || a1<0 || a2<0 || a0>3 || a1>3 || a2>3)
{
vtkErrorMacro("Bad projection axis");
return;
}
for (idx2 = ext[4]; idx2 <= ext[5]; ++idx2)
{
p[a2] = (double)(origin[a2]) + (double)(idx2)*(sample[a2]);
for (idx1 = ext[2]; !this->AbortExecute && idx1 <= ext[3]; ++idx1)
{
if (!(count%target))
{
this->UpdateProgress(count/(50.0*target));
}
count++;
p[a1] = (double)(origin[a1]) + (double)(idx1)*(sample[a1]);
for (idx0 = min0; idx0 <= max0; ++idx0)
{
p[a0] = (double)(origin[a0]) + (double)(idx0)*(sample[a0]);
*ptr = (float)(this->EvaluateSet(p));
++ptr;
// inc0 is 0
}
ptr += inc1;
}
ptr += inc2;
}
// Name the array appropriately.
data->GetPointData()->GetScalars()->SetName("Iterations");
}
//----------------------------------------------------------------------------
// This method selectively supersamples pixels closet to the mandelbrot set.
/*
void vtkImageMandelbrotSource::SuperSample(vtkImageData *data)
{
int *ext;
float *ptr0, *ptr1, *ptr2;
int min0, max0;
int idx0, idx1, idx2;
int inc0, inc1, inc2;
// Get min and max of axis 0 because it is the innermost loop.
ext = data->GetUpdateExtent();
min0 = ext[0];
max0 = ext[1];
data->GetIncrements(inc0, inc1, inc2);
// loop through pixels ignoring the borders.
ptr2 = (float *)(data->GetScalarPointer(min0+1, ext[2]+1, ext[4]+1));
for (idx2 = ext[4]+1; idx2 < ext[5]; ++idx2)
{
ptr1 = ptr2;
for (idx1 = ext[2]+1; idx1 < ext[3]; ++idx1)
{
ptr0 = ptr1;
for (idx0 = min0+1; idx0 < max0; ++idx0)
{
*ptr0 = (float*)(this->EvaluateSet(p));
++ptr0;
// inc0 is 1
}
ptr1 += inc1;
}
ptr2 += inc2;
}
}
*/
//----------------------------------------------------------------------------
float vtkImageMandelbrotSource::EvaluateSet(double p[4])
{
unsigned short count = 0;
double v0, v1;
double cReal, cImag, zReal, zImag;
double zReal2, zImag2;
cReal = p[0];
cImag = p[1];
zReal = p[2];
zImag = p[3];
zReal2 = zReal * zReal;
zImag2 = zImag * zImag;
v0 = 0.0;
v1 = (zReal2 + zImag2);
while ( v1 < 4.0 && count < this->MaximumNumberOfIterations)
{
zImag = 2.0 * zReal * zImag + cImag;
zReal = zReal2 - zImag2 + cReal;
zReal2 = zReal * zReal;
zImag2 = zImag * zImag;
++count;
v0 = v1;
v1 = (zReal2 + zImag2);
}
if (count == this->MaximumNumberOfIterations)
{
return (float)count;
}
return (float)count + (4.0 - v0)/(v1 - v0);
}
<commit_msg>Missed this file yesterday.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMandelbrotSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMandelbrotSource.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkImageMandelbrotSource, "1.31");
vtkStandardNewMacro(vtkImageMandelbrotSource);
//----------------------------------------------------------------------------
vtkImageMandelbrotSource::vtkImageMandelbrotSource()
{
this->MaximumNumberOfIterations = 100;
this->WholeExtent[0] = 0;
this->WholeExtent[1] = 250;
this->WholeExtent[2] = 0;
this->WholeExtent[3] = 250;
this->WholeExtent[4] = 0;
this->WholeExtent[5] = 0;
this->SampleCX[0] = 0.01;
this->SampleCX[1] = 0.01;
this->SampleCX[2] = 0.01;
this->SampleCX[3] = 0.01;
this->SizeCX[0] = 2.5;
this->SizeCX[1] = 2.5;
this->SizeCX[2] = 2.5;
this->SizeCX[3] = 2.5;
this->ConstantSize = 1;
this->OriginCX[0] = -1.75;
this->OriginCX[1] = -1.25;
this->OriginCX[2] = 0.0;
this->OriginCX[3] = 0.0;
this->ProjectionAxes[0] = 0;
this->ProjectionAxes[1] = 1;
this->ProjectionAxes[2] = 2;
}
//----------------------------------------------------------------------------
vtkImageMandelbrotSource::~vtkImageMandelbrotSource()
{
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "OriginC: (" << this->OriginCX[0] << ", "
<< this->OriginCX[1] << ")\n";
os << indent << "OriginX: (" << this->OriginCX[2] << ", "
<< this->OriginCX[3] << ")\n";
os << indent << "SampleC: (" << this->SampleCX[0] << ", "
<< this->SampleCX[1] << ")\n";
os << indent << "SampleX: (" << this->SampleCX[2] << ", "
<< this->SampleCX[3] << ")\n";
double *size = this->GetSizeCX();
os << indent << "SizeC: (" << size[0] << ", " << size[1] << ")\n";
os << indent << "SizeX: (" << size[2] << ", " << size[3] << ")\n";
if (this->ConstantSize)
{
os << indent << "ConstantSize\n";
}
else
{
os << indent << "ConstantSpacing\n";
}
os << indent << "WholeExtent: (" << this->WholeExtent[0] << ", "
<< this->WholeExtent[1] << ", " << this->WholeExtent[2] << ", "
<< this->WholeExtent[3] << ", " << this->WholeExtent[4] << ", "
<< this->WholeExtent[5] << ")\n";
os << "MaximumNumberOfIterations: " << this->MaximumNumberOfIterations << endl;
os << indent << "ProjectionAxes: (" << this->ProjectionAxes[0] << ", "
<< this->ProjectionAxes[1] << this->ProjectionAxes[2] << ")\n";
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::SetWholeExtent(int extent[6])
{
int idx, modified = 0;
double saveSize[4];
this->GetSizeCX(saveSize);
for (idx = 0; idx < 6; ++idx)
{
if (this->WholeExtent[idx] != extent[idx])
{
this->WholeExtent[idx] = extent[idx];
modified = 1;
}
}
if (modified)
{
this->Modified();
if (this->ConstantSize)
{
this->SetSizeCX(saveSize[0], saveSize[1], saveSize[2], saveSize[3]);
}
}
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::SetWholeExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetWholeExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::SetSizeCX(double cReal, double cImag,
double xReal, double xImag)
{
int axis;
int idx;
int d;
double *s = this->GetSizeCX();
if (s[0] == cReal && s[1] == cImag && s[2] == xReal && s[3] == xImag)
{
return;
}
this->Modified();
// Set this because information can be carried over for collapsed axes.
this->SizeCX[0] = cReal;
this->SizeCX[1] = cImag;
this->SizeCX[2] = xReal;
this->SizeCX[3] = xImag;
// Now compute the gold standard (for non collapsed axes.
for (idx = 0; idx < 3; ++idx)
{
d = this->WholeExtent[idx*2+1] - this->WholeExtent[idx*2];
if (d > 0)
{
axis = this->ProjectionAxes[idx];
this->SampleCX[axis] = this->SizeCX[axis] / ((double) d);
}
}
}
//----------------------------------------------------------------------------
double* vtkImageMandelbrotSource::GetSizeCX()
{
int axis;
int idx;
int d;
// Recompute the size for the spacing (gold standard).
for (idx = 0; idx < 3; ++idx)
{
d = this->WholeExtent[idx*2+1] - this->WholeExtent[idx*2];
if (d > 0)
{
axis = this->ProjectionAxes[idx];
this->SizeCX[axis] = this->SampleCX[axis] * ((double) d);
}
}
return this->SizeCX;
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::GetSizeCX(double s[4])
{
double *p = this->GetSizeCX();
s[0] = p[0];
s[1] = p[1];
s[2] = p[2];
s[3] = p[3];
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::ExecuteInformation()
{
int idx, axis;
float origin[3];
float spacing[3];
vtkImageData *output = this->GetOutput();
output->SetWholeExtent(this->WholeExtent);
for (idx = 0; idx < 3; ++idx)
{
axis = this->ProjectionAxes[idx];
if (axis >= 0 && axis < 4)
{
origin[idx] = this->OriginCX[axis];
spacing[idx] = this->SampleCX[axis];
}
else
{
vtkErrorMacro("Bad projection axis.");
origin[idx] = 0.0;
spacing[idx] = 1.0;
}
}
output->SetSpacing(spacing);
output->SetOrigin(origin);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_FLOAT);
}
//----------------------------------------------------------------------------
// We may want separate zooms for mandelbrot and julia.
void vtkImageMandelbrotSource::Zoom(double factor)
{
if (factor == 1.0)
{
return;
}
this->Modified();
this->SampleCX[0] *= factor;
this->SampleCX[1] *= factor;
this->SampleCX[2] *= factor;
this->SampleCX[3] *= factor;
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::Pan(double x, double y, double z)
{
int idx, axis;
double pan[3];
if (x == 0.0 && y == 0.0 && z == 0.0)
{
return;
}
this->Modified();
pan[0]=x; pan[1]=y; pan[2]=z;
for (idx = 0; idx < 3; ++idx)
{
axis = this->ProjectionAxes[idx];
if (axis >= 0 && axis < 4)
{
this->OriginCX[axis] += this->SampleCX[axis] * pan[idx];
}
}
}
//----------------------------------------------------------------------------
void
vtkImageMandelbrotSource::CopyOriginAndSample(vtkImageMandelbrotSource *source)
{
int idx;
for (idx = 0; idx < 4; ++idx)
{
this->OriginCX[idx] = source->OriginCX[idx];
this->SampleCX[idx] = source->SampleCX[idx];
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkImageMandelbrotSource::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
int *ext, a0, a1, a2;
float *ptr;
int min0, max0;
int idx0, idx1, idx2;
int inc0, inc1, inc2;
double *origin, *sample;
double p[4];
unsigned long count = 0;
unsigned long target;
// Copy origin into pixel
for (idx0 = 0; idx0 < 4; ++idx0)
{
p[idx0] = this->OriginCX[idx0];
}
ext = data->GetUpdateExtent();
ptr = (float *)(data->GetScalarPointerForExtent(ext));
vtkDebugMacro("Generating Extent: " << ext[0] << " -> " << ext[1] << ", "
<< ext[2] << " -> " << ext[3]);
// Get min and max of axis 0 because it is the innermost loop.
min0 = ext[0];
max0 = ext[1];
data->GetContinuousIncrements(ext, inc0, inc1, inc2);
target = (unsigned long)((ext[5]-ext[4]+1)*(ext[3]-ext[2]+1)/50.0);
target++;
a0 = this->ProjectionAxes[0];
a1 = this->ProjectionAxes[1];
a2 = this->ProjectionAxes[2];
origin = this->OriginCX;
sample = this->SampleCX;
if (a0<0 || a1<0 || a2<0 || a0>3 || a1>3 || a2>3)
{
vtkErrorMacro("Bad projection axis");
return;
}
for (idx2 = ext[4]; idx2 <= ext[5]; ++idx2)
{
p[a2] = (double)(origin[a2]) + (double)(idx2)*(sample[a2]);
for (idx1 = ext[2]; !this->AbortExecute && idx1 <= ext[3]; ++idx1)
{
if (!(count%target))
{
this->UpdateProgress(count/(50.0*target));
}
count++;
p[a1] = (double)(origin[a1]) + (double)(idx1)*(sample[a1]);
for (idx0 = min0; idx0 <= max0; ++idx0)
{
p[a0] = (double)(origin[a0]) + (double)(idx0)*(sample[a0]);
*ptr = (float)(this->EvaluateSet(p));
++ptr;
// inc0 is 0
}
ptr += inc1;
}
ptr += inc2;
}
// Name the array appropriately.
data->GetPointData()->GetScalars()->SetName("Iterations");
}
//----------------------------------------------------------------------------
float vtkImageMandelbrotSource::EvaluateSet(double p[4])
{
unsigned short count = 0;
double v0, v1;
double cReal, cImag, zReal, zImag;
double zReal2, zImag2;
cReal = p[0];
cImag = p[1];
zReal = p[2];
zImag = p[3];
zReal2 = zReal * zReal;
zImag2 = zImag * zImag;
v0 = 0.0;
v1 = (zReal2 + zImag2);
while ( v1 < 4.0 && count < this->MaximumNumberOfIterations)
{
zImag = 2.0 * zReal * zImag + cImag;
zReal = zReal2 - zImag2 + cReal;
zReal2 = zReal * zReal;
zImag2 = zImag * zImag;
++count;
v0 = v1;
v1 = (zReal2 + zImag2);
}
if (count == this->MaximumNumberOfIterations)
{
return (float)count;
}
return (float)count + (4.0 - v0)/(v1 - v0);
}
<|endoftext|> |
<commit_before>/***********************************************************************
query.cpp - Implements the Query class.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "query.h"
namespace mysqlpp {
Query::Query(const Query& q) :
SQLQuery(q),
OptionalExceptions(q.exceptions()),
Lockable(),
conn_(q.conn_)
{
}
bool Query::exec(const std::string& str)
{
Success = !mysql_real_query(&conn_->mysql, str.c_str(),
str.length());
if (!Success && throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return Success;
}
}
bool Query::success()
{
if (Success) {
return conn_->success();
}
else {
return false;
}
}
/// \if INTERNAL
// Doxygen will not generate documentation for this section.
ResNSel Query::execute(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return ResNSel();
}
}
Success = !mysql_query(&conn_->mysql, str);
unlock();
if (Success) {
return ResNSel(conn_);
}
else {
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return ResNSel();
}
}
}
ResNSel Query::execute(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return execute(str(p, r).c_str());
}
ResUse Query::use(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return ResUse();
}
}
Success = !mysql_query(&conn_->mysql, str);
if (Success) {
MYSQL_RES* res = mysql_use_result(&conn_->mysql);
if (res) {
unlock();
return ResUse(res, conn_, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return ResUse();
}
}
ResUse Query::use(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return use(str(p, r).c_str());
}
Result Query::store(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return Result();
}
}
Success = !mysql_query(&conn_->mysql, str);
if (Success) {
MYSQL_RES* res = mysql_store_result(&conn_->mysql);
if (res) {
unlock();
return Result(res, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return Result();
}
}
Result Query::store(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return store(str(p, r).c_str());
}
/// \endif
my_ulonglong Query::affected_rows() const
{
return conn_->affected_rows();
}
my_ulonglong Query::insert_id()
{
return conn_->insert_id();
}
std::string Query::info()
{
return conn_->info();
}
std::string Query::error()
{
if (errmsg) {
return std::string(errmsg);
}
else {
return conn_->error();
}
}
bool Query::lock()
{
return conn_->lock();
}
void Query::unlock()
{
conn_->unlock();
}
} // end namespace mysqlpp
<commit_msg>Alphabetized functions in query.cpp. This will make it clearer in the diff what came from where in coming SQLQuery merge.<commit_after>/***********************************************************************
query.cpp - Implements the Query class.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "query.h"
namespace mysqlpp {
Query::Query(const Query& q) :
SQLQuery(q),
OptionalExceptions(q.exceptions()),
Lockable(),
conn_(q.conn_)
{
}
my_ulonglong Query::affected_rows() const
{
return conn_->affected_rows();
}
std::string Query::error()
{
if (errmsg) {
return std::string(errmsg);
}
else {
return conn_->error();
}
}
bool Query::exec(const std::string& str)
{
Success = !mysql_real_query(&conn_->mysql, str.c_str(),
str.length());
if (!Success && throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return Success;
}
}
ResNSel Query::execute(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return ResNSel();
}
}
Success = !mysql_query(&conn_->mysql, str);
unlock();
if (Success) {
return ResNSel(conn_);
}
else {
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return ResNSel();
}
}
}
ResNSel Query::execute(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return execute(str(p, r).c_str());
}
std::string Query::info()
{
return conn_->info();
}
my_ulonglong Query::insert_id()
{
return conn_->insert_id();
}
bool Query::lock()
{
return conn_->lock();
}
Result Query::store(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return Result();
}
}
Success = !mysql_query(&conn_->mysql, str);
if (Success) {
MYSQL_RES* res = mysql_store_result(&conn_->mysql);
if (res) {
unlock();
return Result(res, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return Result();
}
}
Result Query::store(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return store(str(p, r).c_str());
}
bool Query::success()
{
if (Success) {
return conn_->success();
}
else {
return false;
}
}
void Query::unlock()
{
conn_->unlock();
}
ResUse Query::use(const char* str)
{
Success = false;
if (lock()) {
if (throw_exceptions()) {
throw BadQuery("lock failed");
}
else {
return ResUse();
}
}
Success = !mysql_query(&conn_->mysql, str);
if (Success) {
MYSQL_RES* res = mysql_use_result(&conn_->mysql);
if (res) {
unlock();
return ResUse(res, conn_, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(conn_->error());
}
else {
return ResUse();
}
}
ResUse Query::use(parms& p)
{
query_reset r = parsed.size() ? DONT_RESET : RESET_QUERY;
return use(str(p, r).c_str());
}
} // end namespace mysqlpp
<|endoftext|> |
<commit_before>// https://projecteuler.net/problem=68
/*
Magic 5-gon ring
Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each
line adding to nine.
4
\
\
3
/ \
/ \
1-----2-----6
/
/
5
Working clockwise, and starting from the group of three with the numerically lowest
external node (4,3,2 in this example), each solution can be described uniquely.
For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.
It is possible to complete the ring with four different totals: 9, 10, 11, and 12.
There are eight solutions in total.
Total Solution Set
9 4,2,3; 5,3,1; 6,1,2
9 4,3,2; 6,2,1; 5,1,3
10 2,3,5; 4,5,1; 6,1,3
10 2,5,3; 6,3,1; 4,1,5
11 1,4,6; 3,6,2; 5,2,4
11 1,6,4; 5,4,2; 3,2,6
12 1,5,6; 2,6,4; 3,4,5
12 1,6,5; 3,5,4; 2,4,6
By concatenating each group it is possible to form 9-digit strings;
the maximum string for a 3-gon ring is 432621513.
Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16-
and 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring?
Solution:
Create all possible pairs of adjacent internal nodes e.g. in case of 3-gon 1-2,1-3,1-4,
1-5,1-6, 2-1,2-3,2-4,... etc.
Given the sum create outer node as sum - total of pair of internal nodes. That will
create all the possible lines for the given sum. If the outer node is zero in the line
that means that line is impossible for the given sum.
Now, run a dfs by selecting 1 internal node at a time from the possible lines. Mask can
be used to avoid duplicate. An internal mask can also be used to avoid visiting different
rotations of the same solution.
*/
#include <iostream>
#include <cstdint>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <chrono>
std::vector<std::vector<int>> lines;
int polygon, maxNumber, imask;
std::vector<int> ngon;
std::set<std::string> solutions;
void addSolution() {
using namespace std;
vector<vector<int>> tbl;
for (int i = 1; i < maxNumber; i += 2)
tbl.push_back({ ngon[i], ngon[i - 1], ngon[(i + 1 < maxNumber) ? (i + 1) : 0] });
auto idx = min_element(begin(tbl), end(tbl), [](const auto& a1, const auto& a2) {
return a1[0] < a2[0];
}) - begin(tbl);
string rep;
for (int i = 0; i < polygon; i++, idx = (idx + 1) % polygon)
rep += to_string(tbl[idx][0]) + to_string(tbl[idx][1]) + to_string(tbl[idx][2]);
solutions.insert(rep);
}
void dfs(int mask, int idx) {
if (idx == maxNumber - 2) {
const auto k = lines[ngon[idx]][ngon[0]];
if (k && !(mask&(1 << k))) {
ngon[idx + 1] = k;
addSolution();
}
return;
}
for (int i = 1; i <= maxNumber; ++i) {
if (!(mask & (1 << i)) && !(imask & (1 << i))) {
const auto k = lines[ngon[idx]][i];
if (k && !(mask&(1 << k))) {
ngon[idx + 1] = k;
ngon[idx + 2] = i;
dfs(mask | (1 << i) | (1 << k), idx + 2);
}
}
}
}
void generate(int sum) {
solutions.clear();
lines.clear();
for (int i = 0; i <= maxNumber; ++i) {
std::vector<int> line = { 0 };
for (int j = 1; j <= maxNumber; ++j) {
const int k = sum - i - j;
line.push_back((k > 0 && k <= maxNumber && k != i && k != j) ? k : 0);
}
lines.emplace_back(line);
}
imask = 0;
for (int i = 1; i <= polygon + 1; ++i) {
ngon[0] = i;
imask |= 1 << i;
dfs(1 << i, 0);
}
}
auto compute() {
polygon = 5;
maxNumber = 2 * polygon;
ngon.resize(maxNumber);
generate(14);
std::string max;
for (const auto& rep : solutions)
if (rep.length() == 16 && rep > max)
max = rep;
return max;
}
int main() {
using namespace std;
using namespace chrono;
auto start = high_resolution_clock::now();
auto result = compute();
cout << "Done in "
<< duration_cast<nanoseconds>(high_resolution_clock::now() - start).count() / 1000000.0
<< " miliseconds." << endl;
cout << result << endl;
}<commit_msg>spacing in problem statement<commit_after>// https://projecteuler.net/problem=68
/*
Magic 5-gon ring
Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each
line adding to nine.
4
\
\
3
/ \
/ \
1-----2-----6
/
/
5
Working clockwise, and starting from the group of three with the numerically lowest
external node (4,3,2 in this example), each solution can be described uniquely.
For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.
It is possible to complete the ring with four different totals: 9, 10, 11, and 12.
There are eight solutions in total.
Total Solution Set
9 4,2,3; 5,3,1; 6,1,2
9 4,3,2; 6,2,1; 5,1,3
10 2,3,5; 4,5,1; 6,1,3
10 2,5,3; 6,3,1; 4,1,5
11 1,4,6; 3,6,2; 5,2,4
11 1,6,4; 5,4,2; 3,2,6
12 1,5,6; 2,6,4; 3,4,5
12 1,6,5; 3,5,4; 2,4,6
By concatenating each group it is possible to form 9-digit strings;
the maximum string for a 3-gon ring is 432621513.
Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16-
and 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring?
Solution:
Create all possible pairs of adjacent internal nodes e.g. in case of 3-gon 1-2,1-3,1-4,
1-5,1-6, 2-1,2-3,2-4,... etc.
Given the sum create outer node as sum - total of pair of internal nodes. That will
create all the possible lines for the given sum. If the outer node is zero in the line
that means that line is impossible for the given sum.
Now, run a dfs by selecting 1 internal node at a time from the possible lines. Mask can
be used to avoid duplicate. An internal mask can also be used to avoid visiting different
rotations of the same solution.
*/
#include <iostream>
#include <cstdint>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <chrono>
std::vector<std::vector<int>> lines;
int polygon, maxNumber, imask;
std::vector<int> ngon;
std::set<std::string> solutions;
void addSolution() {
using namespace std;
vector<vector<int>> tbl;
for (int i = 1; i < maxNumber; i += 2)
tbl.push_back({ ngon[i], ngon[i - 1], ngon[(i + 1 < maxNumber) ? (i + 1) : 0] });
auto idx = min_element(begin(tbl), end(tbl), [](const auto& a1, const auto& a2) {
return a1[0] < a2[0];
}) - begin(tbl);
string rep;
for (int i = 0; i < polygon; i++, idx = (idx + 1) % polygon)
rep += to_string(tbl[idx][0]) + to_string(tbl[idx][1]) + to_string(tbl[idx][2]);
solutions.insert(rep);
}
void dfs(int mask, int idx) {
if (idx == maxNumber - 2) {
const auto k = lines[ngon[idx]][ngon[0]];
if (k && !(mask&(1 << k))) {
ngon[idx + 1] = k;
addSolution();
}
return;
}
for (int i = 1; i <= maxNumber; ++i) {
if (!(mask & (1 << i)) && !(imask & (1 << i))) {
const auto k = lines[ngon[idx]][i];
if (k && !(mask&(1 << k))) {
ngon[idx + 1] = k;
ngon[idx + 2] = i;
dfs(mask | (1 << i) | (1 << k), idx + 2);
}
}
}
}
void generate(int sum) {
solutions.clear();
lines.clear();
for (int i = 0; i <= maxNumber; ++i) {
std::vector<int> line = { 0 };
for (int j = 1; j <= maxNumber; ++j) {
const int k = sum - i - j;
line.push_back((k > 0 && k <= maxNumber && k != i && k != j) ? k : 0);
}
lines.emplace_back(line);
}
imask = 0;
for (int i = 1; i <= polygon + 1; ++i) {
ngon[0] = i;
imask |= 1 << i;
dfs(1 << i, 0);
}
}
auto compute() {
polygon = 5;
maxNumber = 2 * polygon;
ngon.resize(maxNumber);
generate(14);
std::string max;
for (const auto& rep : solutions)
if (rep.length() == 16 && rep > max)
max = rep;
return max;
}
int main() {
using namespace std;
using namespace chrono;
auto start = high_resolution_clock::now();
auto result = compute();
cout << "Done in "
<< duration_cast<nanoseconds>(high_resolution_clock::now() - start).count() / 1000000.0
<< " miliseconds." << endl;
cout << result << endl;
}<|endoftext|> |
<commit_before>//
// Created by Miguel Rentes on 30/01/2017.
//
#include "STL.h"
void printKMax(int arr[], int n, int k) {
deque<int> mydeque;
int greatest = 0;
int value = 0;
int index = 0;
std::deque<int>::iterator it;
for (int i = 0; i < n; i++) {
mydeque.push_front(arr[i]);
}
for (int i = 0; i <= n-k; i++) {
it = mydeque.begin();
while (index < k) {
value = *it;
if (value > greatest)
greatest = value;
it++;
index++;
}
mydeque.pop_front();
mydeque.push_back(greatest);
greatest = 0;
index = 0;
}
for (int i = 0; i <= n-k; i++) {
cout << mydeque.back() << " ";
mydeque.pop_back();
}
cout << endl;
}
int main(void) {
int t;
cin >> t;
while (t > 0) {
int n, k;
cin >> n >> k;
int i;
int arr[n];
for (i = 0; i < n; i++)
cin >> arr[i];
printKMax(arr, n, k);
t--;
}
return EXIT_SUCCESS;
}<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>//
// Created by Miguel Rentes on 30/01/2017.
//
#include "STL.h"
void printKMax(int arr[], int n, int k) {
deque<int> mydeque;
int greatest = 0;
int value = 0;
int index = 0;
int iteration = 0;
// pushing all the greatest values on each k-elements to the front of the deque
for (int i = 0; i < n; ) {
if (index < k) {
value = arr[i];
if (value > greatest)
greatest = value;
if (index == k - 1) {
mydeque.push_front(greatest);
greatest = 0;
index = 0;
iteration++;
i = iteration;
} else {
index++;
i++;
}
}
}
// pop-ing the greatest values from the back of the deque
while(mydeque.size() > 0) {
cout << mydeque.back() << " ";
mydeque.pop_back();
}
cout << endl;
}
int main(void) {
int t;
cin >> t;
while (t > 0) {
int n, k;
cin >> n >> k;
int i;
int arr[n];
for (i = 0; i < n; i++)
cin >> arr[i];
printKMax(arr, n, k);
t--;
}
return EXIT_SUCCESS;
}<|endoftext|> |
<commit_before>#include <osgTerrain/TerrainTile>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
// _tileID
static bool checkTileID( const osgTerrain::TerrainTile& tile )
{
return tile.getTileID().valid();
}
static bool readTileID( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
osgTerrain::TileID id;
is >> id.level >> id.x >> id.y;
tile.setTileID( id );
return true;
}
static bool writeTileID( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
const osgTerrain::TileID& id = tile.getTileID();
os << id.level << id.x << id.y << std::endl;
return true;
}
// _colorLayers
static bool checkColorLayers( const osgTerrain::TerrainTile& tile )
{
return tile.getNumColorLayers()>0;
}
static bool readColorLayers( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0; is >> numValidLayers >> osgDB::BEGIN_BRACKET;
for ( unsigned int i=0; i<numValidLayers; ++i )
{
unsigned int layerNum=0; is >> osgDB::PROPERTY("Layer") >> layerNum;
osgTerrain::Layer* layer = dynamic_cast<osgTerrain::Layer*>( is.readObject() );
if ( layer ) tile.setColorLayer( layerNum, layer );
}
is >> osgDB::END_BRACKET;
return true;
}
static bool writeColorLayers( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) ++numValidLayers;
}
os << numValidLayers << osgDB::BEGIN_BRACKET << std::endl;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) os << osgDB::PROPERTY("Layer") << i << tile.getColorLayer(i);
}
os << osgDB::END_BRACKET << std::endl;
return true;
}
REGISTER_OBJECT_WRAPPER( osgTerrain_TerrainTile,
new osgTerrain::TerrainTile,
osgTerrain::TerrainTile,
"osg::Object osg::Node osg::Group osgTerrain::TerrainTile" )
{
ADD_USER_SERIALIZER( TileID ); // _tileID
ADD_OBJECT_SERIALIZER( TerrainTechnique, osgTerrain::TerrainTechnique, NULL ); // _terrainTechnique
ADD_OBJECT_SERIALIZER( Locator, osgTerrain::Locator, NULL ); // _locator
ADD_OBJECT_SERIALIZER( ElevationLayer, osgTerrain::Layer, NULL ); // _elevationLayer
ADD_USER_SERIALIZER( ColorLayers ); // _colorLayers
ADD_BOOL_SERIALIZER( RequiresNormals, true ); // _requiresNormals
ADD_BOOL_SERIALIZER( TreatBoundariesToValidDataAsDefaultValue, false ); // _treatBoundariesToValidDataAsDefaultValue
BEGIN_ENUM_SERIALIZER( BlendingPolicy, INHERIT );
ADD_ENUM_VALUE( INHERIT );
ADD_ENUM_VALUE( DO_NOT_SET_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING_WHEN_ALPHA_PRESENT );
END_ENUM_SERIALIZER(); // BlendingPolicy
}
<commit_msg>From Wang Rui, "A solution for serialziers to call static functions at the end of reading/writing is to use a user serializer. The serialziers/osgManipulator/Draggers.cpp uses a DefaultGeometry serializer to run setupDefaultGeometry() once the reading process is finished, and this can also be applied to load the TerrainTileCallback.<commit_after>#include <osgTerrain/TerrainTile>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
// _tileID
static bool checkTileID( const osgTerrain::TerrainTile& tile )
{
return tile.getTileID().valid();
}
static bool readTileID( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
osgTerrain::TileID id;
is >> id.level >> id.x >> id.y;
tile.setTileID( id );
return true;
}
static bool writeTileID( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
const osgTerrain::TileID& id = tile.getTileID();
os << id.level << id.x << id.y << std::endl;
return true;
}
// _colorLayers
static bool checkColorLayers( const osgTerrain::TerrainTile& tile )
{
return tile.getNumColorLayers()>0;
}
static bool readColorLayers( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0; is >> numValidLayers >> osgDB::BEGIN_BRACKET;
for ( unsigned int i=0; i<numValidLayers; ++i )
{
unsigned int layerNum=0; is >> osgDB::PROPERTY("Layer") >> layerNum;
osgTerrain::Layer* layer = dynamic_cast<osgTerrain::Layer*>( is.readObject() );
if ( layer ) tile.setColorLayer( layerNum, layer );
}
is >> osgDB::END_BRACKET;
return true;
}
static bool writeColorLayers( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) ++numValidLayers;
}
os << numValidLayers << osgDB::BEGIN_BRACKET << std::endl;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) os << osgDB::PROPERTY("Layer") << i << tile.getColorLayer(i);
}
os << osgDB::END_BRACKET << std::endl;
return true;
}
// TileLoadedCallback
static bool checkTileLoadedCallback( const osgTerrain::TerrainTile& tile )
{ return true; }
static bool readTileLoadedCallback( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
if ( osgTerrain::TerrainTile::getTileLoadedCallback().valid() )
osgTerrain::TerrainTile::getTileLoadedCallback()->loaded( &terrainTile, is.getOptions() );
return true;
}
static bool writeTileLoadedCallback( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{ return true; }
REGISTER_OBJECT_WRAPPER( osgTerrain_TerrainTile,
new osgTerrain::TerrainTile,
osgTerrain::TerrainTile,
"osg::Object osg::Node osg::Group osgTerrain::TerrainTile" )
{
ADD_USER_SERIALIZER( TileID ); // _tileID
ADD_OBJECT_SERIALIZER( TerrainTechnique, osgTerrain::TerrainTechnique, NULL ); // _terrainTechnique
ADD_OBJECT_SERIALIZER( Locator, osgTerrain::Locator, NULL ); // _locator
ADD_OBJECT_SERIALIZER( ElevationLayer, osgTerrain::Layer, NULL ); // _elevationLayer
ADD_USER_SERIALIZER( ColorLayers ); // _colorLayers
ADD_BOOL_SERIALIZER( RequiresNormals, true ); // _requiresNormals
ADD_BOOL_SERIALIZER( TreatBoundariesToValidDataAsDefaultValue, false ); // _treatBoundariesToValidDataAsDefaultValue
BEGIN_ENUM_SERIALIZER( BlendingPolicy, INHERIT );
ADD_ENUM_VALUE( INHERIT );
ADD_ENUM_VALUE( DO_NOT_SET_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING_WHEN_ALPHA_PRESENT );
END_ENUM_SERIALIZER(); // BlendingPolicy
ADD_USER_SERIALIZER( TileLoadedCallback );
}
<|endoftext|> |
<commit_before><commit_msg>If you select a date like Jan 31, and you go to a month with less days than that date, show the last day of the new month instead of doing nothing.<commit_after><|endoftext|> |
<commit_before>// @(#)root/base:$Id$
// Author: Bertrand Bellenot 19/06/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRemoteObject //
// //
// The TRemoteObject class provides protocol for browsing ROOT objects //
// from a remote ROOT session. //
// It contains informations on the real remote object as: //
// - Object Properties (i.e. file stat if the object is a TSystemFile) //
// - Object Name //
// - Class Name //
// - TKey Object Name (if the remote object is a TKey) //
// - TKey Class Name (if the remote object is a TKey) //
// - Remote object address //
// //
//////////////////////////////////////////////////////////////////////////
#include "TApplication.h"
#include "TROOT.h"
#include "TRemoteObject.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"
#include "TClass.h"
ClassImp(TRemoteObject);
//______________________________________________________________________________
TRemoteObject::TRemoteObject()
{
// Create a remote object.
fIsFolder = kFALSE;
fRemoteAddress = 0;
}
//______________________________________________________________________________
TRemoteObject::TRemoteObject(const char *name, const char *title,
const char *classname) : TNamed(name, title)
{
// Create a remote object.
fIsFolder = kFALSE;
fClassName = classname;
if ((fClassName == "TSystemDirectory") ||
(fClassName == "TFile"))
fIsFolder = kTRUE;
if (!strcmp(classname, "TSystemDirectory") ||
!strcmp(classname, "TSystemFile")) {
gSystem->GetPathInfo(name, fFileStat);
}
Long_t raddr = (Long_t) this;
fRemoteAddress = raddr;
}
//______________________________________________________________________________
TRemoteObject::~TRemoteObject()
{
// Delete remote object.
}
//______________________________________________________________________________
void TRemoteObject::Browse(TBrowser *b)
{
// Browse remote object.
TList *ret;
TRemoteObject *robj;
const char *file;
if (fClassName == "TSystemFile") {
if (b)
b->ExecuteDefaultAction(this);
return;
}
if (fClassName == "TKey") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
TObject *obj = (TObject *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseKey(\"%s\");", GetName()));
if (b && obj) {
if (obj->IsA()->GetMethodWithPrototype("SetDirectory", "TDirectory*"))
gROOT->ProcessLine(Form("((%s *)0x%lx)->SetDirectory(0);", obj->ClassName(), (ULong_t)obj));
obj->Browse(b);
b->SetRefreshFlag(kTRUE);
}
}
if (fClassName == "TSystemDirectory") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
ret = (TList *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseDirectory(\"%s\");", GetTitle()));
if (ret) {
TIter next(ret);
while ((robj = (TRemoteObject *)next())) {
file = robj->GetName();
if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
continue;
b->Add(robj, robj->GetName());
}
}
return;
}
if (fClassName == "TFile") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
ret = (TList *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseFile(\"%s\");", GetName()));
if (ret) {
TIter next(ret);
while ((robj = (TRemoteObject *)next())) {
//file = robj->GetName();
b->Add(robj, robj->GetName());
}
}
return;
}
}
//______________________________________________________________________________
TList *TRemoteObject::Browse()
{
// Browse OS system directories.
// Collections to keep track of all browser objects that have been
// generated. It's main goal is to prevent the contineous
// allocations of new objects with the same names during browsing.
TList *objects = new TList;
static Int_t level = 0;
const char *name = GetTitle();
TRemoteObject *sdir;
if (GetName()[0] == '.' && GetName()[1] == '.')
SetName(gSystem->BaseName(name));
TSystemDirectory dir(name, name);
TList *files = dir.GetListOfFiles();
if (files) {
files->Sort();
TIter next(files);
TSystemFile *file;
TString fname;
// directories first
while ((file=(TSystemFile*)next())) {
fname = file->GetName();
if (file->IsDirectory()) {
level++;
TString sdirpath;
if (!strcmp(fname.Data(), "."))
sdirpath = name;
else if (!strcmp(fname.Data(), ".."))
sdirpath = gSystem->DirName(name);
else {
sdirpath = name;
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += fname.Data();
}
sdir = new TRemoteObject(fname.Data(), sdirpath.Data(), "TSystemDirectory");
objects->Add(sdir);
level--;
}
}
// then files...
TIter nextf(files);
while ((file=(TSystemFile*)nextf())) {
fname = file->GetName();
if (!file->IsDirectory()) {
sdir = new TRemoteObject(fname.Data(), gSystem->WorkingDirectory(), "TSystemFile");
objects->Add(sdir);
}
}
delete files;
}
return objects;
}
//______________________________________________________________________________
Bool_t TRemoteObject::GetFileStat(FileStat_t *buf)
{
// Get remote file status.
buf->fDev = fFileStat.fDev;
buf->fIno = fFileStat.fIno;
buf->fMode = fFileStat.fMode;
buf->fUid = fFileStat.fUid;
buf->fGid = fFileStat.fGid;
buf->fSize = fFileStat.fSize;
buf->fMtime = fFileStat.fMtime;
buf->fIsLink = fFileStat.fIsLink;
return kTRUE;
}
//______________________________________________________________________________
void TRemoteObject::Streamer(TBuffer &b)
{
// Remote object streamer.
if (b.IsReading()) {
b >> fFileStat.fDev;
b >> fFileStat.fIno;
b >> fFileStat.fMode;
b >> fFileStat.fUid;
b >> fFileStat.fGid;
b >> fFileStat.fSize;
b >> fFileStat.fMtime;
b >> fFileStat.fIsLink;
b >> fIsFolder;
b >> fRemoteAddress;
b >> fClassName;
b >> fKeyObjectName;
b >> fKeyClassName;
}
else {
b << fFileStat.fDev;
b << fFileStat.fIno;
b << fFileStat.fMode;
b << fFileStat.fUid;
b << fFileStat.fGid;
b << fFileStat.fSize;
b << fFileStat.fMtime;
b << fFileStat.fIsLink;
b << fIsFolder;
b << fRemoteAddress;
b << fClassName;
b << fKeyObjectName;
b << fKeyClassName;
}
TNamed::Streamer(b);
}
<commit_msg>fix coverity 10701.<commit_after>// @(#)root/base:$Id$
// Author: Bertrand Bellenot 19/06/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRemoteObject //
// //
// The TRemoteObject class provides protocol for browsing ROOT objects //
// from a remote ROOT session. //
// It contains informations on the real remote object as: //
// - Object Properties (i.e. file stat if the object is a TSystemFile) //
// - Object Name //
// - Class Name //
// - TKey Object Name (if the remote object is a TKey) //
// - TKey Class Name (if the remote object is a TKey) //
// - Remote object address //
// //
//////////////////////////////////////////////////////////////////////////
#include "TApplication.h"
#include "TROOT.h"
#include "TRemoteObject.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"
#include "TClass.h"
ClassImp(TRemoteObject);
//______________________________________________________________________________
TRemoteObject::TRemoteObject()
{
// Create a remote object.
fIsFolder = kFALSE;
fRemoteAddress = 0;
}
//______________________________________________________________________________
TRemoteObject::TRemoteObject(const char *name, const char *title,
const char *classname) : TNamed(name, title)
{
// Create a remote object.
fIsFolder = kFALSE;
fClassName = classname;
if ((fClassName == "TSystemDirectory") ||
(fClassName == "TFile"))
fIsFolder = kTRUE;
if (!strcmp(classname, "TSystemDirectory") ||
!strcmp(classname, "TSystemFile")) {
gSystem->GetPathInfo(name, fFileStat);
}
Long_t raddr = (Long_t) this;
fRemoteAddress = raddr;
}
//______________________________________________________________________________
TRemoteObject::~TRemoteObject()
{
// Delete remote object.
}
//______________________________________________________________________________
void TRemoteObject::Browse(TBrowser *b)
{
// Browse remote object.
TList *ret;
TRemoteObject *robj;
const char *file;
if (fClassName == "TSystemFile") {
if (b)
b->ExecuteDefaultAction(this);
return;
}
if (fClassName == "TKey") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
TObject *obj = (TObject *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseKey(\"%s\");", GetName()));
if (obj) {
if (obj->IsA()->GetMethodWithPrototype("SetDirectory", "TDirectory*"))
gROOT->ProcessLine(Form("((%s *)0x%lx)->SetDirectory(0);", obj->ClassName(), (ULong_t)obj));
obj->Browse(b);
b->SetRefreshFlag(kTRUE);
}
}
if (fClassName == "TSystemDirectory") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
ret = (TList *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseDirectory(\"%s\");", GetTitle()));
if (ret) {
TIter next(ret);
while ((robj = (TRemoteObject *)next())) {
file = robj->GetName();
if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
continue;
b->Add(robj, robj->GetName());
}
}
return;
}
if (fClassName == "TFile") {
if (b->GetRefreshFlag())
b->SetRefreshFlag(kFALSE);
gApplication->SetBit(TApplication::kProcessRemotely);
ret = (TList *)gROOT->ProcessLine(Form("((TApplicationServer *)gApplication)->BrowseFile(\"%s\");", GetName()));
if (ret) {
TIter next(ret);
while ((robj = (TRemoteObject *)next())) {
//file = robj->GetName();
b->Add(robj, robj->GetName());
}
}
return;
}
}
//______________________________________________________________________________
TList *TRemoteObject::Browse()
{
// Browse OS system directories.
// Collections to keep track of all browser objects that have been
// generated. It's main goal is to prevent the contineous
// allocations of new objects with the same names during browsing.
TList *objects = new TList;
static Int_t level = 0;
const char *name = GetTitle();
TRemoteObject *sdir;
if (GetName()[0] == '.' && GetName()[1] == '.')
SetName(gSystem->BaseName(name));
TSystemDirectory dir(name, name);
TList *files = dir.GetListOfFiles();
if (files) {
files->Sort();
TIter next(files);
TSystemFile *file;
TString fname;
// directories first
while ((file=(TSystemFile*)next())) {
fname = file->GetName();
if (file->IsDirectory()) {
level++;
TString sdirpath;
if (!strcmp(fname.Data(), "."))
sdirpath = name;
else if (!strcmp(fname.Data(), ".."))
sdirpath = gSystem->DirName(name);
else {
sdirpath = name;
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += fname.Data();
}
sdir = new TRemoteObject(fname.Data(), sdirpath.Data(), "TSystemDirectory");
objects->Add(sdir);
level--;
}
}
// then files...
TIter nextf(files);
while ((file=(TSystemFile*)nextf())) {
fname = file->GetName();
if (!file->IsDirectory()) {
sdir = new TRemoteObject(fname.Data(), gSystem->WorkingDirectory(), "TSystemFile");
objects->Add(sdir);
}
}
delete files;
}
return objects;
}
//______________________________________________________________________________
Bool_t TRemoteObject::GetFileStat(FileStat_t *buf)
{
// Get remote file status.
buf->fDev = fFileStat.fDev;
buf->fIno = fFileStat.fIno;
buf->fMode = fFileStat.fMode;
buf->fUid = fFileStat.fUid;
buf->fGid = fFileStat.fGid;
buf->fSize = fFileStat.fSize;
buf->fMtime = fFileStat.fMtime;
buf->fIsLink = fFileStat.fIsLink;
return kTRUE;
}
//______________________________________________________________________________
void TRemoteObject::Streamer(TBuffer &b)
{
// Remote object streamer.
if (b.IsReading()) {
b >> fFileStat.fDev;
b >> fFileStat.fIno;
b >> fFileStat.fMode;
b >> fFileStat.fUid;
b >> fFileStat.fGid;
b >> fFileStat.fSize;
b >> fFileStat.fMtime;
b >> fFileStat.fIsLink;
b >> fIsFolder;
b >> fRemoteAddress;
b >> fClassName;
b >> fKeyObjectName;
b >> fKeyClassName;
}
else {
b << fFileStat.fDev;
b << fFileStat.fIno;
b << fFileStat.fMode;
b << fFileStat.fUid;
b << fFileStat.fGid;
b << fFileStat.fSize;
b << fFileStat.fMtime;
b << fFileStat.fIsLink;
b << fIsFolder;
b << fRemoteAddress;
b << fClassName;
b << fKeyObjectName;
b << fKeyClassName;
}
TNamed::Streamer(b);
}
<|endoftext|> |
<commit_before><commit_msg>Continuing to define the bookkeeping<commit_after><|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../Characters/Format.h"
#include "Reader.h"
//// SEEE http://www.zlib.net/zlib_how.html
/// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object
/// where inner loop is done each time through with a CHUNK
#if qHasFeature_ZLib
#include <zlib.h>
#if defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment(lib, "zlib.lib")
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::DataExchange::Compression;
using namespace Stroika::Foundation::Streams;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
void ThrowIfZLibErr_ (int err)
{
// VERY ROUGH DRAFT - probably need a more specific exception object type
if (err != Z_OK) {
switch (err) {
case Z_VERSION_ERROR:
Execution::Throw (Execution::StringException (L"ZLIB Z_VERSION_ERROR"));
case Z_DATA_ERROR:
Execution::Throw (Execution::StringException (L"ZLIB Z_DATA_ERROR"));
case Z_ERRNO:
Execution::Throw (Execution::StringException (Characters::Format (L"ZLIB Z_ERRNO (errno=%d", errno)));
default:
Execution::Throw (Execution::StringException (Characters::Format (L"ZLIB ERR %d", err)));
}
}
}
using Memory::Byte;
struct MyCompressionStream_ : InputStream<Byte>::Ptr {
struct BaseRep_ : public InputStream<Byte>::_IRep {
static constexpr size_t CHUNK = 16384;
Streams::InputStream<Memory::Byte>::Ptr fInStream_;
z_stream fZStream_;
Byte fInBuf_[CHUNK];
SeekOffsetType _fSeekOffset{};
BaseRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: fInStream_ (in)
, fZStream_{}
{
}
virtual ~BaseRep_ () = default;
virtual bool IsSeekable () const override
{
// for now - KISS
return false; // SHOULD allow seekable IFF src is seekable
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fInStream_.Close ();
Assert (fInStream_ == nullptr);
Ensure (not IsOpenRead ());
}
virtual bool IsOpenRead () const
{
return fInStream_ != nullptr;
}
virtual SeekOffsetType GetReadOffset () const override
{
return _fSeekOffset;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
RequireNotReached ();
return SeekOffsetType{};
}
nonvirtual bool _AssureInputAvailableReturnTrueIfAtEOF ()
{
if (fZStream_.avail_in == 0) {
Assert (NEltsOf (fInBuf_) < numeric_limits<uInt>::max ());
fZStream_.avail_in = static_cast<uInt> (fInStream_.Read (begin (fInBuf_), end (fInBuf_)));
fZStream_.next_in = begin (fInBuf_);
}
return fZStream_.avail_in == 0;
}
};
struct DeflateRep_ : BaseRep_ {
DeflateRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: BaseRep_ (in)
{
int level = Z_DEFAULT_COMPRESSION;
ThrowIfZLibErr_ (::deflateInit (&fZStream_, level));
}
virtual ~DeflateRep_ ()
{
Verify (::deflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
Require (intoStart < intoEnd); // API rule for streams
Again:
bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF ();
Require (intoStart < intoEnd);
ptrdiff_t outBufSize = intoEnd - intoStart;
int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
int ret;
switch (ret = ::deflate (&fZStream_, flush)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF and flush == Z_NO_FLUSH) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - INCOMPLETE IMPL
#if 0
if (intoStart == nullptr) {
// Just check if any data available
}
else {
Assert (intoStart < intoEnd);
Again:
if (fZStream_.avail_in == 0) {
Assert (NEltsOf (fInBuf_) < numeric_limits<uInt>::max ());
if (auto o = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) {
fZStream_.avail_in = static_cast<uInt> (*o);
fZStream_.next_in = begin (fInBuf_);
}
else {
return {};
}
}
ptrdiff_t outBufSize = intoEnd - intoStart;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
bool isAtSrcEOF = fZStream_.avail_in == 0;
int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH;
int ret;
switch (ret = ::deflate (&fZStream_, flush)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
#else
// INCOMPLETE - tricky... most common cases easy, but edges hard...
if (fZStream_.avail_out == 0) {
if (fZStream_.avail_in == 0) {
if (Memory::Optional<size_t> tmpAvail = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) {
}
else {
return {};
}
}
}
#endif
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
};
struct InflateRep_ : BaseRep_ {
InflateRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: BaseRep_ (in)
{
// see http://zlib.net/manual.html for meaning of params and http://www.lemoda.net/c/zlib-open-read/ for example
constexpr int windowBits = 15;
constexpr int ENABLE_ZLIB_GZIP = 32;
ThrowIfZLibErr_ (::inflateInit2 (&fZStream_, windowBits | ENABLE_ZLIB_GZIP));
}
virtual ~InflateRep_ ()
{
Verify (::inflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
Require (intoStart < intoEnd); // API rule for streams
Again:
bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF ();
ptrdiff_t outBufSize = intoEnd - intoStart;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
int ret;
switch (ret = ::inflate (&fZStream_, Z_NO_FLUSH)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - incomplete IMPL
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
};
enum Compression { eCompression };
enum DeCompression { eDeCompression };
MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>::Ptr& in)
: InputStream<Byte>::Ptr (make_shared<DeflateRep_> (in))
{
}
MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>::Ptr& in)
: InputStream<Byte>::Ptr (make_shared<InflateRep_> (in))
{
}
};
}
#endif
#if qHasFeature_ZLib
class Zip::Reader::Rep_ : public Reader::_IRep {
public:
virtual InputStream<Byte>::Ptr Compress (const InputStream<Byte>::Ptr& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eCompression, src);
}
virtual InputStream<Byte>::Ptr Decompress (const InputStream<Byte>::Ptr& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src);
}
};
Zip::Reader::Reader ()
: DataExchange::Compression::Reader (make_shared<Rep_> ())
{
}
#endif
<commit_msg>another missed override<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../Characters/Format.h"
#include "Reader.h"
//// SEEE http://www.zlib.net/zlib_how.html
/// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object
/// where inner loop is done each time through with a CHUNK
#if qHasFeature_ZLib
#include <zlib.h>
#if defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment(lib, "zlib.lib")
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::DataExchange::Compression;
using namespace Stroika::Foundation::Streams;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
void ThrowIfZLibErr_ (int err)
{
// VERY ROUGH DRAFT - probably need a more specific exception object type
if (err != Z_OK) {
switch (err) {
case Z_VERSION_ERROR:
Execution::Throw (Execution::StringException (L"ZLIB Z_VERSION_ERROR"));
case Z_DATA_ERROR:
Execution::Throw (Execution::StringException (L"ZLIB Z_DATA_ERROR"));
case Z_ERRNO:
Execution::Throw (Execution::StringException (Characters::Format (L"ZLIB Z_ERRNO (errno=%d", errno)));
default:
Execution::Throw (Execution::StringException (Characters::Format (L"ZLIB ERR %d", err)));
}
}
}
using Memory::Byte;
struct MyCompressionStream_ : InputStream<Byte>::Ptr {
struct BaseRep_ : public InputStream<Byte>::_IRep {
static constexpr size_t CHUNK = 16384;
Streams::InputStream<Memory::Byte>::Ptr fInStream_;
z_stream fZStream_;
Byte fInBuf_[CHUNK];
SeekOffsetType _fSeekOffset{};
BaseRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: fInStream_ (in)
, fZStream_{}
{
}
virtual ~BaseRep_ () = default;
virtual bool IsSeekable () const override
{
// for now - KISS
return false; // SHOULD allow seekable IFF src is seekable
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fInStream_.Close ();
Assert (fInStream_ == nullptr);
Ensure (not IsOpenRead ());
}
virtual bool IsOpenRead () const override
{
return fInStream_ != nullptr;
}
virtual SeekOffsetType GetReadOffset () const override
{
return _fSeekOffset;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
RequireNotReached ();
return SeekOffsetType{};
}
nonvirtual bool _AssureInputAvailableReturnTrueIfAtEOF ()
{
if (fZStream_.avail_in == 0) {
Assert (NEltsOf (fInBuf_) < numeric_limits<uInt>::max ());
fZStream_.avail_in = static_cast<uInt> (fInStream_.Read (begin (fInBuf_), end (fInBuf_)));
fZStream_.next_in = begin (fInBuf_);
}
return fZStream_.avail_in == 0;
}
};
struct DeflateRep_ : BaseRep_ {
DeflateRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: BaseRep_ (in)
{
int level = Z_DEFAULT_COMPRESSION;
ThrowIfZLibErr_ (::deflateInit (&fZStream_, level));
}
virtual ~DeflateRep_ ()
{
Verify (::deflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
Require (intoStart < intoEnd); // API rule for streams
Again:
bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF ();
Require (intoStart < intoEnd);
ptrdiff_t outBufSize = intoEnd - intoStart;
int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
int ret;
switch (ret = ::deflate (&fZStream_, flush)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF and flush == Z_NO_FLUSH) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - INCOMPLETE IMPL
#if 0
if (intoStart == nullptr) {
// Just check if any data available
}
else {
Assert (intoStart < intoEnd);
Again:
if (fZStream_.avail_in == 0) {
Assert (NEltsOf (fInBuf_) < numeric_limits<uInt>::max ());
if (auto o = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) {
fZStream_.avail_in = static_cast<uInt> (*o);
fZStream_.next_in = begin (fInBuf_);
}
else {
return {};
}
}
ptrdiff_t outBufSize = intoEnd - intoStart;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
bool isAtSrcEOF = fZStream_.avail_in == 0;
int flush = isAtSrcEOF ? Z_FINISH : Z_NO_FLUSH;
int ret;
switch (ret = ::deflate (&fZStream_, flush)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
#else
// INCOMPLETE - tricky... most common cases easy, but edges hard...
if (fZStream_.avail_out == 0) {
if (fZStream_.avail_in == 0) {
if (Memory::Optional<size_t> tmpAvail = fInStream_.ReadNonBlocking (begin (fInBuf_), end (fInBuf_))) {
}
else {
return {};
}
}
}
#endif
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
};
struct InflateRep_ : BaseRep_ {
InflateRep_ (const Streams::InputStream<Memory::Byte>::Ptr& in)
: BaseRep_ (in)
{
// see http://zlib.net/manual.html for meaning of params and http://www.lemoda.net/c/zlib-open-read/ for example
constexpr int windowBits = 15;
constexpr int ENABLE_ZLIB_GZIP = 32;
ThrowIfZLibErr_ (::inflateInit2 (&fZStream_, windowBits | ENABLE_ZLIB_GZIP));
}
virtual ~InflateRep_ ()
{
Verify (::inflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
Require (intoStart < intoEnd); // API rule for streams
Again:
bool isAtSrcEOF = _AssureInputAvailableReturnTrueIfAtEOF ();
ptrdiff_t outBufSize = intoEnd - intoStart;
fZStream_.avail_out = static_cast<uInt> (outBufSize);
fZStream_.next_out = intoStart;
int ret;
switch (ret = ::inflate (&fZStream_, Z_NO_FLUSH)) {
case Z_OK:
break;
case Z_STREAM_END:
break;
default:
ThrowIfZLibErr_ (ret);
}
ptrdiff_t pulledOut = outBufSize - fZStream_.avail_out;
Assert (pulledOut <= outBufSize);
if (pulledOut == 0 and not isAtSrcEOF) {
goto Again;
}
_fSeekOffset += pulledOut;
return pulledOut;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API - incomplete IMPL
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
};
enum Compression { eCompression };
enum DeCompression { eDeCompression };
MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>::Ptr& in)
: InputStream<Byte>::Ptr (make_shared<DeflateRep_> (in))
{
}
MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>::Ptr& in)
: InputStream<Byte>::Ptr (make_shared<InflateRep_> (in))
{
}
};
}
#endif
#if qHasFeature_ZLib
class Zip::Reader::Rep_ : public Reader::_IRep {
public:
virtual InputStream<Byte>::Ptr Compress (const InputStream<Byte>::Ptr& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eCompression, src);
}
virtual InputStream<Byte>::Ptr Decompress (const InputStream<Byte>::Ptr& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src);
}
};
Zip::Reader::Reader ()
: DataExchange::Compression::Reader (make_shared<Rep_> ())
{
}
#endif
<|endoftext|> |
<commit_before>#include "UDPSocket.hpp"
#include "Types.hpp"
#include "Experimental.hpp"
#include "CRC32.hpp"
#include "Debug.hpp"
#include "Log.hpp"
namespace MPACK
{
namespace Network
{
UDPSocket::UDPSocket()
: isNonBlocking(false), isBroadcasting(false), isCRC32Enabled(false)
{
socket=Wrapper::Socket(Protocol::UDP);
}
UDPSocket::~UDPSocket()
{
Shutdown();
}
bool UDPSocket::Bind(int port)
{
inAddress.SetAnyAddress();
inAddress.SetPort(port);
if(bind(socket, inAddress.GetAddrPointer(), sizeof(sockaddr)) == 0)
{
return true;
}
return false;
}
void UDPSocket::Shutdown()
{
Wrapper::CloseSocket(socket);
}
int UDPSocket::SetNonBlocking(const bool &mode)
{
if(mode==isNonBlocking)
{
return 0;
}
isNonBlocking = mode;
u_long set = 1;
if(!isNonBlocking)
{
set = 0;
}
#ifdef WINDOWS_PLATFORM
return ioctlsocket(socket, FIONBIO, &set);
#elif defined(LINUX_PLATFORM)
return 0;//ioctl(sock, FIONBIO, &set);
#endif
}
int UDPSocket::SetBroadcast(const bool &mode)
{
if(mode==isBroadcasting)
{
return 0;
}
isBroadcasting=mode;
u_long set = 0;
if(isBroadcasting)
{
set = 1;
}
return Wrapper::SetBroadcast(socket,set);
}
bool UDPSocket::IsNonBlocking() const
{
return isNonBlocking;
}
bool UDPSocket::IsBroadcasting() const
{
return isBroadcasting;
}
void UDPSocket::EnableCRC32()
{
isCRC32Enabled = true;
}
void UDPSocket::DisableCRC32()
{
isCRC32Enabled = false;
}
bool UDPSocket::IsCRC32Enabled() const
{
return isCRC32Enabled;
}
bool UDPSocket::Poll(UDPMessage &message)
{
int flag=0;
if(isNonBlocking)
{
flag=MSG_DONTWAIT;
}
message.Clear();
int ret=Wrapper::GetPacket(socket, message.data, UDPMSG_MAXBUFFERSIZE, flag, lastContact.GetAddrPointer());
if(ret>0)
{
message.length=ret;
if(isCRC32Enabled)
{
if(message.length <= sizeof(uint32))
{
return false;
}
uint32 crcValue = 0;
memcpy(&crcValue, message.data+message.length-sizeof(uint32), sizeof(uint32));
CRC32 crc;
crc.Reset();
crc.AddData(message.data, message.length - sizeof(uint32));
if(crcValue != crc.Get())
{
message.Clear();
return false;
}
else
{
message.length=ret - sizeof(uint32);
}
}
return true;
}
return false;
}
int UDPSocket::SendTo(UDPMessage &message, const SocketAddress &address)
{
int flag=0;
if(message.length == 0)
{
return 0;
}
if(isNonBlocking)
{
flag=MSG_DONTWAIT;
}
if(isCRC32Enabled)
{
message.data[message.length] = 0;
CRC32 crc;
crc.Reset();
crc.AddData(message.data, message.length);
uint32 crcValue = crc.Get();
message.Write((char*)&crcValue, (int)sizeof(crcValue));
}
return Wrapper::SendPacket(socket, message.data, message.length, flag, (const sockaddr*)address.GetAddrPointer());
}
}
}
<commit_msg>Remove unnecesary crc.reset()<commit_after>#include "UDPSocket.hpp"
#include "Types.hpp"
#include "Experimental.hpp"
#include "CRC32.hpp"
#include "Debug.hpp"
#include "Log.hpp"
namespace MPACK
{
namespace Network
{
UDPSocket::UDPSocket()
: isNonBlocking(false), isBroadcasting(false), isCRC32Enabled(false)
{
socket=Wrapper::Socket(Protocol::UDP);
}
UDPSocket::~UDPSocket()
{
Shutdown();
}
bool UDPSocket::Bind(int port)
{
inAddress.SetAnyAddress();
inAddress.SetPort(port);
if(bind(socket, inAddress.GetAddrPointer(), sizeof(sockaddr)) == 0)
{
return true;
}
return false;
}
void UDPSocket::Shutdown()
{
Wrapper::CloseSocket(socket);
}
int UDPSocket::SetNonBlocking(const bool &mode)
{
if(mode==isNonBlocking)
{
return 0;
}
isNonBlocking = mode;
u_long set = 1;
if(!isNonBlocking)
{
set = 0;
}
#ifdef WINDOWS_PLATFORM
return ioctlsocket(socket, FIONBIO, &set);
#elif defined(LINUX_PLATFORM)
return 0;//ioctl(sock, FIONBIO, &set);
#endif
}
int UDPSocket::SetBroadcast(const bool &mode)
{
if(mode==isBroadcasting)
{
return 0;
}
isBroadcasting=mode;
u_long set = 0;
if(isBroadcasting)
{
set = 1;
}
return Wrapper::SetBroadcast(socket,set);
}
bool UDPSocket::IsNonBlocking() const
{
return isNonBlocking;
}
bool UDPSocket::IsBroadcasting() const
{
return isBroadcasting;
}
void UDPSocket::EnableCRC32()
{
isCRC32Enabled = true;
}
void UDPSocket::DisableCRC32()
{
isCRC32Enabled = false;
}
bool UDPSocket::IsCRC32Enabled() const
{
return isCRC32Enabled;
}
bool UDPSocket::Poll(UDPMessage &message)
{
int flag=0;
if(isNonBlocking)
{
flag=MSG_DONTWAIT;
}
message.Clear();
int ret=Wrapper::GetPacket(socket, message.data, UDPMSG_MAXBUFFERSIZE, flag, lastContact.GetAddrPointer());
if(ret>0)
{
message.length=ret;
if(isCRC32Enabled)
{
if(message.length <= sizeof(uint32))
{
return false;
}
uint32 crcValue = 0;
memcpy(&crcValue, message.data+message.length-sizeof(uint32), sizeof(uint32));
CRC32 crc;
crc.Reset();
crc.AddData(message.data, message.length - sizeof(uint32));
if(crcValue != crc.Get())
{
message.Clear();
return false;
}
else
{
message.length=ret - sizeof(uint32);
}
}
return true;
}
return false;
}
int UDPSocket::SendTo(UDPMessage &message, const SocketAddress &address)
{
int flag=0;
if(message.length == 0)
{
return 0;
}
if(isNonBlocking)
{
flag=MSG_DONTWAIT;
}
if(isCRC32Enabled)
{
message.data[message.length] = 0;
CRC32 crc;
crc.AddData(message.data, message.length);
uint32 crcValue = crc.Get();
message.Write((char*)&crcValue, (int)sizeof(crcValue));
}
return Wrapper::SendPacket(socket, message.data, message.length, flag, (const sockaddr*)address.GetAddrPointer());
}
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010-2011 Openismus GmbH.
** Authors: Peter Penz (ppenz@openismus.com)
** Patricia Santana Cruz (patriciasantanacruz@gmail.com)
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "makefileparser.h"
#include <utils/qtcassert.h>
#include <QFile>
#include <QDir>
#include <QFileInfoList>
#include <QMutexLocker>
using namespace AutotoolsProjectManager::Internal;
MakefileParser::MakefileParser(const QString &makefile) :
QObject(),
m_success(false),
m_cancel(false),
m_mutex(),
m_makefile(makefile),
m_executable(),
m_sources(),
m_makefiles(),
m_includePaths(),
m_line(),
m_textStream()
{
}
MakefileParser::~MakefileParser()
{
delete m_textStream.device();
}
bool MakefileParser::parse()
{
m_mutex.lock();
m_cancel = false;
m_mutex.unlock(),
m_success = true;
m_executable.clear();
m_sources.clear();
m_makefiles.clear();
QFile *file = new QFile(m_makefile);
if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QFileInfo info(m_makefile);
m_makefiles.append(info.fileName());
emit status(tr("Parsing %1 in directory %2").arg(info.fileName()).arg(info.absolutePath()));
m_textStream.setDevice(file);
do {
m_line = m_textStream.readLine();
switch (topTarget()) {
case AmDefaultSourceExt: parseDefaultSourceExtensions(); break;
case BinPrograms: parseBinPrograms(); break;
case BuiltSources: break; // TODO: Add to m_sources?
case Sources: parseSources(); break;
case SubDirs: parseSubDirs(); break;
case Undefined:
default: break;
}
} while (!m_line.isNull());
parseIncludePaths();
return m_success;
}
QStringList MakefileParser::sources() const
{
return m_sources;
}
QStringList MakefileParser::makefiles() const
{
return m_makefiles;
}
QString MakefileParser::executable() const
{
return m_executable;
}
QStringList MakefileParser::includePaths() const
{
return m_includePaths;
}
void MakefileParser::cancel()
{
QMutexLocker locker(&m_mutex);
m_cancel = true;
}
bool MakefileParser::isCanceled() const
{
QMutexLocker locker(&m_mutex);
return m_cancel;
}
MakefileParser::TopTarget MakefileParser::topTarget() const
{
TopTarget topTarget = Undefined;
const QString line = m_line.simplified();
if (!line.isEmpty() && !line.startsWith(QLatin1Char('#'))) {
// TODO: Check how many fixed strings like AM_DEFAULT_SOURCE_EXT will
// be needed vs. variable strings like _SOURCES. Dependent on this a
// more clever way than this (expensive) if-cascading might be done.
if (line.startsWith(QLatin1String("AM_DEFAULT_SOURCE_EXT =")))
topTarget = AmDefaultSourceExt;
else if (line.startsWith(QLatin1String("bin_PROGRAMS =")))
topTarget = BinPrograms;
else if (line.startsWith(QLatin1String("BUILT_SOURCES =")))
topTarget = BuiltSources;
else if (line.contains(QLatin1String("SUBDIRS =")))
topTarget = SubDirs;
else if (line.contains(QLatin1String("_SOURCES =")))
topTarget = Sources;
}
return topTarget;
}
void MakefileParser::parseBinPrograms()
{
QTC_ASSERT(m_line.contains(QLatin1String("bin_PROGRAMS")), return);
const QStringList binPrograms = targetValues();
// TODO: are multiple values possible?
if (binPrograms.size() == 1) {
QFileInfo info(binPrograms.first());
m_executable = info.fileName();
}
}
void MakefileParser::parseSources()
{
QTC_ASSERT(m_line.contains(QLatin1String("_SOURCES")), return);
bool hasVariables = false;
m_sources.append(targetValues(&hasVariables));
// Skip parsing of Makefile.am for getting the sub directories,
// as variables have been used. As fallback all sources will be added.
if (hasVariables)
addAllSources();
// Duplicates might be possible in combination with 'AM_DEFAULT_SOURCE_EXT ='
m_sources.removeDuplicates();
// TODO: Definitions like "SOURCES = ../src.cpp" are ignored currently.
// This case must be handled correctly in MakefileParser::parseSubDirs(),
// where the current sub directory must be shortened.
QStringList::iterator it = m_sources.begin();
while (it != m_sources.end()) {
if ((*it).startsWith(QLatin1String("..")))
it = m_sources.erase(it);
else
++it;
}
}
void MakefileParser::parseDefaultSourceExtensions()
{
QTC_ASSERT(m_line.contains(QLatin1String("AM_DEFAULT_SOURCE_EXT")), return);
const QStringList extensions = targetValues();
if (extensions.isEmpty()) {
m_success = false;
return;
}
QFileInfo info(m_makefile);
const QString dirName = info.absolutePath();
m_sources.append(directorySources(dirName, extensions));
// Duplicates might be possible in combination with '_SOURCES ='
m_sources.removeDuplicates();
}
void MakefileParser::parseSubDirs()
{
QTC_ASSERT(m_line.contains(QLatin1String("SUBDIRS")), return);
if (isCanceled()) {
m_success = false;
return;
}
QFileInfo info(m_makefile);
const QString path = info.absolutePath();
const QString makefileName = info.fileName();
bool hasVariables = false;
QStringList subDirs = targetValues(&hasVariables);
if (hasVariables) {
// Skip parsing of Makefile.am for getting the sub directories,
// as variables have been used. As fallback all sources will be added.
addAllSources();
return;
}
// If the SUBDIRS values contain a '.' or a variable like $(test),
// all the sub directories of the current folder must get parsed.
bool hasDotSubDir = false;
QStringList::iterator it = subDirs.begin();
while (it != subDirs.end()) {
// Erase all entries that represent a '.'
if ((*it) == QLatin1String(".")) {
hasDotSubDir = true;
it = subDirs.erase(it);
} else {
++it;
}
}
if (hasDotSubDir) {
// Add all sub directories of the current folder
QDir dir(path);
dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QFileInfo& info, dir.entryInfoList()) {
subDirs.append(info.fileName());
}
}
subDirs.removeDuplicates();
// Delegate the parsing of all sub directories to a local
// makefile parser and merge the results
foreach (const QString& subDir, subDirs) {
const QChar slash = QLatin1Char('/');
const QString subDirMakefile = path + slash + subDir
+ slash + makefileName;
// Parse sub directory
QFile file(subDirMakefile);
// Don't try to parse a file, that might not exist (e. g.
// if SUBDIRS specifies a 'po' directory).
if (!file.exists())
continue;
MakefileParser parser(subDirMakefile);
connect(&parser, SIGNAL(status(QString)), this, SIGNAL(status(QString)));
const bool success = parser.parse();
// Don't return, try to parse as many sub directories
// as possible
if (!success)
m_success = false;
m_makefiles.append(subDir + slash + makefileName);
// Append the sources of the sub directory to the
// current sources
foreach (const QString& source, parser.sources())
m_sources.append(subDir + slash + source);
// Duplicates might be possible in combination with several
// "..._SUBDIRS" targets
m_makefiles.removeDuplicates();
m_sources.removeDuplicates();
}
if (subDirs.isEmpty())
m_success = false;
}
QStringList MakefileParser::directorySources(const QString &directory,
const QStringList &extensions)
{
if (isCanceled()) {
m_success = false;
return QStringList();
}
emit status(tr("Parsing directory %1").arg(directory));
QStringList list; // return value
QDir dir(directory);
dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
const QFileInfoList infos = dir.entryInfoList();
foreach (const QFileInfo& info, infos) {
if (info.isDir()) {
// Append recursively sources from the sub directory
const QStringList subDirSources = directorySources(info.absoluteFilePath(),
extensions);
const QString dirPath = info.fileName();
foreach (const QString& subDirSource, subDirSources)
list.append(dirPath + QLatin1Char('/') + subDirSource);
} else {
// Check whether the file matches to an extension
foreach (const QString& extension, extensions) {
if (info.fileName().endsWith(extension)) {
list.append(info.fileName());
appendHeader(list, dir, info.baseName());
break;
}
}
}
}
return list;
}
QStringList MakefileParser::targetValues(bool *hasVariables)
{
QStringList values;
if (hasVariables != 0)
*hasVariables = false;
const int index = m_line.indexOf(QLatin1Char('='));
if (index < 0) {
m_success = false;
return QStringList();
}
m_line.remove(0, index + 1); // remove the 'target = ' prefix
bool endReached = false;
do {
m_line = m_line.simplified();
// Get all values of a line separated by spaces.
// Values representing a variable like $(value) get
// removed currently.
QStringList lineValues = m_line.split(QLatin1Char(' '));
QStringList::iterator it = lineValues.begin();
while (it != lineValues.end()) {
if ((*it).startsWith(QLatin1String("$("))) {
it = lineValues.erase(it);
if (hasVariables != 0)
*hasVariables = true;
} else {
++it;
}
}
endReached = lineValues.isEmpty();
if (!endReached) {
const QChar backSlash = QLatin1Char('\\');
QString last = lineValues.last();
if (last.endsWith(backSlash)) {
// The last value contains a backslash. Remove the
// backslash and replace the last value.
lineValues.pop_back();
last.remove(backSlash);
if (!last.isEmpty())
lineValues.push_back(last);
values.append(lineValues);
m_line = m_textStream.readLine();
endReached = m_line.isNull();
} else {
values.append(lineValues);
endReached = true;
}
}
} while (!endReached);
return values;
}
void MakefileParser::appendHeader(QStringList &list, const QDir &dir, const QString &fileName)
{
const char *const headerExtensions[] = { ".h", ".hh", ".hg", ".hxx", ".hpp", 0 };
int i = 0;
while (headerExtensions[i] != 0) {
const QString headerFile = fileName + QLatin1String(headerExtensions[i]);
QFileInfo fileInfo(dir, headerFile);
if (fileInfo.exists())
list.append(headerFile);
++i;
}
}
void MakefileParser::addAllSources()
{
QStringList extensions;
extensions << QLatin1String(".c")
<< QLatin1String(".cpp")
<< QLatin1String(".cc")
<< QLatin1String(".cxx")
<< QLatin1String(".ccg");
QFileInfo info(m_makefile);
m_sources.append(directorySources(info.absolutePath(), extensions));
m_sources.removeDuplicates();
}
void MakefileParser::parseIncludePaths()
{
QFileInfo info(m_makefile);
const QString dirName = info.absolutePath();
QFile file(dirName + QLatin1String("/Makefile"));
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
// TODO: The parsing is done very poor. Comments are ignored and targets
// are ignored too. Whether it is worth to improve this, depends on whether
// we want to parse the generated Makefile at all or whether we want to
// improve the Makefile.am parsing to be aware of variables.
QTextStream textStream(&file);
QString line;
do {
line = textStream.readLine();
QStringList terms = line.split(QLatin1Char(' '), QString::SkipEmptyParts);
foreach (const QString &term, terms) {
if (term.startsWith(QLatin1String("-I"))) {
QString includePath = term.right(term.length() - 2); // remove the "-I"
if (includePath == QLatin1String("."))
includePath = dirName;
if (!includePath.isEmpty())
m_includePaths += includePath;
}
}
} while (!line.isNull());
m_includePaths.removeDuplicates();
}
<commit_msg>autotools: Skip empty parts in target lists<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010-2011 Openismus GmbH.
** Authors: Peter Penz (ppenz@openismus.com)
** Patricia Santana Cruz (patriciasantanacruz@gmail.com)
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "makefileparser.h"
#include <utils/qtcassert.h>
#include <QFile>
#include <QDir>
#include <QFileInfoList>
#include <QMutexLocker>
using namespace AutotoolsProjectManager::Internal;
MakefileParser::MakefileParser(const QString &makefile) :
QObject(),
m_success(false),
m_cancel(false),
m_mutex(),
m_makefile(makefile),
m_executable(),
m_sources(),
m_makefiles(),
m_includePaths(),
m_line(),
m_textStream()
{
}
MakefileParser::~MakefileParser()
{
delete m_textStream.device();
}
bool MakefileParser::parse()
{
m_mutex.lock();
m_cancel = false;
m_mutex.unlock(),
m_success = true;
m_executable.clear();
m_sources.clear();
m_makefiles.clear();
QFile *file = new QFile(m_makefile);
if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QFileInfo info(m_makefile);
m_makefiles.append(info.fileName());
emit status(tr("Parsing %1 in directory %2").arg(info.fileName()).arg(info.absolutePath()));
m_textStream.setDevice(file);
do {
m_line = m_textStream.readLine();
switch (topTarget()) {
case AmDefaultSourceExt: parseDefaultSourceExtensions(); break;
case BinPrograms: parseBinPrograms(); break;
case BuiltSources: break; // TODO: Add to m_sources?
case Sources: parseSources(); break;
case SubDirs: parseSubDirs(); break;
case Undefined:
default: break;
}
} while (!m_line.isNull());
parseIncludePaths();
return m_success;
}
QStringList MakefileParser::sources() const
{
return m_sources;
}
QStringList MakefileParser::makefiles() const
{
return m_makefiles;
}
QString MakefileParser::executable() const
{
return m_executable;
}
QStringList MakefileParser::includePaths() const
{
return m_includePaths;
}
void MakefileParser::cancel()
{
QMutexLocker locker(&m_mutex);
m_cancel = true;
}
bool MakefileParser::isCanceled() const
{
QMutexLocker locker(&m_mutex);
return m_cancel;
}
MakefileParser::TopTarget MakefileParser::topTarget() const
{
TopTarget topTarget = Undefined;
const QString line = m_line.simplified();
if (!line.isEmpty() && !line.startsWith(QLatin1Char('#'))) {
// TODO: Check how many fixed strings like AM_DEFAULT_SOURCE_EXT will
// be needed vs. variable strings like _SOURCES. Dependent on this a
// more clever way than this (expensive) if-cascading might be done.
if (line.startsWith(QLatin1String("AM_DEFAULT_SOURCE_EXT =")))
topTarget = AmDefaultSourceExt;
else if (line.startsWith(QLatin1String("bin_PROGRAMS =")))
topTarget = BinPrograms;
else if (line.startsWith(QLatin1String("BUILT_SOURCES =")))
topTarget = BuiltSources;
else if (line.contains(QLatin1String("SUBDIRS =")))
topTarget = SubDirs;
else if (line.contains(QLatin1String("_SOURCES =")))
topTarget = Sources;
}
return topTarget;
}
void MakefileParser::parseBinPrograms()
{
QTC_ASSERT(m_line.contains(QLatin1String("bin_PROGRAMS")), return);
const QStringList binPrograms = targetValues();
// TODO: are multiple values possible?
if (binPrograms.size() == 1) {
QFileInfo info(binPrograms.first());
m_executable = info.fileName();
}
}
void MakefileParser::parseSources()
{
QTC_ASSERT(m_line.contains(QLatin1String("_SOURCES")), return);
bool hasVariables = false;
m_sources.append(targetValues(&hasVariables));
// Skip parsing of Makefile.am for getting the sub directories,
// as variables have been used. As fallback all sources will be added.
if (hasVariables)
addAllSources();
// Duplicates might be possible in combination with 'AM_DEFAULT_SOURCE_EXT ='
m_sources.removeDuplicates();
// TODO: Definitions like "SOURCES = ../src.cpp" are ignored currently.
// This case must be handled correctly in MakefileParser::parseSubDirs(),
// where the current sub directory must be shortened.
QStringList::iterator it = m_sources.begin();
while (it != m_sources.end()) {
if ((*it).startsWith(QLatin1String("..")))
it = m_sources.erase(it);
else
++it;
}
}
void MakefileParser::parseDefaultSourceExtensions()
{
QTC_ASSERT(m_line.contains(QLatin1String("AM_DEFAULT_SOURCE_EXT")), return);
const QStringList extensions = targetValues();
if (extensions.isEmpty()) {
m_success = false;
return;
}
QFileInfo info(m_makefile);
const QString dirName = info.absolutePath();
m_sources.append(directorySources(dirName, extensions));
// Duplicates might be possible in combination with '_SOURCES ='
m_sources.removeDuplicates();
}
void MakefileParser::parseSubDirs()
{
QTC_ASSERT(m_line.contains(QLatin1String("SUBDIRS")), return);
if (isCanceled()) {
m_success = false;
return;
}
QFileInfo info(m_makefile);
const QString path = info.absolutePath();
const QString makefileName = info.fileName();
bool hasVariables = false;
QStringList subDirs = targetValues(&hasVariables);
if (hasVariables) {
// Skip parsing of Makefile.am for getting the sub directories,
// as variables have been used. As fallback all sources will be added.
addAllSources();
return;
}
// If the SUBDIRS values contain a '.' or a variable like $(test),
// all the sub directories of the current folder must get parsed.
bool hasDotSubDir = false;
QStringList::iterator it = subDirs.begin();
while (it != subDirs.end()) {
// Erase all entries that represent a '.'
if ((*it) == QLatin1String(".")) {
hasDotSubDir = true;
it = subDirs.erase(it);
} else {
++it;
}
}
if (hasDotSubDir) {
// Add all sub directories of the current folder
QDir dir(path);
dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QFileInfo& info, dir.entryInfoList()) {
subDirs.append(info.fileName());
}
}
subDirs.removeDuplicates();
// Delegate the parsing of all sub directories to a local
// makefile parser and merge the results
foreach (const QString& subDir, subDirs) {
const QChar slash = QLatin1Char('/');
const QString subDirMakefile = path + slash + subDir
+ slash + makefileName;
// Parse sub directory
QFile file(subDirMakefile);
// Don't try to parse a file, that might not exist (e. g.
// if SUBDIRS specifies a 'po' directory).
if (!file.exists())
continue;
MakefileParser parser(subDirMakefile);
connect(&parser, SIGNAL(status(QString)), this, SIGNAL(status(QString)));
const bool success = parser.parse();
// Don't return, try to parse as many sub directories
// as possible
if (!success)
m_success = false;
m_makefiles.append(subDir + slash + makefileName);
// Append the sources of the sub directory to the
// current sources
foreach (const QString& source, parser.sources())
m_sources.append(subDir + slash + source);
// Duplicates might be possible in combination with several
// "..._SUBDIRS" targets
m_makefiles.removeDuplicates();
m_sources.removeDuplicates();
}
if (subDirs.isEmpty())
m_success = false;
}
QStringList MakefileParser::directorySources(const QString &directory,
const QStringList &extensions)
{
if (isCanceled()) {
m_success = false;
return QStringList();
}
emit status(tr("Parsing directory %1").arg(directory));
QStringList list; // return value
QDir dir(directory);
dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
const QFileInfoList infos = dir.entryInfoList();
foreach (const QFileInfo& info, infos) {
if (info.isDir()) {
// Append recursively sources from the sub directory
const QStringList subDirSources = directorySources(info.absoluteFilePath(),
extensions);
const QString dirPath = info.fileName();
foreach (const QString& subDirSource, subDirSources)
list.append(dirPath + QLatin1Char('/') + subDirSource);
} else {
// Check whether the file matches to an extension
foreach (const QString& extension, extensions) {
if (info.fileName().endsWith(extension)) {
list.append(info.fileName());
appendHeader(list, dir, info.baseName());
break;
}
}
}
}
return list;
}
QStringList MakefileParser::targetValues(bool *hasVariables)
{
QStringList values;
if (hasVariables != 0)
*hasVariables = false;
const int index = m_line.indexOf(QLatin1Char('='));
if (index < 0) {
m_success = false;
return QStringList();
}
m_line.remove(0, index + 1); // remove the 'target = ' prefix
bool endReached = false;
do {
m_line = m_line.simplified();
// Get all values of a line separated by spaces.
// Values representing a variable like $(value) get
// removed currently.
QStringList lineValues = m_line.split(QLatin1Char(' '), QString::SkipEmptyParts);
QStringList::iterator it = lineValues.begin();
while (it != lineValues.end()) {
if ((*it).startsWith(QLatin1String("$("))) {
it = lineValues.erase(it);
if (hasVariables != 0)
*hasVariables = true;
} else {
++it;
}
}
endReached = lineValues.isEmpty();
if (!endReached) {
const QChar backSlash = QLatin1Char('\\');
QString last = lineValues.last();
if (last.endsWith(backSlash)) {
// The last value contains a backslash. Remove the
// backslash and replace the last value.
lineValues.pop_back();
last.remove(backSlash);
if (!last.isEmpty())
lineValues.push_back(last);
values.append(lineValues);
m_line = m_textStream.readLine();
endReached = m_line.isNull();
} else {
values.append(lineValues);
endReached = true;
}
}
} while (!endReached);
return values;
}
void MakefileParser::appendHeader(QStringList &list, const QDir &dir, const QString &fileName)
{
const char *const headerExtensions[] = { ".h", ".hh", ".hg", ".hxx", ".hpp", 0 };
int i = 0;
while (headerExtensions[i] != 0) {
const QString headerFile = fileName + QLatin1String(headerExtensions[i]);
QFileInfo fileInfo(dir, headerFile);
if (fileInfo.exists())
list.append(headerFile);
++i;
}
}
void MakefileParser::addAllSources()
{
QStringList extensions;
extensions << QLatin1String(".c")
<< QLatin1String(".cpp")
<< QLatin1String(".cc")
<< QLatin1String(".cxx")
<< QLatin1String(".ccg");
QFileInfo info(m_makefile);
m_sources.append(directorySources(info.absolutePath(), extensions));
m_sources.removeDuplicates();
}
void MakefileParser::parseIncludePaths()
{
QFileInfo info(m_makefile);
const QString dirName = info.absolutePath();
QFile file(dirName + QLatin1String("/Makefile"));
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
// TODO: The parsing is done very poor. Comments are ignored and targets
// are ignored too. Whether it is worth to improve this, depends on whether
// we want to parse the generated Makefile at all or whether we want to
// improve the Makefile.am parsing to be aware of variables.
QTextStream textStream(&file);
QString line;
do {
line = textStream.readLine();
QStringList terms = line.split(QLatin1Char(' '), QString::SkipEmptyParts);
foreach (const QString &term, terms) {
if (term.startsWith(QLatin1String("-I"))) {
QString includePath = term.right(term.length() - 2); // remove the "-I"
if (includePath == QLatin1String("."))
includePath = dirName;
if (!includePath.isEmpty())
m_includePaths += includePath;
}
}
} while (!line.isNull());
m_includePaths.removeDuplicates();
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <type_traits>
#include "../Math/Common.h"
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
*********************** DataExchangeFormat::Private_ ***************************
********************************************************************************
*/
namespace Private_ {
template <typename T>
inline typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return t;
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, T>::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
if (Math::NearlyEquals (t, lower)) {
return lower;
}
if (Math::NearlyEquals (t, upper)) {
return upper;
}
return t;
}
}
/*
********************************************************************************
************** DataExchangeFormat::CheckedConverter_Range **********************
********************************************************************************
*/
template <typename RANGE_TYPE>
RANGE_TYPE CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
{
typename RANGE_TYPE::ElementType useS = Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
typename RANGE_TYPE::ElementType useE = Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useS <= useE)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return RANGE_TYPE (useS, useE);
}
/*
********************************************************************************
********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
********************************************************************************
*/
template <typename RANGE_TYPE>
typename RANGE_TYPE::ElementType CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
{
typename RANGE_TYPE::ElementType useVal = Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return useVal;
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<commit_msg>use new Math::PinToSpecialPoint () in DataExchangeFormat/CheckedConverter<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <type_traits>
#include "../Math/Common.h"
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
*********************** DataExchangeFormat::Private_ ***************************
********************************************************************************
*/
namespace Private_ {
template <typename T>
inline typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return t;
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, T>::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return Math::PinToSpecialPoint (PinToSpecialPoint (t, lower), upper);
}
}
/*
********************************************************************************
************** DataExchangeFormat::CheckedConverter_Range **********************
********************************************************************************
*/
template <typename RANGE_TYPE>
RANGE_TYPE CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
{
typename RANGE_TYPE::ElementType useS = Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
typename RANGE_TYPE::ElementType useE = Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useS <= useE)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return RANGE_TYPE (useS, useE);
}
/*
********************************************************************************
********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
********************************************************************************
*/
template <typename RANGE_TYPE>
typename RANGE_TYPE::ElementType CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
{
typename RANGE_TYPE::ElementType useVal = Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return useVal;
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_desktop.hxx"
#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"
#define PLATFORM_ALL "all"
#define PLATFORM_WIN_X86 "windows_x86"
#define PLATFORM_LINUX_X86 "linux_x86"
#define PLATFORM_LINUX_X86_64 "linux_x86_64"
#define PLATFORM_LINUX_SPARC "linux_sparc"
#define PLATFORM_LINUX_POWERPC "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64 "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB "linux_mips_eb"
#define PLATFORM_LINUX_IA64 "linux_ia64"
#define PLATFORM_LINUX_S390 "linux_s390"
#define PLATFORM_LINUX_S390x "linux_s390x"
#define PLATFORM_SOLARIS_SPARC "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64 "solaris_sparc64"
#define PLATFORM_SOLARIS_X86 "solaris_x86"
#define PLATFORM_FREEBSD_X86 "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64 "freebsd_x86_64"
#define PLATFORM_MACOSX_X86 "macosx_x86"
#define PLATFORM_MACOSX_PPC "macosx_powerpc"
#define PLATFORM_OS2_X86 "os2_x86"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_misc
{
namespace
{
struct StrOperatingSystem :
public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
const OUString operator () () {
OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
::rtl::Bootstrap::expandMacros( os );
return os;
}
};
struct StrCPU :
public rtl::StaticWithInit<const OUString, StrCPU> {
const OUString operator () () {
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
return arch;
}
};
struct StrPlatform : public rtl::StaticWithInit<
const OUString, StrPlatform> {
const OUString operator () () {
::rtl::OUStringBuffer buf;
buf.append( StrOperatingSystem::get() );
buf.append( static_cast<sal_Unicode>('_') );
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
buf.append( arch );
return buf.makeStringAndClear();
}
};
bool checkOSandCPU(OUString const & os, OUString const & cpu)
{
return os.equals(StrOperatingSystem::get())
&& cpu.equals(StrCPU::get());
}
bool isValidPlatform(OUString const & token )
{
bool ret = false;
if (token.equals(OUSTR(PLATFORM_ALL)))
ret = true;
else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
else
{
OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
"Check the platform element in the descripion.xml");
ret = false;
}
return ret;
}
} // anon namespace
//=============================================================================
OUString const & getPlatformString()
{
return StrPlatform::get();
}
bool platform_fits( OUString const & platform_string )
{
sal_Int32 index = 0;
for (;;)
{
const OUString token(
platform_string.getToken( 0, ',', index ).trim() );
// check if this platform:
if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
(token.indexOf( '_' ) < 0 && /* check OS part only */
token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
{
return true;
}
if (index < 0)
break;
}
return false;
}
bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
bool ret = false;
for (sal_Int32 i = 0; i < platformStrings.getLength(); i++)
{
if (isValidPlatform(platformStrings[i]))
{
ret = true;
break;
}
}
return ret;
}
}
<commit_msg>linuxaxp01: #i110145# yet another hard-coded list to fall over<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_desktop.hxx"
#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"
#define PLATFORM_ALL "all"
#define PLATFORM_WIN_X86 "windows_x86"
#define PLATFORM_LINUX_X86 "linux_x86"
#define PLATFORM_LINUX_X86_64 "linux_x86_64"
#define PLATFORM_LINUX_SPARC "linux_sparc"
#define PLATFORM_LINUX_POWERPC "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64 "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB "linux_mips_eb"
#define PLATFORM_LINUX_IA64 "linux_ia64"
#define PLATFORM_LINUX_S390 "linux_s390"
#define PLATFORM_LINUX_S390x "linux_s390x"
#define PLATFORM_LINUX_HPPA "linux_hppa"
#define PLATFORM_LINUX_ALPHA "linux_alpha"
#define PLATFORM_SOLARIS_SPARC "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64 "solaris_sparc64"
#define PLATFORM_SOLARIS_X86 "solaris_x86"
#define PLATFORM_FREEBSD_X86 "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64 "freebsd_x86_64"
#define PLATFORM_MACOSX_X86 "macosx_x86"
#define PLATFORM_MACOSX_PPC "macosx_powerpc"
#define PLATFORM_OS2_X86 "os2_x86"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_misc
{
namespace
{
struct StrOperatingSystem :
public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
const OUString operator () () {
OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
::rtl::Bootstrap::expandMacros( os );
return os;
}
};
struct StrCPU :
public rtl::StaticWithInit<const OUString, StrCPU> {
const OUString operator () () {
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
return arch;
}
};
struct StrPlatform : public rtl::StaticWithInit<
const OUString, StrPlatform> {
const OUString operator () () {
::rtl::OUStringBuffer buf;
buf.append( StrOperatingSystem::get() );
buf.append( static_cast<sal_Unicode>('_') );
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
buf.append( arch );
return buf.makeStringAndClear();
}
};
bool checkOSandCPU(OUString const & os, OUString const & cpu)
{
return os.equals(StrOperatingSystem::get())
&& cpu.equals(StrCPU::get());
}
bool isValidPlatform(OUString const & token )
{
bool ret = false;
if (token.equals(OUSTR(PLATFORM_ALL)))
ret = true;
else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
else
{
OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
"Check the platform element in the descripion.xml");
ret = false;
}
return ret;
}
} // anon namespace
//=============================================================================
OUString const & getPlatformString()
{
return StrPlatform::get();
}
bool platform_fits( OUString const & platform_string )
{
sal_Int32 index = 0;
for (;;)
{
const OUString token(
platform_string.getToken( 0, ',', index ).trim() );
// check if this platform:
if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
(token.indexOf( '_' ) < 0 && /* check OS part only */
token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
{
return true;
}
if (index < 0)
break;
}
return false;
}
bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
bool ret = false;
for (sal_Int32 i = 0; i < platformStrings.getLength(); i++)
{
if (isValidPlatform(platformStrings[i]))
{
ret = true;
break;
}
}
return ret;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_
#define _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace IO {
namespace FileSystem {
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
inline Streams::BinaryInputStream BinaryFileInputStream::mk (const String& fileName, BufferFlag bufferFlag)
{
return mk (fileName, eSeekable, bufferFlag);
}
}
}
}
}
#endif /*_Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_*/
<commit_msg>Comments<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_
#define _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace IO {
namespace FileSystem {
/*
********************************************************************************
********************************** BinaryInputStream ***************************
********************************************************************************
*/
inline Streams::BinaryInputStream BinaryFileInputStream::mk (const String& fileName, BufferFlag bufferFlag)
{
return mk (fileName, eSeekable, bufferFlag);
}
}
}
}
}
#endif /*_Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_*/
<|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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"
namespace otb
{
namespace Wrapper
{
class EndmemberNumberEstimation : public Application
{
public:
/** Standard class typedefs. */
typedef EndmemberNumberEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(EndmemberNumberEstimation, otb::Application);
typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
typedef otb::VirtualDimensionality<float> VirtualDimensionalityType;
typedef otb::EigenvalueLikelihoodMaximisation<float> EigenvalueLikelihoodMaximisationType;
private:
void DoInit() override
{
SetName("EndmemberNumberEstimation");
SetDescription("Estimate the number of endmembers in a hyperspectral image");
// Documentation
SetDocName("Endmember Number Estimation");
SetDocLongDescription("Estimate the number of endmembers "
"in a hyperspectral image. First, compute statistics on the image and then "
"apply an endmember number estimation algorithm using these statistics. Two "
"algorithms are available:\n\n"
"1. Virtual Dimensionality (VD) [1][2]\n"
"2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"
"The application then returns the estimated number of endmembers.\n\n"
"[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
"sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
"Sensing, vol. 43, no. 3, mar 2004.\n\n"
"[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
"in endmember extraction and abundance quantification for hyperspectral imagery"
", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
"2601-1616, sep 2006.\n\n"
"[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
"J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"
"[4] Unsupervised classification of hyperspectral images by using "
"linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
"Processing(ICIP) 2009, Cairo, Egypte, 2009"
);
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");
AddDocTag(Tags::Hyperspectral);
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
SetParameterDescription("in","The hyperspectral data cube input");
AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
SetParameterDescription("algo", "The algorithm to use for the estimation");
AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
SetParameterDescription("algo.elm", "");
AddChoice("algo.vd", "Virtual Dimensionality");
SetParameterDescription("algo.vd", "");
AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
SetMinimumParameterFloatValue("algo.vd.far", 0);
SetMaximumParameterFloatValue("algo.vd.far", 1);
SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
SetParameterDescription( "algo.vd.far" ,
"False alarm rate for the virtual dimensionality algorithm");
AddParameter(ParameterType_Int,"number","Number of endmembers");
SetParameterDescription("number", "The output estimated number of endmembers");
SetParameterRole("number", Role_Output);
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
SetDocExampleParameterValue("algo", "vd");
SetDocExampleParameterValue("algo.vd.far", "1.0E-3");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
// Load input image
auto inputImage = GetParameterImage("in");
otbAppLogINFO("Computing statistics on input image...");
auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
statisticsFilter->SetInput(inputImage);
AddProcess(statisticsFilter->GetStreamer(), "Statistic estimation step");
statisticsFilter->Update();
auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
int numberOfEndmembers = 0;
const std::string algorithm = GetParameterString("algo");
if (algorithm=="elm")
{
otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
auto elm = EigenvalueLikelihoodMaximisationType::New();
elm->SetCovariance(covarianceMatrix);
elm->SetCorrelation(correlationMatrix);
elm->SetNumberOfPixels(numberOfPixels);
elm->Compute();
numberOfEndmembers = elm->GetNumberOfEndmembers();
}
else if (algorithm=="vd")
{
otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
auto vd = VirtualDimensionalityType::New();
vd->SetCovariance(covarianceMatrix);
vd->SetCorrelation(correlationMatrix);
vd->SetNumberOfPixels(numberOfPixels);
vd->SetFAR(GetParameterFloat("algo.vd.far"));
vd->Compute();
numberOfEndmembers = vd->GetNumberOfEndmembers();
}
SetParameterInt("number", numberOfEndmembers);
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<commit_msg>DOC: moved the output parameter up in the app so it shows up on top in otbgui<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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"
namespace otb
{
namespace Wrapper
{
class EndmemberNumberEstimation : public Application
{
public:
/** Standard class typedefs. */
typedef EndmemberNumberEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(EndmemberNumberEstimation, otb::Application);
typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
typedef otb::VirtualDimensionality<float> VirtualDimensionalityType;
typedef otb::EigenvalueLikelihoodMaximisation<float> EigenvalueLikelihoodMaximisationType;
private:
void DoInit() override
{
SetName("EndmemberNumberEstimation");
SetDescription("Estimate the number of endmembers in a hyperspectral image");
// Documentation
SetDocName("Endmember Number Estimation");
SetDocLongDescription("Estimate the number of endmembers "
"in a hyperspectral image. First, compute statistics on the image and then "
"apply an endmember number estimation algorithm using these statistics. Two "
"algorithms are available:\n\n"
"1. Virtual Dimensionality (VD) [1][2]\n"
"2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"
"The application then returns the estimated number of endmembers.\n\n"
"[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
"sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
"Sensing, vol. 43, no. 3, mar 2004.\n\n"
"[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
"in endmember extraction and abundance quantification for hyperspectral imagery"
", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
"2601-1616, sep 2006.\n\n"
"[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
"J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"
"[4] Unsupervised classification of hyperspectral images by using "
"linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
"Processing(ICIP) 2009, Cairo, Egypte, 2009"
);
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");
AddDocTag(Tags::Hyperspectral);
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
SetParameterDescription("in","The hyperspectral data cube input");
AddParameter(ParameterType_Int,"number","Number of endmembers");
SetParameterDescription("number", "The output estimated number of endmembers");
SetParameterRole("number", Role_Output);
AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
SetParameterDescription("algo", "The algorithm to use for the estimation");
AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
SetParameterDescription("algo.elm", "");
AddChoice("algo.vd", "Virtual Dimensionality");
SetParameterDescription("algo.vd", "");
AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
SetMinimumParameterFloatValue("algo.vd.far", 0);
SetMaximumParameterFloatValue("algo.vd.far", 1);
SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
SetParameterDescription( "algo.vd.far" ,
"False alarm rate for the virtual dimensionality algorithm");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
SetDocExampleParameterValue("algo", "vd");
SetDocExampleParameterValue("algo.vd.far", "1.0E-3");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
// Load input image
auto inputImage = GetParameterImage("in");
otbAppLogINFO("Computing statistics on input image...");
auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
statisticsFilter->SetInput(inputImage);
AddProcess(statisticsFilter->GetStreamer(), "Statistic estimation step");
statisticsFilter->Update();
auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
int numberOfEndmembers = 0;
const std::string algorithm = GetParameterString("algo");
if (algorithm=="elm")
{
otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
auto elm = EigenvalueLikelihoodMaximisationType::New();
elm->SetCovariance(covarianceMatrix);
elm->SetCorrelation(correlationMatrix);
elm->SetNumberOfPixels(numberOfPixels);
elm->Compute();
numberOfEndmembers = elm->GetNumberOfEndmembers();
}
else if (algorithm=="vd")
{
otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
auto vd = VirtualDimensionalityType::New();
vd->SetCovariance(covarianceMatrix);
vd->SetCorrelation(correlationMatrix);
vd->SetNumberOfPixels(numberOfPixels);
vd->SetFAR(GetParameterFloat("algo.vd.far"));
vd->Compute();
numberOfEndmembers = vd->GetNumberOfEndmembers();
}
SetParameterInt("number", numberOfEndmembers);
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __itkKspaceImageFilter_txx
#define __itkKspaceImageFilter_txx
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "itkKspaceImageFilter.h"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>
#define _USE_MATH_DEFINES
#include <math.h>
namespace itk {
template< class TPixelType >
KspaceImageFilter< TPixelType >
::KspaceImageFilter()
: m_tLine(1)
, m_kOffset(0)
, m_FrequencyMap(NULL)
, m_SimulateRelaxation(true)
, m_SimulateEddyCurrents(false)
, m_Tau(70)
, m_EddyGradientMagnitude(30)
, m_IsBaseline(true)
, m_SignalScale(1)
, m_Spikes(0)
, m_SpikeAmplitude(1)
{
m_DiffusionGradientDirection.Fill(0.0);
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::BeforeThreadedGenerateData()
{
typename OutputImageType::Pointer outputImage = OutputImageType::New();
outputImage->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
outputImage->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
outputImage->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
itk::ImageRegion<2> region; region.SetSize(0, m_OutSize[0]); region.SetSize(1, m_OutSize[1]);
outputImage->SetLargestPossibleRegion( region );
outputImage->SetBufferedRegion( region );
outputImage->SetRequestedRegion( region );
outputImage->Allocate();
m_TEMPIMAGE = InputImageType::New();
m_TEMPIMAGE->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
m_TEMPIMAGE->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
m_TEMPIMAGE->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
m_TEMPIMAGE->SetLargestPossibleRegion( region );
m_TEMPIMAGE->SetBufferedRegion( region );
m_TEMPIMAGE->SetRequestedRegion( region );
m_TEMPIMAGE->Allocate();
m_SimulateDistortions = true;
if (m_FrequencyMap.IsNull())
{
m_SimulateDistortions = false;
m_FrequencyMap = InputImageType::New();
m_FrequencyMap->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
m_FrequencyMap->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
m_FrequencyMap->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
m_FrequencyMap->SetLargestPossibleRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->SetBufferedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->SetRequestedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->Allocate();
m_FrequencyMap->FillBuffer(0);
}
double gamma = 42576000; // Gyromagnetic ratio in Hz/T
if (m_DiffusionGradientDirection.GetNorm()>0.001)
{
m_DiffusionGradientDirection.Normalize();
m_EddyGradientMagnitude /= 1000; // eddy gradient magnitude in T/m
m_DiffusionGradientDirection = m_DiffusionGradientDirection * m_EddyGradientMagnitude * gamma;
m_IsBaseline = false;
}
else
m_EddyGradientMagnitude = gamma*m_EddyGradientMagnitude/1000;
this->SetNthOutput(0, outputImage);
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId)
{
typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0));
ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread);
typedef ImageRegionConstIterator< InputImageType > InputIteratorType;
double kxMax = outputImage->GetLargestPossibleRegion().GetSize(0);
double kyMax = outputImage->GetLargestPossibleRegion().GetSize(1);
double numPix = kxMax*kyMax;
double dt = m_tLine/kxMax;
double fromMaxEcho = - m_tLine*kyMax/2;
double in_szx = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(0);
double in_szy = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(1);
int xOffset = in_szx-kxMax;
int yOffset = in_szy-kyMax;
vcl_complex<double> spike(0,0);
while( !oit.IsAtEnd() )
{
itk::Index< 2 > kIdx;
kIdx[0] = oit.GetIndex()[0];
kIdx[1] = oit.GetIndex()[1];
double t = fromMaxEcho + ((double)kIdx[1]*kxMax+(double)kIdx[0])*dt; // dephasing time
// rearrange slice
if( kIdx[0] < kxMax/2 )
kIdx[0] = kIdx[0] + kxMax/2;
else
kIdx[0] = kIdx[0] - kxMax/2;
if( kIdx[1] < kyMax/2 )
kIdx[1] = kIdx[1] + kyMax/2;
else
kIdx[1] = kIdx[1] - kyMax/2;
// calculate eddy current decay factors
double eddyDecay = 0;
if (m_SimulateEddyCurrents)
eddyDecay = exp(-(m_TE/2 + t)/m_Tau) * t/1000;
// calcualte signal relaxation factors
std::vector< double > relaxFactor;
if (m_SimulateRelaxation)
for (int i=0; i<m_CompartmentImages.size(); i++)
relaxFactor.push_back(exp(-(m_TE+t)/m_T2.at(i) -fabs(t)/m_Tinhom));
double kx = kIdx[0];
double ky = kIdx[1];
if (oit.GetIndex()[1]%2 == 1) // reverse readout direction and add ghosting
{
kIdx[0] = kxMax-kIdx[0]-1; // reverse readout direction
kx = (double)kIdx[0]-m_kOffset; // add gradient delay induced offset
}
else
kx += m_kOffset; // add gradient delay induced offset
// add gibbs ringing offset (cropps k-space)
if (kx>=kxMax/2)
kx += xOffset;
if (ky>=kyMax/2)
ky += yOffset;
vcl_complex<double> s(0,0);
InputIteratorType it(m_CompartmentImages.at(0), m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
while( !it.IsAtEnd() )
{
double x = it.GetIndex()[0]-in_szx/2;
double y = it.GetIndex()[1]-in_szy/2;
vcl_complex<double> f(0, 0);
// sum compartment signals and simulate relaxation
for (int i=0; i<m_CompartmentImages.size(); i++)
if (m_SimulateRelaxation)
f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * relaxFactor.at(i) * m_SignalScale, 0);
else
f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * m_SignalScale );
// simulate eddy currents and other distortions
double omega_t = 0;
if ( m_SimulateEddyCurrents && !m_IsBaseline)
{
itk::Vector< double, 3 > pos; pos[0] = x; pos[1] = y; pos[2] = m_Z;
pos = m_DirectionMatrix*pos/1000; // vector from image center to current position (in meter)
omega_t += (m_DiffusionGradientDirection[0]*pos[0]+m_DiffusionGradientDirection[1]*pos[1]+m_DiffusionGradientDirection[2]*pos[2])*eddyDecay;
}
if (m_SimulateDistortions)
omega_t += m_FrequencyMap->GetPixel(it.GetIndex())*t/1000;
// actual DFT term
s += f * exp( std::complex<double>(0, 2 * M_PI * (kx*x/in_szx + ky*y/in_szy + omega_t )) );
++it;
}
s /= numPix;
if (m_Spikes>0 && sqrt(s.imag()*s.imag()+s.real()*s.real()) > sqrt(spike.imag()*spike.imag()+spike.real()*spike.real()) )
spike = s;
// m_TEMPIMAGE->SetPixel(kIdx, sqrt(s.real()*s.real()+s.imag()*s.imag()));
outputImage->SetPixel(kIdx, s);
++oit;
}
spike *= m_SpikeAmplitude;
for (int i=0; i<m_Spikes; i++)
{
itk::Index< 2 > spikeIdx;
spikeIdx[0] = rand()%(int)kxMax;
spikeIdx[1] = rand()%(int)kyMax;
outputImage->SetPixel(spikeIdx, spike);
}
// typedef itk::ImageFileWriter< InputImageType > WriterType;
// typename WriterType::Pointer writer = WriterType::New();
// writer->SetFileName("/local/kspace.nrrd");
// writer->SetInput(m_TEMPIMAGE);
// writer->Update();
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::AfterThreadedGenerateData()
{
}
}
#endif
<commit_msg>zucker<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __itkKspaceImageFilter_txx
#define __itkKspaceImageFilter_txx
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "itkKspaceImageFilter.h"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>
#define _USE_MATH_DEFINES
#include <math.h>
namespace itk {
template< class TPixelType >
KspaceImageFilter< TPixelType >
::KspaceImageFilter()
: m_tLine(1)
, m_kOffset(0)
, m_FrequencyMap(NULL)
, m_SimulateRelaxation(true)
, m_SimulateEddyCurrents(false)
, m_Tau(70)
, m_EddyGradientMagnitude(30)
, m_IsBaseline(true)
, m_SignalScale(1)
, m_Spikes(0)
, m_SpikeAmplitude(1)
{
m_DiffusionGradientDirection.Fill(0.0);
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::BeforeThreadedGenerateData()
{
typename OutputImageType::Pointer outputImage = OutputImageType::New();
outputImage->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
outputImage->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
outputImage->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
itk::ImageRegion<2> region; region.SetSize(0, m_OutSize[0]); region.SetSize(1, m_OutSize[1]);
outputImage->SetLargestPossibleRegion( region );
outputImage->SetBufferedRegion( region );
outputImage->SetRequestedRegion( region );
outputImage->Allocate();
m_TEMPIMAGE = InputImageType::New();
m_TEMPIMAGE->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
m_TEMPIMAGE->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
m_TEMPIMAGE->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
m_TEMPIMAGE->SetLargestPossibleRegion( region );
m_TEMPIMAGE->SetBufferedRegion( region );
m_TEMPIMAGE->SetRequestedRegion( region );
m_TEMPIMAGE->Allocate();
m_SimulateDistortions = true;
if (m_FrequencyMap.IsNull())
{
m_SimulateDistortions = false;
m_FrequencyMap = InputImageType::New();
m_FrequencyMap->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
m_FrequencyMap->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
m_FrequencyMap->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
m_FrequencyMap->SetLargestPossibleRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->SetBufferedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->SetRequestedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
m_FrequencyMap->Allocate();
m_FrequencyMap->FillBuffer(0);
}
double gamma = 42576000; // Gyromagnetic ratio in Hz/T
if (m_DiffusionGradientDirection.GetNorm()>0.001)
{
m_EddyGradientMagnitude /= 1000; // eddy gradient magnitude in T/m
m_DiffusionGradientDirection.Normalize();
m_DiffusionGradientDirection = m_DiffusionGradientDirection * m_EddyGradientMagnitude * gamma;
m_IsBaseline = false;
}
this->SetNthOutput(0, outputImage);
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId)
{
typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0));
ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread);
typedef ImageRegionConstIterator< InputImageType > InputIteratorType;
double kxMax = outputImage->GetLargestPossibleRegion().GetSize(0);
double kyMax = outputImage->GetLargestPossibleRegion().GetSize(1);
double numPix = kxMax*kyMax;
double dt = m_tLine/kxMax;
double fromMaxEcho = - m_tLine*kyMax/2;
double in_szx = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(0);
double in_szy = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(1);
int xOffset = in_szx-kxMax;
int yOffset = in_szy-kyMax;
vcl_complex<double> spike(0,0);
while( !oit.IsAtEnd() )
{
itk::Index< 2 > kIdx;
kIdx[0] = oit.GetIndex()[0];
kIdx[1] = oit.GetIndex()[1];
double t = fromMaxEcho + ((double)kIdx[1]*kxMax+(double)kIdx[0])*dt; // dephasing time
// rearrange slice
if( kIdx[0] < kxMax/2 )
kIdx[0] = kIdx[0] + kxMax/2;
else
kIdx[0] = kIdx[0] - kxMax/2;
if( kIdx[1] < kyMax/2 )
kIdx[1] = kIdx[1] + kyMax/2;
else
kIdx[1] = kIdx[1] - kyMax/2;
// calculate eddy current decay factors
double eddyDecay = 0;
if (m_SimulateEddyCurrents)
eddyDecay = exp(-(m_TE/2 + t)/m_Tau) * t/1000;
// calcualte signal relaxation factors
std::vector< double > relaxFactor;
if (m_SimulateRelaxation)
for (int i=0; i<m_CompartmentImages.size(); i++)
relaxFactor.push_back(exp(-(m_TE+t)/m_T2.at(i) -fabs(t)/m_Tinhom));
double kx = kIdx[0];
double ky = kIdx[1];
if (oit.GetIndex()[1]%2 == 1) // reverse readout direction and add ghosting
{
kIdx[0] = kxMax-kIdx[0]-1; // reverse readout direction
kx = (double)kIdx[0]-m_kOffset; // add gradient delay induced offset
}
else
kx += m_kOffset; // add gradient delay induced offset
// add gibbs ringing offset (cropps k-space)
if (kx>=kxMax/2)
kx += xOffset;
if (ky>=kyMax/2)
ky += yOffset;
vcl_complex<double> s(0,0);
InputIteratorType it(m_CompartmentImages.at(0), m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
while( !it.IsAtEnd() )
{
double x = it.GetIndex()[0]-in_szx/2;
double y = it.GetIndex()[1]-in_szy/2;
vcl_complex<double> f(0, 0);
// sum compartment signals and simulate relaxation
for (int i=0; i<m_CompartmentImages.size(); i++)
if (m_SimulateRelaxation)
f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * relaxFactor.at(i) * m_SignalScale, 0);
else
f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * m_SignalScale );
// simulate eddy currents and other distortions
double omega_t = 0;
if ( m_SimulateEddyCurrents && !m_IsBaseline)
{
itk::Vector< double, 3 > pos; pos[0] = x; pos[1] = y; pos[2] = m_Z;
pos = m_DirectionMatrix*pos/1000; // vector from image center to current position (in meter)
omega_t += (m_DiffusionGradientDirection[0]*pos[0]+m_DiffusionGradientDirection[1]*pos[1]+m_DiffusionGradientDirection[2]*pos[2])*eddyDecay;
}
if (m_SimulateDistortions)
omega_t += m_FrequencyMap->GetPixel(it.GetIndex())*t/1000;
// actual DFT term
s += f * exp( std::complex<double>(0, 2 * M_PI * (kx*x/in_szx + ky*y/in_szy + omega_t )) );
++it;
}
s /= numPix;
if (m_Spikes>0 && sqrt(s.imag()*s.imag()+s.real()*s.real()) > sqrt(spike.imag()*spike.imag()+spike.real()*spike.real()) )
spike = s;
// m_TEMPIMAGE->SetPixel(kIdx, sqrt(s.real()*s.real()+s.imag()*s.imag()));
outputImage->SetPixel(kIdx, s);
++oit;
}
spike *= m_SpikeAmplitude;
for (int i=0; i<m_Spikes; i++)
{
itk::Index< 2 > spikeIdx;
spikeIdx[0] = rand()%(int)kxMax;
spikeIdx[1] = rand()%(int)kyMax;
outputImage->SetPixel(spikeIdx, spike);
}
// typedef itk::ImageFileWriter< InputImageType > WriterType;
// typename WriterType::Pointer writer = WriterType::New();
// writer->SetFileName("/local/kspace.nrrd");
// writer->SetInput(m_TEMPIMAGE);
// writer->Update();
}
template< class TPixelType >
void KspaceImageFilter< TPixelType >
::AfterThreadedGenerateData()
{
}
}
#endif
<|endoftext|> |
<commit_before>#include "GLFWWindowManager.h"
using namespace phoenix;
/*!
Open function.
*/
bool GLFWWindowManager::open( const Vector2d& _sz, const bool _f )
{
// Set our internal screen size variable.
screensize = _sz;
// No GLFW functions may be called before this
if( !glfwInit() ) return false;
// Important defines
#define RED_BITS 8
#define BLUE_BITS 8
#define GREEN_BITS 8
#define ALPHA_BITS 8
#define STENCIL_BITS 0
#ifdef DISABLE_DEPTHBUFFER
#define DEPTH_BITS 0
#else
#define DEPTH_BITS 8
#endif
int mode = _f ? GLFW_FULLSCREEN : GLFW_WINDOW;
if( !glfwOpenWindow(int(_sz.getX()), int(_sz.getY()), RED_BITS, BLUE_BITS, GREEN_BITS, ALPHA_BITS, DEPTH_BITS, STENCIL_BITS, mode) ) return false;
// Disable vsync.
glfwSwapInterval( 0 );
// Set the window caption
setWindowTitle( PHOENIXCORE_VERSION );
// Set GLFW event callbacks
glfwSetKeyCallback( &GLFWWindowManager::glfwKeyboardCallback );
glfwSetCharCallback( &GLFWWindowManager::glfwCharacterCallback );
glfwSetMouseButtonCallback( &GLFWWindowManager::glfwKeyboardCallback );
glfwSetMousePosCallback( &GLFWWindowManager::glfwMousePosCallback );
glfwSetWindowCloseCallback( &GLFWWindowManager::glfwWindowCloseCallback );
glfwSetMouseWheelCallback( &GLFWWindowManager::glfwMouseWheelPosCallback );
glfwSetWindowSizeCallback( &GLFWWindowManager::glfwWindowResizeCallback );
glfwSetWindowMoveCallback( &GLFWWindowManager::glfwWindowMoveCallback );
// Disable key repeat; event receiver manages that.
glfwDisable(GLFW_KEY_REPEAT);
return true;
}
/*
Swap Buffers and Update Events.
*/
void GLFWWindowManager::update()
{
// send the update event. ( done first because glfwSwapBuffers sends new events ).
WindowEvent e;
e.type = WET_UPDATE;
signal(e);
glfwSwapBuffers();
}
//! Window Resize callback (from GLFW).
void GLFWWindowManager::glfwWindowResizeCallback( int width, int height )
{
WindowManagerPtr wm = WindowManager::Instance();
Vector2d size( (float) width, (float) height );
wm->setWindowSize( size );
WindowEvent e;
e.type = WET_RESIZE;
e.vector_data = size;
wm->signal(e);
}
//! Keyboard callback (from GLFW).
void GLFWWindowManager::glfwKeyboardCallback( int key, int action )
{
WindowEvent e;
e.type = WET_KEY;
e.int_data = key;
e.bool_data = action == GLFW_PRESS ? true : false;
Instance()->signal(e);
}
//! Character callback (from GLFW).
void GLFWWindowManager::glfwCharacterCallback( int key, int action )
{
if( action == GLFW_PRESS ){
WindowEvent e;
e.type = WET_CHAR;
e.int_data = key;
e.bool_data = true;
Instance()->signal(e);
}
}
//! Mouse position callback (from GLFW).
void GLFWWindowManager::glfwMousePosCallback( int x, int y )
{
WindowEvent e;
e.type = WET_MOUSE_POSITION;
e.bool_data = true;
e.vector_data = Vector2d( float(x), float(y) );
Instance()->signal(e);
}
//! Window callback (from GLFW).
int GLFWWindowManager::glfwWindowCloseCallback()
{
WindowEvent e;
e.type = WET_CLOSE;
e.bool_data = true;
Instance()->signal(e);
return false;
}
//! Mouse wheel callback (from GLFW).
void GLFWWindowManager::glfwMouseWheelPosCallback( int pos )
{
WindowEvent e;
e.type = WET_MOUSE_WHEEL;
e.bool_data = true;
e.int_data = pos;
Instance()->signal(e);
}
#ifdef _GLFW_WM_MOVE_HACK
void GLFWWindowManager::glfwWindowMoveCallback( int state )
{
WindowEvent e;
e.type = WET_MOVE;
e.bool_data = state == GLFW_MOVE_ENTER ? 1 : 0;
Instance()->signal(e);
}
#endif //_GLFW_WM_MOVE_HACK<commit_msg>Forgot to check for the glfw move hack definition in the source.<commit_after>#include "GLFWWindowManager.h"
using namespace phoenix;
/*!
Open function.
*/
bool GLFWWindowManager::open( const Vector2d& _sz, const bool _f )
{
// Set our internal screen size variable.
screensize = _sz;
// No GLFW functions may be called before this
if( !glfwInit() ) return false;
// Important defines
#define RED_BITS 8
#define BLUE_BITS 8
#define GREEN_BITS 8
#define ALPHA_BITS 8
#define STENCIL_BITS 0
#ifdef DISABLE_DEPTHBUFFER
#define DEPTH_BITS 0
#else
#define DEPTH_BITS 8
#endif
int mode = _f ? GLFW_FULLSCREEN : GLFW_WINDOW;
if( !glfwOpenWindow(int(_sz.getX()), int(_sz.getY()), RED_BITS, BLUE_BITS, GREEN_BITS, ALPHA_BITS, DEPTH_BITS, STENCIL_BITS, mode) ) return false;
// Disable vsync.
glfwSwapInterval( 0 );
// Set the window caption
setWindowTitle( PHOENIXCORE_VERSION );
// Set GLFW event callbacks
glfwSetKeyCallback( &GLFWWindowManager::glfwKeyboardCallback );
glfwSetCharCallback( &GLFWWindowManager::glfwCharacterCallback );
glfwSetMouseButtonCallback( &GLFWWindowManager::glfwKeyboardCallback );
glfwSetMousePosCallback( &GLFWWindowManager::glfwMousePosCallback );
glfwSetWindowCloseCallback( &GLFWWindowManager::glfwWindowCloseCallback );
glfwSetMouseWheelCallback( &GLFWWindowManager::glfwMouseWheelPosCallback );
glfwSetWindowSizeCallback( &GLFWWindowManager::glfwWindowResizeCallback );
#ifdef _GLFW_WM_MOVE_HACK
glfwSetWindowMoveCallback( &GLFWWindowManager::glfwWindowMoveCallback );
#endif
// Disable key repeat; event receiver manages that.
glfwDisable(GLFW_KEY_REPEAT);
return true;
}
/*
Swap Buffers and Update Events.
*/
void GLFWWindowManager::update()
{
// send the update event. ( done first because glfwSwapBuffers sends new events ).
WindowEvent e;
e.type = WET_UPDATE;
signal(e);
glfwSwapBuffers();
}
//! Window Resize callback (from GLFW).
void GLFWWindowManager::glfwWindowResizeCallback( int width, int height )
{
WindowManagerPtr wm = WindowManager::Instance();
Vector2d size( (float) width, (float) height );
wm->setWindowSize( size );
WindowEvent e;
e.type = WET_RESIZE;
e.vector_data = size;
wm->signal(e);
}
//! Keyboard callback (from GLFW).
void GLFWWindowManager::glfwKeyboardCallback( int key, int action )
{
WindowEvent e;
e.type = WET_KEY;
e.int_data = key;
e.bool_data = action == GLFW_PRESS ? true : false;
Instance()->signal(e);
}
//! Character callback (from GLFW).
void GLFWWindowManager::glfwCharacterCallback( int key, int action )
{
if( action == GLFW_PRESS ){
WindowEvent e;
e.type = WET_CHAR;
e.int_data = key;
e.bool_data = true;
Instance()->signal(e);
}
}
//! Mouse position callback (from GLFW).
void GLFWWindowManager::glfwMousePosCallback( int x, int y )
{
WindowEvent e;
e.type = WET_MOUSE_POSITION;
e.bool_data = true;
e.vector_data = Vector2d( float(x), float(y) );
Instance()->signal(e);
}
//! Window callback (from GLFW).
int GLFWWindowManager::glfwWindowCloseCallback()
{
WindowEvent e;
e.type = WET_CLOSE;
e.bool_data = true;
Instance()->signal(e);
return false;
}
//! Mouse wheel callback (from GLFW).
void GLFWWindowManager::glfwMouseWheelPosCallback( int pos )
{
WindowEvent e;
e.type = WET_MOUSE_WHEEL;
e.bool_data = true;
e.int_data = pos;
Instance()->signal(e);
}
#ifdef _GLFW_WM_MOVE_HACK
void GLFWWindowManager::glfwWindowMoveCallback( int state )
{
WindowEvent e;
e.type = WET_MOVE;
e.bool_data = state == GLFW_MOVE_ENTER ? 1 : 0;
Instance()->signal(e);
}
#endif //_GLFW_WM_MOVE_HACK<|endoftext|> |
<commit_before>// $Id: ooiEnergy.C,v 1.5 2000/05/30 10:35:18 oliver Exp $
#include <BALL/SOLVATION/ooiEnergy.h>
#include <BALL/common.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DATATYPE/stringHashMap.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/STRUCTURE/numericalSAS.h>
#include <BALL/FORMAT/parameters.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/MOLMEC/COMMON/typeRuleProcessor.h>
#define OOI_PARAMETER_FILENAME "solvation/Ooi.ini"
using namespace std;
namespace BALL
{
namespace OoiEnergy
{
bool is_initialized = false;
// a hash map to convert names to Ooi types
StringHashMap<Atom::Type> type_map;
// a type rule assignment processor
TypeRuleProcessor type_rule;
// free energy is calculated as
// dG = \sum_i g_i A_i
// where A_i is the atomic solvent accesible surface
// area. The atomic radii are taken from the vector radius below.
vector<float> radius;
vector<float> g;
// read the parameter files for calculateOoiEnergy
// and set up the basic data structures
void init()
{
// extract the parameters from the file
Path path;
String filename = path.find(OOI_PARAMETER_FILENAME);
if (filename == "")
{
filename = OOI_PARAMETER_FILENAME;
}
Parameters parameters(filename);
ParameterSection parameter_section;
if (!parameter_section.extractSection(parameters, "OoiParameters"))
{
Log.error() << "calculateOoiEnergy: cannot find section [OoiParameters] in file "
<< parameters.getFilename() << "." << endl;
return;
}
if (!parameter_section.hasVariable("g") || !parameter_section.hasVariable("radius"))
{
Log.error() << "OoiEnergy: section [OoiTypes] of file "
<< parameters.getFilename() << " requires at least the columns 'g' and 'radius'." << endl;
return;
}
ParameterSection type_section;
if (!type_section.extractSection(parameters, "OoiTypes"))
{
Log.error() << "calculateOoiEnergy: cannot find section [OoiTypes] in file "
<< parameters.getFilename() << "." << endl;
return;
}
if (!type_section.hasVariable("type"))
{
Log.error() << "OoiEnergy: section [OoiTypes] of file "
<< parameters.getFilename() << " does not contain a variable column 'type'." << endl;
return;
}
// extract the parameters for each type
//
Position radius_column = parameter_section.getColumnIndex("radius");
Position g_column = parameter_section.getColumnIndex("g");
Index max_index = -1;
Size i;
for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
{
Index index = parameter_section.getKey(i).toInt();
if (index < 0)
{
Log.error() << "calculateOoiEnergy: illegal atom type index: " << index << endl;
}
else
{
if (index > max_index)
{
max_index = index;
}
}
}
if (max_index < 0)
{
Log.error() << "calculateOoiEnergy: could not find any atom type in file "
<< parameters.getFilename() << endl;
return;
}
// resize the vectors to hold all indices
radius.resize((Size)max_index + 1);
g.resize((Size)max_index + 1);
// and read all values from the parameter section
for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
{
Index index = parameter_section.getKey(i).toInt();
// we ignore illegal (negative) indices
if (index >= 0)
{
radius[index] = parameter_section.getValue(i, radius_column).toFloat();
g[index] = parameter_section.getValue(i, g_column).toFloat();
}
}
// extract all known types by iterating over all keys
// and construct the hash map type_map
Position type_column = type_section.getColumnIndex("type");
for (i = 1; i <= type_section.getNumberOfKeys(); i++)
{
// retrieve the type and check for validity
Atom::Type type = type_section.getValue(i, type_column).toInt();
if (type >= (Atom::Type)radius.size())
{
Log.error() << "calculateOoiEnergy: illegal atom type: " << type << " while reading parameter file." << endl;
}
else
{
type_map.insert(type_section.getKey(i), (Atom::Type)type_section.getValue(i, type_column).toInt());
}
}
// set up the type rule processor
// from the rules in the INI file
type_rule.initialize(parameters.getParameterFile(), "TypeRules");
// we're done with the initialization
is_initialized = true;
}
}
double calculateOoiEnergy(BaseFragment& fragment)
{
using namespace OoiEnergy;
// read and interpret the parameters
// this is only done the first time calculateOoiEnergy is called
if (!is_initialized)
{
init();
if (!is_initialized)
{
return 0;
}
}
// assign radii and atom types for all atoms
AtomIterator atom_it = fragment.beginAtom();
for (; +atom_it; ++atom_it)
{
// construct correct name, <RESNAME>:<ATOMNAME>
String atom_name = atom_it->getFullName();
// get the atom type from hash table
// first, try a direct match
Atom::Type atom_type = -1;
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
else
{
atom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
else
{
// try wildcard match
atom_name = "*:" + atom_it->getName();
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
}
}
// if the atom type could not be determined, complain
if (atom_type < 0)
{
// try to apply the type rule processor
atom_it->setType(-1);
type_rule(*atom_it);
atom_type = atom_it->getType();
}
if (atom_type < 0)
{
Log.warn() << "calculateOOIEnergy: did not find a suitable type for " << atom_it->getFullName() << endl;
// ignore this atom....
atom_it->setType(-1);
atom_it->setRadius(0.0);
}
else
{
// assign type and radius
atom_it->setType(atom_type);
atom_it->setRadius(radius[atom_type]);
}
}
// calculate the atomic SAS areas
// atom_SAS_areas hashes the atom pointer to the
// surface area (in Angstrom^2)
HashMap<Atom*,float> atom_SAS_areas;
calculateNumericalSASAtomAreas(atom_SAS_areas, fragment, 1.4, 1888);
// iterate over all atoms and add up the energies
float energy = 0.0;
for (atom_it = fragment.beginAtom(); +atom_it; ++atom_it)
{
if (atom_SAS_areas.has(&*atom_it))
{
Atom::Type atom_type = atom_it->getType();
// if the atom type could not be determined, complain
if (atom_type >= 0)
{
// add the energy contribution of the atom
float tmp = atom_SAS_areas[&*atom_it] * g[atom_type];
energy += tmp;
}
}
}
// we're done.
return energy;
}
} // namespace BALL
<commit_msg>changed: adapted to the new interface of numericalSAS<commit_after>// $Id: ooiEnergy.C,v 1.6 2000/06/02 07:14:21 oliver Exp $
#include <BALL/SOLVATION/ooiEnergy.h>
#include <BALL/common.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DATATYPE/stringHashMap.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/STRUCTURE/numericalSAS.h>
#include <BALL/FORMAT/parameters.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/MOLMEC/COMMON/typeRuleProcessor.h>
#define OOI_PARAMETER_FILENAME "solvation/Ooi.ini"
using namespace std;
namespace BALL
{
namespace OoiEnergy
{
bool is_initialized = false;
// a hash map to convert names to Ooi types
StringHashMap<Atom::Type> type_map;
// a type rule assignment processor
TypeRuleProcessor type_rule;
// free energy is calculated as
// dG = \sum_i g_i A_i
// where A_i is the atomic solvent accesible surface
// area. The atomic radii are taken from the vector radius below.
vector<float> radius;
vector<float> g;
// read the parameter files for calculateOoiEnergy
// and set up the basic data structures
void init()
{
// extract the parameters from the file
Path path;
String filename = path.find(OOI_PARAMETER_FILENAME);
if (filename == "")
{
filename = OOI_PARAMETER_FILENAME;
}
Parameters parameters(filename);
ParameterSection parameter_section;
if (!parameter_section.extractSection(parameters, "OoiParameters"))
{
Log.error() << "calculateOoiEnergy: cannot find section [OoiParameters] in file "
<< parameters.getFilename() << "." << endl;
return;
}
if (!parameter_section.hasVariable("g") || !parameter_section.hasVariable("radius"))
{
Log.error() << "OoiEnergy: section [OoiTypes] of file "
<< parameters.getFilename() << " requires at least the columns 'g' and 'radius'." << endl;
return;
}
ParameterSection type_section;
if (!type_section.extractSection(parameters, "OoiTypes"))
{
Log.error() << "calculateOoiEnergy: cannot find section [OoiTypes] in file "
<< parameters.getFilename() << "." << endl;
return;
}
if (!type_section.hasVariable("type"))
{
Log.error() << "OoiEnergy: section [OoiTypes] of file "
<< parameters.getFilename() << " does not contain a variable column 'type'." << endl;
return;
}
// extract the parameters for each type
//
Position radius_column = parameter_section.getColumnIndex("radius");
Position g_column = parameter_section.getColumnIndex("g");
Index max_index = -1;
Size i;
for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
{
Index index = parameter_section.getKey(i).toInt();
if (index < 0)
{
Log.error() << "calculateOoiEnergy: illegal atom type index: " << index << endl;
}
else
{
if (index > max_index)
{
max_index = index;
}
}
}
if (max_index < 0)
{
Log.error() << "calculateOoiEnergy: could not find any atom type in file "
<< parameters.getFilename() << endl;
return;
}
// resize the vectors to hold all indices
radius.resize((Size)max_index + 1);
g.resize((Size)max_index + 1);
// and read all values from the parameter section
for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
{
Index index = parameter_section.getKey(i).toInt();
// we ignore illegal (negative) indices
if (index >= 0)
{
radius[index] = parameter_section.getValue(i, radius_column).toFloat();
g[index] = parameter_section.getValue(i, g_column).toFloat();
}
}
// extract all known types by iterating over all keys
// and construct the hash map type_map
Position type_column = type_section.getColumnIndex("type");
for (i = 1; i <= type_section.getNumberOfKeys(); i++)
{
// retrieve the type and check for validity
Atom::Type type = type_section.getValue(i, type_column).toInt();
if (type >= (Atom::Type)radius.size())
{
Log.error() << "calculateOoiEnergy: illegal atom type: " << type << " while reading parameter file." << endl;
}
else
{
type_map.insert(type_section.getKey(i), (Atom::Type)type_section.getValue(i, type_column).toInt());
}
}
// set up the type rule processor
// from the rules in the INI file
type_rule.initialize(parameters.getParameterFile(), "TypeRules");
// we're done with the initialization
is_initialized = true;
}
}
double calculateOoiEnergy(BaseFragment& fragment)
{
using namespace OoiEnergy;
// read and interpret the parameters
// this is only done the first time calculateOoiEnergy is called
if (!is_initialized)
{
init();
if (!is_initialized)
{
return 0;
}
}
// assign radii and atom types for all atoms
AtomIterator atom_it = fragment.beginAtom();
for (; +atom_it; ++atom_it)
{
// construct correct name, <RESNAME>:<ATOMNAME>
String atom_name = atom_it->getFullName();
// get the atom type from hash table
// first, try a direct match
Atom::Type atom_type = -1;
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
else
{
atom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
else
{
// try wildcard match
atom_name = "*:" + atom_it->getName();
if (type_map.has(atom_name))
{
atom_type = type_map[atom_name];
}
}
}
// if the atom type could not be determined, complain
if (atom_type < 0)
{
// try to apply the type rule processor
atom_it->setType(-1);
type_rule(*atom_it);
atom_type = atom_it->getType();
}
if (atom_type < 0)
{
Log.warn() << "calculateOOIEnergy: did not find a suitable type for " << atom_it->getFullName() << endl;
// ignore this atom....
atom_it->setType(-1);
atom_it->setRadius(0.0);
}
else
{
// assign type and radius
atom_it->setType(atom_type);
atom_it->setRadius(radius[atom_type]);
}
}
// calculate the atomic SAS areas
// atom_SAS_areas hashes the atom pointer to the
// surface area (in Angstrom^2)
HashMap<Atom*,float> atom_SAS_areas;
calculateNumericalSASAtomAreas(fragment, atom_SAS_areas, 1.4, 1888);
// iterate over all atoms and add up the energies
float energy = 0.0;
for (atom_it = fragment.beginAtom(); +atom_it; ++atom_it)
{
if (atom_SAS_areas.has(&*atom_it))
{
Atom::Type atom_type = atom_it->getType();
// if the atom type could not be determined, complain
if (atom_type >= 0)
{
// add the energy contribution of the atom
float tmp = atom_SAS_areas[&*atom_it] * g[atom_type];
energy += tmp;
}
}
}
// we're done.
return energy;
}
} // namespace BALL
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.