text
stringlengths 54
60.6k
|
---|
<commit_before>//
// Created by Vadim N. on 16/03/2016.
//
// #include "benchutils.h"
#include <Inference>
using namespace ymir;
using namespace std;
int main(int argc, char* argv[]) {
// if (argc < 2) {
// std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
// return 1;
// }
// std::chrono::system_clock::time_point tp1, tp2;
// std::vector< std::pair<std::string, size_t> > timepoints;
// std::vector<prob_t> logLvec;
// std::string temp_str;
// time_t vj_single_parse, vdj_single_parse,
// vj_single_prob, vj_single_meta,
// vj_single_infer, vdj_single_prob,
// vdj_single_meta, vdj_single_infer;
// time_t vj_good_parse, vdj_good_parse,
// vj_good_prob, vj_good_meta,
// vj_good_infer, vdj_good_prob,
// vdj_good_meta, vdj_good_infer;
// std::string BENCH_DATA_FOLDER = argv[1];
// std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl;
//
// TCR alpha chain repertoire - VJ recombination
//
VDJRecombinationGenes vj_single_genes("Vgene",
"/home/vadim/ymir/benchmark/data/trav.txt",
"Jgene",
"/home/vadim/ymir/benchmark/data/traj.txt");
VDJRecombinationGenes vj_single_genes2(vj_single_genes);
// VDJRecombinationGenes vj_single_genes3 = vj_single_genes;
// vj_single_genes2 = vj_single_genes;
// string input_alpha_file = "alpha.250k.txt";
// string input_beta_file = "beta.250k.txt";
// CDR3NucParser parser;
// Cloneset cloneset_vj;
// YMIR_BENCHMARK("Parsing VJ",
// parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
// &cloneset_vj,
// vj_single_genes,
// NUCLEOTIDE,
// VJ_RECOMB,
// AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),
// VDJAlignerParameters(2)))
// //
// // TCR beta chain repertoire - VDJ recombination
// //
// // VDJRecombinationGenes vdj_single_genes("Vgene",
// // BENCH_DATA_FOLDER + "trbv.txt",
// // "Jgene",
// // BENCH_DATA_FOLDER + "trbj.txt",
// // "Dgene",
// // BENCH_DATA_FOLDER + "trbd.txt");
// //
// // Cloneset cloneset_vdj;
// // YMIR_BENCHMARK("Parsing VDJ",
// // parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
// // &cloneset_vdj,
// // vdj_single_genes,
// // NUCLEOTIDE,
// // VDJ_RECOMB,
// // AlignmentColumnOptions()
// // .setV(AlignmentColumnOptions::USE_PROVIDED)
// // .setD(AlignmentColumnOptions::OVERWRITE)
// // .setJ(AlignmentColumnOptions::USE_PROVIDED),
// // VDJAlignerParameters(3)))
// //
// // VJ MAAG
// //
// ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);
// //
// // VDJ MAAG
// //
// // ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);
// //
// // Inference
// //
// vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};
// vec_sample = { 100000 };
// vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000};
// // vec_block = {2000, 5000, 10000};
// vec_block = { std::stoi(argv[2]) };
// vector<double> vec_alpha = {.5, .6, .7, .8, .9};
// vec_alpha = { std::stof(argv[3]) };
// vector<double> vec_beta = {.1, .5, 1, 3};
// vec_beta = { std::stof(argv[4]) };
// vector<double> vec_K = {1, 2, 3};
// vec_K = { std::stod(argv[5]) };
// ErrorMode error_mode = COMPUTE_ERRORS;
// // int niter, sample, block;
// // double alpha;
// // niter = 10;
// // int sample = 10000;
// // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode)
// // RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)
// // for(auto val_sample: vec_sample) {
// // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)
// // }
// // ModelParameterVector new_param_vec = vj_single_model.event_probabilities();
// // new_param_vec.fill(1);
// // new_param_vec.normaliseEventFamilies();
// // vj_single_model.updateModelParameterVector(new_param_vec);
// //
// // auto rep_nonc = cloneset_vj.noncoding().sample(2500);
// // auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);
// // vector<prob_t> prob_vec(maag_rep.size(), 0);
// //
// // vector<bool> good_clonotypes(maag_rep.size(), true);
// // for (size_t i = 0; i < maag_rep.size(); ++i) {
// // if (rep_nonc[i].is_good()) {
// // prob_vec[i] = maag_rep[i].fullProbability();
// // if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {
// // good_clonotypes[i] = false;
// // }
// // } else {
// // good_clonotypes[i] = false;
// // }
// // }
// for(auto val_sample: vec_sample) {
// for(auto val_block: vec_block) {
// for (auto val_alpha: vec_alpha) {
// for (auto val_beta: vec_beta) {
// for (auto val_K: vec_K) {
// RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)
// }
// }
// }
// }
// }
}
<commit_msg>debug<commit_after>//
// Created by Vadim N. on 16/03/2016.
//
// #include "benchutils.h"
#include <Inference>
using namespace ymir;
using namespace std;
int main(int argc, char* argv[]) {
// if (argc < 2) {
// std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
// return 1;
// }
// std::chrono::system_clock::time_point tp1, tp2;
// std::vector< std::pair<std::string, size_t> > timepoints;
// std::vector<prob_t> logLvec;
// std::string temp_str;
// time_t vj_single_parse, vdj_single_parse,
// vj_single_prob, vj_single_meta,
// vj_single_infer, vdj_single_prob,
// vdj_single_meta, vdj_single_infer;
// time_t vj_good_parse, vdj_good_parse,
// vj_good_prob, vj_good_meta,
// vj_good_infer, vdj_good_prob,
// vdj_good_meta, vdj_good_infer;
// std::string BENCH_DATA_FOLDER = argv[1];
// std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl;
//
// TCR alpha chain repertoire - VJ recombination
//
VDJRecombinationGenes vj_single_genes("Vgene",
"/home/vadim/ymir/benchmark/data/trav.txt",
"Jgene",
"/home/vadim/ymir/benchmark/data/traj.txt");
// VDJRecombinationGenes vj_single_genes2(vj_single_genes);
VDJRecombinationGenes vj_single_genes3;
vj_single_genes3 = vj_single_genes;
// string input_alpha_file = "alpha.250k.txt";
// string input_beta_file = "beta.250k.txt";
// CDR3NucParser parser;
// Cloneset cloneset_vj;
// YMIR_BENCHMARK("Parsing VJ",
// parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
// &cloneset_vj,
// vj_single_genes,
// NUCLEOTIDE,
// VJ_RECOMB,
// AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),
// VDJAlignerParameters(2)))
// //
// // TCR beta chain repertoire - VDJ recombination
// //
// // VDJRecombinationGenes vdj_single_genes("Vgene",
// // BENCH_DATA_FOLDER + "trbv.txt",
// // "Jgene",
// // BENCH_DATA_FOLDER + "trbj.txt",
// // "Dgene",
// // BENCH_DATA_FOLDER + "trbd.txt");
// //
// // Cloneset cloneset_vdj;
// // YMIR_BENCHMARK("Parsing VDJ",
// // parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
// // &cloneset_vdj,
// // vdj_single_genes,
// // NUCLEOTIDE,
// // VDJ_RECOMB,
// // AlignmentColumnOptions()
// // .setV(AlignmentColumnOptions::USE_PROVIDED)
// // .setD(AlignmentColumnOptions::OVERWRITE)
// // .setJ(AlignmentColumnOptions::USE_PROVIDED),
// // VDJAlignerParameters(3)))
// //
// // VJ MAAG
// //
// ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);
// //
// // VDJ MAAG
// //
// // ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);
// //
// // Inference
// //
// vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};
// vec_sample = { 100000 };
// vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000};
// // vec_block = {2000, 5000, 10000};
// vec_block = { std::stoi(argv[2]) };
// vector<double> vec_alpha = {.5, .6, .7, .8, .9};
// vec_alpha = { std::stof(argv[3]) };
// vector<double> vec_beta = {.1, .5, 1, 3};
// vec_beta = { std::stof(argv[4]) };
// vector<double> vec_K = {1, 2, 3};
// vec_K = { std::stod(argv[5]) };
// ErrorMode error_mode = COMPUTE_ERRORS;
// // int niter, sample, block;
// // double alpha;
// // niter = 10;
// // int sample = 10000;
// // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode)
// // RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)
// // for(auto val_sample: vec_sample) {
// // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)
// // }
// // ModelParameterVector new_param_vec = vj_single_model.event_probabilities();
// // new_param_vec.fill(1);
// // new_param_vec.normaliseEventFamilies();
// // vj_single_model.updateModelParameterVector(new_param_vec);
// //
// // auto rep_nonc = cloneset_vj.noncoding().sample(2500);
// // auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);
// // vector<prob_t> prob_vec(maag_rep.size(), 0);
// //
// // vector<bool> good_clonotypes(maag_rep.size(), true);
// // for (size_t i = 0; i < maag_rep.size(); ++i) {
// // if (rep_nonc[i].is_good()) {
// // prob_vec[i] = maag_rep[i].fullProbability();
// // if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {
// // good_clonotypes[i] = false;
// // }
// // } else {
// // good_clonotypes[i] = false;
// // }
// // }
// for(auto val_sample: vec_sample) {
// for(auto val_block: vec_block) {
// for (auto val_alpha: vec_alpha) {
// for (auto val_beta: vec_beta) {
// for (auto val_K: vec_K) {
// RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)
// }
// }
// }
// }
// }
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include "bench_common.h"
#include <algorithm>
#include <atomic>
#include <boost/program_options.hpp>
#include <chrono>
#include <cmath>
#include <ctime>
#include <dariadb.h>
#include <limits>
#include <random>
#include <storage/capacitor.h>
#include <thread>
#include <utils/fs.h>
#include <utils/metrics.h>
namespace po = boost::program_options;
std::atomic_long append_count{0};
std::atomic_size_t reads_count{0};
bool stop_info = false;
bool stop_readers = false;
class BenchCallback : public dariadb::storage::ReaderClb {
public:
BenchCallback() { count = 0; }
void call(const dariadb::Meas &) { count++; }
size_t count;
};
void show_info(dariadb::storage::Engine *storage) {
clock_t t0 = clock();
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
clock_t t1 = clock();
auto writes_per_sec =
append_count.load() / double((t1 - t0) / CLOCKS_PER_SEC);
auto reads_per_sec =
reads_count.load() / double((t1 - t0) / CLOCKS_PER_SEC);
auto queue_sizes = storage->queue_size();
std::cout << "\r"
<< " in queue: (p:" << queue_sizes.pages_count
<< " cap:" << queue_sizes.cola_count
<< " a:" << queue_sizes.aofs_count << ")"
<< " reads: " << reads_count << " speed:" << reads_per_sec
<< "/sec"
<< " writes: " << append_count << " speed: " << writes_per_sec
<< "/sec progress:"
<< (int64_t(100) * append_count) / dariadb_bench::all_writes
<< "% ";
std::cout.flush();
if (stop_info) {
std::cout.flush();
break;
}
}
std::cout << "\n";
}
void reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set,
dariadb::Time from, dariadb::Time to) {
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to);
std::shared_ptr<BenchCallback> clbk{new BenchCallback};
while (true) {
clbk->count = 0;
auto time_point1 = uniform_dist(e1);
auto f = 0;
auto t = time_point1;
auto qi = dariadb::storage::QueryInterval(
dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);
ms->readInterval(qi)->readAll(clbk.get());
reads_count += clbk->count;
if (stop_readers) {
break;
}
}
}
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
std::cout << "Performance benchmark" << std::endl;
std::cout << "Writers count:" << dariadb_bench::total_threads_count
<< std::endl;
const std::string storage_path = "perf_benchmark_storage";
bool readers_enable = false;
bool metrics_enable = false;
bool readonly = false;
bool readall_enabled = false;
bool dont_clean = false;
po::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")(
"readonly", "readonly mode")("readall", "read all benchmark enable.")(
"dont-clean", "dont clean storage path before start.")(
"enable-readers",
po::value<bool>(&readers_enable)->default_value(readers_enable),
"enable readers threads")(
"enable-metrics",
po::value<bool>(&metrics_enable)->default_value(metrics_enable));
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
} catch (std::exception &ex) {
logger("Error: " << ex.what());
exit(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
if (metrics_enable) {
std::cout << "Enable metrics." << std::endl;
}
if (vm.count("readonly")) {
std::cout << "Readonly mode." << std::endl;
readonly = true;
}
if (vm.count("readall")) {
std::cout << "Read all benchmark enabled." << std::endl;
readall_enabled = true;
}
if (vm.count("dont-clean")) {
std::cout << "Dont clean storage." << std::endl;
dont_clean = true;
}
if (readers_enable) {
std::cout << "Readers enable. count: " << dariadb_bench::total_readers_count
<< std::endl;
}
{
std::cout << "Write..." << std::endl;
const size_t chunk_per_storage = 1024 * 100;
const size_t chunk_size = 1024;
const size_t cap_B = 50;
const size_t max_mem_chunks = 100;
// dont_clean = true;
if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {
if (!readonly) {
std::cout << " remove " << storage_path << std::endl;
dariadb::utils::fs::rm(storage_path);
}
}
dariadb::Time start_time =
dariadb::Time(0); // dariadb::timeutil::current_time();
std::cout << " start time: " << dariadb::timeutil::to_string(start_time)
<< std::endl;
dariadb::storage::PageManager::Params page_param(
storage_path, chunk_per_storage, chunk_size);
dariadb::storage::CapacitorManager::Params cap_param(storage_path, cap_B);
cap_param.max_levels = 11;
cap_param.max_closed_caps = 0;
dariadb::storage::AOFManager::Params aof_param(storage_path, 0);
aof_param.buffer_size = 1000;
aof_param.max_size = cap_param.measurements_count();
cap_param.max_levels = 11;
auto raw_ptr = new dariadb::storage::Engine(
aof_param, page_param, cap_param,
dariadb::storage::Engine::Limits(max_mem_chunks));
dariadb::storage::MeasStorage_ptr ms{raw_ptr};
dariadb::IdSet all_id_set;
append_count = 0;
stop_info = false;
std::thread info_thread(show_info, raw_ptr);
std::vector<std::thread> writers(dariadb_bench::total_threads_count);
std::vector<std::thread> readers(dariadb_bench::total_readers_count);
size_t pos = 0;
for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {
auto id_from = dariadb_bench::get_id_from(pos);
auto id_to = dariadb_bench::get_id_to(pos);
for (size_t j = id_from; j < id_to; j++) {
all_id_set.insert(j);
}
if (!readonly) {
std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),
dariadb::Time(i), &append_count, raw_ptr};
writers[pos] = std::move(t);
}
pos++;
}
if (readers_enable) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {
std::thread t{reader, ms, all_id_set, dariadb::Time(0),
dariadb::timeutil::current_time()};
readers[pos++] = std::move(t);
}
}
if (!readonly) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {
std::thread t = std::move(writers[pos++]);
t.join();
}
}
stop_readers = true;
if (readers_enable) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {
std::thread t = std::move(readers[pos++]);
t.join();
}
}
stop_info = true;
info_thread.join();
std::cout << " total id:" << all_id_set.size() << std::endl;
{
std::cout << "full flush..." << std::endl;
stop_info = false;
std::thread flush_info_thread(show_info, raw_ptr);
auto start = clock();
raw_ptr->flush();
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
stop_info = true;
flush_info_thread.join();
std::cout << "flush time: " << elapsed << std::endl;
}
if(!readonly){
auto ccount =size_t(raw_ptr->queue_size().cola_count * 0.5);
std::cout << "drop part caps to "<<ccount<<"..." << std::endl;
stop_info = false;
std::thread flush_info_thread(show_info, raw_ptr);
auto start = clock();
raw_ptr->drop_part_caps(ccount);
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
stop_info = true;
flush_info_thread.join();
std::cout << "drop time: " << elapsed << std::endl;
}
auto queue_sizes = raw_ptr->queue_size();
std::cout << "\r"
<< " in queue: (p:" << queue_sizes.pages_count
<< " cap:" << queue_sizes.cola_count
<< " a:" << queue_sizes.aofs_count << ")"
<< " reads: " << reads_count << " writes: " << append_count
<< std::endl;
dariadb_bench::readBenchark(all_id_set, ms.get(), 10, start_time,
dariadb::timeutil::current_time());
if (readall_enabled) {
std::cout << "read all..." << std::endl;
std::shared_ptr<BenchCallback> clbk{new BenchCallback()};
auto max_time = ms->maxTime();
std::cout << " end time: " << dariadb::timeutil::to_string(max_time)
<< std::endl;
auto start = clock();
dariadb::storage::QueryInterval qi{
dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,
max_time};
ms->readInterval(qi)->readAll(clbk.get());
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
std::cout << "readed: " << clbk->count << std::endl;
std::cout << "time: " << elapsed << std::endl;
auto expected =
(dariadb_bench::iteration_count * dariadb_bench::total_threads_count *
dariadb_bench::id_per_thread);
if (!readonly && (!dont_clean && clbk->count != expected)) {
std::cout << "expected: " << expected << " get:" << clbk->count
<< std::endl;
throw MAKE_EXCEPTION(
"(clbk->count!=(iteration_count*total_threads_count))");
} else {
if (!readonly && (dont_clean && clbk->count < expected)) {
std::cout << "expected: " << expected << " get:" << clbk->count
<< std::endl;
throw MAKE_EXCEPTION(
"(clbk->count!=(iteration_count*total_threads_count))");
}
}
}
std::cout << "stoping storage...\n";
ms = nullptr;
}
if (!(dont_clean || readonly) &&
(dariadb::utils::fs::path_exists(storage_path))) {
std::cout << "cleaning...\n";
dariadb::utils::fs::rm(storage_path);
}
if (metrics_enable) {
std::cout << "metrics:\n"
<< dariadb::utils::MetricsManager::instance()->to_string()
<< std::endl;
}
}
<commit_msg>debug output.<commit_after>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include "bench_common.h"
#include <algorithm>
#include <atomic>
#include <boost/program_options.hpp>
#include <chrono>
#include <cmath>
#include <ctime>
#include <dariadb.h>
#include <limits>
#include <random>
#include <storage/capacitor.h>
#include <thread>
#include <utils/fs.h>
#include <utils/metrics.h>
#include <utils/thread_manager.h>
namespace po = boost::program_options;
std::atomic_long append_count{0};
std::atomic_size_t reads_count{0};
bool stop_info = false;
bool stop_readers = false;
class BenchCallback : public dariadb::storage::ReaderClb {
public:
BenchCallback() { count = 0; }
void call(const dariadb::Meas &v) { count++; all.push_back(v);}
size_t count;
dariadb::Meas::MeasList all;
};
void show_info(dariadb::storage::Engine *storage) {
clock_t t0 = clock();
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
clock_t t1 = clock();
auto writes_per_sec =
append_count.load() / double((t1 - t0) / CLOCKS_PER_SEC);
auto reads_per_sec =
reads_count.load() / double((t1 - t0) / CLOCKS_PER_SEC);
auto queue_sizes = storage->queue_size();
std::cout << "\r"
<< " in queue: (p:" << queue_sizes.pages_count
<< " cap:" << queue_sizes.cola_count
<< " a:" << queue_sizes.aofs_count << ")"
<< " reads: " << reads_count << " speed:" << reads_per_sec
<< "/sec"
<< " writes: " << append_count << " speed: " << writes_per_sec
<< "/sec progress:"
<< (int64_t(100) * append_count) / dariadb_bench::all_writes
<< "% ";
std::cout.flush();
if (stop_info) {
std::cout.flush();
break;
}
}
std::cout << "\n";
}
void reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set,
dariadb::Time from, dariadb::Time to) {
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to);
std::shared_ptr<BenchCallback> clbk{new BenchCallback};
while (true) {
clbk->count = 0;
auto time_point1 = uniform_dist(e1);
auto f = 0;
auto t = time_point1;
auto qi = dariadb::storage::QueryInterval(
dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);
ms->readInterval(qi)->readAll(clbk.get());
reads_count += clbk->count;
if (stop_readers) {
break;
}
}
}
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
std::cout << "Performance benchmark" << std::endl;
std::cout << "Writers count:" << dariadb_bench::total_threads_count
<< std::endl;
const std::string storage_path = "perf_benchmark_storage";
bool readers_enable = false;
bool metrics_enable = false;
bool readonly = false;
bool readall_enabled = false;
bool dont_clean = false;
po::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")(
"readonly", "readonly mode")("readall", "read all benchmark enable.")(
"dont-clean", "dont clean storage path before start.")(
"enable-readers",
po::value<bool>(&readers_enable)->default_value(readers_enable),
"enable readers threads")(
"enable-metrics",
po::value<bool>(&metrics_enable)->default_value(metrics_enable));
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
} catch (std::exception &ex) {
logger("Error: " << ex.what());
exit(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
if (metrics_enable) {
std::cout << "Enable metrics." << std::endl;
}
if (vm.count("readonly")) {
std::cout << "Readonly mode." << std::endl;
readonly = true;
}
if (vm.count("readall")) {
std::cout << "Read all benchmark enabled." << std::endl;
readall_enabled = true;
}
if (vm.count("dont-clean")) {
std::cout << "Dont clean storage." << std::endl;
dont_clean = true;
}
if (readers_enable) {
std::cout << "Readers enable. count: " << dariadb_bench::total_readers_count
<< std::endl;
}
{
std::cout << "Write..." << std::endl;
const size_t chunk_per_storage = 1024 * 100;
const size_t chunk_size = 1024;
const size_t cap_B = 50;
const size_t max_mem_chunks = 100;
// dont_clean = true;
if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {
if (!readonly) {
std::cout << " remove " << storage_path << std::endl;
dariadb::utils::fs::rm(storage_path);
}
}
dariadb::Time start_time =
dariadb::Time(0); // dariadb::timeutil::current_time();
std::cout << " start time: " << dariadb::timeutil::to_string(start_time)
<< std::endl;
dariadb::storage::PageManager::Params page_param(
storage_path, chunk_per_storage, chunk_size);
dariadb::storage::CapacitorManager::Params cap_param(storage_path, cap_B);
cap_param.max_levels = 11;
cap_param.max_closed_caps = 0;
dariadb::storage::AOFManager::Params aof_param(storage_path, 0);
aof_param.buffer_size = 1000;
aof_param.max_size = cap_param.measurements_count();
cap_param.max_levels = 11;
auto raw_ptr = new dariadb::storage::Engine(
aof_param, page_param, cap_param,
dariadb::storage::Engine::Limits(max_mem_chunks));
dariadb::storage::MeasStorage_ptr ms{raw_ptr};
dariadb::IdSet all_id_set;
append_count = 0;
stop_info = false;
std::thread info_thread(show_info, raw_ptr);
std::vector<std::thread> writers(dariadb_bench::total_threads_count);
std::vector<std::thread> readers(dariadb_bench::total_readers_count);
size_t pos = 0;
for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {
auto id_from = dariadb_bench::get_id_from(pos);
auto id_to = dariadb_bench::get_id_to(pos);
for (size_t j = id_from; j < id_to; j++) {
all_id_set.insert(j);
}
if (!readonly) {
std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),
dariadb::Time(i), &append_count, raw_ptr};
writers[pos] = std::move(t);
}
pos++;
}
if (readers_enable) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {
std::thread t{reader, ms, all_id_set, dariadb::Time(0),
dariadb::timeutil::current_time()};
readers[pos++] = std::move(t);
}
}
if (!readonly) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {
std::thread t = std::move(writers[pos++]);
t.join();
}
}
stop_readers = true;
if (readers_enable) {
pos = 0;
for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {
std::thread t = std::move(readers[pos++]);
t.join();
}
}
stop_info = true;
info_thread.join();
std::cout << " total id:" << all_id_set.size() << std::endl;
{
std::cout << "full flush..." << std::endl;
stop_info = false;
std::thread flush_info_thread(show_info, raw_ptr);
auto start = clock();
raw_ptr->flush();
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
stop_info = true;
flush_info_thread.join();
std::cout << "flush time: " << elapsed << std::endl;
}
if(!readonly){
auto ccount =size_t(raw_ptr->queue_size().cola_count * 0.5);
std::cout << "drop part caps to "<<ccount<<"..." << std::endl;
stop_info = false;
std::thread flush_info_thread(show_info, raw_ptr);
auto start = clock();
raw_ptr->drop_part_caps(ccount);
raw_ptr->flush();
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
stop_info = true;
flush_info_thread.join();
std::cout << "drop time: " << elapsed << std::endl;
}
auto queue_sizes = raw_ptr->queue_size();
std::cout << "\r"
<< " in queue: (p:" << queue_sizes.pages_count
<< " cap:" << queue_sizes.cola_count
<< " a:" << queue_sizes.aofs_count << ")"
<< " reads: " << reads_count << " writes: " << append_count
<< std::endl;
dariadb_bench::readBenchark(all_id_set, ms.get(), 10, start_time,
dariadb::timeutil::current_time());
std::cout
<< "Active threads: "
<< dariadb::utils::async::ThreadManager::instance()->active_works()
<< std::endl;
if (readall_enabled) {
std::cout << "read all..." << std::endl;
std::shared_ptr<BenchCallback> clbk{new BenchCallback()};
auto max_time = ms->maxTime();
std::cout << " end time: " << dariadb::timeutil::to_string(max_time)
<< std::endl;
auto start = clock();
dariadb::storage::QueryInterval qi{
dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,
max_time};
ms->readInterval(qi)->readAll(clbk.get());
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
std::cout << "readed: " << clbk->count << std::endl;
std::cout << "time: " << elapsed << std::endl;
auto expected =
(dariadb_bench::iteration_count * dariadb_bench::total_threads_count *
dariadb_bench::id_per_thread);
std::map<dariadb::Id, dariadb::Meas::MeasList> _dict;
for (auto &v : clbk->all) {
_dict[v.id].push_back(v);
}
if (!readonly && (!dont_clean && clbk->count != expected)) {
std::cout << "expected: " << expected << " get:" << clbk->count
<< std::endl;
for(auto&kv:_dict){
std::cout<<" "<<kv.first<<" -> "<<kv.second.size()<<std::endl;
}
throw MAKE_EXCEPTION(
"(clbk->count!=(iteration_count*total_threads_count))");
} else {
if (!readonly && (dont_clean && clbk->count < expected)) {
std::cout << "expected: " << expected << " get:" << clbk->count
<< std::endl;
throw MAKE_EXCEPTION(
"(clbk->count!=(iteration_count*total_threads_count))");
}
}
}
std::cout << "stoping storage...\n";
ms = nullptr;
}
if (!(dont_clean || readonly) &&
(dariadb::utils::fs::path_exists(storage_path))) {
std::cout << "cleaning...\n";
dariadb::utils::fs::rm(storage_path);
}
if (metrics_enable) {
std::cout << "metrics:\n"
<< dariadb::utils::MetricsManager::instance()->to_string()
<< std::endl;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: VisAreaContext.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: cl $ $Date: 2001-02-21 18:04:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_VISAREACONTEXT_HXX
#define _XMLOFF_VISAREACONTEXT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif
class Rectangle;
namespace com { namespace sun { namespace star { namespace awt {
struct Rectangle;
} } } }
class XMLVisAreaContext : public SvXMLImportContext
{
public:
// read all attributes and set the values in rRect
XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
Rectangle& rRect, const MapUnit aMapUnit);
XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
::com::sun::star::awt::Rectangle& rRect, const sal_Int16 nMeasureUnit);
virtual ~XMLVisAreaContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const NAMESPACE_RTL(OUString)& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
private:
void process( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
::com::sun::star::awt::Rectangle& rRect,
const sal_Int16 nMeasureUnit );
};
#endif
<commit_msg>remove <xmloff/<commit_after>/*************************************************************************
*
* $RCSfile: VisAreaContext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: sab $ $Date: 2001-02-27 10:40:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_VISAREACONTEXT_HXX
#define _XMLOFF_VISAREACONTEXT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif
class Rectangle;
namespace com { namespace sun { namespace star { namespace awt {
struct Rectangle;
} } } }
class XMLVisAreaContext : public SvXMLImportContext
{
public:
// read all attributes and set the values in rRect
XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
Rectangle& rRect, const MapUnit aMapUnit);
XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
::com::sun::star::awt::Rectangle& rRect, const sal_Int16 nMeasureUnit);
virtual ~XMLVisAreaContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const NAMESPACE_RTL(OUString)& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
private:
void process( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
::com::sun::star::awt::Rectangle& rRect,
const sal_Int16 nMeasureUnit );
};
#endif
<|endoftext|> |
<commit_before>#ifndef GROUP__BY__HPP
#define GROUP__BY__HPP
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<iterator_deref<Container>>()));
GroupBy(Container container, KeyFunc key_func)
: container(std::forward<Container>(container)),
key_func(key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_iter_peek;
const iterator_type<Container> sub_end;
KeyFunc key_func;
public:
Iterator (iterator_type<Container> si,
iterator_type<Container> end,
KeyFunc key_func)
: sub_iter{si},
sub_end{end},
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator&) const {
return !this->exhausted();
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
iterator_deref<Container> current() {
return *this->sub_iter;
}
key_func_ret next_key() {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator& owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// movable, non-copyable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
const key_func_ret key;
const Group& group;
bool not_at_end() {
return !this->group.owner.exhausted()&&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group& group,
key_func_ret key)
: key{key},
group{group}
{ }
GroupIterator(const GroupIterator&) = default;
bool operator!=(const GroupIterator&) const {
return !this->group.completed;
#if 0
if (this->not_at_end()) {
return true;
} else {
this->group.completed = true;
return false;
}
#endif
}
bool operator==(const GroupIterator& other) const {
return !(*this != other);
}
GroupIterator& operator++() {
this->group.owner.increment_iterator();
if (!this->not_at_end()) {
this->group.completed = true;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group.owner.current();
}
};
GroupIterator begin() {
return {*this, key};
}
GroupIterator end() {
return {*this, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif //#ifndef GROUP__BY__HPP
<commit_msg>corrects include guards<commit_after>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<iterator_deref<Container>>()));
GroupBy(Container container, KeyFunc key_func)
: container(std::forward<Container>(container)),
key_func(key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_iter_peek;
const iterator_type<Container> sub_end;
KeyFunc key_func;
public:
Iterator (iterator_type<Container> si,
iterator_type<Container> end,
KeyFunc key_func)
: sub_iter{si},
sub_end{end},
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator&) const {
return !this->exhausted();
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
iterator_deref<Container> current() {
return *this->sub_iter;
}
key_func_ret next_key() {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator& owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// movable, non-copyable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
const key_func_ret key;
const Group& group;
bool not_at_end() {
return !this->group.owner.exhausted()&&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group& group,
key_func_ret key)
: key{key},
group{group}
{ }
GroupIterator(const GroupIterator&) = default;
bool operator!=(const GroupIterator&) const {
return !this->group.completed;
#if 0
if (this->not_at_end()) {
return true;
} else {
this->group.completed = true;
return false;
}
#endif
}
bool operator==(const GroupIterator& other) const {
return !(*this != other);
}
GroupIterator& operator++() {
this->group.owner.increment_iterator();
if (!this->not_at_end()) {
this->group.completed = true;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group.owner.current();
}
};
GroupIterator begin() {
return {*this, key};
}
GroupIterator end() {
return {*this, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_
#include "iterbase.hpp"
#include <type_traits>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret = typename
std::result_of<KeyFunc(iterator_deref<Container>)>::type;
GroupBy(Container&& in_container, KeyFunc in_key_func)
: container(std::forward<Container>(in_container)),
key_func(in_key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
DerefHolder<iterator_deref<Container>> item;
KeyFunc *key_func;
public:
Iterator(iterator_type<Container>&& si,
iterator_type<Container>&& end,
KeyFunc& in_key_func)
: sub_iter{std::move(si)},
sub_end{std::move(end)},
key_func(&in_key_func)
{
if (this->sub_iter != this->sub_end) {
this->item.reset(*this->sub_iter);
}
}
KeyGroupPair operator*() {
// FIXME double deref
return {
(*this->key_func)(this->item.get()),
Group{*this, (*this->key_func)(this->item.get())}
};
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
this->item.reset(*this->sub_iter);
}
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
iterator_deref<Container> pull() {
return this->item.pull();
}
// FIXME double deref. Two deref holders?
key_func_ret next_key() {
return (*this->key_func)(this->item.get());
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
bool completed = false;
Group(Iterator& in_owner, key_func_ret in_key) :
owner(in_owner),
key(in_key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// move-constructible, non-copy-constructible,
// non-assignable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
typename std::remove_reference<key_func_ret>::type *key;
Group *group_p;
bool not_at_end() {
return !this->group_p->owner.exhausted()&&
this->group_p->owner.next_key() == *this->key;
}
public:
GroupIterator(Group *in_group_p,
key_func_ret& in_key)
: key{&in_key},
group_p{in_group_p}
{ }
bool operator!=(const GroupIterator& other) const {
return !(*this == other);
}
bool operator==(const GroupIterator& other) const {
return this->group_p == other.group_p;
}
GroupIterator& operator++() {
this->group_p->owner.increment_iterator();
if (!this->not_at_end()) {
this->group_p->completed = true;
this->group_p = nullptr;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group_p->owner.pull();
}
};
GroupIterator begin() {
return {this, key};
}
GroupIterator end() {
return {nullptr, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif
<commit_msg>groupby uses get() instead of pull()<commit_after>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_
#include "iterbase.hpp"
#include <type_traits>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret = typename
std::result_of<KeyFunc(iterator_deref<Container>)>::type;
GroupBy(Container&& in_container, KeyFunc in_key_func)
: container(std::forward<Container>(in_container)),
key_func(in_key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
using Holder = DerefHolder<iterator_deref<Container>>;
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
Holder item;
KeyFunc *key_func;
public:
Iterator(iterator_type<Container>&& si,
iterator_type<Container>&& end,
KeyFunc& in_key_func)
: sub_iter{std::move(si)},
sub_end{std::move(end)},
key_func(&in_key_func)
{
if (this->sub_iter != this->sub_end) {
this->item.reset(*this->sub_iter);
}
}
KeyGroupPair operator*() {
return {
(*this->key_func)(this->item.get()),
Group{*this, (*this->key_func)(this->item.get())}
};
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
this->item.reset(*this->sub_iter);
}
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
typename Holder::reference get() {
return this->item.get();
}
key_func_ret next_key() {
return (*this->key_func)(this->item.get());
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
bool completed = false;
Group(Iterator& in_owner, key_func_ret in_key) :
owner(in_owner),
key(in_key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// move-constructible, non-copy-constructible,
// non-assignable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
typename std::remove_reference<key_func_ret>::type *key;
Group *group_p;
bool not_at_end() {
return !this->group_p->owner.exhausted()&&
this->group_p->owner.next_key() == *this->key;
}
public:
GroupIterator(Group *in_group_p,
key_func_ret& in_key)
: key{&in_key},
group_p{in_group_p}
{ }
bool operator!=(const GroupIterator& other) const {
return !(*this == other);
}
bool operator==(const GroupIterator& other) const {
return this->group_p == other.group_p;
}
GroupIterator& operator++() {
this->group_p->owner.increment_iterator();
if (!this->not_at_end()) {
this->group_p->completed = true;
this->group_p = nullptr;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group_p->owner.get();
}
};
GroupIterator begin() {
return {this, key};
}
GroupIterator end() {
return {nullptr, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif
<|endoftext|> |
<commit_before>
#include "simulation.h"
/*! \mainpage Molecular Simulation
*
* \section int_sec Introduction
*
* \par This program is a simulated molecular lab for experimenting with DNA operations.
*
* \par Execution of a directory of DIMACS CNF (*.cnf) expressions can be performed with the Perl runSimulation.pl.
*
* \section sys_sec System requirements
*
* \par MolecularSimulation requires the following software to be installed on your system:
* - GCC
* - Perl
*
* \par Additional requirements for generating documentation:
* - Doxygen
*
* \par This program was designed to execute in a 64-bit *NIX environment. It has been tested on Apple OS X 10.6.8. The final build will execute natively on the RIT CS machines (portability of the Perl scripts is in progress).
*
* \section alg_sec Algorithms
* \par There are three molecular Satisfiability algorithms implemented in this environment.
*
* \subsection lip_sec Lipton's algorithm
*
* \par Introduced in 1995 by Lipton, this algorithm creates an exponential search space for the CNF expression. Once the space is created, each variable is evaluated and the space is reduced to only the solutions that satisfy all remaining strings. This algorithm is analogous to a conventional brute-force search for all solutions.
*
* \subsection ogi_sec Ogihara and Ray's algorithm
*
* \par Originally introduced in 1996 by Ogihara, and extended in 1997 with Ray, this algorithm builds a solution space with a breadth-first search evaluation. Prior to execution to the algorithm, each of the clauses variable's in the CNF expression are sorted.
*
* \subsection dis_sec Distribution algorithm
*
* \par The distribution algorithm parses an input CNF expression into growing and self regulated set of possible combinations. A possible combination begins with all members of the first clause, and subsequent variables from independent clauses are built upon the reduced state. If there exist self-complementary assignments spanning a clause, then the clause is eliminated.
*
* \section exe_sec Execution
*
* \par Automation of execution can be done simply by executing the perl script
*
* $ perl runSimulation.pl
*
* \par from the directory: project/implementation/molecularSimulation/
*
* \par This file will sequentially invoke `build.pl' and `executeMolecularSat.pl'
*
* \subsection input_sec Input
*
* \par Input is provided as DIMACS CNF (*.cnf) to execute a specified algorithm. Arguments may be provided to assist in debugging (-d) or write the simulation results to a file.
*
*
* \subsection output_sec Output
*
* \par Output consists of a summary of a test execution. This output conforms to the SAT Competition format for the status of the `*.cnf' expression. If desired, the output may be directed to a file. Conditional formatting of comment fields provide execution details.
*/
///
/// Default constructor for simulation.
///
simulation::simulation(){
}
///
/// Destructor for simulation.
///
simulation::~simulation(){
}
///
/// Start simulation.
///
void simulation::start(int argc, char ** argv){
arguments testArguments;
// Set version revision number
testArguments.versionNumber = (char*) malloc (10);
strcpy(testArguments.versionNumber, "1.0.1");
testArguments.parseArguments(argc, argv); ///< Parse user arguments
// Print debug argument list
if(testArguments.debug) testArguments.printArguments();
testArguments.inputCNF.parseCNF( testArguments.filename); ///< Parse DIMACS CNF
// Print CNF details
/*
if(testArguments.debug){
testArguments.inputCNF.printCNF_table();
testArguments.inputCNF.printCNF_order();
}
*/
testArguments = executeTest(testArguments); ///< Execute algorithm
testArguments.writeOutput(); ///< Write output results
// Print debug argument list
if(testArguments.debug) testArguments.printArguments();
}
///
/// main simulation entry
///
int main(int argc, char ** argv){
simulation myRun;
myRun.start(argc, argv);
return 0;
}
<commit_msg>Main entry<commit_after>#include "simulation.h"
/*! \mainpage Molecular Simulation
*
* \section int_sec Introduction
*
* \par This program is a simulated molecular lab for experimenting with DNA operations.
*
* \par Execution of a directory of DIMACS CNF (*.cnf) expressions can be performed with the Perl runSimulation.pl.
*
* \section sys_sec System requirements
*
* \par MolecularSimulation requires the following software to be installed on your system:
* - GCC
* - Perl
*
* \par Additional requirements for generating documentation:
* - Doxygen
*
* \par This program was designed to execute in a 64-bit *NIX environment. It has been tested on Apple OS X 10.6.8. The final build will execute natively on the RIT CS machines (portability of the Perl scripts is in progress).
*
* \section alg_sec Algorithms
* \par There are three molecular Satisfiability algorithms implemented in this environment.
*
* \subsection lip_sec Lipton's algorithm
*
* \par Introduced in 1995 by Lipton, this algorithm creates an exponential search space for the CNF expression. Once the space is created, each variable is evaluated and the space is reduced to only the solutions that satisfy all remaining strings. This algorithm is analogous to a conventional brute-force search for all solutions.
*
* \subsection ogi_sec Ogihara and Ray's algorithm
*
* \par Originally introduced in 1996 by Ogihara, and extended in 1997 with Ray, this algorithm builds a solution space with a breadth-first search evaluation. Prior to execution to the algorithm, each of the clauses variable's in the CNF expression are sorted.
*
* \subsection dis_sec Distribution algorithm
*
* \par The distribution algorithm parses an input CNF expression into growing and self regulated set of possible combinations. A possible combination begins with all members of the first clause, and subsequent variables from independent clauses are built upon the reduced state. If there exist self-complementary assignments spanning a clause, then the clause is eliminated.
*
* \section exe_sec Execution
*
* \par Automation of execution can be done simply by executing the perl script
*
* $ perl runSimulation.pl
*
* \par from the directory: project/implementation/molecularSimulation/
*
* \par This file will sequentially invoke `build.pl' and `executeMolecularSat.pl'
*
* \subsection input_sec Input
*
* \par Input is provided as DIMACS CNF (*.cnf) to execute a specified algorithm. Arguments may be provided to assist in debugging (-d) or write the simulation results to a file.
*
*
* \subsection output_sec Output
*
* \par Output consists of a summary of a test execution. This output conforms to the SAT Competition format for the status of the `*.cnf' expression. If desired, the output may be directed to a file. Conditional formatting of comment fields provide execution details.
*/
///
/// Default constructor for simulation.
///
simulation::simulation(){
}
///
/// Destructor for simulation.
///
simulation::~simulation(){
}
///
/// Start simulation.
///
void simulation::start(int argc, char ** argv){
arguments testArguments;
// Set version revision number
testArguments.versionNumber = (char*) malloc (10);
strcpy(testArguments.versionNumber, "1.0.1");
testArguments.parseArguments(argc, argv); ///< Parse user arguments
// Print debug argument list
if(testArguments.debug) testArguments.printArguments();
testArguments.inputCNF.parseCNF( testArguments.filename); ///< Parse DIMACS CNF
// Print CNF details
/*
if(testArguments.debug){
testArguments.inputCNF.printCNF_table();
testArguments.inputCNF.printCNF_order();
}
*/
testArguments = executeTest(testArguments); ///< Execute algorithm
testArguments.writeOutput(); ///< Write output results
// Print debug argument list
if(testArguments.debug) testArguments.printArguments();
}
///
/// main simulation entry
///
int main(int argc, char ** argv){
simulation myRun;
myRun.start(argc, argv);
return 0;
}
<|endoftext|> |
<commit_before>// time complexity - O(n)
// space complexity - O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
if (nums.size() == 1) return 1;
int size = nums.size();
int i = 1;
int last = nums[0];
while (i < size) {
if (last == nums[i]) {
nums.erase(nums.begin() + i);
size--;
} else {
last = nums[i];
i++;
}
}
return i;
}
};<commit_msg>updated removeDupe.cpp<commit_after>// time complexity - O(n)
// space complexity - O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int writing = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[writing-1] != nums[i]) {
nums[writing++] = nums[i];
}
}
return writing;
}
};<|endoftext|> |
<commit_before>// Correctness 100%
// Performance 80%
// Task score 90%
// you can use includes, for example:
// #include <algorithm>
#include <bitset>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(int M, vector<int> &A) {
// for(unsigned int i=0; i<A.size(); ++i)
// cout << A[i] << " ";
// cout << endl;
// write your code in C++11
long i(0);
long j(0);
long k(0);
long count(0);
bitset<100001> mybitset;
vector<long> myvector(100001,0);
while( i<A.size() ) {
// cout << i << " " << j << " ";
if( j<A.size() ) {
if( mybitset[A[j]]==0 ) {
mybitset[A[j]]= 1;
myvector[A[j]]= j;
j++;
}
else {
k=myvector[A[j]];
// cout << i << " " << k << " " << j << endl;
count += (j-i+2)*(j-i+1)/2;
count -= k-i+1;
count -= (j-k+1)*(j-k)/2;
i=k+1;
j=i;
mybitset.reset();
}
}
else {
count += (j-i+1)*(j-i)/2;
i=j;
}
if( count>1000000000 )
return 1000000000;
// cout << count << endl;
}
return count;
}
<commit_msg>Update solution.cpp<commit_after>// Correctness 100%
// Performance 80%
// Task score 90%
// Note: codility may have a bug here
// because random access for vector should be O(1)
// i.e. performance will be not affected by N
// but in the codility test, the performance drops linear like O(N)
// you can use includes, for example:
// #include <algorithm>
#include <bitset>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(int M, vector<int> &A) {
// for(unsigned int i=0; i<A.size(); ++i)
// cout << A[i] << " ";
// cout << endl;
// write your code in C++11
long i(0);
long j(0);
long k(0);
long count(0);
bitset<100001> mybitset;
vector<long> myvector(100001,0);
while( i<A.size() ) {
// cout << i << " " << j << " ";
if( j<A.size() ) {
if( mybitset[A[j]]==0 ) {
mybitset[A[j]]= 1;
myvector[A[j]]= j;
j++;
}
else {
k=myvector[A[j]];
// cout << i << " " << k << " " << j << endl;
count += (j-i+2)*(j-i+1)/2;
count -= k-i+1;
count -= (j-k+1)*(j-k)/2;
i=k+1;
j=i;
mybitset.reset();
}
}
else {
count += (j-i+1)*(j-i)/2;
i=j;
}
if( count>1000000000 )
return 1000000000;
// cout << count << endl;
}
return count;
}
<|endoftext|> |
<commit_before>// Copyright 2013 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/local_discovery/service_discovery_shared_client.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_WIN)
#include "base/files/file_path.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/local_discovery/service_discovery_client_utility.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/firewall_manager_win.h"
#endif // OS_WIN
#if defined(OS_MACOSX)
#include "chrome/browser/local_discovery/service_discovery_client_mac_factory.h"
#endif
#if defined(ENABLE_MDNS)
#include "chrome/browser/local_discovery/service_discovery_client_mdns.h"
#endif // ENABLE_MDNS
namespace {
#if defined(OS_WIN)
bool IsFirewallReady() {
base::FilePath exe_path;
if (!PathService::Get(base::FILE_EXE, &exe_path))
return false;
base::ElapsedTimer timer;
scoped_ptr<installer::FirewallManager> manager =
installer::FirewallManager::Create(BrowserDistribution::GetDistribution(),
exe_path);
if (!manager)
return false;
bool is_ready = manager->CanUseLocalPorts();
UMA_HISTOGRAM_TIMES("LocalDiscovery.FirewallAccessTime", timer.Elapsed());
UMA_HISTOGRAM_BOOLEAN("LocalDiscovery.IsFirewallReady", is_ready);
return is_ready;
}
#endif // OS_WIN
} // namespace
namespace local_discovery {
using content::BrowserThread;
namespace {
ServiceDiscoverySharedClient* g_service_discovery_client = NULL;
} // namespace
ServiceDiscoverySharedClient::ServiceDiscoverySharedClient() {
DCHECK(!g_service_discovery_client);
g_service_discovery_client = this;
}
ServiceDiscoverySharedClient::~ServiceDiscoverySharedClient() {
DCHECK_EQ(g_service_discovery_client, this);
g_service_discovery_client = NULL;
}
#if defined(ENABLE_MDNS) || defined(OS_MACOSX)
scoped_refptr<ServiceDiscoverySharedClient>
ServiceDiscoverySharedClient::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (g_service_discovery_client)
return g_service_discovery_client;
#if defined(OS_MACOSX)
return ServiceDiscoveryClientMacFactory::CreateInstance();
#else
#if defined(OS_WIN)
static bool is_firewall_ready = IsFirewallReady();
if (!is_firewall_ready) {
// TODO(vitalybuka): Remove after we find what to do with firewall for
// user-level installs. crbug.com/366408
return new ServiceDiscoveryClientUtility();
}
#endif // OS_WIN
return new ServiceDiscoveryClientMdns();
#endif
}
#else
scoped_refptr<ServiceDiscoverySharedClient>
ServiceDiscoverySharedClient::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
NOTIMPLEMENTED();
return NULL;
}
#endif // ENABLE_MDNS
} // namespace local_discovery
<commit_msg>Disable firewall check. It takes signifficant time, need to be on FILE thread.<commit_after>// Copyright 2013 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/local_discovery/service_discovery_shared_client.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_WIN)
#include "base/files/file_path.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/local_discovery/service_discovery_client_utility.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/firewall_manager_win.h"
#endif // OS_WIN
#if defined(OS_MACOSX)
#include "chrome/browser/local_discovery/service_discovery_client_mac_factory.h"
#endif
#if defined(ENABLE_MDNS)
#include "chrome/browser/local_discovery/service_discovery_client_mdns.h"
#endif // ENABLE_MDNS
namespace {
#if defined(OS_WIN)
void ReportFirewallStats() {
base::FilePath exe_path;
if (!PathService::Get(base::FILE_EXE, &exe_path))
return;
base::ElapsedTimer timer;
scoped_ptr<installer::FirewallManager> manager =
installer::FirewallManager::Create(BrowserDistribution::GetDistribution(),
exe_path);
if (!manager)
return;
bool is_ready = manager->CanUseLocalPorts();
UMA_HISTOGRAM_TIMES("LocalDiscovery.FirewallAccessTime", timer.Elapsed());
UMA_HISTOGRAM_BOOLEAN("LocalDiscovery.IsFirewallReady", is_ready);
}
#endif // OS_WIN
} // namespace
namespace local_discovery {
using content::BrowserThread;
namespace {
ServiceDiscoverySharedClient* g_service_discovery_client = NULL;
} // namespace
ServiceDiscoverySharedClient::ServiceDiscoverySharedClient() {
DCHECK(!g_service_discovery_client);
g_service_discovery_client = this;
}
ServiceDiscoverySharedClient::~ServiceDiscoverySharedClient() {
DCHECK_EQ(g_service_discovery_client, this);
g_service_discovery_client = NULL;
}
#if defined(ENABLE_MDNS) || defined(OS_MACOSX)
scoped_refptr<ServiceDiscoverySharedClient>
ServiceDiscoverySharedClient::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (g_service_discovery_client)
return g_service_discovery_client;
#if defined(OS_MACOSX)
return ServiceDiscoveryClientMacFactory::CreateInstance();
#else
#if defined(OS_WIN)
static bool reported =
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&ReportFirewallStats));
// TODO(vitalybuka): Switch to |ServiceDiscoveryClientMdns| after we find what
// to do with firewall for user-level installs. crbug.com/366408
return new ServiceDiscoveryClientUtility();
#endif // OS_WIN
return new ServiceDiscoveryClientMdns();
#endif
}
#else
scoped_refptr<ServiceDiscoverySharedClient>
ServiceDiscoverySharedClient::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
NOTIMPLEMENTED();
return NULL;
}
#endif // ENABLE_MDNS
} // namespace local_discovery
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/privacy_blacklist/blacklist_manager.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
const GURL& url,
bool *has_match) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
*has_match = (match.get() != NULL);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new MessageLoop::QuitTask());
}
} // namespace
class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
public:
virtual void SetUp() {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnablePrivacyBlacklists);
ExtensionBrowserTest::SetUp();
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
received_blacklist_notification_ = false;
host_resolver()->AddSimulatedFailure("www.example.com");
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
ExtensionBrowserTest::Observe(type, source, details);
return;
}
received_blacklist_notification_ = true;
MessageLoop::current()->Quit();
}
protected:
BlacklistManager* GetBlacklistManager() {
return browser()->profile()->GetBlacklistManager();
}
bool GetAndResetReceivedBlacklistNotification() {
bool result = received_blacklist_notification_;
received_blacklist_notification_ = false;
return result;
}
bool BlacklistHasMatch(const std::string& url) {
bool has_match = false;
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
GetBlacklistManager(),
GURL(url),
&has_match));
ui_test_utils::RunMessageLoop();
return has_match;
}
private:
bool received_blacklist_notification_;
};
IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, Basic) {
static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";
NotificationRegistrar registrar;
registrar.Add(this,
NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
Source<Profile>(browser()->profile()));
// Test loading an extension with blacklist.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));
// Wait until the blacklist is loaded and ready.
if (!GetAndResetReceivedBlacklistNotification())
ui_test_utils::RunMessageLoop();
// The blacklist should block our test URL.
EXPECT_TRUE(BlacklistHasMatch(kTestUrl));
// TODO(phajdan.jr): Verify that we really blocked the request etc.
ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<commit_msg>Mark BlacklistManagerBrowserTest.Basic as flaky. BUG=29113<commit_after>// Copyright (c) 2009 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/privacy_blacklist/blacklist_manager.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
const GURL& url,
bool *has_match) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
*has_match = (match.get() != NULL);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new MessageLoop::QuitTask());
}
} // namespace
class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
public:
virtual void SetUp() {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnablePrivacyBlacklists);
ExtensionBrowserTest::SetUp();
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
received_blacklist_notification_ = false;
host_resolver()->AddSimulatedFailure("www.example.com");
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
ExtensionBrowserTest::Observe(type, source, details);
return;
}
received_blacklist_notification_ = true;
MessageLoop::current()->Quit();
}
protected:
BlacklistManager* GetBlacklistManager() {
return browser()->profile()->GetBlacklistManager();
}
bool GetAndResetReceivedBlacklistNotification() {
bool result = received_blacklist_notification_;
received_blacklist_notification_ = false;
return result;
}
bool BlacklistHasMatch(const std::string& url) {
bool has_match = false;
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
GetBlacklistManager(),
GURL(url),
&has_match));
ui_test_utils::RunMessageLoop();
return has_match;
}
private:
bool received_blacklist_notification_;
};
IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, FLAKY_Basic) {
static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";
NotificationRegistrar registrar;
registrar.Add(this,
NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
Source<Profile>(browser()->profile()));
// Test loading an extension with blacklist.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));
// Wait until the blacklist is loaded and ready.
if (!GetAndResetReceivedBlacklistNotification())
ui_test_utils::RunMessageLoop();
// The blacklist should block our test URL.
EXPECT_TRUE(BlacklistHasMatch(kTestUrl));
// TODO(phajdan.jr): Verify that we really blocked the request etc.
ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<|endoftext|> |
<commit_before><commit_msg>coverity#707864 Uninitialized scalar field<commit_after><|endoftext|> |
<commit_before>// JPetReader.cpp - Reader
#include "JPetReader.h"
#include <cassert>
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"
JPetReader::JPetReader() :
fBranch(0),
fEvent(0),
fTree(0),
fFile(0),
fCurrentEventNumber(-1)
{/**/}
JPetReader::JPetReader(const char* p_filename) :
fBranch(0),
fEvent(0),
fTree(0),
fFile(0),
fCurrentEventNumber(-1)
{
if (!openFileAndLoadData(p_filename, "tree")) {
ERROR("error in opening file");
}
}
JPetReader::~JPetReader()
{
if (fFile) {
delete fFile;
fFile = 0;
}
}
JPetReader::MyEvent& JPetReader::getCurrentEvent()
{
if (loadCurrentEvent()) {
return *fEvent;
} else {
ERROR("Could not read the current event");
if (fEvent) {
delete fEvent;
}
fEvent = new TNamed("Empty event", "Empty event");
}
return *fEvent;
}
bool JPetReader::JPetReader::nextEvent()
{
fCurrentEventNumber++;
return loadCurrentEvent();
}
bool JPetReader::firstEvent()
{
fCurrentEventNumber = 0;
return loadCurrentEvent();
}
bool JPetReader::lastEvent()
{
fCurrentEventNumber = getNbOfAllEvents() - 1;
return loadCurrentEvent();
}
bool JPetReader::nthEvent(int n)
{
fCurrentEventNumber = n;
return loadCurrentEvent();
}
void JPetReader::closeFile ()
{
if (fFile) delete fFile;
fFile = 0;
fBranch = 0;
fEvent = 0;
fTree = 0;
fCurrentEventNumber = -1;
}
bool JPetReader::openFile (const char* filename)
{
closeFile();
fFile = new TFile(filename);
if ((!isOpen()) || fFile->IsZombie()) {
ERROR(std::string("Cannot open file:")+std::string(filename));
return false;
}
return true;
}
bool JPetReader::loadData(const char* treename)
{
if (!isOpen() ) {
ERROR("File not open");
return false;
}
if (!treename) {
ERROR("empty tree name");
return false;
}
fTree = static_cast<TTree*>(fFile->Get(treename));
if (!fTree) {
ERROR("in reading tree");
return false;
}
TObjArray* arr = fTree->GetListOfBranches();
fBranch = (TBranch*)(arr->At(0));
if (!fBranch) {
ERROR("in reading branch from tree");
return false;
}
fBranch->SetAddress(&fEvent);
firstEvent();
return true;
}
/**
* @brief Returns a copy of the header read from input file.
*
* Using a copy rather than direct pointer is essential as the original header belongs to JPetReader::fTree and would be deleted along with it.
*/
JPetTreeHeader* JPetReader::getHeaderClone() const
{
if (!fTree) {
ERROR("No tree available");
return 0;
}
// get a pointer to a header wchich belongs to fTree
JPetTreeHeader* header = (JPetTreeHeader*)fTree->GetUserInfo()->At(JPetUserInfoStructure::kHeader);
// return a COPY of this header
return new JPetTreeHeader( *header );
}
<commit_msg>Reformatting JPetReader.cpp<commit_after>// JPetReader.cpp - Reader
#include "JPetReader.h"
#include <cassert>
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"
JPetReader::JPetReader() :
fBranch(0),
fEvent(0),
fTree(0),
fFile(0),
fCurrentEventNumber(-1)
{/**/}
JPetReader::JPetReader(const char* p_filename) :
fBranch(0),
fEvent(0),
fTree(0),
fFile(0),
fCurrentEventNumber(-1)
{
if (!openFileAndLoadData(p_filename, "tree")) {
ERROR("error in opening file");
}
}
JPetReader::~JPetReader()
{
if (fFile) {
delete fFile;
fFile = 0;
}
}
JPetReader::MyEvent& JPetReader::getCurrentEvent()
{
if (loadCurrentEvent()) {
return *fEvent;
} else {
ERROR("Could not read the current event");
if (fEvent) {
delete fEvent;
}
fEvent = new TNamed("Empty event", "Empty event");
}
return *fEvent;
}
bool JPetReader::JPetReader::nextEvent()
{
fCurrentEventNumber++;
return loadCurrentEvent();
}
bool JPetReader::firstEvent()
{
fCurrentEventNumber = 0;
return loadCurrentEvent();
}
bool JPetReader::lastEvent()
{
fCurrentEventNumber = getNbOfAllEvents() - 1;
return loadCurrentEvent();
}
bool JPetReader::nthEvent(int n)
{
fCurrentEventNumber = n;
return loadCurrentEvent();
}
void JPetReader::closeFile ()
{
if (fFile) delete fFile;
fFile = 0;
fBranch = 0;
fEvent = 0;
fTree = 0;
fCurrentEventNumber = -1;
}
bool JPetReader::openFile (const char* filename)
{
closeFile();
fFile = new TFile(filename);
if ((!isOpen()) || fFile->IsZombie()) {
ERROR(std::string("Cannot open file:")+std::string(filename));
return false;
}
return true;
}
bool JPetReader::loadData(const char* treename)
{
if (!isOpen() ) {
ERROR("File not open");
return false;
}
if (!treename) {
ERROR("empty tree name");
return false;
}
fTree = static_cast<TTree*>(fFile->Get(treename));
if (!fTree) {
ERROR("in reading tree");
return false;
}
TObjArray* arr = fTree->GetListOfBranches();
fBranch = (TBranch*)(arr->At(0));
if (!fBranch) {
ERROR("in reading branch from tree");
return false;
}
fBranch->SetAddress(&fEvent);
firstEvent();
return true;
}
/**
* @brief Returns a copy of the header read from input file.
*
* Using a copy rather than direct pointer is essential as the original header belongs to JPetReader::fTree and would be deleted along with it.
*/
JPetTreeHeader* JPetReader::getHeaderClone() const
{
if (!fTree) {
ERROR("No tree available");
return 0;
}
// get a pointer to a header wchich belongs to fTree
JPetTreeHeader* header = (JPetTreeHeader*)fTree->GetUserInfo()->At(JPetUserInfoStructure::kHeader);
// return a COPY of this header
return new JPetTreeHeader( *header );
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if(eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";")
for(int i = 0; i < xDataList.GetCount(); ++i)
{
if(nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if(nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for(bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",")
if(xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if(strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if(nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<commit_msg>fixed for compile<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if (eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";");
for (int i = 0; i < xDataList.GetCount(); ++i)
{
if (nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",");
if (xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if (strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if (nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<|endoftext|> |
<commit_before>// NearIntegers.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main(int argc, char* argv[])
{
const double epsilon = 0.0000001;
srand(static_cast<unsigned int>(time(NULL)));
while (1)
{
ExpressionMaker e;
// Hack
if (std::find(e.opCodes.begin(), e.opCodes.end(), Op_sin) == e.opCodes.end())
{
continue;
}
//printf("TESTING: \n");
//e.Dump();
double ret = e.Run();
double modResult = fmod(ret, 1);
// printf("MODRESULT: %.32f, %d, %d\n", modResult, static_cast<int>(modResult), static_cast<int>(modResult) != modResult);
if (fabs(fmod(ret, 1)) < epsilon && fabs(ret) > 1 && fabs(ret) < 10 && static_cast<int>(modResult) != modResult)
{
printf("Found result: %f\n", ret);
e.Dump();
printf("\n");
}
}
return 0;
}
ExpressionMaker::ExpressionMaker()
{
int stackDepth = 1;
opCodes.push_back(Op_value);
while (1)
{
OpCode op;
if (opCodes.size() > MaxOpCodes)
{
break;
}
else
{
op = static_cast<OpCode>(rand() % Op_value);
}
for (int i = stackDepth; i < opCodeArgCount[op]; ++i)
{
opCodes.push_back(Op_value);
stackDepth++;
}
opCodes.push_back(op);
stackDepth -= opCodeArgCount[op] - 1;
}
}
void ExpressionMaker::Dump()
{
auto it = values.begin();
for (OpCode op : opCodes)
{
if (op == Op_value && it != values.end())
{
printf("%f\n", *it++);
}
else
{
printf("%s\n", opCodeNames[op]);
}
}
assert(it == values.end());
}
double ExpressionMaker::MakeValue()
{
return rand() % 100;
}
double ExpressionMaker::Run()
{
std::list<double> stack;
for (OpCode op : opCodes)
{
std::vector<double> args;
assert(stack.size() >= static_cast<size_t>(opCodeArgCount[op]));
// Build the arguments list.
for (int i = 0; i < opCodeArgCount[op]; ++i)
{
args.push_back(stack.back());
stack.pop_back();
}
double val;
switch (op)
{
case Op_value:
val = MakeValue();
values.push_back(val);
stack.push_back(val);
break;
case Op_add:
stack.push_back(args[0] + args[1]);
break;
case Op_mul:
stack.push_back(args[0] * args[1]);
break;
case Op_div:
stack.push_back(args[0] / args[1]);
break;
case Op_sin:
stack.push_back(sin(args[0]));
break;
case Op_log:
stack.push_back(log(args[0]));
break;
}
}
// TODO: we will insert unnecessary values sometimes, ignore this
// assert(stack.size() == 1);
return stack.back();
}
char *opCodeNames[] = {
#define OPCODE(name, numArgs) \
#name
#include "OpCodes.h"
#undef OPCODE
};
int opCodeArgCount[] = {
#define OPCODE(name, numArgs) \
numArgs
#include "OpCodes.h"
#undef OPCODE
};
<commit_msg>Add a MRU list<commit_after>// NearIntegers.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main(int argc, char* argv[])
{
const double epsilon = 0.00000001;
srand(static_cast<unsigned int>(time(NULL)));
std::list<std::list<OpCode>> seen;
while (1)
{
ExpressionMaker e;
// Hack
if (std::find(e.opCodes.begin(), e.opCodes.end(), Op_sin) == e.opCodes.end())
{
continue;
}
//printf("TESTING: \n");
//e.Dump();
double ret = e.Run();
double modResult = fmod(ret, 1);
// printf("MODRESULT: %.32f, %d, %d\n", modResult, static_cast<int>(modResult), static_cast<int>(modResult) != modResult);
if (fabs(fmod(ret, 1)) < epsilon && fabs(ret) > 1 && fabs(ret) < 10 && static_cast<int>(modResult) != modResult)
{
// This is expensive, but should be rare.
bool seenBefore = false;
for (auto it = seen.begin(); it != seen.end(); ++it)
{
if (it->size() == e.opCodes.size())
{
for (auto x1 = it->begin(), x2 = e.opCodes.begin(); x1 != it->end(); ++x1, ++x2)
{
if (*x1 != *x2)
{
break;
}
}
seenBefore = true;
break;
}
}
if (!seenBefore)
{
printf("Found result: %f\n", ret);
e.Dump();
printf("\n");
seen.push_back(e.opCodes);
}
}
}
return 0;
}
ExpressionMaker::ExpressionMaker()
{
int stackDepth = 1;
opCodes.push_back(Op_value);
while (1)
{
OpCode op;
if (opCodes.size() > MaxOpCodes)
{
break;
}
else
{
op = static_cast<OpCode>(rand() % Op_value);
}
for (int i = stackDepth; i < opCodeArgCount[op]; ++i)
{
opCodes.push_back(Op_value);
stackDepth++;
}
opCodes.push_back(op);
stackDepth -= opCodeArgCount[op] - 1;
}
}
void ExpressionMaker::Dump()
{
auto it = values.begin();
for (OpCode op : opCodes)
{
if (op == Op_value && it != values.end())
{
printf("%f\n", *it++);
}
else
{
printf("%s\n", opCodeNames[op]);
}
}
assert(it == values.end());
}
double ExpressionMaker::MakeValue()
{
return rand() % 100;
}
double ExpressionMaker::Run()
{
std::list<double> stack;
for (OpCode op : opCodes)
{
std::vector<double> args;
assert(stack.size() >= static_cast<size_t>(opCodeArgCount[op]));
// Build the arguments list.
for (int i = 0; i < opCodeArgCount[op]; ++i)
{
args.push_back(stack.back());
stack.pop_back();
}
double val;
switch (op)
{
case Op_value:
val = MakeValue();
values.push_back(val);
stack.push_back(val);
break;
case Op_add:
stack.push_back(args[0] + args[1]);
break;
case Op_mul:
stack.push_back(args[0] * args[1]);
break;
case Op_div:
stack.push_back(args[0] / args[1]);
break;
case Op_sin:
stack.push_back(sin(args[0]));
break;
case Op_log:
stack.push_back(log(args[0]));
break;
}
}
// TODO: we will insert unnecessary values sometimes, ignore this
// assert(stack.size() == 1);
return stack.back();
}
char *opCodeNames[] = {
#define OPCODE(name, numArgs) \
#name
#include "OpCodes.h"
#undef OPCODE
};
int opCodeArgCount[] = {
#define OPCODE(name, numArgs) \
numArgs
#include "OpCodes.h"
#undef OPCODE
};
<|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.
===================================================================*/
#include "mitkVerboseLimitedLinearUndo.h"
#include "mitkOperationEvent.h"
mitk::VerboseLimitedLinearUndo::VerboseLimitedLinearUndo()
{
}
mitk::VerboseLimitedLinearUndo::~VerboseLimitedLinearUndo()
{
}
bool mitk::VerboseLimitedLinearUndo::SetOperationEvent(UndoStackItem *undoStackItem)
{
if (!undoStackItem)
return false;
// clear the redolist, if a new operation is saved
if (!m_RedoList.empty())
{
this->ClearList(&m_RedoList);
InvokeEvent(RedoEmptyEvent());
}
std::size_t undoLimit = this->GetUndoLimit();
if (undoLimit > 0 && m_UndoList.size() == undoLimit)
{
m_UndoList.pop_front();
}
m_UndoList.push_back(undoStackItem);
InvokeEvent(UndoNotEmptyEvent());
return true;
}
mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetUndoDescriptions()
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions;
if (m_UndoList.empty())
return descriptions;
int oeid = m_UndoList.back()->GetObjectEventId(); // ObjectEventID of current group
std::string currentDescription; // description of current group
int currentDescriptionCount(0); // counter, how many items of the current group gave descriptions
bool niceDescriptionFound(false); // have we yet seen a plain descriptive entry (not OperationEvent)?
std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
// name is always the same
for (auto iter = m_UndoList.rbegin(); iter != m_UndoList.rend(); ++iter)
{
if (oeid != (*iter)->GetObjectEventId())
{
// current description complete, append to list
if (currentDescription.empty())
currentDescription = "Some unnamed action"; // set a default description
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
currentDescription = ""; // prepare for next group
currentDescriptionCount = 0;
niceDescriptionFound = false;
oeid = (*iter)->GetObjectEventId();
}
if (!(*iter)->GetDescription().empty()) // if there is a description
{
if (!dynamic_cast<OperationEvent *>(*iter))
{
// anything but an OperationEvent overrides the collected descriptions
currentDescription = (*iter)->GetDescription();
niceDescriptionFound = true;
}
else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
{
if (currentDescriptionCount) // if we have already seen another description
{
if (lastDescription != (*iter)->GetDescription())
{
// currentDescription += '\n'; // concatenate descriptions with newline
currentDescription += " AND "; // this has to wait until the popup can process multiline items
currentDescription += (*iter)->GetDescription();
}
}
else
{
currentDescription += (*iter)->GetDescription();
}
}
lastDescription = (*iter)->GetDescription();
++currentDescriptionCount;
}
} // for
// add last description to list
if (currentDescription.empty())
currentDescription = "Some unnamed action";
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
return descriptions; // list ready
}
mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetRedoDescriptions()
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions;
if (m_RedoList.empty())
return descriptions;
int oeid = m_RedoList.back()->GetObjectEventId(); // ObjectEventID of current group
std::string currentDescription; // description of current group
int currentDescriptionCount(0); // counter, how many items of the current group gave descriptions
bool niceDescriptionFound(false); // have we yet seen a plain descriptive entry (not OperationEvent)?
std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
// name is always the same
for (auto iter = m_RedoList.rbegin(); iter != m_RedoList.rend(); ++iter)
{
if (oeid != (*iter)->GetObjectEventId())
{
// current description complete, append to list
if (currentDescription.empty())
currentDescription = "Some unnamed action"; // set a default description
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
currentDescription = ""; // prepare for next group
currentDescriptionCount = 0;
niceDescriptionFound = false;
oeid = (*iter)->GetObjectEventId();
}
if (!(*iter)->GetDescription().empty()) // if there is a description
{
if (!dynamic_cast<OperationEvent *>(*iter))
{
// anything but an OperationEvent overrides the collected descriptions
currentDescription = (*iter)->GetDescription();
niceDescriptionFound = true;
}
else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
{
if (currentDescriptionCount) // if we have already seen another description
{
if (lastDescription != (*iter)->GetDescription())
{
// currentDescription += '\n'; // concatenate descriptions with newline
currentDescription += " AND "; // this has to wait until the popup can process multiline items
currentDescription += (*iter)->GetDescription();
}
}
else
{
currentDescription += (*iter)->GetDescription();
}
}
lastDescription = (*iter)->GetDescription();
++currentDescriptionCount;
}
} // for
// add last description to list
if (currentDescription.empty())
currentDescription = "Some unnamed action";
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
return descriptions; // list ready
}
<commit_msg>Fix memory leak<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.
===================================================================*/
#include "mitkVerboseLimitedLinearUndo.h"
#include "mitkOperationEvent.h"
mitk::VerboseLimitedLinearUndo::VerboseLimitedLinearUndo()
{
}
mitk::VerboseLimitedLinearUndo::~VerboseLimitedLinearUndo()
{
}
bool mitk::VerboseLimitedLinearUndo::SetOperationEvent(UndoStackItem *undoStackItem)
{
if (!undoStackItem)
return false;
// clear the redolist, if a new operation is saved
if (!m_RedoList.empty())
{
this->ClearList(&m_RedoList);
InvokeEvent(RedoEmptyEvent());
}
std::size_t undoLimit = this->GetUndoLimit();
if (0 != undoLimit && m_UndoList.size() == undoLimit)
{
auto item = m_UndoList.front();
m_UndoList.pop_front();
delete item;
}
m_UndoList.push_back(undoStackItem);
InvokeEvent(UndoNotEmptyEvent());
return true;
}
mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetUndoDescriptions()
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions;
if (m_UndoList.empty())
return descriptions;
int oeid = m_UndoList.back()->GetObjectEventId(); // ObjectEventID of current group
std::string currentDescription; // description of current group
int currentDescriptionCount(0); // counter, how many items of the current group gave descriptions
bool niceDescriptionFound(false); // have we yet seen a plain descriptive entry (not OperationEvent)?
std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
// name is always the same
for (auto iter = m_UndoList.rbegin(); iter != m_UndoList.rend(); ++iter)
{
if (oeid != (*iter)->GetObjectEventId())
{
// current description complete, append to list
if (currentDescription.empty())
currentDescription = "Some unnamed action"; // set a default description
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
currentDescription = ""; // prepare for next group
currentDescriptionCount = 0;
niceDescriptionFound = false;
oeid = (*iter)->GetObjectEventId();
}
if (!(*iter)->GetDescription().empty()) // if there is a description
{
if (!dynamic_cast<OperationEvent *>(*iter))
{
// anything but an OperationEvent overrides the collected descriptions
currentDescription = (*iter)->GetDescription();
niceDescriptionFound = true;
}
else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
{
if (currentDescriptionCount) // if we have already seen another description
{
if (lastDescription != (*iter)->GetDescription())
{
// currentDescription += '\n'; // concatenate descriptions with newline
currentDescription += " AND "; // this has to wait until the popup can process multiline items
currentDescription += (*iter)->GetDescription();
}
}
else
{
currentDescription += (*iter)->GetDescription();
}
}
lastDescription = (*iter)->GetDescription();
++currentDescriptionCount;
}
} // for
// add last description to list
if (currentDescription.empty())
currentDescription = "Some unnamed action";
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
return descriptions; // list ready
}
mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetRedoDescriptions()
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions;
if (m_RedoList.empty())
return descriptions;
int oeid = m_RedoList.back()->GetObjectEventId(); // ObjectEventID of current group
std::string currentDescription; // description of current group
int currentDescriptionCount(0); // counter, how many items of the current group gave descriptions
bool niceDescriptionFound(false); // have we yet seen a plain descriptive entry (not OperationEvent)?
std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
// name is always the same
for (auto iter = m_RedoList.rbegin(); iter != m_RedoList.rend(); ++iter)
{
if (oeid != (*iter)->GetObjectEventId())
{
// current description complete, append to list
if (currentDescription.empty())
currentDescription = "Some unnamed action"; // set a default description
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
currentDescription = ""; // prepare for next group
currentDescriptionCount = 0;
niceDescriptionFound = false;
oeid = (*iter)->GetObjectEventId();
}
if (!(*iter)->GetDescription().empty()) // if there is a description
{
if (!dynamic_cast<OperationEvent *>(*iter))
{
// anything but an OperationEvent overrides the collected descriptions
currentDescription = (*iter)->GetDescription();
niceDescriptionFound = true;
}
else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
{
if (currentDescriptionCount) // if we have already seen another description
{
if (lastDescription != (*iter)->GetDescription())
{
// currentDescription += '\n'; // concatenate descriptions with newline
currentDescription += " AND "; // this has to wait until the popup can process multiline items
currentDescription += (*iter)->GetDescription();
}
}
else
{
currentDescription += (*iter)->GetDescription();
}
}
lastDescription = (*iter)->GetDescription();
++currentDescriptionCount;
}
} // for
// add last description to list
if (currentDescription.empty())
currentDescription = "Some unnamed action";
descriptions.push_back(StackDescriptionItem(oeid, currentDescription));
return descriptions; // list ready
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkGenericAttributeCollection.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkGenericAttributeCollection - objects that own attributes of a data set
// .DESCRIPTION They can also select an active attribute component to process
// (contouring, clipping) and others attributes to interpolate.
#include "vtkGenericAttributeCollection.h"
#include "vtkObjectFactory.h"
#include "vtkGenericAttribute.h"
#include <vtkstd/vector>
#include <assert.h>
vtkCxxRevisionMacro(vtkGenericAttributeCollection,"1.1");
vtkStandardNewMacro(vtkGenericAttributeCollection);
class vtkGenericAttributeInternalVector
{
public:
typedef vtkstd::vector<vtkGenericAttribute* > VectorType;
VectorType Vector;
};
//----------------------------------------------------------------------------
// Description:
// Default constructor: empty collection
vtkGenericAttributeCollection::vtkGenericAttributeCollection()
{
this->AttributeInternalVector = new vtkGenericAttributeInternalVector;
this->ActiveAttribute = 0;
this->ActiveComponent = 0;
this->NumberOfAttributesToInterpolate = 0;
this->NumberOfComponents = 0;
this->MaxNumberOfComponents = 0; // cache
this->ActualMemorySize = 0;
}
//----------------------------------------------------------------------------
vtkGenericAttributeCollection::~vtkGenericAttributeCollection()
{
for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
{
this->AttributeInternalVector->Vector[i]->Delete();
}
delete this->AttributeInternalVector;
}
//----------------------------------------------------------------------------
void vtkGenericAttributeCollection::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
int i;
int c = this->GetNumberOfAttributes();
os << indent << "Number Of Attributes: " << this->GetNumberOfAttributes() << "\n";
for(i=0; i<c; ++i)
{
os << indent << "Attribute #"<<i<<":\n";
this->GetAttribute(i)->PrintSelf(os,indent.GetNextIndent());
}
c=this->GetNumberOfAttributesToInterpolate();
os << indent << "Number Of Attributes to interpolate: " << c << endl;
os << indent << "Attributes to interpolate:";
for(i=0; i<c; ++i)
{
os << ' ' << this->AttributesToInterpolate[i];
}
os << endl;
os << indent << "Active Attribute: " << this->ActiveAttribute << endl;
os << indent << "Active Component" << this->ActiveComponent << endl;
}
//----------------------------------------------------------------------------
// Description:
// Number of attributes.
int vtkGenericAttributeCollection::GetNumberOfAttributes()
{
int result = this->AttributeInternalVector->Vector.size();
//assert("post: positive_result" && result>=0); size() is an unsigned type according to STL vector definition
return result;
}
//----------------------------------------------------------------------------
int vtkGenericAttributeCollection::GetNumberOfComponents()
{
this->ComputeNumbers();
return this->NumberOfComponents;
}
//----------------------------------------------------------------------------
// Description:
// Maximum number of components encountered among all attributes.
// \post positive_result: result>=0
// \post valid_result: result<=GetNumberOfComponents()
int vtkGenericAttributeCollection::GetMaxNumberOfComponents()
{
this->ComputeNumbers();
assert("post: positive_result" && this->MaxNumberOfComponents>=0);
assert("post: valid_result" && this->MaxNumberOfComponents<=GetNumberOfComponents());
return this->MaxNumberOfComponents;
}
//----------------------------------------------------------------------------
// Description:
// Actual size of the data in kilobytes; only valid after the pipeline has
// updated. It is guaranteed to be greater than or equal to the memory
// required to represent the data.
unsigned long vtkGenericAttributeCollection::GetActualMemorySize()
{
this->ComputeNumbers();
return this->ActualMemorySize;
}
//----------------------------------------------------------------------------
// Description:
// Does `this' have no attribute?
int vtkGenericAttributeCollection::IsEmpty()
{
return this->GetNumberOfAttributes()==0;
}
//----------------------------------------------------------------------------
// Description:
// Attribute `i'.
vtkGenericAttribute *vtkGenericAttributeCollection::GetAttribute(int i)
{
assert("pre: not_empty" && !IsEmpty());
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
vtkGenericAttribute *result=this->AttributeInternalVector->Vector[i];
assert("post: result_exists" && result!=0);
return result;
}
//----------------------------------------------------------------------------
// Description:
// Return the index of attribute `name', if found. Return -1 otherwise.
int vtkGenericAttributeCollection::FindAttribute(const char *name)
{
assert("pre: name_exists:" && name!=0);
int numAtt = this->GetNumberOfAttributes();
for( int i = 0; i < numAtt; ++i )
{
if( strcmp( this->GetAttribute(i)->GetName(), name ) == 0)
{
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
// Description:
// Add attribute `a' at the end.
void vtkGenericAttributeCollection::InsertNextAttribute(vtkGenericAttribute *a)
{
assert("pre: a_exists" && a!=0);
#ifndef NDEBUG
int oldnumber=this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector.push_back(a);
this->Modified();
assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber+1);
assert("post: a_is_set" && this->GetAttribute(this->GetNumberOfAttributes()-1)==a);
}
//----------------------------------------------------------------------------
// Description:
// Replace attribute at index `i' by `a'.
void vtkGenericAttributeCollection::InsertAttribute(int i, vtkGenericAttribute *a)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: a_exists" && a!=0);
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
#ifndef NDEBUG
int oldnumber = this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector[i] = a;
this->Modified();
assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber);
assert("post: a_is_set" && this->GetAttribute(i)==a);
}
//----------------------------------------------------------------------------
// Description:
// Remove Attribute at `i'.
void vtkGenericAttributeCollection::RemoveAttribute(int i)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
#ifndef NDEBUG
int oldnumber=this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector.erase(
this->AttributeInternalVector->Vector.begin()+i);
this->Modified();
assert("post: fewer_items" && this->GetNumberOfAttributes()==(oldnumber-1));
}
//----------------------------------------------------------------------------
// Description:
// Remove all attributes.
void vtkGenericAttributeCollection::Reset()
{
for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
{
this->AttributeInternalVector->Vector[i]->Delete();
}
this->AttributeInternalVector->Vector.clear();
this->Modified();
assert("post: is_empty" && this->IsEmpty());
}
//----------------------------------------------------------------------------
// Description:
// Recursive duplication of `other' in `this'.
void vtkGenericAttributeCollection::DeepCopy(vtkGenericAttributeCollection *other)
{
assert("pre: other_exists" && other!=0);
assert("pre: not_self" && other!=this);
this->AttributeInternalVector->Vector.resize(
other->AttributeInternalVector->Vector.size());
int c = this->AttributeInternalVector->Vector.size();
for(int i=0; i<c; i++)
{
if(this->AttributeInternalVector->Vector[i] == 0)
{
this->AttributeInternalVector->Vector[i] =
other->AttributeInternalVector->Vector[i]->NewInstance();
}
this->AttributeInternalVector->Vector[i]->DeepCopy(
other->AttributeInternalVector->Vector[i]);
}
this->Modified();
assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}
//----------------------------------------------------------------------------
// Description:
// Update `this' using fields of `other'.
void vtkGenericAttributeCollection::ShallowCopy(vtkGenericAttributeCollection *other)
{
assert("pre: other_exists" && other!=0);
assert("pre: not_self" && other!=this);
this->AttributeInternalVector->Vector =
other->AttributeInternalVector->Vector;
this->Modified();
assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}
//----------------------------------------------------------------------------
// Description:
// Collection is composite object and need to check each part for MTime.
unsigned long int vtkGenericAttributeCollection::GetMTime()
{
unsigned long result;
unsigned long mtime;
result = vtkObject::GetMTime();
for(int i = 0; i < this->GetNumberOfAttributes(); ++i)
{
mtime = this->GetAttribute(i)->GetMTime();
result = ( mtime > result ? mtime : result );
}
return result;
}
//----------------------------------------------------------------------------
// Description:
// Compute number of components, max number of components and actual memory
// size.
void vtkGenericAttributeCollection::ComputeNumbers()
{
if ( this->GetMTime() > this->ComputeTime )
{
int nb = 0;
int count = 0;
int maxNb = 0;
unsigned long memory=0;
int c = this->GetNumberOfAttributes();
for(int i = 0; i < c; ++i)
{
count = this->GetAttribute(i)->GetNumberOfComponents();
memory=memory+this->GetAttribute(i)->GetActualMemorySize();
if(count > maxNb)
{
maxNb = count;
}
nb += count;
}
this->NumberOfComponents = nb;
this->MaxNumberOfComponents = maxNb;
this->ActualMemorySize = memory;
assert("check: positive_number" && this->NumberOfComponents>=0);
assert("check: positiveMaxNumber" && this->MaxNumberOfComponents>=0);
assert("check: valid_number" && this->MaxNumberOfComponents<=this->NumberOfComponents);
this->ComputeTime.Modified();
}
}
//----------------------------------------------------------------------------
// *** ALL THE FOLLOWING METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** BEGIN
// Description:
// Set the scalar attribute to be processed.
void vtkGenericAttributeCollection::SetActiveAttribute(int attribute,
int component)
{
assert("pre: not_empty" && !IsEmpty());
assert("pre: valid_attribute" && (attribute>=0)&&(attribute<this->GetNumberOfAttributes()));
assert("pre: valid_component" && (component>=0)&&(component<this->GetAttribute(attribute)->GetNumberOfComponents()));
this->ActiveAttribute = attribute;
this->ActiveComponent = component;
assert("post: is_set" && (this->GetActiveAttribute()==attribute) && (this->GetActiveComponent()==component));
}
//----------------------------------------------------------------------------
// Description:
// Indices of attributes to interpolate.
// \pre not_empty: !IsEmpty()
// \post valid_result: GetNumberOfAttributesToInterpolate()>0 implies
// result!=0
int *vtkGenericAttributeCollection::GetAttributesToInterpolate()
{
assert("pre: not_empty" && !IsEmpty());
assert("post: valid_result" && ((!(this->NumberOfAttributesToInterpolate>0))
|| this->AttributesToInterpolate!=0));
// A=>B !A||B
return this->AttributesToInterpolate;
}
//----------------------------------------------------------------------------
// Description
// Does the array `attributes' of size `size' have `attribute'?
int vtkGenericAttributeCollection::HasAttribute(int size,
int *attributes,
int attribute)
{
assert("pre: positive_size" && size>=0);
assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )
int result = 0; // false
int i;
if(size != 0)
{
i = 0;
while( !result && i++ < size )
{
result = attributes[i] == attribute;
}
}
return result;
}
//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolate(int size,
int *attributes)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: positive_size" && size>=0);
assert("pre: magic_number" && size<=10);
assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )
assert("pre: valid_attributes_contents" && (!(attributes!=0) || !(!this->HasAttribute(size,attributes,this->GetActiveAttribute())))); // attributes!=0 => !this->HasAttribute(size,attributes,this->GetActiveAttribute()) (A=>B: !A||B )
this->NumberOfAttributesToInterpolate = size;
for(int i=0; i<size; ++i)
{
this->AttributesToInterpolate[i] = attributes[i];
}
assert("post: is_set" && (this->GetNumberOfAttributesToInterpolate()==size));
}
//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolateToAll()
{
assert("pre: not_empty" && !this->IsEmpty());
this->NumberOfAttributesToInterpolate = this->GetMaxNumberOfComponents();
for(int i=0; i<this->NumberOfAttributesToInterpolate; ++i)
{
this->AttributesToInterpolate[i] = i;
}
}
//----------------------------------------------------------------------------
// *** ALL THE PREVIOUS METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** END
<commit_msg>DOC: doxygen in cxx are not seen<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkGenericAttributeCollection.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkGenericAttributeCollection.h"
#include "vtkObjectFactory.h"
#include "vtkGenericAttribute.h"
#include <vtkstd/vector>
#include <assert.h>
vtkCxxRevisionMacro(vtkGenericAttributeCollection,"1.2");
vtkStandardNewMacro(vtkGenericAttributeCollection);
class vtkGenericAttributeInternalVector
{
public:
typedef vtkstd::vector<vtkGenericAttribute* > VectorType;
VectorType Vector;
};
//----------------------------------------------------------------------------
// Description:
// Default constructor: empty collection
vtkGenericAttributeCollection::vtkGenericAttributeCollection()
{
this->AttributeInternalVector = new vtkGenericAttributeInternalVector;
this->ActiveAttribute = 0;
this->ActiveComponent = 0;
this->NumberOfAttributesToInterpolate = 0;
this->NumberOfComponents = 0;
this->MaxNumberOfComponents = 0; // cache
this->ActualMemorySize = 0;
}
//----------------------------------------------------------------------------
vtkGenericAttributeCollection::~vtkGenericAttributeCollection()
{
for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
{
this->AttributeInternalVector->Vector[i]->Delete();
}
delete this->AttributeInternalVector;
}
//----------------------------------------------------------------------------
void vtkGenericAttributeCollection::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
int i;
int c = this->GetNumberOfAttributes();
os << indent << "Number Of Attributes: " << this->GetNumberOfAttributes() << "\n";
for(i=0; i<c; ++i)
{
os << indent << "Attribute #"<<i<<":\n";
this->GetAttribute(i)->PrintSelf(os,indent.GetNextIndent());
}
c=this->GetNumberOfAttributesToInterpolate();
os << indent << "Number Of Attributes to interpolate: " << c << endl;
os << indent << "Attributes to interpolate:";
for(i=0; i<c; ++i)
{
os << ' ' << this->AttributesToInterpolate[i];
}
os << endl;
os << indent << "Active Attribute: " << this->ActiveAttribute << endl;
os << indent << "Active Component" << this->ActiveComponent << endl;
}
//----------------------------------------------------------------------------
// Description:
// Number of attributes.
int vtkGenericAttributeCollection::GetNumberOfAttributes()
{
int result = this->AttributeInternalVector->Vector.size();
//assert("post: positive_result" && result>=0); size() is an unsigned type according to STL vector definition
return result;
}
//----------------------------------------------------------------------------
int vtkGenericAttributeCollection::GetNumberOfComponents()
{
this->ComputeNumbers();
return this->NumberOfComponents;
}
//----------------------------------------------------------------------------
// Description:
// Maximum number of components encountered among all attributes.
// \post positive_result: result>=0
// \post valid_result: result<=GetNumberOfComponents()
int vtkGenericAttributeCollection::GetMaxNumberOfComponents()
{
this->ComputeNumbers();
assert("post: positive_result" && this->MaxNumberOfComponents>=0);
assert("post: valid_result" && this->MaxNumberOfComponents<=GetNumberOfComponents());
return this->MaxNumberOfComponents;
}
//----------------------------------------------------------------------------
// Description:
// Actual size of the data in kilobytes; only valid after the pipeline has
// updated. It is guaranteed to be greater than or equal to the memory
// required to represent the data.
unsigned long vtkGenericAttributeCollection::GetActualMemorySize()
{
this->ComputeNumbers();
return this->ActualMemorySize;
}
//----------------------------------------------------------------------------
// Description:
// Does `this' have no attribute?
int vtkGenericAttributeCollection::IsEmpty()
{
return this->GetNumberOfAttributes()==0;
}
//----------------------------------------------------------------------------
// Description:
// Attribute `i'.
vtkGenericAttribute *vtkGenericAttributeCollection::GetAttribute(int i)
{
assert("pre: not_empty" && !IsEmpty());
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
vtkGenericAttribute *result=this->AttributeInternalVector->Vector[i];
assert("post: result_exists" && result!=0);
return result;
}
//----------------------------------------------------------------------------
// Description:
// Return the index of attribute `name', if found. Return -1 otherwise.
int vtkGenericAttributeCollection::FindAttribute(const char *name)
{
assert("pre: name_exists:" && name!=0);
int numAtt = this->GetNumberOfAttributes();
for( int i = 0; i < numAtt; ++i )
{
if( strcmp( this->GetAttribute(i)->GetName(), name ) == 0)
{
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
// Description:
// Add attribute `a' at the end.
void vtkGenericAttributeCollection::InsertNextAttribute(vtkGenericAttribute *a)
{
assert("pre: a_exists" && a!=0);
#ifndef NDEBUG
int oldnumber=this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector.push_back(a);
this->Modified();
assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber+1);
assert("post: a_is_set" && this->GetAttribute(this->GetNumberOfAttributes()-1)==a);
}
//----------------------------------------------------------------------------
// Description:
// Replace attribute at index `i' by `a'.
void vtkGenericAttributeCollection::InsertAttribute(int i, vtkGenericAttribute *a)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: a_exists" && a!=0);
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
#ifndef NDEBUG
int oldnumber = this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector[i] = a;
this->Modified();
assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber);
assert("post: a_is_set" && this->GetAttribute(i)==a);
}
//----------------------------------------------------------------------------
// Description:
// Remove Attribute at `i'.
void vtkGenericAttributeCollection::RemoveAttribute(int i)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
#ifndef NDEBUG
int oldnumber=this->GetNumberOfAttributes();
#endif
this->AttributeInternalVector->Vector.erase(
this->AttributeInternalVector->Vector.begin()+i);
this->Modified();
assert("post: fewer_items" && this->GetNumberOfAttributes()==(oldnumber-1));
}
//----------------------------------------------------------------------------
// Description:
// Remove all attributes.
void vtkGenericAttributeCollection::Reset()
{
for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
{
this->AttributeInternalVector->Vector[i]->Delete();
}
this->AttributeInternalVector->Vector.clear();
this->Modified();
assert("post: is_empty" && this->IsEmpty());
}
//----------------------------------------------------------------------------
// Description:
// Recursive duplication of `other' in `this'.
void vtkGenericAttributeCollection::DeepCopy(vtkGenericAttributeCollection *other)
{
assert("pre: other_exists" && other!=0);
assert("pre: not_self" && other!=this);
this->AttributeInternalVector->Vector.resize(
other->AttributeInternalVector->Vector.size());
int c = this->AttributeInternalVector->Vector.size();
for(int i=0; i<c; i++)
{
if(this->AttributeInternalVector->Vector[i] == 0)
{
this->AttributeInternalVector->Vector[i] =
other->AttributeInternalVector->Vector[i]->NewInstance();
}
this->AttributeInternalVector->Vector[i]->DeepCopy(
other->AttributeInternalVector->Vector[i]);
}
this->Modified();
assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}
//----------------------------------------------------------------------------
// Description:
// Update `this' using fields of `other'.
void vtkGenericAttributeCollection::ShallowCopy(vtkGenericAttributeCollection *other)
{
assert("pre: other_exists" && other!=0);
assert("pre: not_self" && other!=this);
this->AttributeInternalVector->Vector =
other->AttributeInternalVector->Vector;
this->Modified();
assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}
//----------------------------------------------------------------------------
// Description:
// Collection is composite object and need to check each part for MTime.
unsigned long int vtkGenericAttributeCollection::GetMTime()
{
unsigned long result;
unsigned long mtime;
result = vtkObject::GetMTime();
for(int i = 0; i < this->GetNumberOfAttributes(); ++i)
{
mtime = this->GetAttribute(i)->GetMTime();
result = ( mtime > result ? mtime : result );
}
return result;
}
//----------------------------------------------------------------------------
// Description:
// Compute number of components, max number of components and actual memory
// size.
void vtkGenericAttributeCollection::ComputeNumbers()
{
if ( this->GetMTime() > this->ComputeTime )
{
int nb = 0;
int count = 0;
int maxNb = 0;
unsigned long memory=0;
int c = this->GetNumberOfAttributes();
for(int i = 0; i < c; ++i)
{
count = this->GetAttribute(i)->GetNumberOfComponents();
memory=memory+this->GetAttribute(i)->GetActualMemorySize();
if(count > maxNb)
{
maxNb = count;
}
nb += count;
}
this->NumberOfComponents = nb;
this->MaxNumberOfComponents = maxNb;
this->ActualMemorySize = memory;
assert("check: positive_number" && this->NumberOfComponents>=0);
assert("check: positiveMaxNumber" && this->MaxNumberOfComponents>=0);
assert("check: valid_number" && this->MaxNumberOfComponents<=this->NumberOfComponents);
this->ComputeTime.Modified();
}
}
//----------------------------------------------------------------------------
// *** ALL THE FOLLOWING METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** BEGIN
// Description:
// Set the scalar attribute to be processed.
void vtkGenericAttributeCollection::SetActiveAttribute(int attribute,
int component)
{
assert("pre: not_empty" && !IsEmpty());
assert("pre: valid_attribute" && (attribute>=0)&&(attribute<this->GetNumberOfAttributes()));
assert("pre: valid_component" && (component>=0)&&(component<this->GetAttribute(attribute)->GetNumberOfComponents()));
this->ActiveAttribute = attribute;
this->ActiveComponent = component;
assert("post: is_set" && (this->GetActiveAttribute()==attribute) && (this->GetActiveComponent()==component));
}
//----------------------------------------------------------------------------
// Description:
// Indices of attributes to interpolate.
// \pre not_empty: !IsEmpty()
// \post valid_result: GetNumberOfAttributesToInterpolate()>0 implies
// result!=0
int *vtkGenericAttributeCollection::GetAttributesToInterpolate()
{
assert("pre: not_empty" && !IsEmpty());
assert("post: valid_result" && ((!(this->NumberOfAttributesToInterpolate>0))
|| this->AttributesToInterpolate!=0));
// A=>B !A||B
return this->AttributesToInterpolate;
}
//----------------------------------------------------------------------------
// Description
// Does the array `attributes' of size `size' have `attribute'?
int vtkGenericAttributeCollection::HasAttribute(int size,
int *attributes,
int attribute)
{
assert("pre: positive_size" && size>=0);
assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )
int result = 0; // false
int i;
if(size != 0)
{
i = 0;
while( !result && i++ < size )
{
result = attributes[i] == attribute;
}
}
return result;
}
//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolate(int size,
int *attributes)
{
assert("pre: not_empty" && !this->IsEmpty());
assert("pre: positive_size" && size>=0);
assert("pre: magic_number" && size<=10);
assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )
assert("pre: valid_attributes_contents" && (!(attributes!=0) || !(!this->HasAttribute(size,attributes,this->GetActiveAttribute())))); // attributes!=0 => !this->HasAttribute(size,attributes,this->GetActiveAttribute()) (A=>B: !A||B )
this->NumberOfAttributesToInterpolate = size;
for(int i=0; i<size; ++i)
{
this->AttributesToInterpolate[i] = attributes[i];
}
assert("post: is_set" && (this->GetNumberOfAttributesToInterpolate()==size));
}
//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolateToAll()
{
assert("pre: not_empty" && !this->IsEmpty());
this->NumberOfAttributesToInterpolate = this->GetMaxNumberOfComponents();
for(int i=0; i<this->NumberOfAttributesToInterpolate; ++i)
{
this->AttributesToInterpolate[i] = i;
}
}
//----------------------------------------------------------------------------
// *** ALL THE PREVIOUS METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** END
<|endoftext|> |
<commit_before>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */
#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"
void init_sensor(py::module &m) {
/** rs_sensor.hpp **/
py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
notification.def(py::init<>())
.def("get_category", &rs2::notification::get_category,
"Retrieve the notification's category.")
.def_property_readonly("category", &rs2::notification::get_category,
"The notification's category. Identical to calling get_category.")
.def("get_description", &rs2::notification::get_description,
"Retrieve the notification's description.")
.def_property_readonly("description", &rs2::notification::get_description,
"The notification's description. Identical to calling get_description.")
.def("get_timestamp", &rs2::notification::get_timestamp,
"Retrieve the notification's arrival timestamp.")
.def_property_readonly("timestamp", &rs2::notification::get_timestamp,
"The notification's arrival timestamp. Identical to calling get_timestamp.")
.def("get_severity", &rs2::notification::get_severity,
"Retrieve the notification's severity.")
.def_property_readonly("severity", &rs2::notification::get_severity,
"The notification's severity. Identical to calling get_severity.")
.def("get_serialized_data", &rs2::notification::get_severity,
"Retrieve the notification's serialized data.")
.def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
"The notification's serialized data. Identical to calling get_serialized_data.")
.def("__repr__", [](const rs2::notification &n) {
return n.get_description();
});
// not binding notifications_callback, templated
py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
"Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
.def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
"Check if specific camera info is supported.", "info")
.def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
"Check if specific camera info is supported.", "info")
.def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
"like versions of various internal components.", "info"_a)
.def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
self.set_notifications_callback(callback);
}, "Register Notifications callback", "callback"_a)
.def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
"Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
"more stream profiles.", "profiles"_a)
.def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
.def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
self.start(callback);
}, "Start passing frames into user provided callback.", "callback"_a)
.def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
self.start(syncer);
}, "Start passing frames into user provided syncer.", "syncer"_a)
.def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
self.start(queue);
}, "start passing frames into specified frame_queue", "queue"_a)
.def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
.def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
.def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
.def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
.def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
.def(py::init<>())
.def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
.def(BIND_DOWNCAST(sensor, roi_sensor))
.def(BIND_DOWNCAST(sensor, depth_sensor))
.def(BIND_DOWNCAST(sensor, color_sensor))
.def(BIND_DOWNCAST(sensor, motion_sensor))
.def(BIND_DOWNCAST(sensor, fisheye_sensor))
.def(BIND_DOWNCAST(sensor, pose_sensor))
.def(BIND_DOWNCAST(sensor, calibrated_sensor))
.def(BIND_DOWNCAST(sensor, wheel_odometer));
// rs2::sensor_from_frame [frame.def("get_sensor", ...)?
// rs2::sensor==sensor?
py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
.def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
.def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++
py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
"Retrieves mapping between the units of the depth image and meters.")
.def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++
py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++
py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++
py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++
py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
.def( "override_intrinsics", &rs2::calibrated_sensor::override_intrinsics, "intrinsics"_a )
.def( "override_extrinsics", &rs2::calibrated_sensor::override_extrinsics, "extrinsics"_a )
.def( "get_dsm_params", &rs2::calibrated_sensor::get_dsm_params )
.def( "override_dsm_params", &rs2::calibrated_sensor::override_dsm_params, "dsm_params"_a )
.def( "reset_calibration", &rs2::calibrated_sensor::reset_calibration )
.def( "__nonzero__", &rs2::calibrated_sensor::operator bool );
// rs2::depth_stereo_sensor
py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
depth_stereo_sensor.def(py::init<rs2::sensor>())
.def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");
py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("import_localization_map", &rs2::pose_sensor::import_localization_map,
"Load relocalization map onto device. Only one relocalization map can be imported at a time; "
"any previously existing map will be overwritten.\n"
"The imported map exists simultaneously with the map created during the most recent tracking "
"session after start(),"
"and they are merged after the imported map is relocalized.\n"
"This operation must be done before start().", "lmap_buf"_a)
.def("export_localization_map", &rs2::pose_sensor::export_localization_map,
"Get relocalization map that is currently on device, created and updated during most "
"recent tracking session.\n"
"Can be called before or after stop().")
.def("set_static_node", &rs2::pose_sensor::set_static_node,
"Creates a named virtual landmark in the current map, known as static node.\n"
"The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
"This function fails if the current tracker confidence is below 3 (high confidence).",
"guid"_a, "pos"_a, "orient"_a)
.def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
rs2_vector pos;
rs2_quaternion orient;
bool res = self.get_static_node(guid, pos, orient);
return std::make_tuple(res, pos, orient);
}, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
"Static nodes of imported maps are available after relocalizing the imported map.\n"
"The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
"Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
"This function fails if the current tracker confidence is below 3 (high confidence).",
"guid"_a)
.def("remove_static_node", &rs2::pose_sensor::remove_static_node,
"Removes a named virtual landmark in the current map, known as static node.\n"
"guid"_a)
.def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++
py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
.def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
"Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
.def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
"Send wheel odometry data for each individual sensor (wheel)",
"wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
.def("__nonzero__", &rs2::wheel_odometer::operator bool);
/** end rs_sensor.hpp **/
}
<commit_msg>PR #7076 from Eran: fix GIL locks in calibrated_sensor APIs which can cause frame drops<commit_after>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */
#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"
void init_sensor(py::module &m) {
/** rs_sensor.hpp **/
py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
notification.def(py::init<>())
.def("get_category", &rs2::notification::get_category,
"Retrieve the notification's category.")
.def_property_readonly("category", &rs2::notification::get_category,
"The notification's category. Identical to calling get_category.")
.def("get_description", &rs2::notification::get_description,
"Retrieve the notification's description.")
.def_property_readonly("description", &rs2::notification::get_description,
"The notification's description. Identical to calling get_description.")
.def("get_timestamp", &rs2::notification::get_timestamp,
"Retrieve the notification's arrival timestamp.")
.def_property_readonly("timestamp", &rs2::notification::get_timestamp,
"The notification's arrival timestamp. Identical to calling get_timestamp.")
.def("get_severity", &rs2::notification::get_severity,
"Retrieve the notification's severity.")
.def_property_readonly("severity", &rs2::notification::get_severity,
"The notification's severity. Identical to calling get_severity.")
.def("get_serialized_data", &rs2::notification::get_severity,
"Retrieve the notification's serialized data.")
.def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
"The notification's serialized data. Identical to calling get_serialized_data.")
.def("__repr__", [](const rs2::notification &n) {
return n.get_description();
});
// not binding notifications_callback, templated
py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
"Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
.def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
"Check if specific camera info is supported.", "info")
.def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
"Check if specific camera info is supported.", "info")
.def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
"like versions of various internal components.", "info"_a)
.def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
self.set_notifications_callback(callback);
}, "Register Notifications callback", "callback"_a)
.def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
"Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
"more stream profiles.", "profiles"_a)
.def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
.def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
self.start(callback);
}, "Start passing frames into user provided callback.", "callback"_a)
.def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
self.start(syncer);
}, "Start passing frames into user provided syncer.", "syncer"_a)
.def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
self.start(queue);
}, "start passing frames into specified frame_queue", "queue"_a)
.def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
.def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
.def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
.def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
.def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
.def(py::init<>())
.def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
.def(BIND_DOWNCAST(sensor, roi_sensor))
.def(BIND_DOWNCAST(sensor, depth_sensor))
.def(BIND_DOWNCAST(sensor, color_sensor))
.def(BIND_DOWNCAST(sensor, motion_sensor))
.def(BIND_DOWNCAST(sensor, fisheye_sensor))
.def(BIND_DOWNCAST(sensor, pose_sensor))
.def(BIND_DOWNCAST(sensor, calibrated_sensor))
.def(BIND_DOWNCAST(sensor, wheel_odometer));
// rs2::sensor_from_frame [frame.def("get_sensor", ...)?
// rs2::sensor==sensor?
py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
.def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
.def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++
py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
"Retrieves mapping between the units of the depth image and meters.")
.def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++
py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++
py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++
py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++
py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
.def( "override_intrinsics",
&rs2::calibrated_sensor::override_intrinsics,
"intrinsics"_a,
py::call_guard< py::gil_scoped_release >() )
.def( "override_extrinsics",
&rs2::calibrated_sensor::override_extrinsics,
"extrinsics"_a,
py::call_guard< py::gil_scoped_release >() )
.def( "get_dsm_params",
&rs2::calibrated_sensor::get_dsm_params,
py::call_guard< py::gil_scoped_release >() )
.def( "override_dsm_params",
&rs2::calibrated_sensor::override_dsm_params,
"dsm_params"_a,
py::call_guard< py::gil_scoped_release >() )
.def( "reset_calibration",
&rs2::calibrated_sensor::reset_calibration,
py::call_guard< py::gil_scoped_release >() )
.def( "__nonzero__", &rs2::calibrated_sensor::operator bool );
// rs2::depth_stereo_sensor
py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
depth_stereo_sensor.def(py::init<rs2::sensor>())
.def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");
py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
.def("import_localization_map", &rs2::pose_sensor::import_localization_map,
"Load relocalization map onto device. Only one relocalization map can be imported at a time; "
"any previously existing map will be overwritten.\n"
"The imported map exists simultaneously with the map created during the most recent tracking "
"session after start(),"
"and they are merged after the imported map is relocalized.\n"
"This operation must be done before start().", "lmap_buf"_a)
.def("export_localization_map", &rs2::pose_sensor::export_localization_map,
"Get relocalization map that is currently on device, created and updated during most "
"recent tracking session.\n"
"Can be called before or after stop().")
.def("set_static_node", &rs2::pose_sensor::set_static_node,
"Creates a named virtual landmark in the current map, known as static node.\n"
"The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
"This function fails if the current tracker confidence is below 3 (high confidence).",
"guid"_a, "pos"_a, "orient"_a)
.def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
rs2_vector pos;
rs2_quaternion orient;
bool res = self.get_static_node(guid, pos, orient);
return std::make_tuple(res, pos, orient);
}, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
"Static nodes of imported maps are available after relocalizing the imported map.\n"
"The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
"Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
"This function fails if the current tracker confidence is below 3 (high confidence).",
"guid"_a)
.def("remove_static_node", &rs2::pose_sensor::remove_static_node,
"Removes a named virtual landmark in the current map, known as static node.\n"
"guid"_a)
.def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++
py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
.def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
"Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
.def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
"Send wheel odometry data for each individual sensor (wheel)",
"wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
.def("__nonzero__", &rs2::wheel_odometer::operator bool);
/** end rs_sensor.hpp **/
}
<|endoftext|> |
<commit_before>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"
// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"
// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"
// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"
// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"
// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"
#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"
#include <iostream>
#include <cmath>
AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fMCEvent(0x0),
fESDEvent(0x0),
fAODEvent(0x0),
fRunNumber(-1),
fJetsCont(0),
fTracksCont(0),
fCaloClustersCont(0),
fOutputList(0x0),
fShortTaskId("jets_evshape")
{
// default ctor
SetMakeGeneralHistograms(kTRUE);
DefineOutput(kOutputEmcal, TList::Class());
AliInfo(Form("creating output slot #%i", kOutputTask));
DefineOutput(kOutputTask, TList::Class());
}
AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
// dtor
}
void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
// create user output objects
AliInfo("creating output objects");
// common EMCAL framework
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
PostData(kOutputEmcal, fOutput);
fJetsCont = GetJetContainer(0);
printf("setup jet container: %p, from available:\n", fJetsCont);
fJetCollArray.Print();
printf("end\n");
if(fJetsCont) { //get particles and clusters connected to jets
fTracksCont = fJetsCont->GetParticleContainer();
fCaloClustersCont = fJetsCont->GetClusterContainer();
} else { //no jets, just analysis tracks and clusters
fTracksCont = GetParticleContainer(0);
fCaloClustersCont = GetClusterContainer(0);
}
if(fTracksCont) fTracksCont->SetClassName("AliVTrack");
if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");
// setup list
OpenFile(kOutputTask);
fOutputList = new TList();
fOutputList->SetOwner();
// setup histograms
TH1 *hist;
TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
kStatLast-1, .5, kStatLast-.5);
histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));
AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
40, 0., 40.);
AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
100, 0., 400.);
PostData(kOutputTask, fOutputList);
}
Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
// actions to be taken upon notification about input file change
return AliAnalysisTaskEmcalJet::Notify();
}
void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
// actions at task termination
AliAnalysisTaskEmcalJet::Terminate(option);
}
void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
AliAnalysisTaskEmcalJet::PrintTask(option, indent);
std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}
Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
Bool_t eventGood = kTRUE;
// check for run change
if (fRunNumber != InputEvent()->GetRunNumber()) {
fRunNumber = InputEvent()->GetRunNumber();
}
return eventGood;
}
Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
return kTRUE;
}
void AliAnalysisTaskJetsEvshape::ExecOnce()
{
AliAnalysisTaskEmcalJet::ExecOnce();
}
Bool_t AliAnalysisTaskJetsEvshape::Run()
{
return kTRUE;
}
Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
FillH1(kHistStat, kStatUsed);
AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
Int_t nTracklets = mult->GetNumberOfTracklets();
FillH1(kHistMult, nTracklets);
if (fJetsCont) {
fJetsCont->ResetCurrentID();
AliEmcalJet *jet = fJetsCont->GetNextAcceptJet();
Int_t i = 0;
while (jet) {
FillH1(kHistJetPt, jet->Pt());
jet = fJetsCont->GetNextAcceptJet();
}
}
return kTRUE;
}
void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
// actual work
AliAnalysisTaskEmcalJet::UserExec(option);
// setup pointers to input data (null if unavailable)
// mcEvent: MC input
// esdEvent: ESD input
// outEvent: AOD output
// aodEvent: AOD input if available, otherwise AOD output
fMCEvent = this->MCEvent();
fESDEvent = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
AliAODEvent* outEvent = this->AODEvent();
fAODEvent = dynamic_cast<AliAODEvent*> (this->InputEvent());
if (!fAODEvent)
fAODEvent = outEvent;
if ((fDebug > 0) && fESDEvent)
printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());
// record number of sampled events and detect trigger contributions
FillH1(kHistStat, kStatSeen);
// so far, no trigger selection, we accept all
FillH1(kHistStat, kStatTrg);
// prepare the event
// (make sure it is cleaned up in the end)
if (PrepareEvent()) {
// here we have passed the event cuts
FillH1(kHistStat, kStatEvCuts);
// multiplicity selection
// event shape selection
InputEvent()->GetList()->ls();
}
stop:
CleanUpEvent();
PostData(kOutputEmcal, fOutput);
PostData(kOutputTask, fOutputList);
}
// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = new TH1I(hName.Data(), title,
xbins, xmin, xmax);
else
h = new TH1F(hName.Data(), title,
xbins, xmin, xmax);
GetHistogram(hist) = h;
fOutputList->Add(h);
return h;
}
TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t ybins, Float_t ymin, Float_t ymax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = GetHistogram(hist) = new TH2I(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax);
else
h = GetHistogram(hist) = new TH2F(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax);
fOutputList->Add(h);
return (TH2*) h;
}
TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t ybins, Float_t ymin, Float_t ymax,
Int_t zbins, Float_t zmin, Float_t zmax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = GetHistogram(hist) = new TH3I(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax,
zbins, zmin, zmax);
else
h = GetHistogram(hist) = new TH3F(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax,
zbins, zmin, zmax);
fOutputList->Add(h);
return (TH3*) h;
}
<commit_msg>disable debug output<commit_after>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"
// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"
// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"
// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"
// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"
// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"
#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"
#include <iostream>
#include <cmath>
AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fMCEvent(0x0),
fESDEvent(0x0),
fAODEvent(0x0),
fRunNumber(-1),
fJetsCont(0),
fTracksCont(0),
fCaloClustersCont(0),
fOutputList(0x0),
fShortTaskId("jets_evshape")
{
// default ctor
SetMakeGeneralHistograms(kTRUE);
DefineOutput(kOutputEmcal, TList::Class());
AliInfo(Form("creating output slot #%i", kOutputTask));
DefineOutput(kOutputTask, TList::Class());
}
AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
// dtor
}
void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
// create user output objects
AliInfo("creating output objects");
// common EMCAL framework
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
PostData(kOutputEmcal, fOutput);
fJetsCont = GetJetContainer(0);
printf("setup jet container: %p, from available:\n", fJetsCont);
fJetCollArray.Print();
printf("end\n");
if(fJetsCont) { //get particles and clusters connected to jets
fTracksCont = fJetsCont->GetParticleContainer();
fCaloClustersCont = fJetsCont->GetClusterContainer();
} else { //no jets, just analysis tracks and clusters
fTracksCont = GetParticleContainer(0);
fCaloClustersCont = GetClusterContainer(0);
}
if(fTracksCont) fTracksCont->SetClassName("AliVTrack");
if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");
// setup list
OpenFile(kOutputTask);
fOutputList = new TList();
fOutputList->SetOwner();
// setup histograms
TH1 *hist;
TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
kStatLast-1, .5, kStatLast-.5);
histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));
AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
40, 0., 40.);
AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
100, 0., 400.);
PostData(kOutputTask, fOutputList);
}
Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
// actions to be taken upon notification about input file change
return AliAnalysisTaskEmcalJet::Notify();
}
void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
// actions at task termination
AliAnalysisTaskEmcalJet::Terminate(option);
}
void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
AliAnalysisTaskEmcalJet::PrintTask(option, indent);
std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}
Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
Bool_t eventGood = kTRUE;
// check for run change
if (fRunNumber != InputEvent()->GetRunNumber()) {
fRunNumber = InputEvent()->GetRunNumber();
}
return eventGood;
}
Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
return kTRUE;
}
void AliAnalysisTaskJetsEvshape::ExecOnce()
{
AliAnalysisTaskEmcalJet::ExecOnce();
}
Bool_t AliAnalysisTaskJetsEvshape::Run()
{
return kTRUE;
}
Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
FillH1(kHistStat, kStatUsed);
AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
Int_t nTracklets = mult->GetNumberOfTracklets();
FillH1(kHistMult, nTracklets);
if (fJetsCont) {
fJetsCont->ResetCurrentID();
AliEmcalJet *jet = fJetsCont->GetNextAcceptJet();
Int_t i = 0;
while (jet) {
FillH1(kHistJetPt, jet->Pt());
jet = fJetsCont->GetNextAcceptJet();
}
}
return kTRUE;
}
void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
// actual work
AliAnalysisTaskEmcalJet::UserExec(option);
// setup pointers to input data (null if unavailable)
// mcEvent: MC input
// esdEvent: ESD input
// outEvent: AOD output
// aodEvent: AOD input if available, otherwise AOD output
fMCEvent = this->MCEvent();
fESDEvent = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
AliAODEvent* outEvent = this->AODEvent();
fAODEvent = dynamic_cast<AliAODEvent*> (this->InputEvent());
if (!fAODEvent)
fAODEvent = outEvent;
if ((fDebug > 0) && fESDEvent)
printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());
// record number of sampled events and detect trigger contributions
FillH1(kHistStat, kStatSeen);
// so far, no trigger selection, we accept all
FillH1(kHistStat, kStatTrg);
// prepare the event
// (make sure it is cleaned up in the end)
if (PrepareEvent()) {
// here we have passed the event cuts
FillH1(kHistStat, kStatEvCuts);
// multiplicity selection
// event shape selection
// InputEvent()->GetList()->ls();
}
stop:
CleanUpEvent();
PostData(kOutputEmcal, fOutput);
PostData(kOutputTask, fOutputList);
}
// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = new TH1I(hName.Data(), title,
xbins, xmin, xmax);
else
h = new TH1F(hName.Data(), title,
xbins, xmin, xmax);
GetHistogram(hist) = h;
fOutputList->Add(h);
return h;
}
TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t ybins, Float_t ymin, Float_t ymax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = GetHistogram(hist) = new TH2I(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax);
else
h = GetHistogram(hist) = new TH2F(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax);
fOutputList->Add(h);
return (TH2*) h;
}
TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
Int_t xbins, Float_t xmin, Float_t xmax,
Int_t ybins, Float_t ymin, Float_t ymax,
Int_t zbins, Float_t zmin, Float_t zmax,
Int_t binType)
{
TString hName;
hName.Form("%s_%s", fShortTaskId, hid);
hName.ToLower();
TH1 *h = 0x0;
if (binType == 0)
h = GetHistogram(hist) = new TH3I(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax,
zbins, zmin, zmax);
else
h = GetHistogram(hist) = new TH3F(hName.Data(), title,
xbins, xmin, xmax,
ybins, ymin, ymax,
zbins, zmin, zmax);
fOutputList->Add(h);
return (TH3*) h;
}
<|endoftext|> |
<commit_before>#include <Ogre.h>
#include <utility>
#include "core/engine.h"
#include "core/entity.h"
#include "core/system_loader.h"
#include "ogrerender.h"
using namespace Ogre;
Ygg::OgreRenderSystem::OgreRenderSystem(unsigned long window, SystemLoader *loader)
:m_parentwindow(window),
m_loader(loader)
{
}
Ygg::OgreRenderSystem::~OgreRenderSystem()
{
delete m_root;
}
void Ygg::OgreRenderSystem::Init(Ygg::Engine *engine)
{
m_root = new Ogre::Root("", "", "");
// Load required systems
Ogre::StringVector required_plugins;
required_plugins.push_back("./RenderSystem_GL");
required_plugins.push_back("./Plugin_OctreeSceneManager");
for (auto it = required_plugins.begin(); it != required_plugins.end(); ++it) {
#ifdef _DEBUG
m_root->loadPlugin(*it + Ogre::String("_d"));
#else
m_root->loadPlugin(*it);
#endif
}
// ToDo, check that plugins were actually loaded
m_root->setRenderSystem(m_root->getRenderSystemByName("OpenGL Rendering Subsystem"));
m_root->initialise(false);
// Setup the window
Ogre::NameValuePairList params;
params.insert(std::make_pair("parentWindowHandle", Ogre::StringConverter::toString(m_parentwindow)));
m_window = m_root->createRenderWindow("Yggdrasil", 800, 600, false, ¶ms);
m_window->setVisible(true);
// Setup the scenemanager
m_scenemgr = m_root->createSceneManager("OctreeSceneManager", "DefaultSceneManager");
// Setup the camera
m_camera = m_scenemgr->createCamera("Camera");
m_camera->setPosition(Ogre::Vector3(10, 10, 10));
m_camera->lookAt(Ogre::Vector3(0, 0, 0));
m_camera->setNearClipDistance(5);
// Setup the viewport
Ogre::Viewport *vp = m_window->addViewport(m_camera);
vp->setBackgroundColour(Ogre::ColourValue(0.5f, 1.0f, 0.0f));
// Match the camera aspect ratio to the viewport
m_camera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
// Create a default material
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
"DefaultMaterial",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
material->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_AMBIENT);
material->getTechnique(0)->getPass(0)->setDiffuse(Ogre::ColourValue(0.0, 0.2, 1.0, 0.0));
// Set ambient light
m_scenemgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
// Create a light
Ogre::Light *light = m_scenemgr->createLight("MainLight");
light->setPosition(20, 80, 50);
}
static void convert_mesh(const std::string& mname, Ygg::Mesh *mdata)
{
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(mname, "General");
Ogre::SubMesh *submesh = mesh->createSubMesh();
const size_t nverts = mdata->vertices.size();
float verts[3 * 2 * nverts];
const size_t ibufcount = 3 * mdata->indices.size();
unsigned short faces[ibufcount];
for (size_t i = 0; i < nverts; ++i) {
verts[6*i+0] = mdata->vertices[i].x;
verts[6*i+1] = mdata->vertices[i].y;
verts[6*i+2] = mdata->vertices[i].z;
verts[6*i+3] = mdata->normals[i].x;
verts[6*i+4] = mdata->normals[i].y;
verts[6*i+5] = mdata->normals[i].z;
}
for (size_t i = 0; i < mdata->indices.size(); ++i) {
faces[i] = mdata->indices[i];
}
mesh->sharedVertexData = new Ogre::VertexData();
mesh->sharedVertexData->vertexCount = nverts;
mesh->sharedVertexData->vertexStart = 0;
// Create declaration (memory format) of vertex data
Ogre::VertexDeclaration *decl = mesh->sharedVertexData->vertexDeclaration;
size_t offset = 0;
offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION).getSize();
offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL).getSize();
// Allocate vertex buffer
Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(0), nverts,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
// Upload the vertex data to the GPU
vbuf->writeData(0, vbuf->getSizeInBytes(), verts, true);
// Bind the vertex buffer
Ogre::VertexBufferBinding *binding = mesh->sharedVertexData->vertexBufferBinding;
binding->setBinding(0, vbuf);
// Allocate index buffer
Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(
Ogre::HardwareIndexBuffer::IT_16BIT,
ibufcount,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
// Upload the index data to the GPU
ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);
// Set parameters of the submesh
submesh->useSharedVertices = true;
submesh->indexData->indexBuffer = ibuf;
submesh->indexData->indexCount = ibufcount;
submesh->indexData->indexStart = 0;
// Set bounding information for culling
// ToDo set better bounds
mesh->_setBounds(Ogre::AxisAlignedBox(-100, -100, -100, 100, 100, 100));
mesh->_setBoundingSphereRadius(1000);
mesh->load();
}
void Ygg::OgreRenderSystem::Convert(Ygg::Engine *engine, std::vector<Entity> *entity_queue)
{
for (auto it = entity_queue->begin(); it != entity_queue->end(); ++it) {
Entity *entity = &(*it);
std::cout << "OGRE: Converting " << entity->name << std::endl;
// Convert mesh
MeshComponent *mesh_component = (MeshComponent*)engine->GetComponent(entity, SystemLoader::CID_MESH);
if (mesh_component != NULL)
{
std::cout << "\tFound Mesh" << std::endl;
convert_mesh(entity->name, &(*m_loader->GetMeshes())[mesh_component->mesh_handles[0]]);
Ogre::Entity *head = m_scenemgr->createEntity(entity->name, entity->name);
head->setMaterialName("DefaultMaterial");
Ogre::SceneNode *headnode = m_scenemgr->getRootSceneNode()->createChildSceneNode();
headnode->attachObject(head);
headnode->setPosition(0, 0, 0);
}
}
}
void Ygg::OgreRenderSystem::Update(Ygg::Engine *engine, float dt)
{
m_root->renderOneFrame();
}
<commit_msg>OgreRender: Using externalWindowHandle instead of parentWindowHandle.<commit_after>#include <Ogre.h>
#include <utility>
#include "core/engine.h"
#include "core/entity.h"
#include "core/system_loader.h"
#include "ogrerender.h"
using namespace Ogre;
Ygg::OgreRenderSystem::OgreRenderSystem(unsigned long window, SystemLoader *loader)
:m_parentwindow(window),
m_loader(loader)
{
}
Ygg::OgreRenderSystem::~OgreRenderSystem()
{
delete m_root;
}
void Ygg::OgreRenderSystem::Init(Ygg::Engine *engine)
{
m_root = new Ogre::Root("", "", "");
// Load required systems
Ogre::StringVector required_plugins;
required_plugins.push_back("./RenderSystem_GL");
required_plugins.push_back("./Plugin_OctreeSceneManager");
for (auto it = required_plugins.begin(); it != required_plugins.end(); ++it) {
#ifdef _DEBUG
m_root->loadPlugin(*it + Ogre::String("_d"));
#else
m_root->loadPlugin(*it);
#endif
}
// ToDo, check that plugins were actually loaded
m_root->setRenderSystem(m_root->getRenderSystemByName("OpenGL Rendering Subsystem"));
m_root->initialise(false);
// Setup the window
Ogre::NameValuePairList params;
params.insert(std::make_pair("externalWindowHandle", Ogre::StringConverter::toString(m_parentwindow)));
m_window = m_root->createRenderWindow("Yggdrasil", 800, 600, false, ¶ms);
m_window->setVisible(true);
// Setup the scenemanager
m_scenemgr = m_root->createSceneManager("OctreeSceneManager", "DefaultSceneManager");
// Setup the camera
m_camera = m_scenemgr->createCamera("Camera");
m_camera->setPosition(Ogre::Vector3(10, 10, 10));
m_camera->lookAt(Ogre::Vector3(0, 0, 0));
m_camera->setNearClipDistance(5);
// Setup the viewport
Ogre::Viewport *vp = m_window->addViewport(m_camera);
vp->setBackgroundColour(Ogre::ColourValue(0.5f, 1.0f, 0.0f));
// Match the camera aspect ratio to the viewport
m_camera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
// Create a default material
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
"DefaultMaterial",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
material->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_AMBIENT);
material->getTechnique(0)->getPass(0)->setDiffuse(Ogre::ColourValue(0.0, 0.2, 1.0, 0.0));
// Set ambient light
m_scenemgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
// Create a light
Ogre::Light *light = m_scenemgr->createLight("MainLight");
light->setPosition(20, 80, 50);
}
static void convert_mesh(const std::string& mname, Ygg::Mesh *mdata)
{
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(mname, "General");
Ogre::SubMesh *submesh = mesh->createSubMesh();
const size_t nverts = mdata->vertices.size();
float verts[3 * 2 * nverts];
const size_t ibufcount = 3 * mdata->indices.size();
unsigned short faces[ibufcount];
for (size_t i = 0; i < nverts; ++i) {
verts[6*i+0] = mdata->vertices[i].x;
verts[6*i+1] = mdata->vertices[i].y;
verts[6*i+2] = mdata->vertices[i].z;
verts[6*i+3] = mdata->normals[i].x;
verts[6*i+4] = mdata->normals[i].y;
verts[6*i+5] = mdata->normals[i].z;
}
for (size_t i = 0; i < mdata->indices.size(); ++i) {
faces[i] = mdata->indices[i];
}
mesh->sharedVertexData = new Ogre::VertexData();
mesh->sharedVertexData->vertexCount = nverts;
mesh->sharedVertexData->vertexStart = 0;
// Create declaration (memory format) of vertex data
Ogre::VertexDeclaration *decl = mesh->sharedVertexData->vertexDeclaration;
size_t offset = 0;
offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION).getSize();
offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL).getSize();
// Allocate vertex buffer
Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(0), nverts,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
// Upload the vertex data to the GPU
vbuf->writeData(0, vbuf->getSizeInBytes(), verts, true);
// Bind the vertex buffer
Ogre::VertexBufferBinding *binding = mesh->sharedVertexData->vertexBufferBinding;
binding->setBinding(0, vbuf);
// Allocate index buffer
Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(
Ogre::HardwareIndexBuffer::IT_16BIT,
ibufcount,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
// Upload the index data to the GPU
ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);
// Set parameters of the submesh
submesh->useSharedVertices = true;
submesh->indexData->indexBuffer = ibuf;
submesh->indexData->indexCount = ibufcount;
submesh->indexData->indexStart = 0;
// Set bounding information for culling
// ToDo set better bounds
mesh->_setBounds(Ogre::AxisAlignedBox(-100, -100, -100, 100, 100, 100));
mesh->_setBoundingSphereRadius(1000);
mesh->load();
}
void Ygg::OgreRenderSystem::Convert(Ygg::Engine *engine, std::vector<Entity> *entity_queue)
{
for (auto it = entity_queue->begin(); it != entity_queue->end(); ++it) {
Entity *entity = &(*it);
std::cout << "OGRE: Converting " << entity->name << std::endl;
// Convert mesh
MeshComponent *mesh_component = (MeshComponent*)engine->GetComponent(entity, SystemLoader::CID_MESH);
if (mesh_component != NULL)
{
std::cout << "\tFound Mesh" << std::endl;
convert_mesh(entity->name, &(*m_loader->GetMeshes())[mesh_component->mesh_handles[0]]);
Ogre::Entity *head = m_scenemgr->createEntity(entity->name, entity->name);
head->setMaterialName("DefaultMaterial");
Ogre::SceneNode *headnode = m_scenemgr->getRootSceneNode()->createChildSceneNode();
headnode->attachObject(head);
headnode->setPosition(0, 0, 0);
}
}
}
void Ygg::OgreRenderSystem::Update(Ygg::Engine *engine, float dt)
{
m_root->renderOneFrame();
}
<|endoftext|> |
<commit_before>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
lib::lib() {}
/**
* Copy constructor.
*
* @param[in] l Object to copy.
*/
lib::lib(lib const& l)
: backend(l), _filename(l._filename), _metric(l._metric) {}
/**
* Destructor.
*/
lib::~lib() {}
/**
* Assignment operator.
*
* @param[in] l Object to copy.
*
* @return This object.
*/
lib& lib::operator=(lib const& l) {
backend::operator=(l);
_filename = l._filename;
_metric = l._metric;
return (*this);
}
/**
* @brief Initiates the bulk load of multiple commands.
*
* With the librrd backend, this method does nothing.
*/
void lib::begin() {
return ;
}
/**
* Close the RRD file.
*/
void lib::close() {
_filename.clear();
_metric.clear();
return ;
}
/**
* @brief Commit transaction started with begin().
*
* With the librrd backend, the method does nothing.
*/
void lib::commit() {
return ;
}
/**
* Normalize a metric name.
*
* @param[in] metric Metric name.
*
* @return Normalized metric name.
*/
QString lib::normalize_metric_name(QString const& metric) {
QString normalized(metric.toLatin1());
normalized.replace("/", "slash_");
normalized.replace("#S#", "slash_");
normalized.replace("\\", "bslash_");
normalized.replace("#BS#", "bslash_");
normalized.replace("%", "pct_");
normalized.replace("#P#", "pct_");
for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
char current(normalized.at(i).toAscii());
if (!isalnum(current) && (current != '-') && (current != '_'))
normalized.replace(i, 1, '-');
}
if (normalized.isEmpty())
normalized = "x";
else if (normalized.size() > max_metric_length)
normalized.resize(max_metric_length);
if (!isalnum(normalized.at(0).toLatin1()))
normalized.replace(0, 1, 'x');
return (normalized);
}
/**
* Open a RRD file which already exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
*/
void lib::open(QString const& filename,
QString const& metric) {
// Close previous file.
this->close();
// Check that the file exists.
if (!QFile::exists(filename))
throw (exceptions::open() << "RRD: file '"
<< filename << "' does not exist");
// Remember information for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
return ;
}
/**
* Open a RRD file and create it if it does not exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
* @param[in] length Number of recording in the RRD file.
* @param[in] from Timestamp of the first record.
* @param[in] interval Time interval between each record.
*/
void lib::open(QString const& filename,
QString const& metric,
unsigned int length,
time_t from,
time_t interval) {
// Close previous file.
this->close();
// Remember informations for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
/* Find step of RRD file if already existing. */
/* XXX : why is it here ?
rrd_info_t* rrdinfo(rrd_info_r(_filename));
time_t interval_offset(0);
for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
if (!strcmp(rrdinfo->key, "step"))
if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
interval_offset = rrdinfo->value.u_cnt / interval - 1;
rrd_info_free(rrdinfo);
*/
/* Remove previous file. */
QFile::remove(_filename);
/* Set parameters. */
std::ostringstream ds_oss;
std::ostringstream rra1_oss;
std::ostringstream rra2_oss;
ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
std::string ds(ds_oss.str());
std::string rra1(rra1_oss.str());
std::string rra2(rra2_oss.str());
char const* argv[5];
argv[0] = ds.c_str();
argv[1] = rra1.c_str();
argv[2] = rra2.c_str();
argv[3] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: opening file '" << filename
<< "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
<< ", interval " << interval << ", from " << from << ")";
// Create RRD file.
rrd_clear_error();
if (rrd_create_r(_filename.toStdString().c_str(),
interval,
from,
3,
argv))
throw (exceptions::open() << "RRD: could not create file '"
<< _filename << "': " << rrd_get_error());
// Set parameters.
std::string fn(_filename.toStdString());
std::string hb;
{
std::ostringstream oss;
oss << qPrintable(_metric) << ":" << interval * 10;
hb = oss.str();
}
argv[0] = "librrd";
argv[1] = fn.c_str();
argv[2] = "-h"; // --heartbeat
argv[3] = hb.c_str();
argv[4] = NULL;
// Tune file.
if (rrd_tune(4, (char**)argv))
logging::error << logging::MEDIUM << "RRD: could not tune "\
"heartbeat of file '" << _filename << "'";
return ;
}
/**
* Update the RRD file with new value.
*
* @param[in] t Timestamp of value.
* @param[in] value Associated value.
*/
void lib::update(time_t t, QString const& value) {
// Build argument string.
std::string arg;
{
std::ostringstream oss;
oss << t << ":" << value.toStdString();
arg = oss.str();
}
// Set argument table.
char const* argv[2];
argv[0] = arg.c_str();
argv[1] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: updating file '"
<< _filename << "' (metric '" << _metric << "', " << argv[0] << ")";
// Update RRD file.
int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
if (fd < 0) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not open file '"
<< _filename << "': " << msg;
}
else {
try {
// Set lock.
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (-1 == fcntl(fd, F_SETLK, &fl)) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not lock file '"
<< _filename << "': " << msg;
}
else {
rrd_clear_error();
if (rrd_update_r(_filename.toStdString().c_str(),
_metric.toStdString().c_str(),
sizeof(argv) / sizeof(*argv) - 1,
argv))
throw (exceptions::update()
<< "RRD: failed to update value for metric "
<< _metric << ": " << rrd_get_error());
}
}
catch (...) {
::close(fd);
throw ;
}
::close(fd);
}
return ;
}
<commit_msg>Do not change first character of RRD DS name if it is a '-' or a '_'.<commit_after>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
lib::lib() {}
/**
* Copy constructor.
*
* @param[in] l Object to copy.
*/
lib::lib(lib const& l)
: backend(l), _filename(l._filename), _metric(l._metric) {}
/**
* Destructor.
*/
lib::~lib() {}
/**
* Assignment operator.
*
* @param[in] l Object to copy.
*
* @return This object.
*/
lib& lib::operator=(lib const& l) {
backend::operator=(l);
_filename = l._filename;
_metric = l._metric;
return (*this);
}
/**
* @brief Initiates the bulk load of multiple commands.
*
* With the librrd backend, this method does nothing.
*/
void lib::begin() {
return ;
}
/**
* Close the RRD file.
*/
void lib::close() {
_filename.clear();
_metric.clear();
return ;
}
/**
* @brief Commit transaction started with begin().
*
* With the librrd backend, the method does nothing.
*/
void lib::commit() {
return ;
}
/**
* Normalize a metric name.
*
* @param[in] metric Metric name.
*
* @return Normalized metric name.
*/
QString lib::normalize_metric_name(QString const& metric) {
QString normalized(metric.toLatin1());
normalized.replace("/", "slash_");
normalized.replace("#S#", "slash_");
normalized.replace("\\", "bslash_");
normalized.replace("#BS#", "bslash_");
normalized.replace("%", "pct_");
normalized.replace("#P#", "pct_");
for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
char current(normalized.at(i).toAscii());
if (!isalnum(current) && (current != '-') && (current != '_'))
normalized.replace(i, 1, '-');
}
if (normalized.isEmpty())
normalized = "x";
else if (normalized.size() > max_metric_length)
normalized.resize(max_metric_length);
return (normalized);
}
/**
* Open a RRD file which already exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
*/
void lib::open(QString const& filename,
QString const& metric) {
// Close previous file.
this->close();
// Check that the file exists.
if (!QFile::exists(filename))
throw (exceptions::open() << "RRD: file '"
<< filename << "' does not exist");
// Remember information for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
return ;
}
/**
* Open a RRD file and create it if it does not exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
* @param[in] length Number of recording in the RRD file.
* @param[in] from Timestamp of the first record.
* @param[in] interval Time interval between each record.
*/
void lib::open(QString const& filename,
QString const& metric,
unsigned int length,
time_t from,
time_t interval) {
// Close previous file.
this->close();
// Remember informations for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
/* Find step of RRD file if already existing. */
/* XXX : why is it here ?
rrd_info_t* rrdinfo(rrd_info_r(_filename));
time_t interval_offset(0);
for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
if (!strcmp(rrdinfo->key, "step"))
if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
interval_offset = rrdinfo->value.u_cnt / interval - 1;
rrd_info_free(rrdinfo);
*/
/* Remove previous file. */
QFile::remove(_filename);
/* Set parameters. */
std::ostringstream ds_oss;
std::ostringstream rra1_oss;
std::ostringstream rra2_oss;
ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
std::string ds(ds_oss.str());
std::string rra1(rra1_oss.str());
std::string rra2(rra2_oss.str());
char const* argv[5];
argv[0] = ds.c_str();
argv[1] = rra1.c_str();
argv[2] = rra2.c_str();
argv[3] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: opening file '" << filename
<< "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
<< ", interval " << interval << ", from " << from << ")";
// Create RRD file.
rrd_clear_error();
if (rrd_create_r(_filename.toStdString().c_str(),
interval,
from,
3,
argv))
throw (exceptions::open() << "RRD: could not create file '"
<< _filename << "': " << rrd_get_error());
// Set parameters.
std::string fn(_filename.toStdString());
std::string hb;
{
std::ostringstream oss;
oss << qPrintable(_metric) << ":" << interval * 10;
hb = oss.str();
}
argv[0] = "librrd";
argv[1] = fn.c_str();
argv[2] = "-h"; // --heartbeat
argv[3] = hb.c_str();
argv[4] = NULL;
// Tune file.
if (rrd_tune(4, (char**)argv))
logging::error << logging::MEDIUM << "RRD: could not tune "\
"heartbeat of file '" << _filename << "'";
return ;
}
/**
* Update the RRD file with new value.
*
* @param[in] t Timestamp of value.
* @param[in] value Associated value.
*/
void lib::update(time_t t, QString const& value) {
// Build argument string.
std::string arg;
{
std::ostringstream oss;
oss << t << ":" << value.toStdString();
arg = oss.str();
}
// Set argument table.
char const* argv[2];
argv[0] = arg.c_str();
argv[1] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: updating file '"
<< _filename << "' (metric '" << _metric << "', " << argv[0] << ")";
// Update RRD file.
int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
if (fd < 0) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not open file '"
<< _filename << "': " << msg;
}
else {
try {
// Set lock.
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (-1 == fcntl(fd, F_SETLK, &fl)) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not lock file '"
<< _filename << "': " << msg;
}
else {
rrd_clear_error();
if (rrd_update_r(_filename.toStdString().c_str(),
_metric.toStdString().c_str(),
sizeof(argv) / sizeof(*argv) - 1,
argv))
throw (exceptions::update()
<< "RRD: failed to update value for metric "
<< _metric << ": " << rrd_get_error());
}
}
catch (...) {
::close(fd);
throw ;
}
::close(fd);
}
return ;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: filebuff.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: np $ $Date: 2002-08-08 16:08:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "filebuff.hxx"
#include <string.h>
#include <fstream>
#include <ctype.h>
bool
LoadXmlFile( Buffer & o_rBuffer,
const char * i_sXmlFilePath )
{
std::ifstream aXmlFile;
aXmlFile.open(i_sXmlFilePath, std::ios::in
#ifdef WNT
| std::ios::binary
#endif // WNT
);
if (! aXmlFile)
return false;
// Prepare buffer:
aXmlFile.seekg(0, std::ios::end);
unsigned long nBufferSize = aXmlFile.tellg();
o_rBuffer.SetSize(nBufferSize + 1);
o_rBuffer.Data()[nBufferSize] = '\0';
aXmlFile.seekg(0);
// Read file:
aXmlFile.read(o_rBuffer.Data(), nBufferSize);
bool ret = aXmlFile.good() != 0;
aXmlFile.close();
return ret;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.92); FILE MERGED 2005/09/05 14:47:39 rt 1.6.92.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filebuff.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:02:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "filebuff.hxx"
#include <string.h>
#include <fstream>
#include <ctype.h>
bool
LoadXmlFile( Buffer & o_rBuffer,
const char * i_sXmlFilePath )
{
std::ifstream aXmlFile;
aXmlFile.open(i_sXmlFilePath, std::ios::in
#ifdef WNT
| std::ios::binary
#endif // WNT
);
if (! aXmlFile)
return false;
// Prepare buffer:
aXmlFile.seekg(0, std::ios::end);
unsigned long nBufferSize = aXmlFile.tellg();
o_rBuffer.SetSize(nBufferSize + 1);
o_rBuffer.Data()[nBufferSize] = '\0';
aXmlFile.seekg(0);
// Read file:
aXmlFile.read(o_rBuffer.Data(), nBufferSize);
bool ret = aXmlFile.good() != 0;
aXmlFile.close();
return ret;
}
<|endoftext|> |
<commit_before>
// vim:sw=2:ai
/*
* Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
* See COPYRIGHT.txt for details.
*/
#ifndef DENA_MYSQL_INCL_HPP
#define DENA_MYSQL_INCL_HPP
#ifndef HAVE_CONFIG_H
#define HAVE_CONFIG_H
#endif
#define MYSQL_DYNAMIC_PLUGIN
#define MYSQL_SERVER 1
#include <my_config.h>
#ifdef DBUG_ON
#define SAFE_MUTEX
#endif
#include <mysql_version.h>
#if MYSQL_VERSION_ID >= 50505
#include <my_pthread.h>
#include <sql_priv.h>
#include "sql_class.h"
#include "unireg.h"
#include "lock.h"
#include "key.h" // key_copy()
#include <my_global.h>
#include <mysql/plugin.h>
#include <transaction.h>
#include <sql_base.h>
#define safeFree(X) my_free(X)
#define pthread_cond_timedwait mysql_cond_timedwait
#define pthread_mutex_lock mysql_mutex_lock
#define pthread_mutex_unlock mysql_mutex_unlock
#define current_stmt_binlog_row_based is_current_stmt_binlog_format_row
#define clear_current_stmt_binlog_row_based clear_current_stmt_binlog_format_row
#else
#include "mysql_priv.h"
#endif
#undef min
#undef max
#endif
<commit_msg>temp commit<commit_after>
// vim:sw=2:ai
/*
* Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
* See COPYRIGHT.txt for details.
*/
#ifndef DENA_MYSQL_INCL_HPP
#define DENA_MYSQL_INCL_HPP
#ifndef HAVE_CONFIG_H
#define HAVE_CONFIG_H
#endif
#define MYSQL_DYNAMIC_PLUGIN
#define MYSQL_SERVER 1
#include <my_config.h>
#ifdef DBUG_ON
#define SAFE_MUTEX
#endif
#include <mysql_version.h>
#if MYSQL_VERSION_ID >= 50505
#include <my_pthread.h>
#include <sql_priv.h>
#include "sql_class.h"
#include "unireg.h"
#include "lock.h"
#include "key.h" // key_copy()
#include <my_global.h>
#include <mysql/plugin.h>
#include <transaction.h>
#include <sql_base.h>
// FIXME FIXME FIXME
#define safeFree(X) my_free(X)
#define pthread_cond_timedwait mysql_cond_timedwait
#define pthread_mutex_lock mysql_mutex_lock
#define pthread_mutex_unlock mysql_mutex_unlock
#define current_stmt_binlog_row_based is_current_stmt_binlog_format_row
#define clear_current_stmt_binlog_row_based clear_current_stmt_binlog_format_row
#else
#include "mysql_priv.h"
#endif
#undef min
#undef max
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* vlc-libvlc-jni.cc: JNI interface for vlc Java Bindings
*****************************************************************************
* Copyright (C) 1998-2006 the VideoLAN team
*
* Authors: Filippo Carone <[email protected]>
* Philippe Morin <[email protected]>
*
* $Id: core-jni.cc 156 2006-08-01 09:23:01Z littlejohn $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/* These are a must*/
#include <jni.h>
#include <vlc/libvlc.h>
#include <stdio.h> // for printf
#include <stdlib.h> // for calloc
#include <string.h> // for strcmp
#include <unistd.h> // for usleep
/* JVLC internal imports, generated by gcjh */
#include "../includes/JVLC.h"
#include <jawt.h>
#include <jawt_md.h>
#include "utils.h"
jlong getClassInstance (JNIEnv *env, jobject _this);
JNIEXPORT jlong JNICALL Java_org_videolan_jvlc_JVLC_createInstance (JNIEnv *env, jobject _this, jobjectArray args) {
long res;
int argc;
const char **argv;
libvlc_exception_t *exception = ( libvlc_exception_t * ) malloc( sizeof( libvlc_exception_t ) );
libvlc_exception_init( exception );
argc = (int) env->GetArrayLength((jarray) args);
argv = (const char **) malloc(argc * sizeof(char*));
for (int i = 0; i < argc; i++) {
argv[i] = env->GetStringUTFChars((jstring) env->GetObjectArrayElement(args, i),
0
);
}
res = (long) libvlc_new(argc, (char**) argv, exception );
free( exception );
return res;
}
JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1destroy (JNIEnv *env, jobject _this)
{
long instance;
instance = getClassInstance( env, _this );
libvlc_destroy( (libvlc_instance_t *) instance, NULL);
return;
}
//JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1paint (JNIEnv *env, jobject _this, jobject canvas, jobject graphics)
/*
* Utility functions
*/
jlong getClassInstance (JNIEnv *env, jobject _this) {
/* get the id field of object */
jclass cls = env->GetObjectClass(_this);
jmethodID mid = env->GetMethodID(cls, "getInstance", "()J");
jlong field = env->CallLongMethod(_this, mid);
return field;
}
<commit_msg>Fix include for WIN32 version.<commit_after>/*****************************************************************************
* vlc-libvlc-jni.cc: JNI interface for vlc Java Bindings
*****************************************************************************
* Copyright (C) 1998-2006 the VideoLAN team
*
* Authors: Filippo Carone <[email protected]>
* Philippe Morin <[email protected]>
*
* $Id: core-jni.cc 156 2006-08-01 09:23:01Z littlejohn $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/* These are a must*/
#include <jni.h>
#include <vlc/libvlc.h>
#include <stdio.h> // for printf
#include <stdlib.h> // for calloc
#include <string.h> // for strcmp
#ifdef WIN32
#undef usleep
#define usleep(var) Sleep(var/1000)
#else
#include <unistd.h> // for usleep
#endif
/* JVLC internal imports, generated by gcjh */
#include "../includes/JVLC.h"
#include <jawt.h>
#include <jawt_md.h>
#include "utils.h"
jlong getClassInstance (JNIEnv *env, jobject _this);
JNIEXPORT jlong JNICALL Java_org_videolan_jvlc_JVLC_createInstance (JNIEnv *env, jobject _this, jobjectArray args) {
long res;
int argc;
const char **argv;
libvlc_exception_t *exception = ( libvlc_exception_t * ) malloc( sizeof( libvlc_exception_t ) );
libvlc_exception_init( exception );
argc = (int) env->GetArrayLength((jarray) args);
argv = (const char **) malloc(argc * sizeof(char*));
for (int i = 0; i < argc; i++) {
argv[i] = env->GetStringUTFChars((jstring) env->GetObjectArrayElement(args, i),
0
);
}
res = (long) libvlc_new(argc, (char**) argv, exception );
free( exception );
return res;
}
JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1destroy (JNIEnv *env, jobject _this)
{
long instance;
instance = getClassInstance( env, _this );
libvlc_destroy( (libvlc_instance_t *) instance, NULL);
return;
}
//JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1paint (JNIEnv *env, jobject _this, jobject canvas, jobject graphics)
/*
* Utility functions
*/
jlong getClassInstance (JNIEnv *env, jobject _this) {
/* get the id field of object */
jclass cls = env->GetObjectClass(_this);
jmethodID mid = env->GetMethodID(cls, "getInstance", "()J");
jlong field = env->CallLongMethod(_this, mid);
return field;
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Bo Thorsen <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kmailchanges.h"
#include "kolabconfig.h"
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
public:
CreateDisconnectedImapAccount()
: KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
{
}
// This sucks as this is a 1:1 copy from KMAccount::encryptStr()
static QString encryptStr(const QString& aStr)
{
QString result;
for (uint i = 0; i < aStr.length(); i++)
result += (aStr[i].unicode() < 0x20) ? aStr[i] :
QChar(0x1001F - aStr[i].unicode());
return result;
}
void apply()
{
QString email;
QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
// with kolab the userid _is_ the full email
if ( pos > 0 )
// The user typed in a full email address. Assume it's correct
email = user;
else
// Construct the email address. And use it for the username also
user = email = user+"@"+KolabConfig::self()->server();
KConfig c( "kmailrc" );
c.setGroup( "General" );
c.writeEntry( "Default domain", KolabConfig::self()->server() );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
uint transCnt = c.readNumEntry( "transports", 0 );
c.writeEntry( "transports", transCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "cachedimap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "login", user );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
c.setGroup( QString("Transport %1").arg(transCnt+1) );
c.writeEntry( "name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "type", "smtp" );
c.writeEntry( "port", "465" );
c.writeEntry( "encryption", "SSL" );
c.writeEntry( "auth", true );
c.writeEntry( "authtype", "PLAIN" );
c.writeEntry( "user", email );
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "storepass", "true" );
// Write email in "default kcontrol settings", used by IdentityManager
// if it has to create a default identity.
KEMailSettings es;
es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
es.setSetting( KEMailSettings::EmailAddress, email );
es.setSetting( KEMailSettings::ClientProgram, "kontact" );
KPIM::IdentityManager identityManager;
if ( !identityManager.allEmails().contains( email ) ) {
// Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
KPIM::Identity& identity = identityManager.newFromScratch( i18n( "Kolab" ) );
identity.setFullName( KolabConfig::self()->realName() );
identity.setEmailAddr( email );
identityManager.commit();
}
// This needs to be done here, since it reference just just generated id
c.setGroup( "IMAP Resource" );
c.writeEntry("TheIMAPResourceAccount", uid);
c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
}
};
void createKMailChanges( KConfigPropagator::Change::List& changes )
{
KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoAccept";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoDeclConflict";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyMangleFromToHeaders";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyBodyInvites";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceEnabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceStorageFormat";
c->value = "XML";
changes.append( c );
changes.append( new CreateDisconnectedImapAccount );
}
<commit_msg>Take the domain from the emailaddress if it looks like user@domain, as requested in https://intevation.de/roundup/kolab/issue522<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Bo Thorsen <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kmailchanges.h"
#include "kolabconfig.h"
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
public:
CreateDisconnectedImapAccount()
: KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
{
}
// This sucks as this is a 1:1 copy from KMAccount::encryptStr()
static QString encryptStr(const QString& aStr)
{
QString result;
for (uint i = 0; i < aStr.length(); i++)
result += (aStr[i].unicode() < 0x20) ? aStr[i] :
QChar(0x1001F - aStr[i].unicode());
return result;
}
void apply()
{
QString defaultDomain = KolabConfig::self()->server();
QString email;
QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
// with kolab the userid _is_ the full email
if ( pos > 0 ) {
// The user typed in a full email address. Assume it's correct
email = user;
const QString h = user.mid( pos+1 );
if ( !h.isEmpty() )
// The user did type in a domain on the email address. Use that
defaultDomain = h;
}
else
// Construct the email address. And use it for the username also
user = email = user+"@"+KolabConfig::self()->server();
KConfig c( "kmailrc" );
c.setGroup( "General" );
c.writeEntry( "Default domain", defaultDomain );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
uint transCnt = c.readNumEntry( "transports", 0 );
c.writeEntry( "transports", transCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "cachedimap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "login", user );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
c.setGroup( QString("Transport %1").arg(transCnt+1) );
c.writeEntry( "name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "type", "smtp" );
c.writeEntry( "port", "465" );
c.writeEntry( "encryption", "SSL" );
c.writeEntry( "auth", true );
c.writeEntry( "authtype", "PLAIN" );
c.writeEntry( "user", email );
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "storepass", "true" );
// Write email in "default kcontrol settings", used by IdentityManager
// if it has to create a default identity.
KEMailSettings es;
es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
es.setSetting( KEMailSettings::EmailAddress, email );
es.setSetting( KEMailSettings::ClientProgram, "kontact" );
KPIM::IdentityManager identityManager;
if ( !identityManager.allEmails().contains( email ) ) {
// Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
KPIM::Identity& identity = identityManager.newFromScratch( i18n( "Kolab" ) );
identity.setFullName( KolabConfig::self()->realName() );
identity.setEmailAddr( email );
identityManager.commit();
}
// This needs to be done here, since it reference just just generated id
c.setGroup( "IMAP Resource" );
c.writeEntry("TheIMAPResourceAccount", uid);
c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
}
};
void createKMailChanges( KConfigPropagator::Change::List& changes )
{
KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoAccept";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoDeclConflict";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyMangleFromToHeaders";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyBodyInvites";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceEnabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceStorageFormat";
c->value = "XML";
changes.append( c );
changes.append( new CreateDisconnectedImapAccount );
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
template <typename T>
class StaticRmq
{
public:
StaticRmq(const vector<T>& array):
ranges(array.size(), vector<T>(log2(array.size()) + 1))
{
typename vector<T>::size_type n = array.size();
for (typename vector<T>::size_type i = 0; i < n; ++i)
{
ranges[i][0] = array[i];
}
for (typename vector<T>::size_type j = 1; (1 << j) <= n; ++j)
{
for (typename vector<T>::size_type i = 0; i + (1 << j) - 1 < n; ++i)
{
if (ranges[i][j - 1] > ranges[i + (1 << (j - 1))][j - 1])
{
ranges[i][j] = ranges[i][j - 1];
}
else
{
ranges[i][j] = ranges[i + (1 << (j - 1))][j - 1];
}
}
}
}
T query(unsigned int left, unsigned int right) const
{
unsigned int k = log2(right - left + 1);
if (ranges[left][k] >= ranges[right - (1 << k) + 1][k])
{
return ranges[left][k];
}
else
{
return ranges[right - (1 << k) + 1][k];
}
}
private:
vector< vector<T> > ranges;
};
void read_input(unsigned int& elements_count,
vector<unsigned int>& elements,
unsigned int& subarray_size)
{
cin >> elements_count;
elements = vector<unsigned int>(elements_count);
for (unsigned int i = 0; i < elements_count; ++i)
{
cin >> elements[i];
}
cin >> subarray_size;
}
void write_output(unsigned int elements_count,
unsigned int subarray_size,
const StaticRmq<unsigned int>& rmq)
{
for (unsigned int i = 0; i < elements_count - subarray_size + 1; ++i)
{
cout << rmq.query(i, i + subarray_size - 1);
if (i < elements_count - 1)
{
cout << ' ';
}
}
cout << '\n';
}
int main()
{
use_io_optimizations();
unsigned int elements_count;
vector<unsigned int> elements;
unsigned int subarray_size;
read_input(elements_count, elements, subarray_size);
StaticRmq<unsigned int> rmq(elements);
write_output(elements_count, subarray_size, rmq);
return 0;
}
<commit_msg>spoj; improve the solution to "subarrays"<commit_after>#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
class StaticRmq
{
public:
StaticRmq(const vector<unsigned int>& array):
ranges(array.size(), vector<unsigned int>(log2(array.size()) + 1))
{
typedef vector<unsigned int>::size_type index;
index n = array.size();
for (index i = 0; i < n; ++i)
{
ranges[i][0] = array[i];
}
for (index j = 1; (1 << j) <= n; ++j)
{
for (index i = 0; i + (1 << j) - 1 < n; ++i)
{
ranges[i][j] = max(ranges[i][j - 1],
ranges[i + (1 << (j - 1))][j - 1]);
}
}
}
unsigned int get(unsigned int left, unsigned int right) const
{
unsigned int k = log2(right - left + 1);
return max(ranges[left][k], ranges[right - (1 << k) + 1][k]);
}
private:
vector< vector<unsigned int> > ranges;
};
void read_input(unsigned int& elements_count,
vector<unsigned int>& elements,
unsigned int& subarray_size)
{
cin >> elements_count;
elements = vector<unsigned int>(elements_count);
for (unsigned int i = 0; i < elements_count; ++i)
{
cin >> elements[i];
}
cin >> subarray_size;
}
void write_output(unsigned int elements_count,
unsigned int subarray_size,
const StaticRmq& rmq)
{
for (unsigned int i = 0; i < elements_count - subarray_size + 1; ++i)
{
cout << rmq.get(i, i + subarray_size - 1);
if (i < elements_count - 1)
{
cout << ' ';
}
}
cout << '\n';
}
int main()
{
use_io_optimizations();
unsigned int elements_count;
vector<unsigned int> elements;
unsigned int subarray_size;
read_input(elements_count, elements, subarray_size);
StaticRmq rmq(elements);
write_output(elements_count, subarray_size, rmq);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../general/forall.hpp"
#include "bilininteg.hpp"
#include "gridfunc.hpp"
#include "../linalg/elementmatrix.hpp"
namespace mfem
{
static void EADGTraceAssemble1D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext)
{
auto D = Reshape(padata.Read(), 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), 2, NF);
MFEM_FORALL(f, NF,
{
double val_int0 = D(0, 0, f);
double val_int1 = D(1, 1, f);
double val_ext01 = D(1, 0, f);
double val_ext10 = D(0, 1, f);
A_int(0, f) = val_int0;
A_int(1, f) = val_int1;
A_ext(0, f) = val_ext01;
A_ext(1, f) = val_ext10;
});
}
template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble2D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext,
const int d1d = 0,
const int q1d = 0)
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
MFEM_VERIFY(D1D <= MAX_D1D, "");
MFEM_VERIFY(Q1D <= MAX_Q1D, "");
auto B = Reshape(basis.Read(), Q1D, D1D);
auto D = Reshape(padata.Read(), Q1D, 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), D1D, D1D, 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, 2, NF);
MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
double r_Bi[MQ1];
double r_Bj[MQ1];
for (int q = 0; q < Q1D; q++)
{
r_Bi[q] = B(q,MFEM_THREAD_ID(x));
r_Bj[q] = B(q,MFEM_THREAD_ID(y));
}
MFEM_FOREACH_THREAD(i1,x,D1D)
{
MFEM_FOREACH_THREAD(j1,y,D1D)
{
double val_int0 = 0.0;
double val_int1 = 0.0;
double val_ext01 = 0.0;
double val_ext10 = 0.0;
for (int k1 = 0; k1 < Q1D; ++k1)
{
val_int0 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 0, f);
val_int1 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 1, f);
val_ext01 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 0, f);
val_ext10 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 1, f);
}
A_int(i1, j1, 0, f) = val_int0;
A_int(i1, j1, 1, f) = val_int1;
A_ext(i1, j1, 0, f) = val_ext01;
A_ext(i1, j1, 1, f) = val_ext10;
}
}
});
}
template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble3D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext,
const int d1d = 0,
const int q1d = 0)
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
MFEM_VERIFY(D1D <= MAX_D1D, "");
MFEM_VERIFY(Q1D <= MAX_Q1D, "");
auto B = Reshape(basis.Read(), Q1D, D1D);
auto D = Reshape(padata.Read(), Q1D, Q1D, 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), D1D, D1D, D1D, D1D, 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, D1D, D1D, 2, NF);
MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
constexpr int MD1 = T_D1D ? T_D1D : MAX_D1D;
constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
double r_B[MQ1][MD1];
for (int d = 0; d < D1D; d++)
{
for (int q = 0; q < Q1D; q++)
{
r_B[q][d] = B(q,d);
}
}
MFEM_SHARED double s_D[MQ1][MQ1][2][2];
for (int i; i < 2; i++)
{
for (int j; j < 2; j++)
{
MFEM_FOREACH_THREAD(k1,x,Q1D)
{
MFEM_FOREACH_THREAD(k2,y,Q1D)
{
s_D[k1][k2][i][j] = D(k1,k2,i,j,f);
}
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(i1,x,D1D)
{
MFEM_FOREACH_THREAD(i2,y,D1D)
{
for (int j1 = 0; j1 < D1D; ++j1)
{
for (int j2 = 0; j2 < D1D; ++j2)
{
double val_int0 = 0.0;
double val_int1 = 0.0;
double val_ext01 = 0.0;
double val_ext10 = 0.0;
for (int k1 = 0; k1 < Q1D; ++k1)
{
for (int k2 = 0; k2 < Q1D; ++k2)
{
val_int0 += r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][0][0];
val_int1 += r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][1][1];
val_ext01+= r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][1][0];
val_ext10+= r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][0][1];
}
}
A_int(i1, i2, j1, j2, 0, f) = val_int0;
A_int(i1, i2, j1, j2, 1, f) = val_int1;
A_ext(i1, i2, j1, j2, 0, f) = val_ext01;
A_ext(i1, i2, j1, j2, 1, f) = val_ext10;
}
}
}
}
});
}
void DGTraceIntegrator::SetupEA(const FiniteElementSpace &fes,
Vector &ea_data_int,
Vector &ea_data_ext,
FaceType type)
{
SetupPA(fes, type);
nf = fes.GetNFbyType(type);
const Array<double> &B = maps->B;
if (dim == 1)
{
return EADGTraceAssemble1D(nf,B,pa_data,ea_data_int,ea_data_ext);
}
else if (dim == 2)
{
switch ((dofs1D << 4 ) | quad1D)
{
case 0x22: return EADGTraceAssemble2D<2,2>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x33: return EADGTraceAssemble2D<3,3>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x44: return EADGTraceAssemble2D<4,4>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x55: return EADGTraceAssemble2D<5,5>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x66: return EADGTraceAssemble2D<6,6>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x77: return EADGTraceAssemble2D<7,7>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x88: return EADGTraceAssemble2D<8,8>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x99: return EADGTraceAssemble2D<9,9>(nf,B,pa_data,ea_data_int,ea_data_ext);
default: return EADGTraceAssemble2D(nf,B,pa_data,ea_data_int,ea_data_ext,dofs1D,quad1D);
}
}
else if (dim == 3)
{
switch ((dofs1D << 4 ) | quad1D)
{
case 0x23: return EADGTraceAssemble3D<2,3>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x34: return EADGTraceAssemble3D<3,4>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x45: return EADGTraceAssemble3D<4,5>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x56: return EADGTraceAssemble3D<5,6>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x67: return EADGTraceAssemble3D<6,7>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x78: return EADGTraceAssemble3D<7,8>(nf,B,pa_data,ea_data_int,ea_data_ext);
case 0x89: return EADGTraceAssemble3D<8,9>(nf,B,pa_data,ea_data_int,ea_data_ext);
default: return EADGTraceAssemble3D(nf,B,pa_data,ea_data_int,ea_data_ext,dofs1D,quad1D);
}
}
MFEM_ABORT("Unknown kernel.");
}
void DGTraceIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes,
Vector &ea_data_int,
Vector &ea_data_ext)
{
SetupEA(fes, ea_data_int, ea_data_ext, FaceType::Interior);
}
void DGTraceIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes,
Vector &ea_data_bdr)
{
//TODO this is wrong
SetupEA(fes, ea_data_bdr, ea_data_bdr, FaceType::Boundary);
}
}
<commit_msg>Integrate change for boundary vs interior faces.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../general/forall.hpp"
#include "bilininteg.hpp"
#include "gridfunc.hpp"
#include "../linalg/elementmatrix.hpp"
namespace mfem
{
static void EADGTraceAssemble1D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext,
FaceType type)
{
const bool bdr = type==FaceType::Boundary;
auto D = Reshape(padata.Read(), 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), 2, NF);
MFEM_FORALL(f, NF,
{
double val_int0, val_int1, val_ext01, val_ext10;
val_int0 = D(0, 0, f);
if (bdr)
{
val_ext01 = D(1, 0, f);
val_ext10 = D(0, 1, f);
}
val_int1 = D(1, 1, f);
A_int(0, f) = val_int0;
A_int(1, f) = val_int1;
if (bdr)
{
A_ext(0, f) = val_ext01;
A_ext(1, f) = val_ext10;
}
});
}
template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble2D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext,
FaceType type,
const int d1d = 0,
const int q1d = 0)
{
const bool bdr = type==FaceType::Boundary;
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
MFEM_VERIFY(D1D <= MAX_D1D, "");
MFEM_VERIFY(Q1D <= MAX_Q1D, "");
auto B = Reshape(basis.Read(), Q1D, D1D);
auto D = Reshape(padata.Read(), Q1D, 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), D1D, D1D, 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, 2, NF);
MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
double r_Bi[MQ1];
double r_Bj[MQ1];
for (int q = 0; q < Q1D; q++)
{
r_Bi[q] = B(q,MFEM_THREAD_ID(x));
r_Bj[q] = B(q,MFEM_THREAD_ID(y));
}
MFEM_FOREACH_THREAD(i1,x,D1D)
{
MFEM_FOREACH_THREAD(j1,y,D1D)
{
double val_int0 = 0.0;
double val_int1 = 0.0;
double val_ext01 = 0.0;
double val_ext10 = 0.0;
for (int k1 = 0; k1 < Q1D; ++k1)
{
val_int0 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 0, f);
if (bdr)
{
val_ext01 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 0, f);
val_ext10 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 1, f);
}
val_int1 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 1, f);
}
A_int(i1, j1, 0, f) = val_int0;
A_int(i1, j1, 1, f) = val_int1;
if (bdr)
{
A_ext(i1, j1, 0, f) = val_ext01;
A_ext(i1, j1, 1, f) = val_ext10;
}
}
}
});
}
template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble3D(const int NF,
const Array<double> &basis,
const Vector &padata,
Vector &eadata_int,
Vector &eadata_ext,
FaceType type,
const int d1d = 0,
const int q1d = 0)
{
const bool bdr = type==FaceType::Boundary;
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
MFEM_VERIFY(D1D <= MAX_D1D, "");
MFEM_VERIFY(Q1D <= MAX_Q1D, "");
auto B = Reshape(basis.Read(), Q1D, D1D);
auto D = Reshape(padata.Read(), Q1D, Q1D, 2, 2, NF);
auto A_int = Reshape(eadata_int.Write(), D1D, D1D, D1D, D1D, 2, NF);
auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, D1D, D1D, 2, NF);
MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
constexpr int MD1 = T_D1D ? T_D1D : MAX_D1D;
constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
double r_B[MQ1][MD1];
for (int d = 0; d < D1D; d++)
{
for (int q = 0; q < Q1D; q++)
{
r_B[q][d] = B(q,d);
}
}
MFEM_SHARED double s_D[MQ1][MQ1][2][2];
for (int i; i < 2; i++)
{
for (int j; j < 2; j++)
{
MFEM_FOREACH_THREAD(k1,x,Q1D)
{
MFEM_FOREACH_THREAD(k2,y,Q1D)
{
s_D[k1][k2][i][j] = D(k1,k2,i,j,f);
}
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(i1,x,D1D)
{
MFEM_FOREACH_THREAD(i2,y,D1D)
{
for (int j1 = 0; j1 < D1D; ++j1)
{
for (int j2 = 0; j2 < D1D; ++j2)
{
double val_int0 = 0.0;
double val_int1 = 0.0;
double val_ext01 = 0.0;
double val_ext10 = 0.0;
for (int k1 = 0; k1 < Q1D; ++k1)
{
for (int k2 = 0; k2 < Q1D; ++k2)
{
val_int0 += r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][0][0];
val_int1 += r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][1][1];
if (bdr)
{
val_ext01+= r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][1][0];
val_ext10+= r_B[k1][i1] * r_B[k1][j1]
* r_B[k2][i2] * r_B[k2][j2]
* s_D[k1][k2][0][1];
}
}
}
A_int(i1, i2, j1, j2, 0, f) = val_int0;
A_int(i1, i2, j1, j2, 1, f) = val_int1;
if (bdr)
{
A_ext(i1, i2, j1, j2, 0, f) = val_ext01;
A_ext(i1, i2, j1, j2, 1, f) = val_ext10;
}
}
}
}
}
});
}
void DGTraceIntegrator::SetupEA(const FiniteElementSpace &fes,
Vector &ea_data_int,
Vector &ea_data_ext,
FaceType type)
{
SetupPA(fes, type);
nf = fes.GetNFbyType(type);
const Array<double> &B = maps->B;
if (dim == 1)
{
return EADGTraceAssemble1D(nf,B,pa_data,ea_data_int,ea_data_ext,type);
}
else if (dim == 2)
{
switch ((dofs1D << 4 ) | quad1D)
{
case 0x22: return EADGTraceAssemble2D<2,2>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x33: return EADGTraceAssemble2D<3,3>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x44: return EADGTraceAssemble2D<4,4>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x55: return EADGTraceAssemble2D<5,5>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x66: return EADGTraceAssemble2D<6,6>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x77: return EADGTraceAssemble2D<7,7>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x88: return EADGTraceAssemble2D<8,8>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x99: return EADGTraceAssemble2D<9,9>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
default: return EADGTraceAssemble2D(nf,B,pa_data,ea_data_int,ea_data_ext,type,dofs1D,quad1D);
}
}
else if (dim == 3)
{
switch ((dofs1D << 4 ) | quad1D)
{
case 0x23: return EADGTraceAssemble3D<2,3>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x34: return EADGTraceAssemble3D<3,4>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x45: return EADGTraceAssemble3D<4,5>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x56: return EADGTraceAssemble3D<5,6>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x67: return EADGTraceAssemble3D<6,7>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x78: return EADGTraceAssemble3D<7,8>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
case 0x89: return EADGTraceAssemble3D<8,9>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
default: return EADGTraceAssemble3D(nf,B,pa_data,ea_data_int,ea_data_ext,type,dofs1D,quad1D);
}
}
MFEM_ABORT("Unknown kernel.");
}
void DGTraceIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes,
Vector &ea_data_int,
Vector &ea_data_ext)
{
SetupEA(fes, ea_data_int, ea_data_ext, FaceType::Interior);
}
void DGTraceIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes,
Vector &ea_data_bdr)
{
SetupEA(fes, ea_data_bdr, ea_data_bdr, FaceType::Boundary);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureSerializer.h"
#include <fstream>
#include <memory>
#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "Core.h"
#include "EventTracer.h"
#include "OrbitModule.h"
#include "OrbitProcess.h"
#include "Pdb.h"
#include "PrintVar.h"
#include "SamplingProfiler.h"
#include "ScopeTimer.h"
#include "Serialization.h"
#include "TextBox.h"
#include "TimeGraph.h"
#include "TimerChain.h"
#include "absl/strings/str_format.h"
//-----------------------------------------------------------------------------
CaptureSerializer::CaptureSerializer() {
m_Version = 2;
m_TimerVersion = Timer::Version;
m_SizeOfTimer = sizeof(Timer);
}
//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Save(
const std::string& filename) {
Capture::PreSave();
std::basic_ostream<char> Stream(&GStreamCounter);
cereal::BinaryOutputArchive CountingArchive(Stream);
GStreamCounter.Reset();
Save(CountingArchive);
PRINT_VAR(GStreamCounter.Size());
GStreamCounter.Reset();
// Binary
m_CaptureName = filename;
std::ofstream file(m_CaptureName, std::ios::binary);
if (file.fail()) {
ERROR("Saving capture in \"%s\": %s", filename, "file.fail()");
return outcome::failure("Error opening the file for writing");
}
try {
SCOPE_TIMER_LOG(absl::StrFormat("Saving capture in \"%s\"", filename));
cereal::BinaryOutputArchive archive(file);
Save(archive);
return outcome::success();
} catch (std::exception& e) {
ERROR("Saving capture in \"%s\": %s", filename, e.what());
return outcome::failure("Error serializing the capture");
}
}
//-----------------------------------------------------------------------------
template <class T>
void CaptureSerializer::Save(T& archive) {
m_NumTimers = time_graph_->GetNumTimers();
// Header
archive(cereal::make_nvp("Capture", *this));
{
ORBIT_SIZE_SCOPE("Functions");
std::vector<Function> functions;
for (auto& pair : Capture::GSelectedFunctionsMap) {
Function* func = pair.second;
if (func != nullptr) {
functions.push_back(*func);
}
}
archive(functions);
}
{
ORBIT_SIZE_SCOPE("Capture::GFunctionCountMap");
archive(Capture::GFunctionCountMap);
}
{
ORBIT_SIZE_SCOPE("Capture::GCallstacks");
archive(Capture::GCallstacks);
}
{
ORBIT_SIZE_SCOPE("Capture::GAddressInfos");
archive(Capture::GAddressInfos);
}
{
ORBIT_SIZE_SCOPE("Capture::GAddressToFunctionName");
archive(Capture::GAddressToFunctionName);
}
{
ORBIT_SIZE_SCOPE("SamplingProfiler");
archive(Capture::GSamplingProfiler);
}
{
ORBIT_SIZE_SCOPE("String manager");
archive(*time_graph_->GetStringManager());
}
{
ORBIT_SIZE_SCOPE("Event Buffer");
archive(GEventTracer.GetEventBuffer());
}
// Timers
int numWrites = 0;
std::vector<std::shared_ptr<TimerChain>> chains =
time_graph_->GetAllTimerChains();
for (const std::shared_ptr<TimerChain>& chain : chains) {
if (!chain) continue;
for (TimerChainIterator& it = chain->begin(); it != chain->end(); ++it) {
TimerBlock& block = *it;
for (int k = 0; k < block.size(); ++k) {
archive(cereal::binary_data(&(block[k].GetTimer()), sizeof(Timer)));
if (++numWrites > m_NumTimers) {
return;
}
}
}
}
}
//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Load(
const std::string& filename) {
SCOPE_TIMER_LOG(absl::StrFormat("Loading capture from \"%s\"", filename));
// Binary
std::ifstream file(filename, std::ios::binary);
if (file.fail()) {
ERROR("Loading capture from \"%s\": %s", filename, "file.fail()");
return outcome::failure("Error opening the file for reading");
}
try {
// Header
cereal::BinaryInputArchive archive(file);
archive(*this);
// Functions
std::vector<Function> functions;
archive(functions);
Capture::GSelectedFunctions.clear();
Capture::GSelectedFunctionsMap.clear();
for (const auto& function : functions) {
std::shared_ptr<Function> function_ptr =
std::make_shared<Function>(function);
Capture::GSelectedFunctions.push_back(function_ptr);
Capture::GSelectedFunctionsMap[function_ptr->GetVirtualAddress()] =
function_ptr.get();
}
Capture::GVisibleFunctionsMap = Capture::GSelectedFunctionsMap;
archive(Capture::GFunctionCountMap);
archive(Capture::GCallstacks);
archive(Capture::GAddressInfos);
archive(Capture::GAddressToFunctionName);
archive(Capture::GSamplingProfiler);
if (Capture::GSamplingProfiler == nullptr) {
Capture::GSamplingProfiler = std::make_shared<SamplingProfiler>();
}
Capture::GSamplingProfiler->SortByThreadUsage();
time_graph_->Clear();
archive(*time_graph_->GetStringManager());
// Event buffer
archive(GEventTracer.GetEventBuffer());
// Timers
Timer timer;
while (file.read(reinterpret_cast<char*>(&timer), sizeof(Timer))) {
time_graph_->ProcessTimer(timer);
}
GOrbitApp->AddSamplingReport(Capture::GSamplingProfiler);
GOrbitApp->FireRefreshCallbacks();
return outcome::success();
} catch (std::exception& e) {
ERROR("Loading capture from \"%s\": %s", filename, e.what());
return outcome::failure("Error parsing the capture");
}
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(CaptureSerializer, 0) {
ORBIT_NVP_VAL(0, m_CaptureName);
ORBIT_NVP_VAL(0, m_Version);
ORBIT_NVP_VAL(0, m_TimerVersion);
ORBIT_NVP_VAL(0, m_NumTimers);
ORBIT_NVP_VAL(0, m_SizeOfTimer);
}
<commit_msg>Fix build.<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureSerializer.h"
#include <fstream>
#include <memory>
#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "Core.h"
#include "EventTracer.h"
#include "OrbitModule.h"
#include "OrbitProcess.h"
#include "Pdb.h"
#include "PrintVar.h"
#include "SamplingProfiler.h"
#include "ScopeTimer.h"
#include "Serialization.h"
#include "TextBox.h"
#include "TimeGraph.h"
#include "TimerChain.h"
#include "absl/strings/str_format.h"
//-----------------------------------------------------------------------------
CaptureSerializer::CaptureSerializer() {
m_Version = 2;
m_TimerVersion = Timer::Version;
m_SizeOfTimer = sizeof(Timer);
}
//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Save(
const std::string& filename) {
Capture::PreSave();
std::basic_ostream<char> Stream(&GStreamCounter);
cereal::BinaryOutputArchive CountingArchive(Stream);
GStreamCounter.Reset();
Save(CountingArchive);
PRINT_VAR(GStreamCounter.Size());
GStreamCounter.Reset();
// Binary
m_CaptureName = filename;
std::ofstream file(m_CaptureName, std::ios::binary);
if (file.fail()) {
ERROR("Saving capture in \"%s\": %s", filename, "file.fail()");
return outcome::failure("Error opening the file for writing");
}
try {
SCOPE_TIMER_LOG(absl::StrFormat("Saving capture in \"%s\"", filename));
cereal::BinaryOutputArchive archive(file);
Save(archive);
return outcome::success();
} catch (std::exception& e) {
ERROR("Saving capture in \"%s\": %s", filename, e.what());
return outcome::failure("Error serializing the capture");
}
}
//-----------------------------------------------------------------------------
template <class T>
void CaptureSerializer::Save(T& archive) {
m_NumTimers = time_graph_->GetNumTimers();
// Header
archive(cereal::make_nvp("Capture", *this));
{
ORBIT_SIZE_SCOPE("Functions");
std::vector<Function> functions;
for (auto& pair : Capture::GSelectedFunctionsMap) {
Function* func = pair.second;
if (func != nullptr) {
functions.push_back(*func);
}
}
archive(functions);
}
{
ORBIT_SIZE_SCOPE("Capture::GFunctionCountMap");
archive(Capture::GFunctionCountMap);
}
{
ORBIT_SIZE_SCOPE("Capture::GCallstacks");
archive(Capture::GCallstacks);
}
{
ORBIT_SIZE_SCOPE("Capture::GAddressInfos");
archive(Capture::GAddressInfos);
}
{
ORBIT_SIZE_SCOPE("Capture::GAddressToFunctionName");
archive(Capture::GAddressToFunctionName);
}
{
ORBIT_SIZE_SCOPE("SamplingProfiler");
archive(Capture::GSamplingProfiler);
}
{
ORBIT_SIZE_SCOPE("String manager");
archive(*time_graph_->GetStringManager());
}
{
ORBIT_SIZE_SCOPE("Event Buffer");
archive(GEventTracer.GetEventBuffer());
}
// Timers
int numWrites = 0;
std::vector<std::shared_ptr<TimerChain>> chains =
time_graph_->GetAllTimerChains();
for (auto& chain : chains) {
if (!chain) continue;
for (TimerChainIterator& it = chain->begin(); it != chain->end(); ++it) {
TimerBlock& block = *it;
for (int k = 0; k < block.size(); ++k) {
archive(cereal::binary_data(&(block[k].GetTimer()), sizeof(Timer)));
if (++numWrites > m_NumTimers) {
return;
}
}
}
}
}
//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Load(
const std::string& filename) {
SCOPE_TIMER_LOG(absl::StrFormat("Loading capture from \"%s\"", filename));
// Binary
std::ifstream file(filename, std::ios::binary);
if (file.fail()) {
ERROR("Loading capture from \"%s\": %s", filename, "file.fail()");
return outcome::failure("Error opening the file for reading");
}
try {
// Header
cereal::BinaryInputArchive archive(file);
archive(*this);
// Functions
std::vector<Function> functions;
archive(functions);
Capture::GSelectedFunctions.clear();
Capture::GSelectedFunctionsMap.clear();
for (const auto& function : functions) {
std::shared_ptr<Function> function_ptr =
std::make_shared<Function>(function);
Capture::GSelectedFunctions.push_back(function_ptr);
Capture::GSelectedFunctionsMap[function_ptr->GetVirtualAddress()] =
function_ptr.get();
}
Capture::GVisibleFunctionsMap = Capture::GSelectedFunctionsMap;
archive(Capture::GFunctionCountMap);
archive(Capture::GCallstacks);
archive(Capture::GAddressInfos);
archive(Capture::GAddressToFunctionName);
archive(Capture::GSamplingProfiler);
if (Capture::GSamplingProfiler == nullptr) {
Capture::GSamplingProfiler = std::make_shared<SamplingProfiler>();
}
Capture::GSamplingProfiler->SortByThreadUsage();
time_graph_->Clear();
archive(*time_graph_->GetStringManager());
// Event buffer
archive(GEventTracer.GetEventBuffer());
// Timers
Timer timer;
while (file.read(reinterpret_cast<char*>(&timer), sizeof(Timer))) {
time_graph_->ProcessTimer(timer);
}
GOrbitApp->AddSamplingReport(Capture::GSamplingProfiler);
GOrbitApp->FireRefreshCallbacks();
return outcome::success();
} catch (std::exception& e) {
ERROR("Loading capture from \"%s\": %s", filename, e.what());
return outcome::failure("Error parsing the capture");
}
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(CaptureSerializer, 0) {
ORBIT_NVP_VAL(0, m_CaptureName);
ORBIT_NVP_VAL(0, m_Version);
ORBIT_NVP_VAL(0, m_TimerVersion);
ORBIT_NVP_VAL(0, m_NumTimers);
ORBIT_NVP_VAL(0, m_SizeOfTimer);
}
<|endoftext|> |
<commit_before>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "highwayhash/arch_specific.h"
#include <stdint.h>
#if HH_ARCH_X64 && !HH_MSC_VERSION
#include <cpuid.h>
#endif
#if HH_ARCH_PPC
#include <sys/platform/ppc.h> // __ppc_get_timebase_freq
#endif
#include <string.h> // memcpy
#include <string>
namespace highwayhash {
const char* TargetName(const TargetBits target_bit) {
switch (target_bit) {
case HH_TARGET_Portable:
return "Portable";
case HH_TARGET_SSE41:
return "SSE41";
case HH_TARGET_AVX2:
return "AVX2";
case HH_TARGET_VSX:
return "VSX";
case HH_TARGET_NEON:
return "NEON";
default:
return nullptr; // zero, multiple, or unknown bits
}
}
#if HH_ARCH_X64
namespace {
std::string BrandString() {
char brand_string[49];
uint32_t abcd[4];
// Check if brand string is supported (it is on all reasonable Intel/AMD)
Cpuid(0x80000000U, 0, abcd);
if (abcd[0] < 0x80000004U) {
return std::string();
}
for (int i = 0; i < 3; ++i) {
Cpuid(0x80000002U + i, 0, abcd);
memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
}
brand_string[48] = 0;
return brand_string;
}
} // namespace
void Cpuid(const uint32_t level, const uint32_t count,
uint32_t* HH_RESTRICT abcd) {
#if HH_MSC_VERSION
int regs[4];
__cpuidex(regs, level, count);
for (int i = 0; i < 4; ++i) {
abcd[i] = regs[i];
}
#else
uint32_t a, b, c, d;
__cpuid_count(level, count, a, b, c, d);
abcd[0] = a;
abcd[1] = b;
abcd[2] = c;
abcd[3] = d;
#endif
}
uint32_t ApicId() {
uint32_t abcd[4];
Cpuid(1, 0, abcd);
return abcd[1] >> 24; // ebx
}
#endif // HH_ARCH_X64
namespace {
double DetectNominalClockRate() {
#if HH_ARCH_X64
const std::string& brand_string = BrandString();
// Brand strings include the maximum configured frequency. These prefixes are
// defined by Intel CPUID documentation.
const char* prefixes[3] = {"MHz", "GHz", "THz"};
const double multipliers[3] = {1E6, 1E9, 1E12};
for (size_t i = 0; i < 3; ++i) {
const size_t pos_prefix = brand_string.find(prefixes[i]);
if (pos_prefix != std::string::npos) {
const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
if (pos_space != std::string::npos) {
const std::string digits =
brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
return std::stod(digits) * multipliers[i];
}
}
}
#elif HH_ARCH_PPC
double freq = -1;
char line[200];
char* s;
char* value;
FILE* f = fopen("/proc/cpuinfo", "r");
if (f != nullptr) {
while (fgets(line, sizeof(line), f) != nullptr) {
// NOTE: the ':' is the only character we can rely on
if (!(value = strchr(line, ':'))) continue;
// terminate the valuename
*value++ = '\0';
// skip any leading spaces
while (*value == ' ') value++;
if ((s = strchr(value, '\n'))) *s = '\0';
if (!strncasecmp(line, "clock", strlen("clock")) &&
sscanf(value, "%lf", &freq) == 1) {
freq *= 1E6;
break;
}
}
fclose(f);
return freq;
}
#endif
return 0.0;
}
} // namespace
double NominalClockRate() {
// Thread-safe caching - this is called several times.
static const double cycles_per_second = DetectNominalClockRate();
return cycles_per_second;
}
double InvariantTicksPerSecond() {
#if HH_ARCH_PPC
static const double cycles_per_second = __ppc_get_timebase_freq();
return cycles_per_second;
#else
return NominalClockRate();
#endif
}
} // namespace highwayhash
<commit_msg>Fix build on FreeBSD/powerpc64<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "highwayhash/arch_specific.h"
#include <stdint.h>
#if HH_ARCH_X64 && !HH_MSC_VERSION
#include <cpuid.h>
#endif
#if HH_ARCH_PPC
#if __GLIBC__
#include <sys/platform/ppc.h> // __ppc_get_timebase_freq
#elif __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include <string.h> // memcpy
#include <string>
namespace highwayhash {
const char* TargetName(const TargetBits target_bit) {
switch (target_bit) {
case HH_TARGET_Portable:
return "Portable";
case HH_TARGET_SSE41:
return "SSE41";
case HH_TARGET_AVX2:
return "AVX2";
case HH_TARGET_VSX:
return "VSX";
case HH_TARGET_NEON:
return "NEON";
default:
return nullptr; // zero, multiple, or unknown bits
}
}
#if HH_ARCH_X64
namespace {
std::string BrandString() {
char brand_string[49];
uint32_t abcd[4];
// Check if brand string is supported (it is on all reasonable Intel/AMD)
Cpuid(0x80000000U, 0, abcd);
if (abcd[0] < 0x80000004U) {
return std::string();
}
for (int i = 0; i < 3; ++i) {
Cpuid(0x80000002U + i, 0, abcd);
memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
}
brand_string[48] = 0;
return brand_string;
}
} // namespace
void Cpuid(const uint32_t level, const uint32_t count,
uint32_t* HH_RESTRICT abcd) {
#if HH_MSC_VERSION
int regs[4];
__cpuidex(regs, level, count);
for (int i = 0; i < 4; ++i) {
abcd[i] = regs[i];
}
#else
uint32_t a, b, c, d;
__cpuid_count(level, count, a, b, c, d);
abcd[0] = a;
abcd[1] = b;
abcd[2] = c;
abcd[3] = d;
#endif
}
uint32_t ApicId() {
uint32_t abcd[4];
Cpuid(1, 0, abcd);
return abcd[1] >> 24; // ebx
}
#endif // HH_ARCH_X64
namespace {
double DetectNominalClockRate() {
#if HH_ARCH_X64
const std::string& brand_string = BrandString();
// Brand strings include the maximum configured frequency. These prefixes are
// defined by Intel CPUID documentation.
const char* prefixes[3] = {"MHz", "GHz", "THz"};
const double multipliers[3] = {1E6, 1E9, 1E12};
for (size_t i = 0; i < 3; ++i) {
const size_t pos_prefix = brand_string.find(prefixes[i]);
if (pos_prefix != std::string::npos) {
const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
if (pos_space != std::string::npos) {
const std::string digits =
brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
return std::stod(digits) * multipliers[i];
}
}
}
#elif HH_ARCH_PPC
double freq = -1;
#if __linux__
char line[200];
char* s;
char* value;
FILE* f = fopen("/proc/cpuinfo", "r");
if (f != nullptr) {
while (fgets(line, sizeof(line), f) != nullptr) {
// NOTE: the ':' is the only character we can rely on
if (!(value = strchr(line, ':'))) continue;
// terminate the valuename
*value++ = '\0';
// skip any leading spaces
while (*value == ' ') value++;
if ((s = strchr(value, '\n'))) *s = '\0';
if (!strncasecmp(line, "clock", strlen("clock")) &&
sscanf(value, "%lf", &freq) == 1) {
freq *= 1E6;
break;
}
}
fclose(f);
return freq;
}
#elif __FreeBSD__
size_t length = sizeof(freq);
sysctlbyname("dev.cpu.0.freq"), &freq, &length, NULL, 0);
freq *= 1E6;
return freq;
#endif
#endif
return 0.0;
}
} // namespace
double NominalClockRate() {
// Thread-safe caching - this is called several times.
static const double cycles_per_second = DetectNominalClockRate();
return cycles_per_second;
}
double InvariantTicksPerSecond() {
#if HH_ARCH_PPC
#if __GLIBC__
static const double cycles_per_second = __ppc_get_timebase_freq();
#elif __FreeBSD__
static double cycles_per_second = 0;
size_t length = sizeof(cycles_per_second);
sysctlbyname("kern.timecounter.tc.timebase.frequency", &cycles_per_second, &length, NULL, 0);
#endif
return cycles_per_second;
#else
return NominalClockRate();
#endif
}
} // namespace highwayhash
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/ui/file_dialog.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "browser/native_window.h"
#include "browser/ui/gtk/gtk_util.h"
#include "ui/base/gtk/gtk_signal.h"
namespace file_dialog {
namespace {
class FileChooserDialog {
public:
FileChooserDialog(GtkFileChooserAction action,
atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path) {
GtkWindow* window = parent_window ? parent_window->GetNativeWindow() : NULL;
dialog_ = gtk_file_chooser_dialog_new(
title.c_str(),
window,
action,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
NULL);
if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
TRUE);
if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);
// Set window-to-parent modality by adding the dialog to the same window
// group as the parent.
gtk_window_group_add_window(gtk_window_get_group(window),
GTK_WINDOW(dialog_));
gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
if (!default_path.empty()) {
if (base::DirectoryExists(default_path))
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
default_path.value().c_str());
else
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog_),
default_path.value().c_str());
}
}
virtual ~FileChooserDialog() {
gtk_widget_destroy(dialog_);
}
void RunSaveAsynchronous(const SaveDialogCallback& callback) {
save_callback_ = callback;
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), NULL);
g_signal_connect(dialog_, "response",
G_CALLBACK(OnFileSaveDialogResponseThunk), this);
gtk_widget_show_all(dialog_);
}
base::FilePath GetFileName() const {
gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
base::FilePath path(filename);
g_free(filename);
return path;
}
CHROMEGTK_CALLBACK_1(FileChooserDialog, void,
OnFileSaveDialogResponse, int);
GtkWidget* dialog() const { return dialog_; }
private:
GtkWidget* dialog_;
SaveDialogCallback save_callback_;
OpenDialogCallback open_callback_;
DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};
void FileChooserDialog::OnFileSaveDialogResponse(GtkWidget* widget,
int response) {
gtk_widget_hide_all(dialog_);
if (response == GTK_RESPONSE_ACCEPT)
save_callback_.Run(true, GetFileName());
else
save_callback_.Run(false, base::FilePath());
delete this;
}
} // namespace
bool ShowOpenDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
int properties,
std::vector<base::FilePath>* paths) {
return false;
}
void ShowOpenDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
int properties,
const OpenDialogCallback& callback) {
callback.Run(false, std::vector<base::FilePath>());
}
bool ShowSaveDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
base::FilePath* path) {
FileChooserDialog save_dialog(
GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
gtk_widget_show_all(save_dialog.dialog());
int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
if (response == GTK_RESPONSE_ACCEPT) {
*path = save_dialog.GetFileName();
return true;
} else {
return false;
}
}
void ShowSaveDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
const SaveDialogCallback& callback) {
FileChooserDialog* dialog = new FileChooserDialog(
GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
dialog->RunSaveAsynchronous(callback);
}
} // namespace file_dialog
<commit_msg>gtk: Add file open dialog.<commit_after>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/ui/file_dialog.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "browser/native_window.h"
#include "browser/ui/gtk/gtk_util.h"
#include "ui/base/gtk/gtk_signal.h"
namespace file_dialog {
namespace {
class FileChooserDialog {
public:
FileChooserDialog(GtkFileChooserAction action,
atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path) {
const char* confirm_text = GTK_STOCK_OK;
if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
confirm_text = GTK_STOCK_SAVE;
else if (action == GTK_FILE_CHOOSER_ACTION_OPEN)
confirm_text = GTK_STOCK_OPEN;
GtkWindow* window = parent_window ? parent_window->GetNativeWindow() : NULL;
dialog_ = gtk_file_chooser_dialog_new(
title.c_str(),
window,
action,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
confirm_text, GTK_RESPONSE_ACCEPT,
NULL);
if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
TRUE);
if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);
// Set window-to-parent modality by adding the dialog to the same window
// group as the parent.
gtk_window_group_add_window(gtk_window_get_group(window),
GTK_WINDOW(dialog_));
gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
if (!default_path.empty()) {
if (base::DirectoryExists(default_path))
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
default_path.value().c_str());
else
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog_),
default_path.value().c_str());
}
}
virtual ~FileChooserDialog() {
gtk_widget_destroy(dialog_);
}
void RunAsynchronous() {
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), NULL);
g_signal_connect(dialog_, "response",
G_CALLBACK(OnFileDialogResponseThunk), this);
gtk_widget_show_all(dialog_);
}
void RunSaveAsynchronous(const SaveDialogCallback& callback) {
save_callback_ = callback;
RunAsynchronous();
}
void RunOpenAsynchronous(const OpenDialogCallback& callback) {
open_callback_ = callback;
RunAsynchronous();
}
base::FilePath GetFileName() const {
gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
base::FilePath path(filename);
g_free(filename);
return path;
}
std::vector<base::FilePath> GetFileNames() const {
std::vector<base::FilePath> paths;
GSList* filenames = gtk_file_chooser_get_filenames(
GTK_FILE_CHOOSER(dialog_));
for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) {
base::FilePath path(static_cast<char*>(iter->data));
g_free(iter->data);
paths.push_back(path);
}
g_slist_free(filenames);
return paths;
}
CHROMEGTK_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, int);
GtkWidget* dialog() const { return dialog_; }
private:
GtkWidget* dialog_;
SaveDialogCallback save_callback_;
OpenDialogCallback open_callback_;
DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};
void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
gtk_widget_hide_all(dialog_);
if (!save_callback_.is_null()) {
if (response == GTK_RESPONSE_ACCEPT)
save_callback_.Run(true, GetFileName());
else
save_callback_.Run(false, base::FilePath());
} else if (!open_callback_.is_null()) {
if (response == GTK_RESPONSE_ACCEPT)
open_callback_.Run(true, GetFileNames());
else
open_callback_.Run(false, std::vector<base::FilePath>());
}
delete this;
}
} // namespace
bool ShowOpenDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
int properties,
std::vector<base::FilePath>* paths) {
return false;
}
void ShowOpenDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
int properties,
const OpenDialogCallback& callback) {
GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
if (properties & FILE_DIALOG_OPEN_DIRECTORY)
action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
FileChooserDialog* open_dialog = new FileChooserDialog(
action, parent_window, title, default_path);
if (properties & FILE_DIALOG_MULTI_SELECTIONS)
gtk_file_chooser_set_select_multiple(
GTK_FILE_CHOOSER(open_dialog->dialog()), TRUE);
open_dialog->RunOpenAsynchronous(callback);
}
bool ShowSaveDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
base::FilePath* path) {
FileChooserDialog save_dialog(
GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
gtk_widget_show_all(save_dialog.dialog());
int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
if (response == GTK_RESPONSE_ACCEPT) {
*path = save_dialog.GetFileName();
return true;
} else {
return false;
}
}
void ShowSaveDialog(atom::NativeWindow* parent_window,
const std::string& title,
const base::FilePath& default_path,
const SaveDialogCallback& callback) {
FileChooserDialog* save_dialog = new FileChooserDialog(
GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
save_dialog->RunSaveAsynchronous(callback);
}
} // namespace file_dialog
<|endoftext|> |
<commit_before>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity but masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return humidity;
}
void Adafruit_HDC1000::ReadTempHumidity(void) {
// HDC1008 setup to measure both temperature and humidity in one conversion
// this is a different way to access data in ONE read
// this sets internal private variables that can be accessed by Get() functions
uint32_t rt,rh ; // working variables
rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together
rh = rt; // save a copy for humidity processing
float (temp = (rt >> 16)); // convert to temp first
temp /= 65536;
temp *= 165;
temp -= 40;
float (humidity = (rh & 0xFFFF)); // now convert to humidity
humidity /= 65536;
humidity *= 100;
}
float Adafruit_HDC1000::GetTemperature(void) {
// getter function to access private temp variable
return temp ;
}
float Adafruit_HDC1000::GetHumidity(void) {
// getter function to access private humidity variable
return humidity ;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should use d RMB
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<commit_msg>parentheses important in float cast of private var<commit_after>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity but masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return humidity;
}
void Adafruit_HDC1000::ReadTempHumidity(void) {
// HDC1008 setup to measure both temperature and humidity in one conversion
// this is a different way to access data in ONE read
// this sets internal private variables that can be accessed by Get() functions
uint32_t rt,rh ; // working variables
rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together
rh = rt; // save a copy for humidity processing
// important to use ( ) around temp so private variable accessed and float cast done
float (temp = (rt >> 16)); // convert to temp first
temp /= 65536;
temp *= 165;
temp -= 40;
// important to use ( ) around humidity so private variable accessed and float cast done
float (humidity = (rh & 0xFFFF)); // now convert to humidity
humidity /= 65536;
humidity *= 100;
}
float Adafruit_HDC1000::GetTemperature(void) {
// getter function to access private temp variable
return temp ;
}
float Adafruit_HDC1000::GetHumidity(void) {
// getter function to access private humidity variable
return humidity ;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should use d RMB
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <cstdio>
#include <memory>
#include "dxutil.h"
#include "renderer.h"
#include "camera.h"
#include <shellapi.h> // must be after windows.h
#include <ShellScalingApi.h>
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "ninput.lib")
#pragma comment(lib, "shcore.lib")
// Constants
static const int kSwapChainBufferCount = 3;
static const DXGI_FORMAT kSwapChainFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
static const int kUpdateFrequency = 60;
// Globals
HWND ghWnd;
bool gShouldClose;
ComPtr<IDXGISwapChain> gpSwapChain;
ComPtr<ID3D11Device> gpDevice;
ComPtr<ID3D11DeviceContext> gpDeviceContext;
std::unique_ptr<Renderer> gpRenderer;
OrbitCamera gCamera;
UINT64 gPerformanceFrequency;
UINT64 gLastFrameTicks;
UINT64 gAccumulatedFrameTicks;
double gRenderScale;
int gWindowWidth = 1280;
int gWindowHeight = 720;
int gRenderWidth;
int gRenderHeight;
void InitApp()
{
LARGE_INTEGER performanceFrequency, firstFrameTicks;
CHECK_WIN32(QueryPerformanceFrequency(&performanceFrequency));
CHECK_WIN32(QueryPerformanceCounter(&firstFrameTicks));
gPerformanceFrequency = performanceFrequency.QuadPart;
gLastFrameTicks = firstFrameTicks.QuadPart;
gAccumulatedFrameTicks = 0;
gpRenderer = std::make_unique<Renderer>(gpDevice.Get(), gpDeviceContext.Get());
gpRenderer->Init();
#define SIM_ORBIT_RADIUS 50.f
#define SIM_DISC_RADIUS 12.f
auto center = DirectX::XMVectorSet(0.0f, 0.4f*SIM_DISC_RADIUS, 0.0f, 0.0f);
auto radius = 15.0f;
auto minRadius = SIM_ORBIT_RADIUS - 3.25f * SIM_DISC_RADIUS;
auto maxRadius = SIM_ORBIT_RADIUS + 3.0f * SIM_DISC_RADIUS;
auto longAngle = 4.50f;
auto latAngle = 1.45f;
gCamera.View(center, radius, minRadius, maxRadius, longAngle, latAngle);
}
void ResizeApp(int width, int height)
{
CHECK_HR(gpSwapChain->ResizeBuffers(kSwapChainBufferCount, width, height, kSwapChainFormat, 0));
gpRenderer->Resize(width, height);
float aspect = (float)gRenderWidth / gRenderHeight;
gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
}
void UpdateApp()
{
gCamera.ProcessInertia();
LARGE_INTEGER currFrameTicks;
CHECK_WIN32(QueryPerformanceCounter(&currFrameTicks));
UINT64 deltaTicks = currFrameTicks.QuadPart - gLastFrameTicks;
gAccumulatedFrameTicks += deltaTicks;
const UINT64 kMillisecondsPerUpdate = 1000 / kUpdateFrequency;
const UINT64 kTicksPerMillisecond = gPerformanceFrequency / 1000;
const UINT64 kTicksPerUpdate = kMillisecondsPerUpdate * kTicksPerMillisecond;
while (gAccumulatedFrameTicks >= kTicksPerUpdate)
{
gpRenderer->Update(kMillisecondsPerUpdate);
gAccumulatedFrameTicks -= kTicksPerUpdate;
}
gLastFrameTicks = currFrameTicks.QuadPart;
}
void RenderApp()
{
ComPtr<ID3D11Texture2D> pBackBuffer;
CHECK_HR(gpSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)));
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc{};
rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
ComPtr<ID3D11RenderTargetView> pBackBufferRTV;
CHECK_HR(gpDevice->CreateRenderTargetView(pBackBuffer.Get(), &rtvDesc, &pBackBufferRTV));
gpRenderer->RenderFrame(pBackBufferRTV.Get(), gCamera);
}
// Event handler
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
gShouldClose = true;
return 0;
case WM_SIZE: {
UINT ww = LOWORD(lParam);
UINT wh = HIWORD(lParam);
// Ignore resizing to minimized
if (ww == 0 || wh == 0) return 0;
gWindowWidth = (int)ww;
gWindowHeight = (int)wh;
gRenderWidth = (UINT)(double(gWindowWidth) * gRenderScale);
gRenderHeight = (UINT)(double(gWindowHeight) * gRenderScale);
// Update camera projection
float aspect = (float)gRenderWidth / (float)gRenderHeight;
gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
ResizeApp(gRenderWidth, gRenderHeight);
return 0;
}
case WM_MOUSEWHEEL: {
auto delta = GET_WHEEL_DELTA_WPARAM(wParam);
gCamera.ZoomRadius(-0.07f * delta);
return 0;
}
case WM_POINTERDOWN:
case WM_POINTERUPDATE:
case WM_POINTERUP: {
auto pointerId = GET_POINTERID_WPARAM(wParam);
POINTER_INFO pointerInfo;
if (GetPointerInfo(pointerId, &pointerInfo)) {
if (message == WM_POINTERDOWN) {
// Compute pointer position in render units
POINT p = pointerInfo.ptPixelLocation;
ScreenToClient(hWnd, &p);
RECT clientRect;
GetClientRect(hWnd, &clientRect);
p.x = p.x * gRenderWidth / (clientRect.right - clientRect.left);
p.y = p.y * gRenderHeight / (clientRect.bottom - clientRect.top);
gCamera.AddPointer(pointerId);
}
// Otherwise send it to the camera controls
gCamera.ProcessPointerFrames(pointerId, &pointerInfo);
if (message == WM_POINTERUP) gCamera.RemovePointer(pointerId);
}
return 0;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
UINT SetupDPI()
{
// Just do system DPI awareness for now for simplicity... scale the 3D content
SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);
UINT dpiX = 0, dpiY;
POINT pt = { 1, 1 };
auto hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
if (SUCCEEDED(GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY))) {
return dpiX;
}
else {
return 96; // default
}
}
int main()
{
UINT dpi = SetupDPI();
gRenderScale = 96.0 / double(dpi);
// Scale default window size based on dpi
gWindowWidth *= dpi / 96;
gWindowHeight *= dpi / 96;
// Create window
{
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MyWndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
wc.lpszClassName = TEXT("WindowClass");
CHECK_WIN32(RegisterClassEx(&wc));
RECT wr = { 0, 0, gWindowWidth, gWindowHeight };
CHECK_WIN32(AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE));
ghWnd = CHECK_WIN32(CreateWindowEx(
0, TEXT("WindowClass"),
TEXT("Spooky"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
0, 0, GetModuleHandle(NULL), 0));
}
// Create D3D11 device and swap chain
{
ComPtr<IDXGIFactory> pFactory;
CHECK_HR(CreateDXGIFactory(IID_PPV_ARGS(&pFactory)));
UINT deviceFlags = 0;
#ifdef _DEBUG
deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
RECT clientRect;
GetClientRect(ghWnd, &clientRect);
DXGI_SWAP_CHAIN_DESC scd{};
scd.BufferCount = kSwapChainBufferCount;
scd.BufferDesc.Format = kSwapChainFormat;
scd.BufferDesc.Width = clientRect.right - clientRect.left;
scd.BufferDesc.Height = clientRect.bottom - clientRect.top;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = ghWnd;
scd.Windowed = TRUE;
scd.SampleDesc.Count = 1;
scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
CHECK_HR(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, NULL, 0, D3D11_SDK_VERSION, &scd, &gpSwapChain, &gpDevice, NULL, &gpDeviceContext));
}
InitApp();
ShowWindow(ghWnd, SW_SHOWNORMAL);
while (!gShouldClose)
{
// Handle all events
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UpdateApp();
RenderApp();
// Swap buffers
CHECK_HR(gpSwapChain->Present(0, 0));
}
CHECK_HR(gpSwapChain->SetFullscreenState(FALSE, NULL));
}<commit_msg>swapchain nonsense<commit_after>#include <cassert>
#include <cstdio>
#include <memory>
#include "dxutil.h"
#include "renderer.h"
#include "camera.h"
#include <shellapi.h> // must be after windows.h
#include <ShellScalingApi.h>
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "ninput.lib")
#pragma comment(lib, "shcore.lib")
// Constants
static const int kSwapChainBufferCount = 3;
static const DXGI_FORMAT kSwapChainFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
static const int kUpdateFrequency = 60;
// Globals
HWND ghWnd;
bool gShouldClose;
ComPtr<IDXGISwapChain> gpSwapChain;
ComPtr<ID3D11Device> gpDevice;
ComPtr<ID3D11DeviceContext> gpDeviceContext;
std::unique_ptr<Renderer> gpRenderer;
OrbitCamera gCamera;
UINT64 gPerformanceFrequency;
UINT64 gLastFrameTicks;
UINT64 gAccumulatedFrameTicks;
double gRenderScale;
int gWindowWidth = 1280;
int gWindowHeight = 720;
int gRenderWidth;
int gRenderHeight;
void InitApp()
{
LARGE_INTEGER performanceFrequency, firstFrameTicks;
CHECK_WIN32(QueryPerformanceFrequency(&performanceFrequency));
CHECK_WIN32(QueryPerformanceCounter(&firstFrameTicks));
gPerformanceFrequency = performanceFrequency.QuadPart;
gLastFrameTicks = firstFrameTicks.QuadPart;
gAccumulatedFrameTicks = 0;
gpRenderer = std::make_unique<Renderer>(gpDevice.Get(), gpDeviceContext.Get());
gpRenderer->Init();
#define SIM_ORBIT_RADIUS 50.f
#define SIM_DISC_RADIUS 12.f
auto center = DirectX::XMVectorSet(0.0f, 0.4f*SIM_DISC_RADIUS, 0.0f, 0.0f);
auto radius = 15.0f;
auto minRadius = SIM_ORBIT_RADIUS - 3.25f * SIM_DISC_RADIUS;
auto maxRadius = SIM_ORBIT_RADIUS + 3.0f * SIM_DISC_RADIUS;
auto longAngle = 4.50f;
auto latAngle = 1.45f;
gCamera.View(center, radius, minRadius, maxRadius, longAngle, latAngle);
}
void ResizeApp(int width, int height)
{
CHECK_HR(gpSwapChain->ResizeBuffers(kSwapChainBufferCount, width, height, kSwapChainFormat, 0));
gpRenderer->Resize(width, height);
float aspect = (float)gRenderWidth / gRenderHeight;
gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
}
void UpdateApp()
{
gCamera.ProcessInertia();
LARGE_INTEGER currFrameTicks;
CHECK_WIN32(QueryPerformanceCounter(&currFrameTicks));
UINT64 deltaTicks = currFrameTicks.QuadPart - gLastFrameTicks;
gAccumulatedFrameTicks += deltaTicks;
const UINT64 kMillisecondsPerUpdate = 1000 / kUpdateFrequency;
const UINT64 kTicksPerMillisecond = gPerformanceFrequency / 1000;
const UINT64 kTicksPerUpdate = kMillisecondsPerUpdate * kTicksPerMillisecond;
while (gAccumulatedFrameTicks >= kTicksPerUpdate)
{
gpRenderer->Update(kMillisecondsPerUpdate);
gAccumulatedFrameTicks -= kTicksPerUpdate;
}
gLastFrameTicks = currFrameTicks.QuadPart;
}
void RenderApp()
{
ComPtr<ID3D11Texture2D> pBackBuffer;
CHECK_HR(gpSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)));
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc{};
rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
ComPtr<ID3D11RenderTargetView> pBackBufferRTV;
CHECK_HR(gpDevice->CreateRenderTargetView(pBackBuffer.Get(), &rtvDesc, &pBackBufferRTV));
gpRenderer->RenderFrame(pBackBufferRTV.Get(), gCamera);
}
// Event handler
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
gShouldClose = true;
return 0;
case WM_SIZE: {
UINT ww = LOWORD(lParam);
UINT wh = HIWORD(lParam);
// Ignore resizing to minimized
if (ww == 0 || wh == 0) return 0;
gWindowWidth = (int)ww;
gWindowHeight = (int)wh;
gRenderWidth = (UINT)(double(gWindowWidth) * gRenderScale);
gRenderHeight = (UINT)(double(gWindowHeight) * gRenderScale);
// Update camera projection
float aspect = (float)gRenderWidth / (float)gRenderHeight;
gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
ResizeApp(gWindowWidth, gWindowHeight);
return 0;
}
case WM_MOUSEWHEEL: {
auto delta = GET_WHEEL_DELTA_WPARAM(wParam);
gCamera.ZoomRadius(-0.07f * delta);
return 0;
}
case WM_POINTERDOWN:
case WM_POINTERUPDATE:
case WM_POINTERUP: {
auto pointerId = GET_POINTERID_WPARAM(wParam);
POINTER_INFO pointerInfo;
if (GetPointerInfo(pointerId, &pointerInfo)) {
if (message == WM_POINTERDOWN) {
// Compute pointer position in render units
POINT p = pointerInfo.ptPixelLocation;
ScreenToClient(hWnd, &p);
RECT clientRect;
GetClientRect(hWnd, &clientRect);
p.x = p.x * gRenderWidth / (clientRect.right - clientRect.left);
p.y = p.y * gRenderHeight / (clientRect.bottom - clientRect.top);
gCamera.AddPointer(pointerId);
}
// Otherwise send it to the camera controls
gCamera.ProcessPointerFrames(pointerId, &pointerInfo);
if (message == WM_POINTERUP) gCamera.RemovePointer(pointerId);
}
return 0;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
UINT SetupDPI()
{
// Just do system DPI awareness for now for simplicity... scale the 3D content
SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);
UINT dpiX = 0, dpiY;
POINT pt = { 1, 1 };
auto hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
if (SUCCEEDED(GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY))) {
return dpiX;
}
else {
return 96; // default
}
}
int main()
{
UINT dpi = SetupDPI();
gRenderScale = 96.0 / double(dpi);
// Scale default window size based on dpi
gWindowWidth *= dpi / 96;
gWindowHeight *= dpi / 96;
// Create window
{
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MyWndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
wc.lpszClassName = TEXT("WindowClass");
CHECK_WIN32(RegisterClassEx(&wc));
RECT wr = { 0, 0, gWindowWidth, gWindowHeight };
CHECK_WIN32(AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE));
ghWnd = CHECK_WIN32(CreateWindowEx(
0, TEXT("WindowClass"),
TEXT("Spooky"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
0, 0, GetModuleHandle(NULL), 0));
}
// Create D3D11 device and swap chain
{
ComPtr<IDXGIFactory> pFactory;
CHECK_HR(CreateDXGIFactory(IID_PPV_ARGS(&pFactory)));
UINT deviceFlags = 0;
#ifdef _DEBUG
deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
RECT clientRect;
GetClientRect(ghWnd, &clientRect);
DXGI_SWAP_CHAIN_DESC scd{};
scd.BufferCount = kSwapChainBufferCount;
scd.BufferDesc.Format = kSwapChainFormat;
scd.BufferDesc.Width = clientRect.right - clientRect.left;
scd.BufferDesc.Height = clientRect.bottom - clientRect.top;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = ghWnd;
scd.Windowed = TRUE;
scd.SampleDesc.Count = 1;
scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
CHECK_HR(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, NULL, 0, D3D11_SDK_VERSION, &scd, &gpSwapChain, &gpDevice, NULL, &gpDeviceContext));
}
InitApp();
ShowWindow(ghWnd, SW_SHOWNORMAL);
while (!gShouldClose)
{
// Handle all events
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UpdateApp();
RenderApp();
// Swap buffers
CHECK_HR(gpSwapChain->Present(0, 0));
}
CHECK_HR(gpSwapChain->SetFullscreenState(FALSE, NULL));
}<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: Accumulator.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#include <boost/call_traits.hpp>
namespace Nektar
{
template<typename DataType>
class Accumulator
{
public:
explicit Accumulator(typename boost::call_traits<DataType>::reference data) :
m_isInitialized(false),
m_data(data)
{
}
void operator=(typename boost::call_traits<DataType>::const_reference rhs)
{
m_isInitialized = true;
m_data = rhs;
}
bool IsInitialized() const
{
return m_isInitialized;
}
typename boost::call_traits<DataType>::reference GetData() const
{
m_isInitialized = true;
return m_data;
}
typename boost::call_traits<DataType>::reference operator*() const
{
m_isInitialized = true;
return m_data;
}
private:
Accumulator(const Accumulator<DataType>& rhs);
Accumulator<DataType>& operator=(const Accumulator<DataType>& rhs);
mutable bool m_isInitialized;
typename boost::call_traits<DataType>::reference m_data;
};
}
#endif //NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
/**
$Log: Accumulator.hpp,v $
Revision 1.2 2007/01/16 17:37:55 bnelson
Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
Revision 1.1 2007/01/16 05:29:49 bnelson
Major improvements for expression templates.
**/
<commit_msg>Added comments and removed some unused code.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: Accumulator.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#include <boost/call_traits.hpp>
namespace Nektar
{
/// \brief A wrapper for a piece of data to be passed through the expression templates.
template<typename DataType>
class Accumulator
{
public:
explicit Accumulator(typename boost::call_traits<DataType>::reference data) :
m_isInitialized(false),
m_data(data)
{
}
/// \brief Returns true if the accumulator contains valid data, false otherwise.
///
/// When starting an expression evaluation, the accumulator starts out in an uninitialized
/// state and this method will return false. At some point the accumulator will obtain
/// valid values, and after this point this method will return true.
bool IsInitialized() const
{
return m_isInitialized;
}
/// \brief Returns the data held by the accumulator.
///
/// Without a little more infrastructure, it is impossible to determine
/// if the data has been modified after this call is made. Therefore,
/// pessimistically, we will assume that it will be modified so all
/// subsequent calls to IsInitialized will return true.
typename boost::call_traits<DataType>::reference operator*() const
{
m_isInitialized = true;
return m_data;
}
private:
/// By definition an accumulator stores a particular value and updates
/// it as the expression is being evaluated. So a copy constructor and
/// assignment operator don't really make much sense.
Accumulator(const Accumulator<DataType>& rhs);
Accumulator<DataType>& operator=(const Accumulator<DataType>& rhs);
mutable bool m_isInitialized;
typename boost::call_traits<DataType>::reference m_data;
};
}
#endif //NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
/**
$Log: Accumulator.hpp,v $
Revision 1.3 2007/01/30 23:37:15 bnelson
*** empty log message ***
Revision 1.2 2007/01/16 17:37:55 bnelson
Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
Revision 1.1 2007/01/16 05:29:49 bnelson
Major improvements for expression templates.
**/
<|endoftext|> |
<commit_before>#include "CommandsConfigReader.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "Command.h"
#include "CommandMetadata.h"
#include "XPLMDataAccess.h"
using namespace xcopilot;
namespace pt = boost::property_tree;
static std::map<std::string, CommandType> commandTypeProvider = {
{ "int", CommandType::INT },
{ "float", CommandType::FLOAT },
{ "double", CommandType::DOUBLE },
{ "boolean", CommandType::BOOLEAN }
};
std::vector<XPLMDataRef> readDataRefs(const pt::ptree& node, XPlaneDataRefSDK* xPlaneSDK) {
// TODO: make this iteration only once
std::vector<std::string> dataRefs;
std::transform(std::begin(node), std::end(node), std::back_inserter(dataRefs),
[](const pt::ptree::value_type& value) { return value.second.get<std::string>(""); });
std::vector<XPLMDataRef> dataRefsIds;
std::transform(dataRefs.begin(), dataRefs.end(), std::back_inserter(dataRefsIds),
[xPlaneSDK](const std::string &dataRef) { return xPlaneSDK->findDataRef(dataRef); });
return dataRefsIds;
}
std::vector<std::shared_ptr<Command>> CommandsConfigReader::getCommandsForAircraft(const std::string configFilePath) {
pt::ptree root;
pt::read_json(configFilePath, root);
std::vector<std::shared_ptr<Command>> commands;
for (auto& node : root) {
auto name = node.first;
auto type = node.second.get<std::string>("type");
auto regex = node.second.get<std::string>("regex");
auto dataRefs = readDataRefs(node.second.get_child("dataRefs"), xPlaneSDK);
CommandMetadata commandMetadata(name, commandTypeProvider[type], regex, dataRefs);
commands.push_back(std::make_shared<Command>(commandMetadata));
std::cout << "Command: " << name << " - Regex: " << regex << std::endl;
}
return commands;
}
<commit_msg>implement TODO (remove double iteration over datarefs list)<commit_after>#include "CommandsConfigReader.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "Command.h"
#include "CommandMetadata.h"
#include "XPLMDataAccess.h"
using namespace xcopilot;
namespace pt = boost::property_tree;
static std::map<std::string, CommandType> commandTypeProvider = {
{ "int", CommandType::INT },
{ "float", CommandType::FLOAT },
{ "double", CommandType::DOUBLE },
{ "boolean", CommandType::BOOLEAN }
};
std::vector<XPLMDataRef> readDataRefs(const pt::ptree& node, XPlaneDataRefSDK* xPlaneSDK) {
std::vector<XPLMDataRef> dataRefsIds;
std::transform(std::begin(node), std::end(node), std::back_inserter(dataRefsIds),
[xPlaneSDK](const pt::ptree::value_type& value) {
auto dataRef = value.second.get<std::string>("");
return xPlaneSDK->findDataRef(dataRef);
});
return dataRefsIds;
}
std::vector<std::shared_ptr<Command>> CommandsConfigReader::getCommandsForAircraft(const std::string configFilePath) {
pt::ptree root;
pt::read_json(configFilePath, root);
std::vector<std::shared_ptr<Command>> commands;
for (auto& node : root) {
auto name = node.first;
auto type = node.second.get<std::string>("type");
auto regex = node.second.get<std::string>("regex");
auto dataRefs = readDataRefs(node.second.get_child("dataRefs"), xPlaneSDK);
CommandMetadata commandMetadata(name, commandTypeProvider[type], regex, dataRefs);
commands.push_back(std::make_shared<Command>(commandMetadata));
std::cout << "Command: " << name << " - Regex: " << regex << std::endl;
}
return commands;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTMLImageElementImp.h"
#include <boost/bind.hpp>
#include "DocumentImp.h"
#include "css/Box.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLImageElementImp::HTMLImageElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"img")
{
}
HTMLImageElementImp::HTMLImageElementImp(HTMLImageElementImp* org, bool deep) :
ObjectMixin(org, deep)
{
}
void HTMLImageElementImp::eval()
{
HTMLElementImp::eval();
HTMLElementImp::evalBorder(this);
HTMLElementImp::evalHeight(this);
HTMLElementImp::evalWidth(this);
HTMLElementImp::evalHspace(this);
HTMLElementImp::evalVspace(this);
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", getSrc());
request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
document->incrementLoadEventDelayCount();
request->send();
} else
active = false;
}
void HTMLImageElementImp::notify()
{
if (request->getStatus() != 200)
active = false;
else {
// TODO: Check type
image = new(std::nothrow) BoxImage();
if (!image)
active = false;
else {
if (FILE* file = request->openFile()) {
image->open(file);
fclose(file);
}
if (image->getState() != BoxImage::CompletelyAvailable) {
active = false;
delete image;
image = 0;
}
}
}
if (Box* box = getBox())
box->setFlags(1);
DocumentImp* document = getOwnerDocumentImp();
document->decrementLoadEventDelayCount();
}
// Node
Node HTMLImageElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLImageElementImp(this, deep);
}
// HTMLImageElement
std::u16string HTMLImageElementImp::getAlt()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setAlt(std::u16string alt)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getSrc()
{
return getAttribute(u"src");
}
void HTMLImageElementImp::setSrc(std::u16string src)
{
setAttribute(u"src", src);
}
std::u16string HTMLImageElementImp::getCrossOrigin()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setCrossOrigin(std::u16string crossOrigin)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getUseMap()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setUseMap(std::u16string useMap)
{
// TODO: implement me!
}
bool HTMLImageElementImp::getIsMap()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setIsMap(bool isMap)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getWidth()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setWidth(unsigned int width)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getHeight()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setHeight(unsigned int height)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getNaturalWidth()
{
// TODO: implement me!
return 0;
}
unsigned int HTMLImageElementImp::getNaturalHeight()
{
// TODO: implement me!
return 0;
}
bool HTMLImageElementImp::getComplete()
{
// TODO: implement me!
return 0;
}
std::u16string HTMLImageElementImp::getName()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setName(std::u16string name)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getAlign()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setAlign(std::u16string align)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getBorder()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setBorder(std::u16string border)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getHspace()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setHspace(unsigned int hspace)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getLongDesc()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setLongDesc(std::u16string longDesc)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getVspace()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setVspace(unsigned int vspace)
{
// TODO: implement me!
}
} // org::w3c::dom::bootstrap
namespace html {
namespace {
class Constructor : public Object
{
public:
// Object
virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv) {
bootstrap::HTMLImageElementImp* img = 0;
switch (argc) {
case 0:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
break;
case 1:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
if (img)
img->setWidth(argv[0]);
break;
case 2:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
if (img) {
img->setWidth(argv[0]);
img->setHeight(argv[1]);
}
break;
default:
break;
}
return img;
}
Constructor() :
Object(this) {
}
};
} // namespace
Object HTMLImageElement::getConstructor()
{
static Constructor constructor;
return constructor.self();
}
}
}}} // org::w3c::dom
<commit_msg>(HTMLImageElementImp::setSrc, HTMLImageElementImp::notify) : Get the specified image.<commit_after>/*
* Copyright 2010-2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTMLImageElementImp.h"
#include <boost/bind.hpp>
#include "DocumentImp.h"
#include "css/Box.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLImageElementImp::HTMLImageElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"img")
{
}
HTMLImageElementImp::HTMLImageElementImp(HTMLImageElementImp* org, bool deep) :
ObjectMixin(org, deep)
{
}
void HTMLImageElementImp::eval()
{
HTMLElementImp::eval();
HTMLElementImp::evalBorder(this);
HTMLElementImp::evalHeight(this);
HTMLElementImp::evalWidth(this);
HTMLElementImp::evalHspace(this);
HTMLElementImp::evalVspace(this);
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", getSrc());
request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
document->incrementLoadEventDelayCount();
request->send();
} else
active = false;
}
void HTMLImageElementImp::notify()
{
if (request->getStatus() != 200)
active = false;
else {
// TODO: Check type
delete image;
image = new(std::nothrow) BoxImage();
if (!image)
active = false;
else {
if (FILE* file = request->openFile()) {
image->open(file);
fclose(file);
}
if (image->getState() != BoxImage::CompletelyAvailable) {
active = false;
delete image;
image = 0;
}
}
}
if (Box* box = getBox())
box->setFlags(1);
DocumentImp* document = getOwnerDocumentImp();
document->decrementLoadEventDelayCount();
}
// Node
Node HTMLImageElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLImageElementImp(this, deep);
}
// HTMLImageElement
std::u16string HTMLImageElementImp::getAlt()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setAlt(std::u16string alt)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getSrc()
{
return getAttribute(u"src");
}
void HTMLImageElementImp::setSrc(std::u16string src)
{
setAttribute(u"src", src);
DocumentImp* document = getOwnerDocumentImp();
if (request)
request->abort();
else
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", getSrc());
request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
std::u16string HTMLImageElementImp::getCrossOrigin()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setCrossOrigin(std::u16string crossOrigin)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getUseMap()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setUseMap(std::u16string useMap)
{
// TODO: implement me!
}
bool HTMLImageElementImp::getIsMap()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setIsMap(bool isMap)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getWidth()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setWidth(unsigned int width)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getHeight()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setHeight(unsigned int height)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getNaturalWidth()
{
// TODO: implement me!
return 0;
}
unsigned int HTMLImageElementImp::getNaturalHeight()
{
// TODO: implement me!
return 0;
}
bool HTMLImageElementImp::getComplete()
{
// TODO: implement me!
return 0;
}
std::u16string HTMLImageElementImp::getName()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setName(std::u16string name)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getAlign()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setAlign(std::u16string align)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getBorder()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setBorder(std::u16string border)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getHspace()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setHspace(unsigned int hspace)
{
// TODO: implement me!
}
std::u16string HTMLImageElementImp::getLongDesc()
{
// TODO: implement me!
return u"";
}
void HTMLImageElementImp::setLongDesc(std::u16string longDesc)
{
// TODO: implement me!
}
unsigned int HTMLImageElementImp::getVspace()
{
// TODO: implement me!
return 0;
}
void HTMLImageElementImp::setVspace(unsigned int vspace)
{
// TODO: implement me!
}
} // org::w3c::dom::bootstrap
namespace html {
namespace {
class Constructor : public Object
{
public:
// Object
virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv) {
bootstrap::HTMLImageElementImp* img = 0;
switch (argc) {
case 0:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
break;
case 1:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
if (img)
img->setWidth(argv[0]);
break;
case 2:
img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
if (img) {
img->setWidth(argv[0]);
img->setHeight(argv[1]);
}
break;
default:
break;
}
return img;
}
Constructor() :
Object(this) {
}
};
} // namespace
Object HTMLImageElement::getConstructor()
{
static Constructor constructor;
return constructor.self();
}
}
}}} // org::w3c::dom
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: txtstyle.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: mtg $ $Date: 2001-03-22 15:30:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
//#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHSTYLECATEGORY_HPP_
#include <com/sun/star/style/ParagraphStyleCategory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
//#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLSMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX
#include "families.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
//#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_TXTPARAE_HXX
#include "txtparae.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONEXPORT_HXX
#include "XMLSectionExport.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGEXPORT_HXX_
#include "XMLLineNumberingExport.hxx"
#endif
#ifndef _XMLOFF_STYLEEXP_HXX
//#include "styleexp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
void XMLTextParagraphExport::exportStyleAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::style::XStyle > & rStyle )
{
Any aAny;
Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( xPropSetInfo->hasPropertyByName( sCategory ) )
{
aAny = xPropSet->getPropertyValue( sCategory );
sal_Int16 nCategory;
aAny >>= nCategory;
const sal_Char *pValue = 0;
if( -1 != nCategory )
{
switch( nCategory )
{
case ParagraphStyleCategory::TEXT:
pValue = sXML_text;
break;
case ParagraphStyleCategory::CHAPTER:
pValue = sXML_chapter;
break;
case ParagraphStyleCategory::LIST:
pValue = sXML_list;
break;
case ParagraphStyleCategory::INDEX:
pValue = sXML_index;
break;
case ParagraphStyleCategory::EXTRA:
pValue = sXML_extra;
break;
case ParagraphStyleCategory::HTML:
pValue = sXML_html;
break;
}
}
if( pValue )
GetExport().AddAttributeASCII( XML_NAMESPACE_STYLE, sXML_class,
pValue );
}
if( xPropSetInfo->hasPropertyByName( sPageDescName ) )
{
Reference< XPropertyState > xPropState( xPropSet, uno::UNO_QUERY );
if( PropertyState_DIRECT_VALUE ==
xPropState->getPropertyState( sPageDescName ) )
{
aAny = xPropSet->getPropertyValue( sPageDescName );
OUString sName;
aAny >>= sName;
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
sXML_master_page_name,
sName );
}
}
}
void XMLTextParagraphExport::exportNumStyles( sal_Bool bUsed )
{
SvxXMLNumRuleExport aNumRuleExport( GetExport() );
aNumRuleExport.exportStyles( bUsed, pListAutoPool, !IsBlockMode() );
}
void XMLTextParagraphExport::exportTextStyles( sal_Bool bUsed )
{
Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
if (xFactory.is())
{
Reference < XInterface > xInt = xFactory->createInstance (
OUString( RTL_CONSTASCII_USTRINGPARAM (
"com.sun.star.text.Defaults") ) );
if ( xInt.is() )
{
Reference < XPropertySet > xPropSet (xInt, UNO_QUERY);
if (xPropSet.is())
exportDefaultStyle( xPropSet, sXML_text, GetParaPropMapper());
}
}
exportStyleFamily( "ParagraphStyles", sXML_paragraph, GetParaPropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_PARAGRAPH, 0);
exportStyleFamily( "CharacterStyles", sXML_text, GetTextPropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_TEXT );
// get shape export to make sure the the frame family is added correctly.
GetExport().GetShapeExport();
exportStyleFamily( "FrameStyles", XML_STYLE_FAMILY_SD_GRAPHICS_NAME, GetFramePropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_FRAME, 0);
exportNumStyles( bUsed );
if( !IsBlockMode() )
{
exportTextFootnoteConfiguration();
XMLSectionExport::ExportBibliographyConfiguration(GetExport());
XMLLineNumberingExport aLineNumberingExport(GetExport());
aLineNumberingExport.Export();
}
}
<commit_msg>export default style as family: paragraph and not text<commit_after>/*************************************************************************
*
* $RCSfile: txtstyle.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: mtg $ $Date: 2001-03-22 21:02:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
//#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHSTYLECATEGORY_HPP_
#include <com/sun/star/style/ParagraphStyleCategory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
//#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLSMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX
#include "families.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
//#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_TXTPARAE_HXX
#include "txtparae.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONEXPORT_HXX
#include "XMLSectionExport.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGEXPORT_HXX_
#include "XMLLineNumberingExport.hxx"
#endif
#ifndef _XMLOFF_STYLEEXP_HXX
//#include "styleexp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
void XMLTextParagraphExport::exportStyleAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::style::XStyle > & rStyle )
{
Any aAny;
Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( xPropSetInfo->hasPropertyByName( sCategory ) )
{
aAny = xPropSet->getPropertyValue( sCategory );
sal_Int16 nCategory;
aAny >>= nCategory;
const sal_Char *pValue = 0;
if( -1 != nCategory )
{
switch( nCategory )
{
case ParagraphStyleCategory::TEXT:
pValue = sXML_text;
break;
case ParagraphStyleCategory::CHAPTER:
pValue = sXML_chapter;
break;
case ParagraphStyleCategory::LIST:
pValue = sXML_list;
break;
case ParagraphStyleCategory::INDEX:
pValue = sXML_index;
break;
case ParagraphStyleCategory::EXTRA:
pValue = sXML_extra;
break;
case ParagraphStyleCategory::HTML:
pValue = sXML_html;
break;
}
}
if( pValue )
GetExport().AddAttributeASCII( XML_NAMESPACE_STYLE, sXML_class,
pValue );
}
if( xPropSetInfo->hasPropertyByName( sPageDescName ) )
{
Reference< XPropertyState > xPropState( xPropSet, uno::UNO_QUERY );
if( PropertyState_DIRECT_VALUE ==
xPropState->getPropertyState( sPageDescName ) )
{
aAny = xPropSet->getPropertyValue( sPageDescName );
OUString sName;
aAny >>= sName;
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
sXML_master_page_name,
sName );
}
}
}
void XMLTextParagraphExport::exportNumStyles( sal_Bool bUsed )
{
SvxXMLNumRuleExport aNumRuleExport( GetExport() );
aNumRuleExport.exportStyles( bUsed, pListAutoPool, !IsBlockMode() );
}
void XMLTextParagraphExport::exportTextStyles( sal_Bool bUsed )
{
Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
if (xFactory.is())
{
Reference < XInterface > xInt = xFactory->createInstance (
OUString( RTL_CONSTASCII_USTRINGPARAM (
"com.sun.star.text.Defaults") ) );
if ( xInt.is() )
{
Reference < XPropertySet > xPropSet (xInt, UNO_QUERY);
if (xPropSet.is())
exportDefaultStyle( xPropSet, sXML_paragraph, GetParaPropMapper());
}
}
exportStyleFamily( "ParagraphStyles", sXML_paragraph, GetParaPropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_PARAGRAPH, 0);
exportStyleFamily( "CharacterStyles", sXML_text, GetTextPropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_TEXT );
// get shape export to make sure the the frame family is added correctly.
GetExport().GetShapeExport();
exportStyleFamily( "FrameStyles", XML_STYLE_FAMILY_SD_GRAPHICS_NAME, GetFramePropMapper(),
bUsed, XML_STYLE_FAMILY_TEXT_FRAME, 0);
exportNumStyles( bUsed );
if( !IsBlockMode() )
{
exportTextFootnoteConfiguration();
XMLSectionExport::ExportBibliographyConfiguration(GetExport());
XMLLineNumberingExport aLineNumberingExport(GetExport());
aLineNumberingExport.Export();
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#include <OptionList.h>
#include <SQLiteDatabase.h>
#include <NaiveSimilarityStrategy.h>
#include <Generator.h>
#include <TextOutput.h>
#define PARAMS 1
using namespace SoundCity;
using std::cout;
using std::endl;
using std::cin;
using std::string;
void
usage (char *s)
{
fprintf(stderr, "Usage: %s <database>\n", s);
fprintf(stderr, "Options :\n");
fprintf(stderr, "-h : Affiche l'aide.\n");
fprintf(stderr, "-y <startYear[1-3000]> <endYear[1-3000]> : Définit un intervalle d'années de morceaux.\n");
fprintf(stderr, "-e <energy[0.0-1.0]> : Impose une valeur d'énergie dans la playlist générée.\n");
fprintf(stderr, "-p <popularity[0.0-1.0]> : Impose une valeur de popularité dans la playlist générée.\n");
fprintf(stderr, "-r <rhythm[0.0-1.0]> : Impose un rythme dans la playlist générée.\n");
fprintf(stderr, "-m <mood[0.0-1.0]> : Impose une humeur dans la playlist générée (plus la valeur est grande plus le morceau est joyeux).\n");
fprintf(stderr, "-s <size[1-100]> : Choix de la taille de la playlist générée (10 par défaut).\n");
fprintf(stderr, "-o <fileName> : Choix du nom du fichier de sortie.\n");
exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
if (argc < PARAMS+1)
usage(argv[0]);
cout << "Création de la liste d'options." << endl;
int size = 10;
float energy = 0;
float mood = 0;
float rhythm = 0;
float popularity = 0;
int startYear = 1;
int endYear = 3000;
string fileName = "playlist.txt";
//Lecture des paramètres
for(int i = PARAMS; i < argc; ++i)
{
if(strcmp(argv[i],"-h") == 0) usage(argv[0]);
else if(strcmp(argv[i],"-e") == 0) energy = atof(argv[++i]);
else if(strcmp(argv[i],"-s") == 0) size = atoi(argv[++i]);
else if(strcmp(argv[i],"-m") == 0) mood = atof(argv[++i]);
else if(strcmp(argv[i],"-p") == 0) popularity = atof(argv[++i]);
else if(strcmp(argv[i],"-r") == 0) rhythm = atof(argv[++i]);
else if(strcmp(argv[i],"-o") == 0) fileName = argv[++i];
else if(strcmp(argv[i],"-y") == 0)
{
startYear = atoi(argv[++i]);
endYear = atoi(argv[++i]);
}
}
//Création de la liste d'options
OptionList options("",startYear,endYear,popularity,energy,rhythm,mood,size);
cout << "Initialisation du générateur." << endl;
NaiveSimilarityStrategy similarity;
SQLiteDatabase database(argv[1]);
Generator generator(database, similarity);
if(generator.initialization() == 0)
{
cout << "Erreur d'initialisation." << endl;
exit(EXIT_FAILURE);
}
cout << "Lancement de la génération" << endl;
Playlist playlist = generator.generate(options);
cout << "Génération terminée" << endl;
if(!playlist.isValid())
{
cout << "La génération n'a pas été satisfaisante, voulez-vous relancer une génération ? (O/N) : ";
char answer;
cin >> answer;
if(answer == 'o' || answer == 'O')
{
cout << "Lancement de la re-génération" << endl;
generator.regenerate(options, playlist);
cout << "Re-génération terminée" << endl;
}
}
TextOutput output;
output.format(fileName,playlist);
cout << "Taille de la playlist générée : " << playlist.size() << endl;
return EXIT_SUCCESS;
}
<commit_msg>Utilisation de la strétégie de similarité non naïve<commit_after>#include <iostream>
#include <string.h>
#include <OptionList.h>
#include <SQLiteDatabase.h>
#include <SimilarityStrategy.h>
#include <Generator.h>
#include <TextOutput.h>
#define PARAMS 1
using namespace SoundCity;
using std::cout;
using std::endl;
using std::cin;
using std::string;
void
usage (char *s)
{
fprintf(stderr, "Usage: %s <database>\n", s);
fprintf(stderr, "Options :\n");
fprintf(stderr, "-h : Affiche l'aide.\n");
fprintf(stderr, "-y <startYear[1-3000]> <endYear[1-3000]> : Définit un intervalle d'années de morceaux.\n");
fprintf(stderr, "-e <energy[0.0-1.0]> : Impose une valeur d'énergie dans la playlist générée.\n");
fprintf(stderr, "-p <popularity[0.0-1.0]> : Impose une valeur de popularité dans la playlist générée.\n");
fprintf(stderr, "-r <rhythm[0.0-1.0]> : Impose un rythme dans la playlist générée.\n");
fprintf(stderr, "-m <mood[0.0-1.0]> : Impose une humeur dans la playlist générée (plus la valeur est grande plus le morceau est joyeux).\n");
fprintf(stderr, "-s <size[1-100]> : Choix de la taille de la playlist générée (10 par défaut).\n");
fprintf(stderr, "-o <fileName> : Choix du nom du fichier de sortie.\n");
exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
if (argc < PARAMS+1)
usage(argv[0]);
cout << "Création de la liste d'options." << endl;
int size = 10;
float energy = 0;
float mood = 0;
float rhythm = 0;
float popularity = 0;
int startYear = 1;
int endYear = 3000;
string fileName = "playlist.txt";
//Lecture des paramètres
for(int i = PARAMS; i < argc; ++i)
{
if(strcmp(argv[i],"-h") == 0) usage(argv[0]);
else if(strcmp(argv[i],"-e") == 0) energy = atof(argv[++i]);
else if(strcmp(argv[i],"-s") == 0) size = atoi(argv[++i]);
else if(strcmp(argv[i],"-m") == 0) mood = atof(argv[++i]);
else if(strcmp(argv[i],"-p") == 0) popularity = atof(argv[++i]);
else if(strcmp(argv[i],"-r") == 0) rhythm = atof(argv[++i]);
else if(strcmp(argv[i],"-o") == 0) fileName = argv[++i];
else if(strcmp(argv[i],"-y") == 0)
{
startYear = atoi(argv[++i]);
endYear = atoi(argv[++i]);
}
}
//Création de la liste d'options
OptionList options("",startYear,endYear,popularity,energy,rhythm,mood,size);
cout << "Initialisation du générateur." << endl;
SimilarityStrategy similarity;
SQLiteDatabase database(argv[1]);
Generator generator(database, similarity);
if(generator.initialization() == 0)
{
cout << "Erreur d'initialisation." << endl;
exit(EXIT_FAILURE);
}
cout << "Lancement de la génération" << endl;
Playlist playlist = generator.generate(options);
cout << "Génération terminée" << endl;
if(!playlist.isValid())
{
cout << "La génération n'a pas été satisfaisante, voulez-vous relancer une génération ? (O/N) : ";
char answer;
cin >> answer;
if(answer == 'o' || answer == 'O')
{
cout << "Lancement de la re-génération" << endl;
generator.regenerate(options, playlist);
cout << "Re-génération terminée" << endl;
}
}
TextOutput output;
output.format(fileName,playlist);
cout << "Taille de la playlist générée : " << playlist.size() << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>Add include guard to PPG node's header file.<commit_after>#ifndef __PATTERN_POSTURE_GENERATOR_NODE_H_INCLUDE__
#define __PATTERN_POSTURE_GENERATOR_NODE_H_INCLUDE__
#endif
<|endoftext|> |
<commit_before>#include "Buffer.h"
#include "Debug.h"
#include "Error.h"
#include "JITCompiledModule.h"
namespace Halide {
namespace Internal {
namespace {
template<typename UnsignedType>
bool checked_multiply(const UnsignedType &a, const UnsignedType &c, UnsignedType &result) {
if (a == 0) {
result = 0;
} else {
UnsignedType t = a * c;
if (t / a != c)
return false;
result = t;
}
return true;
}
template<typename UnsignedType>
bool checked_multiply_assert(const UnsignedType &a, const UnsignedType &b, UnsignedType &result) {
bool no_overflow = checked_multiply(a, b, result);
internal_assert(no_overflow) << "Overflow in checked multiply\n";
return no_overflow;
}
}
struct BufferContents {
/** The buffer_t object we're wrapping. */
buffer_t buf;
/** The type of the allocation. buffer_t's don't currently track this so we do it here. */
Type type;
/** If we made the allocation ourselves via a Buffer constructor,
* and hence should delete it when this buffer dies, then this
* pointer is set to the memory we need to free. Otherwise it's
* NULL. */
uint8_t *allocation;
/** How many Buffer objects point to this BufferContents */
mutable RefCount ref_count;
/** What is the name of the buffer? Useful for debugging symbols. */
std::string name;
/** If this buffer was generated by a jit-compiled module, we need
* to hang onto the module, as it may contain internal state that
* tells us how to use this buffer. In particular, if the buffer
* was generated on the gpu and hasn't been copied back yet, only
* the module knows how to do that, so we'd better keep the module
* alive. */
JITCompiledModule source_module;
BufferContents(Type t, int x_size, int y_size, int z_size, int w_size,
uint8_t* data, const std::string &n) :
type(t), allocation(NULL), name(n.empty() ? unique_name('b') : n) {
user_assert(t.width == 1) << "Can't create of a buffer of a vector type";
buf.elem_size = t.bytes();
size_t size = 1;
if (x_size)
checked_multiply_assert<size_t>(size, x_size, size);
if (y_size)
checked_multiply_assert<size_t>(size, y_size, size);
if (z_size)
checked_multiply_assert<size_t>(size, z_size, size);
if (w_size)
checked_multiply_assert<size_t>(size, w_size, size);
if (!data) {
checked_multiply_assert<size_t>(size, buf.elem_size, size);
user_assert(size < ((1UL << 31) - 1)) << "Total size of buffer " << name << " exceeds 2^31 - 1\n";
size = size + 32;
allocation = (uint8_t *)calloc(1, size);
user_assert(allocation) << "Out of memory allocating buffer " << name << " of size " << size << "\n";
buf.host = allocation;
while ((size_t)(buf.host) & 0x1f) buf.host++;
} else {
buf.host = data;
}
buf.dev = 0;
buf.host_dirty = false;
buf.dev_dirty = false;
buf.extent[0] = x_size;
buf.extent[1] = y_size;
buf.extent[2] = z_size;
buf.extent[3] = w_size;
buf.stride[0] = 1;
buf.stride[1] = x_size;
buf.stride[2] = x_size*y_size;
buf.stride[3] = x_size*y_size*z_size;
buf.min[0] = 0;
buf.min[1] = 0;
buf.min[2] = 0;
buf.min[3] = 0;
}
BufferContents(Type t, const buffer_t *b, const std::string &n) :
type(t), allocation(NULL), name(n.empty() ? unique_name('b') : n) {
buf = *b;
user_assert(t.width == 1) << "Can't create of a buffer of a vector type";
}
};
template<>
RefCount &ref_count<BufferContents>(const BufferContents *p) {
return p->ref_count;
}
template<>
void destroy<BufferContents>(const BufferContents *p) {
// Free any device-side allocation
if (p->source_module.free_dev_buffer) {
p->source_module.free_dev_buffer(NULL, const_cast<buffer_t *>(&p->buf));
}
free(p->allocation);
delete p;
}
}
namespace {
int32_t size_or_zero(const std::vector<int32_t> &sizes, size_t index) {
return (index < sizes.size()) ? sizes[index] : 0;
}
std::string make_buffer_name(const std::string &n, Buffer *b) {
if (n.empty()) {
return Internal::make_entity_name(b, "Halide::Buffer", 'b');
} else {
return n;
}
}
}
Buffer::Buffer(Type t, int x_size, int y_size, int z_size, int w_size,
uint8_t* data, const std::string &name) :
contents(new Internal::BufferContents(t, x_size, y_size, z_size, w_size, data,
make_buffer_name(name, this))) {
}
Buffer::Buffer(Type t, const std::vector<int32_t> &sizes,
uint8_t* data, const std::string &name) :
contents(new Internal::BufferContents(t,
size_or_zero(sizes, 0),
size_or_zero(sizes, 1),
size_or_zero(sizes, 2),
size_or_zero(sizes, 3),
data,
make_buffer_name(name, this))) {
user_assert(sizes.size() <= 4) << "Buffer dimensions greater than 4 are not supported.";
}
Buffer::Buffer(Type t, const buffer_t *buf, const std::string &name) :
contents(new Internal::BufferContents(t, buf,
make_buffer_name(name, this))) {
}
void *Buffer::host_ptr() const {
user_assert(defined()) << "Buffer is undefined\n";
return (void *)contents.ptr->buf.host;
}
buffer_t *Buffer::raw_buffer() const {
user_assert(defined()) << "Buffer is undefined\n";
return &(contents.ptr->buf);
}
uint64_t Buffer::device_handle() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.dev;
}
bool Buffer::host_dirty() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.host_dirty;
}
void Buffer::set_host_dirty(bool dirty) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.host_dirty = dirty;
}
bool Buffer::device_dirty() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.dev_dirty;
}
void Buffer::set_device_dirty(bool dirty) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.host_dirty = dirty;
}
int Buffer::dimensions() const {
for (int i = 0; i < 4; i++) {
if (extent(i) == 0) return i;
}
return 4;
}
int Buffer::extent(int dim) const {
user_assert(defined()) << "Buffer is undefined\n";
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.extent[dim];
}
int Buffer::stride(int dim) const {
user_assert(defined());
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.stride[dim];
}
int Buffer::min(int dim) const {
user_assert(defined()) << "Buffer is undefined\n";
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.min[dim];
}
void Buffer::set_min(int m0, int m1, int m2, int m3) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.min[0] = m0;
contents.ptr->buf.min[1] = m1;
contents.ptr->buf.min[2] = m2;
contents.ptr->buf.min[3] = m3;
}
Type Buffer::type() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->type;
}
bool Buffer::same_as(const Buffer &other) const {
return contents.same_as(other.contents);
}
bool Buffer::defined() const {
return contents.defined();
}
const std::string &Buffer::name() const {
return contents.ptr->name;
}
Buffer::operator Argument() const {
return Argument(name(), true, type());
}
void Buffer::set_source_module(const Internal::JITCompiledModule &module) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->source_module = module;
}
const Internal::JITCompiledModule &Buffer::source_module() {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->source_module;
}
void Buffer::copy_to_host() {
void (*copy_to_host)(void *, buffer_t *) =
contents.ptr->source_module.copy_to_host;
if (copy_to_host) {
/* The user context is always NULL when jitting, so it's safe to
* pass NULL here. */
copy_to_host(NULL, raw_buffer());
}
}
void Buffer::copy_to_dev() {
void (*copy_to_dev)(void *, buffer_t *) =
contents.ptr->source_module.copy_to_dev;
if (copy_to_dev) {
copy_to_dev(NULL, raw_buffer());
}
}
void Buffer::free_dev_buffer() {
void (*free_dev_buffer)(void *, buffer_t *) =
contents.ptr->source_module.free_dev_buffer;
if (free_dev_buffer) {
free_dev_buffer(NULL, raw_buffer());
}
}
}
<commit_msg>moved error for too large buffers<commit_after>#include "Buffer.h"
#include "Debug.h"
#include "Error.h"
#include "JITCompiledModule.h"
namespace Halide {
namespace Internal {
namespace {
void check_buffer_size(uint64_t bytes, const std::string &name) {
user_assert(bytes < (1UL << 31)) << "Total size of buffer " << name << " exceeds 2^31 - 1\n";
}
}
struct BufferContents {
/** The buffer_t object we're wrapping. */
buffer_t buf;
/** The type of the allocation. buffer_t's don't currently track this so we do it here. */
Type type;
/** If we made the allocation ourselves via a Buffer constructor,
* and hence should delete it when this buffer dies, then this
* pointer is set to the memory we need to free. Otherwise it's
* NULL. */
uint8_t *allocation;
/** How many Buffer objects point to this BufferContents */
mutable RefCount ref_count;
/** What is the name of the buffer? Useful for debugging symbols. */
std::string name;
/** If this buffer was generated by a jit-compiled module, we need
* to hang onto the module, as it may contain internal state that
* tells us how to use this buffer. In particular, if the buffer
* was generated on the gpu and hasn't been copied back yet, only
* the module knows how to do that, so we'd better keep the module
* alive. */
JITCompiledModule source_module;
BufferContents(Type t, int x_size, int y_size, int z_size, int w_size,
uint8_t* data, const std::string &n) :
type(t), allocation(NULL), name(n.empty() ? unique_name('b') : n) {
user_assert(t.width == 1) << "Can't create of a buffer of a vector type";
buf.elem_size = t.bytes();
uint64_t size = 1;
if (x_size) {
size *= x_size;
check_buffer_size(size, name);
}
if (y_size) {
size *= y_size;
check_buffer_size(size, name);
}
if (z_size) {
size *= z_size;
check_buffer_size(size, name);
}
if (w_size) {
size *= w_size;
check_buffer_size(size, name);
}
size *= buf.elem_size;
check_buffer_size(size, name);
if (!data) {
size = size + 32;
check_buffer_size(size, name);
allocation = (uint8_t *)calloc(1, (size_t)size);
user_assert(allocation) << "Out of memory allocating buffer " << name << " of size " << size << "\n";
buf.host = allocation;
while ((size_t)(buf.host) & 0x1f) buf.host++;
} else {
buf.host = data;
}
buf.dev = 0;
buf.host_dirty = false;
buf.dev_dirty = false;
buf.extent[0] = x_size;
buf.extent[1] = y_size;
buf.extent[2] = z_size;
buf.extent[3] = w_size;
buf.stride[0] = 1;
buf.stride[1] = x_size;
buf.stride[2] = x_size*y_size;
buf.stride[3] = x_size*y_size*z_size;
buf.min[0] = 0;
buf.min[1] = 0;
buf.min[2] = 0;
buf.min[3] = 0;
}
BufferContents(Type t, const buffer_t *b, const std::string &n) :
type(t), allocation(NULL), name(n.empty() ? unique_name('b') : n) {
buf = *b;
user_assert(t.width == 1) << "Can't create of a buffer of a vector type";
}
};
template<>
RefCount &ref_count<BufferContents>(const BufferContents *p) {
return p->ref_count;
}
template<>
void destroy<BufferContents>(const BufferContents *p) {
// Free any device-side allocation
if (p->source_module.free_dev_buffer) {
p->source_module.free_dev_buffer(NULL, const_cast<buffer_t *>(&p->buf));
}
free(p->allocation);
delete p;
}
}
namespace {
int32_t size_or_zero(const std::vector<int32_t> &sizes, size_t index) {
return (index < sizes.size()) ? sizes[index] : 0;
}
std::string make_buffer_name(const std::string &n, Buffer *b) {
if (n.empty()) {
return Internal::make_entity_name(b, "Halide::Buffer", 'b');
} else {
return n;
}
}
}
Buffer::Buffer(Type t, int x_size, int y_size, int z_size, int w_size,
uint8_t* data, const std::string &name) :
contents(new Internal::BufferContents(t, x_size, y_size, z_size, w_size, data,
make_buffer_name(name, this))) {
}
Buffer::Buffer(Type t, const std::vector<int32_t> &sizes,
uint8_t* data, const std::string &name) :
contents(new Internal::BufferContents(t,
size_or_zero(sizes, 0),
size_or_zero(sizes, 1),
size_or_zero(sizes, 2),
size_or_zero(sizes, 3),
data,
make_buffer_name(name, this))) {
user_assert(sizes.size() <= 4) << "Buffer dimensions greater than 4 are not supported.";
}
Buffer::Buffer(Type t, const buffer_t *buf, const std::string &name) :
contents(new Internal::BufferContents(t, buf,
make_buffer_name(name, this))) {
}
void *Buffer::host_ptr() const {
user_assert(defined()) << "Buffer is undefined\n";
return (void *)contents.ptr->buf.host;
}
buffer_t *Buffer::raw_buffer() const {
user_assert(defined()) << "Buffer is undefined\n";
return &(contents.ptr->buf);
}
uint64_t Buffer::device_handle() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.dev;
}
bool Buffer::host_dirty() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.host_dirty;
}
void Buffer::set_host_dirty(bool dirty) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.host_dirty = dirty;
}
bool Buffer::device_dirty() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->buf.dev_dirty;
}
void Buffer::set_device_dirty(bool dirty) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.host_dirty = dirty;
}
int Buffer::dimensions() const {
for (int i = 0; i < 4; i++) {
if (extent(i) == 0) return i;
}
return 4;
}
int Buffer::extent(int dim) const {
user_assert(defined()) << "Buffer is undefined\n";
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.extent[dim];
}
int Buffer::stride(int dim) const {
user_assert(defined());
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.stride[dim];
}
int Buffer::min(int dim) const {
user_assert(defined()) << "Buffer is undefined\n";
user_assert(dim >= 0 && dim < 4) << "We only support 4-dimensional buffers for now";
return contents.ptr->buf.min[dim];
}
void Buffer::set_min(int m0, int m1, int m2, int m3) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->buf.min[0] = m0;
contents.ptr->buf.min[1] = m1;
contents.ptr->buf.min[2] = m2;
contents.ptr->buf.min[3] = m3;
}
Type Buffer::type() const {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->type;
}
bool Buffer::same_as(const Buffer &other) const {
return contents.same_as(other.contents);
}
bool Buffer::defined() const {
return contents.defined();
}
const std::string &Buffer::name() const {
return contents.ptr->name;
}
Buffer::operator Argument() const {
return Argument(name(), true, type());
}
void Buffer::set_source_module(const Internal::JITCompiledModule &module) {
user_assert(defined()) << "Buffer is undefined\n";
contents.ptr->source_module = module;
}
const Internal::JITCompiledModule &Buffer::source_module() {
user_assert(defined()) << "Buffer is undefined\n";
return contents.ptr->source_module;
}
void Buffer::copy_to_host() {
void (*copy_to_host)(void *, buffer_t *) =
contents.ptr->source_module.copy_to_host;
if (copy_to_host) {
/* The user context is always NULL when jitting, so it's safe to
* pass NULL here. */
copy_to_host(NULL, raw_buffer());
}
}
void Buffer::copy_to_dev() {
void (*copy_to_dev)(void *, buffer_t *) =
contents.ptr->source_module.copy_to_dev;
if (copy_to_dev) {
copy_to_dev(NULL, raw_buffer());
}
}
void Buffer::free_dev_buffer() {
void (*free_dev_buffer)(void *, buffer_t *) =
contents.ptr->source_module.free_dev_buffer;
if (free_dev_buffer) {
free_dev_buffer(NULL, raw_buffer());
}
}
}
<|endoftext|> |
<commit_before>#include <QStringList>
#include "kernel.h"
#include "raster.h"
#include "astnode.h"
#include "idnode.h"
#include "kernel.h"
#include "symboltable.h"
#include "operationnode.h"
#include "expressionnode.h"
#include "parametersnode.h"
#include "selectornode.h"
#include "termnode.h"
#include "commandhandler.h"
using namespace Ilwis;
TermNode::TermNode() : _logicalNegation(false), _numericalNegation(false)
{
}
void TermNode::setNumerical(char *num)
{
QString s(num);
_content = csNumerical;
if ( s == "?") {
_number = Ilwis::rUNDEF;
return;
}
bool ok;
double b =s.toDouble(&ok);
_number = b;
if(!ok) {
_number = Ilwis::rUNDEF;
}
}
void TermNode::setId(IDNode *node)
{
_id = QSharedPointer<IDNode>(node) ;
_content = csID;
}
void TermNode::setExpression(ExpressionNode *n)
{
_expression = QSharedPointer<ExpressionNode>(n);
_content = csExpression;
}
void TermNode::setString(char *s)
{
_string = QString(s);
_content = csString;
}
void TermNode::setParameters(ParametersNode *n)
{
_parameters = QSharedPointer<ParametersNode>(n);
_content = csMethod;
}
QString TermNode::nodeType() const
{
return "term";
}
void TermNode::setLogicalNegation(bool yesno)
{
_logicalNegation = yesno;
}
void TermNode::setNumericalNegation(bool yesno)
{
_numericalNegation = yesno;
}
bool TermNode::evaluate(SymbolTable &symbols, int scope, ExecutionContext *ctx)
{
if ( _content == csExpression) {
if (_expression->evaluate(symbols, scope, ctx)) {
_value = {_expression->value(), NodeValue::ctExpression};
return true;
}
} else if (_content == csNumerical) {
if ( _numericalNegation)
_value = {-_number, NodeValue::ctNumerical};
else
_value = {_number, NodeValue::ctNumerical};
return true;
} else if ( _content == csString) {
_value = {_string, NodeValue::ctString};
return true;
} else if ( _content == csMethod) {
QString parms = "(";
for(int i=0; i < _parameters->noOfChilderen(); ++i) {
bool ok = _parameters->child(i)->evaluate(symbols, scope, ctx);
if (!ok)
return false;
QString name = getName(_parameters->child(i)->value());
if ( i != 0)
parms += ",";
parms += name;
}
parms += ")";
QString expression = _id->id() + parms;
bool ok = Ilwis::commandhandler()->execute(expression, ctx, symbols);
if ( !ok || ctx->_results.size() != 1)
throw ScriptExecutionError(TR("Expression execution error in script; script aborted. See log for further details"));
_value = {symbols.getValue(ctx->_results[0]), ctx->_results[0], NodeValue::ctMethod};
return true;
} else if ( _content == csID) {
_id->evaluate(symbols, scope, ctx);
QString value;
if ( _id->isReference()) {
if ( symbols.getSymbol(_id->id(),scope).isValid())
value = _id->id();
else
return false;
}
else
value = _id->id();
if ( _selectors.size() > 0) {
// selectors are handled by successive calls to the selection operation and in the end giving the temp object to the value
for(QSharedPointer<Selector> selector: _selectors) {
QString selectordef;
if ( !selector->box().isNull())
selectordef = QString("\"box=%1 %2, %3 %4\"").arg(selector->box().min_corner().x).arg(selector->box().min_corner().y).
arg(selector->box().max_corner().x).arg(selector->box().max_corner().y);
else if (selector->selectorType() == "index") {
selectordef = "\"index=" + selector->variable() + "\"";
} else if (selector->selectorType() == "columnrange") {
selectordef = QString("\"columnrange=%1,%2").arg(selector->beginCol()).arg(selector->endCol());
if ( selector->keyColumns() != sUNDEF)
selectordef += "," + selector->keyColumns();
selectordef += "\"";
}else if (selector->selectorType() == "recordrange") {
selectordef = QString("\"recordrange=%1,%2").arg(selector->beginRec()).arg(selector->endRec());
selectordef += "\"";
}else if (selector->selectorType() == "columnrecordrange") {
selectordef = QString("\"columnrecordrange=%1,%2,%3, %4").arg(selector->beginCol()).
arg(selector->endCol()).
arg(selector->beginRec()).
arg(selector->endRec());
if ( selector->keyColumns() != sUNDEF)
selectordef += "," + selector->keyColumns();
selectordef += "\"";
}
else if ( selector->variable() != sUNDEF)
selectordef = "\"attribute=" + selector->variable() + "\"";
QString outname = ANONYMOUS_PREFIX;
QString expression = QString("%1=selection(%2,%3)").arg(outname).arg(value).arg(selectordef);
if(!Ilwis::commandhandler()->execute(expression, ctx, symbols)) {
throw ScriptExecutionError(TR("Expression execution error in script; script aborted. See log for further details"));
}
QString outgc = ctx->_results[0];
value = outgc;
}
}
_value = {value, NodeValue::ctID};
return value != "" && value != sUNDEF;
}
return false;
}
QString TermNode::getName(const NodeValue& var) const {
QString name = var.toString();
if (name != sUNDEF)
return name;
// QString typeName = var.typeName();
// if ( typeName == "Ilwis::IRasterCoverage") {
// Ilwis::IRasterCoverage raster = var.value<Ilwis::IRasterCoverage>();
// name = raster->name();
// }
// if ( typeName == "Coordinate") {
// name = var.id();
// }
// if ( typeName == "Voxel") {
// name = var.id();
// }
return var.id();
}
void TermNode::addSelector(Selector *n)
{
_selectors.push_back(QSharedPointer<Selector>(n));
}
<commit_msg>added handling of auto parameters<commit_after>#include <QStringList>
#include "kernel.h"
#include "raster.h"
#include "astnode.h"
#include "idnode.h"
#include "kernel.h"
#include "symboltable.h"
#include "operationnode.h"
#include "expressionnode.h"
#include "parametersnode.h"
#include "selectornode.h"
#include "selectnode.h"
#include "termnode.h"
#include "commandhandler.h"
using namespace Ilwis;
TermNode::TermNode() : _logicalNegation(false), _numericalNegation(false)
{
}
void TermNode::setNumerical(char *num)
{
QString s(num);
_content = csNumerical;
if ( s == "?") {
_number = Ilwis::rUNDEF;
return;
}
bool ok;
double b =s.toDouble(&ok);
_number = b;
if(!ok) {
_number = Ilwis::rUNDEF;
}
}
void TermNode::setId(IDNode *node)
{
_id = QSharedPointer<IDNode>(node) ;
_content = csID;
}
void TermNode::setExpression(ExpressionNode *n)
{
_expression = QSharedPointer<ExpressionNode>(n);
_content = csExpression;
}
void TermNode::setString(char *s)
{
_string = QString(s);
_content = csString;
}
void TermNode::setParameters(ParametersNode *n)
{
_parameters = QSharedPointer<ParametersNode>(n);
_content = csMethod;
}
QString TermNode::nodeType() const
{
return "term";
}
void TermNode::setLogicalNegation(bool yesno)
{
_logicalNegation = yesno;
}
void TermNode::setNumericalNegation(bool yesno)
{
_numericalNegation = yesno;
}
bool TermNode::evaluate(SymbolTable &symbols, int scope, ExecutionContext *ctx)
{
if ( _content == csExpression) {
if (_expression->evaluate(symbols, scope, ctx)) {
_value = {_expression->value(), NodeValue::ctExpression};
return true;
}
} else if (_content == csNumerical) {
if ( _numericalNegation)
_value = {-_number, NodeValue::ctNumerical};
else
_value = {_number, NodeValue::ctNumerical};
return true;
} else if ( _content == csString) {
_value = {_string, NodeValue::ctString};
return true;
} else if ( _content == csMethod) {
QString parms = "(";
for(int i=0; i < ctx->_additionalInfo.size() && ctx->_useAdditionalParameters; ++i){
QString extrapar = "extra" + QString::number(i);
auto iter = ctx->_additionalInfo.find(extrapar);
if ( iter != ctx->_additionalInfo.end()){
if ( parms.size() > 1)
parms += ",";
parms += (*iter).second;
}
}
for(int i=0; i < _parameters->noOfChilderen(); ++i) {
bool ok = _parameters->child(i)->evaluate(symbols, scope, ctx);
if (!ok)
return false;
QString name = getName(_parameters->child(i)->value());
if ( parms.size() > 1)
parms += ",";
parms += name;
}
parms += ")";
QString expression = _id->id() + parms;
bool ok = Ilwis::commandhandler()->execute(expression, ctx, symbols);
if ( !ok || ctx->_results.size() != 1)
throw ScriptExecutionError(TR("Expression execution error in script; script aborted. See log for further details"));
_value = {symbols.getValue(ctx->_results[0]), ctx->_results[0], NodeValue::ctMethod};
return true;
} else if ( _content == csID) {
_id->evaluate(symbols, scope, ctx);
QString value;
if ( _id->isReference()) {
if ( symbols.getSymbol(_id->id(),scope).isValid())
value = _id->id();
else
return false;
}
else
value = _id->id();
if ( _selectors.size() > 0) {
// selectors are handled by successive calls to the selection operation and in the end giving the temp object to the value
for(QSharedPointer<Selector> selector: _selectors) {
QString selectordef;
if ( !selector->box().isNull())
selectordef = QString("\"box=%1 %2, %3 %4\"").arg(selector->box().min_corner().x).arg(selector->box().min_corner().y).
arg(selector->box().max_corner().x).arg(selector->box().max_corner().y);
else if (selector->selectorType() == "index") {
selectordef = "\"index=" + selector->variable() + "\"";
} else if (selector->selectorType() == "columnrange") {
selectordef = QString("\"columnrange=%1,%2").arg(selector->beginCol()).arg(selector->endCol());
if ( selector->keyColumns() != sUNDEF)
selectordef += "," + selector->keyColumns();
selectordef += "\"";
}else if (selector->selectorType() == "recordrange") {
selectordef = QString("\"recordrange=%1,%2").arg(selector->beginRec()).arg(selector->endRec());
selectordef += "\"";
}else if (selector->selectorType() == "columnrecordrange") {
selectordef = QString("\"columnrecordrange=%1,%2,%3, %4").arg(selector->beginCol()).
arg(selector->endCol()).
arg(selector->beginRec()).
arg(selector->endRec());
if ( selector->keyColumns() != sUNDEF)
selectordef += "," + selector->keyColumns();
selectordef += "\"";
}
else if ( selector->variable() != sUNDEF)
selectordef = "\"attribute=" + selector->variable() + "\"";
QString outname = ANONYMOUS_PREFIX;
QString expression = QString("%1=selection(%2,%3)").arg(outname).arg(value).arg(selectordef);
if(!Ilwis::commandhandler()->execute(expression, ctx, symbols)) {
throw ScriptExecutionError(TR("Expression execution error in script; script aborted. See log for further details"));
}
QString outgc = ctx->_results[0];
value = outgc;
}
}
_value = {value, NodeValue::ctID};
return value != "" && value != sUNDEF;
}
return false;
}
QString TermNode::getName(const NodeValue& var) const {
QString name = var.toString();
if (name != sUNDEF)
return name;
// QString typeName = var.typeName();
// if ( typeName == "Ilwis::IRasterCoverage") {
// Ilwis::IRasterCoverage raster = var.value<Ilwis::IRasterCoverage>();
// name = raster->name();
// }
// if ( typeName == "Coordinate") {
// name = var.id();
// }
// if ( typeName == "Voxel") {
// name = var.id();
// }
return var.id();
}
void TermNode::addSelector(Selector *n)
{
_selectors.push_back(QSharedPointer<Selector>(n));
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/common/cyclic_barrier.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Emanuel Jbstl <[email protected]>
*
* This file has no license. Only Timo Bingmann can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_COMMON_CYCLIC_BARRIER_HEADER
#define C7A_COMMON_CYCLIC_BARRIER_HEADER
#include <mutex>
#include <atomic>
#include <condition_variable>
namespace c7a {
namespace common {
/**
* @brief Implements a cyclic barrier that can be shared between threads.
*/
class Barrier
{
std::mutex m;
std::condition_variable_any event;
const int threadCount;
int counts[2];
int current;
public:
/**
* @brief Creates a new barrier that waits for n threads.
*
* @param n The count of threads to wait for.
*/
Barrier(int n) : threadCount(n), current(0) {
counts[0] = 0;
counts[1] = 0;
}
/**
* @brief Waits for n threads to arrive.
* @details This method blocks and returns as soon as n threads are waiting inside the method.
*/
void await() {
std::atomic_thread_fence(std::memory_order_release);
m.lock();
int localCurrent = current;
counts[localCurrent]++;
if (counts[localCurrent] < threadCount) {
while (counts[localCurrent] < threadCount) {
event.wait(m);
}
}
else {
current = current ? 0 : 1;
counts[current] = 0;
event.notify_all();
}
m.unlock();
}
};
} // namespace common
} // namespace c7a
#endif // !C7A_COMMON_CYCLIC_BARRIER_HEADER
/******************************************************************************/
<commit_msg>make member variables private<commit_after>/*******************************************************************************
* c7a/common/cyclic_barrier.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Emanuel Jbstl <[email protected]>
*
* This file has no license. Only Timo Bingmann can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_COMMON_CYCLIC_BARRIER_HEADER
#define C7A_COMMON_CYCLIC_BARRIER_HEADER
#include <mutex>
#include <atomic>
#include <condition_variable>
namespace c7a {
namespace common {
/**
* @brief Implements a cyclic barrier that can be shared between threads.
*/
class Barrier
{
private:
std::mutex m;
std::condition_variable_any event;
const int threadCount;
int counts[2];
int current;
public:
/**
* @brief Creates a new barrier that waits for n threads.
*
* @param n The count of threads to wait for.
*/
Barrier(int n) : threadCount(n), current(0) {
counts[0] = 0;
counts[1] = 0;
}
/**
* @brief Waits for n threads to arrive.
* @details This method blocks and returns as soon as n threads are waiting inside the method.
*/
void await() {
std::atomic_thread_fence(std::memory_order_release);
m.lock();
int localCurrent = current;
counts[localCurrent]++;
if (counts[localCurrent] < threadCount) {
while (counts[localCurrent] < threadCount) {
event.wait(m);
}
}
else {
current = current ? 0 : 1;
counts[current] = 0;
event.notify_all();
}
m.unlock();
}
};
} // namespace common
} // namespace c7a
#endif // !C7A_COMMON_CYCLIC_BARRIER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>//
// Camera.cpp
// Cinder-EDSDK
//
// Created by Jean-Pierre Mouilleseaux on 08 Dec 2013.
// Copyright 2013-2014 Chorded Constructions. All rights reserved.
//
#include "Camera.h"
#include "CameraBrowser.h"
using namespace ci;
using namespace ci::app;
namespace Cinder { namespace EDSDK {
#pragma mark CAMERA FILE
CameraFileRef CameraFile::create(EdsDirectoryItemRef directoryItem) {
return CameraFileRef(new CameraFile(directoryItem))->shared_from_this();
}
CameraFile::CameraFile(EdsDirectoryItemRef directoryItem) {
if (!directoryItem) {
throw Exception();
}
EdsRetain(directoryItem);
mDirectoryItem = directoryItem;
EdsError error = EdsGetDirectoryItemInfo(mDirectoryItem, &mDirectoryItemInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get directory item info" << std::endl;
throw Exception();
}
}
CameraFile::~CameraFile() {
EdsRelease(mDirectoryItem);
mDirectoryItem = NULL;
}
std::string CameraFile::getName() const {
return std::string(mDirectoryItemInfo.szFileName);
}
uint32_t CameraFile::getSize() const {
return mDirectoryItemInfo.size;
}
#pragma mark - CAMERA
CameraRef Camera::create(EdsCameraRef camera) {
return CameraRef(new Camera(camera))->shared_from_this();
}
Camera::Camera(EdsCameraRef camera) {
if (!camera) {
throw Exception();
}
EdsRetain(camera);
mCamera = camera;
EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get device info" << std::endl;
// TODO - NULL out mDeviceInfo
}
mHasOpenSession = false;
// set event handlers
error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set property event handler" << std::endl;
}
error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
}
Camera::~Camera() {
mRemovedHandler = NULL;
mFileAddedHandler = NULL;
if (mHasOpenSession) {
requestCloseSession();
}
// NB - after EDSDK 2.10 releasing the EdsCameraRef will cause an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) at the end of the runloop
// EdsRelease(mCamera);
mCamera = NULL;
}
#pragma mark -
void Camera::connectRemovedHandler(const std::function<void(CameraRef)>& handler) {
mRemovedHandler = handler;
}
void Camera::connectFileAddedHandler(const std::function<void(CameraRef, CameraFileRef)>& handler) {
mFileAddedHandler = handler;
}
std::string Camera::getName() const {
return std::string(mDeviceInfo.szDeviceDescription);
}
std::string Camera::getPortName() const {
return std::string(mDeviceInfo.szPortName);
}
bool Camera::hasOpenSession() const {
return mHasOpenSession;
}
EdsError Camera::requestOpenSession(const Settings &settings) {
if (mHasOpenSession) {
return EDS_ERR_SESSION_ALREADY_OPEN;
}
EdsError error = EdsOpenSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to open camera session" << std::endl;
return error;
}
mHasOpenSession = true;
mShouldKeepAlive = settings.getShouldKeepAlive();
EdsUInt32 saveTo = settings.getPictureSaveLocation();
error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set save destination host/device" << std::endl;
return error;
}
if (saveTo == kEdsSaveTo_Host) {
// ??? - requires UI lock?
EdsCapacity capacity = {0x7FFFFFFF, 0x1000, 1};
error = EdsSetCapacity(mCamera, capacity);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set capacity of host" << std::endl;
return error;
}
}
return EDS_ERR_OK;
}
EdsError Camera::requestCloseSession() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsCloseSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to close camera session" << std::endl;
return error;
}
mHasOpenSession = false;
return EDS_ERR_OK;
}
EdsError Camera::requestTakePicture() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsSendCommand(mCamera, kEdsCameraCommand_TakePicture, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to take picture" << std::endl;
}
return error;
}
void Camera::requestDownloadFile(const CameraFileRef file, const fs::path destinationFolderPath, std::function<void(EdsError error, ci::fs::path outputFilePath)> callback) {
// check if destination exists and create if not
if (!fs::exists(destinationFolderPath)) {
bool status = fs::create_directories(destinationFolderPath);
if (!status) {
console() << "ERROR - failed to create destination folder path '" << destinationFolderPath << "'" << std::endl;
return callback(EDS_ERR_INTERNAL_ERROR, NULL);
}
}
fs::path filePath = destinationFolderPath / file->getName();
EdsStreamRef stream = NULL;
EdsError error = EdsCreateFileStream(filePath.generic_string().c_str(), kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create file stream" << std::endl;
goto download_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto download_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto download_cleanup;
}
download_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, filePath);
}
void Camera::requestReadFile(const CameraFileRef file, std::function<void(EdsError error, ci::Surface8u surface)> callback) {
Buffer buffer = NULL;
ci::Surface surface;
EdsStreamRef stream = NULL;
EdsError error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto read_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto read_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto read_cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto read_cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get stream length" << std::endl;
goto read_cleanup;
}
buffer = Buffer(data, length);
surface = Surface8u(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
read_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, surface);
}
#pragma mark - CALLBACKS
EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 inEvent, EdsBaseRef inRef, EdsVoid* inContext) {
Camera* c = (Camera*)inContext;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (inEvent) {
case kEdsObjectEvent_DirItemRequestTransfer: {
EdsDirectoryItemRef directoryItem = (EdsDirectoryItemRef)inRef;
CameraFileRef file = NULL;
try {
file = CameraFile::create(directoryItem);
} catch (...) {
EdsRelease(directoryItem);
break;
}
EdsRelease(directoryItem);
directoryItem = NULL;
if (camera->mFileAddedHandler) {
camera->mFileAddedHandler(camera, file);
}
break;
}
default:
if (inRef) {
EdsRelease(inRef);
inRef = NULL;
}
break;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 inEvent, EdsUInt32 inPropertyID, EdsUInt32 inParam, EdsVoid* inContext) {
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 inEvent, EdsUInt32 inParam, EdsVoid* inContext) {
Camera* c = (Camera*)inContext;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (inEvent) {
case kEdsStateEvent_WillSoonShutDown:
if (camera->mHasOpenSession && camera->mShouldKeepAlive) {
EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to extend shut down timer" << std::endl;
}
}
break;
case kEdsStateEvent_Shutdown:
camera->requestCloseSession();
// send handler and browser removal notices
if (camera->mRemovedHandler) {
camera->mRemovedHandler(camera);
}
CameraBrowser::instance()->removeCamera(camera);
break;
default:
break;
}
return EDS_ERR_OK;
}
}}
<commit_msg>clarify crash on release comment<commit_after>//
// Camera.cpp
// Cinder-EDSDK
//
// Created by Jean-Pierre Mouilleseaux on 08 Dec 2013.
// Copyright 2013-2014 Chorded Constructions. All rights reserved.
//
#include "Camera.h"
#include "CameraBrowser.h"
using namespace ci;
using namespace ci::app;
namespace Cinder { namespace EDSDK {
#pragma mark CAMERA FILE
CameraFileRef CameraFile::create(EdsDirectoryItemRef directoryItem) {
return CameraFileRef(new CameraFile(directoryItem))->shared_from_this();
}
CameraFile::CameraFile(EdsDirectoryItemRef directoryItem) {
if (!directoryItem) {
throw Exception();
}
EdsRetain(directoryItem);
mDirectoryItem = directoryItem;
EdsError error = EdsGetDirectoryItemInfo(mDirectoryItem, &mDirectoryItemInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get directory item info" << std::endl;
throw Exception();
}
}
CameraFile::~CameraFile() {
EdsRelease(mDirectoryItem);
mDirectoryItem = NULL;
}
std::string CameraFile::getName() const {
return std::string(mDirectoryItemInfo.szFileName);
}
uint32_t CameraFile::getSize() const {
return mDirectoryItemInfo.size;
}
#pragma mark - CAMERA
CameraRef Camera::create(EdsCameraRef camera) {
return CameraRef(new Camera(camera))->shared_from_this();
}
Camera::Camera(EdsCameraRef camera) {
if (!camera) {
throw Exception();
}
EdsRetain(camera);
mCamera = camera;
EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get device info" << std::endl;
// TODO - NULL out mDeviceInfo
}
mHasOpenSession = false;
// set event handlers
error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set property event handler" << std::endl;
}
error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
}
Camera::~Camera() {
mRemovedHandler = NULL;
mFileAddedHandler = NULL;
if (mHasOpenSession) {
requestCloseSession();
}
// NB - starting with EDSDK 2.10, this release will cause an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) at the end of the runloop
// EdsRelease(mCamera);
mCamera = NULL;
}
#pragma mark -
void Camera::connectRemovedHandler(const std::function<void(CameraRef)>& handler) {
mRemovedHandler = handler;
}
void Camera::connectFileAddedHandler(const std::function<void(CameraRef, CameraFileRef)>& handler) {
mFileAddedHandler = handler;
}
std::string Camera::getName() const {
return std::string(mDeviceInfo.szDeviceDescription);
}
std::string Camera::getPortName() const {
return std::string(mDeviceInfo.szPortName);
}
bool Camera::hasOpenSession() const {
return mHasOpenSession;
}
EdsError Camera::requestOpenSession(const Settings &settings) {
if (mHasOpenSession) {
return EDS_ERR_SESSION_ALREADY_OPEN;
}
EdsError error = EdsOpenSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to open camera session" << std::endl;
return error;
}
mHasOpenSession = true;
mShouldKeepAlive = settings.getShouldKeepAlive();
EdsUInt32 saveTo = settings.getPictureSaveLocation();
error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set save destination host/device" << std::endl;
return error;
}
if (saveTo == kEdsSaveTo_Host) {
// ??? - requires UI lock?
EdsCapacity capacity = {0x7FFFFFFF, 0x1000, 1};
error = EdsSetCapacity(mCamera, capacity);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set capacity of host" << std::endl;
return error;
}
}
return EDS_ERR_OK;
}
EdsError Camera::requestCloseSession() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsCloseSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to close camera session" << std::endl;
return error;
}
mHasOpenSession = false;
return EDS_ERR_OK;
}
EdsError Camera::requestTakePicture() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsSendCommand(mCamera, kEdsCameraCommand_TakePicture, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to take picture" << std::endl;
}
return error;
}
void Camera::requestDownloadFile(const CameraFileRef file, const fs::path destinationFolderPath, std::function<void(EdsError error, ci::fs::path outputFilePath)> callback) {
// check if destination exists and create if not
if (!fs::exists(destinationFolderPath)) {
bool status = fs::create_directories(destinationFolderPath);
if (!status) {
console() << "ERROR - failed to create destination folder path '" << destinationFolderPath << "'" << std::endl;
return callback(EDS_ERR_INTERNAL_ERROR, NULL);
}
}
fs::path filePath = destinationFolderPath / file->getName();
EdsStreamRef stream = NULL;
EdsError error = EdsCreateFileStream(filePath.generic_string().c_str(), kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create file stream" << std::endl;
goto download_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto download_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto download_cleanup;
}
download_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, filePath);
}
void Camera::requestReadFile(const CameraFileRef file, std::function<void(EdsError error, ci::Surface8u surface)> callback) {
Buffer buffer = NULL;
ci::Surface surface;
EdsStreamRef stream = NULL;
EdsError error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto read_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto read_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto read_cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto read_cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get stream length" << std::endl;
goto read_cleanup;
}
buffer = Buffer(data, length);
surface = Surface8u(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
read_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, surface);
}
#pragma mark - CALLBACKS
EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 inEvent, EdsBaseRef inRef, EdsVoid* inContext) {
Camera* c = (Camera*)inContext;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (inEvent) {
case kEdsObjectEvent_DirItemRequestTransfer: {
EdsDirectoryItemRef directoryItem = (EdsDirectoryItemRef)inRef;
CameraFileRef file = NULL;
try {
file = CameraFile::create(directoryItem);
} catch (...) {
EdsRelease(directoryItem);
break;
}
EdsRelease(directoryItem);
directoryItem = NULL;
if (camera->mFileAddedHandler) {
camera->mFileAddedHandler(camera, file);
}
break;
}
default:
if (inRef) {
EdsRelease(inRef);
inRef = NULL;
}
break;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 inEvent, EdsUInt32 inPropertyID, EdsUInt32 inParam, EdsVoid* inContext) {
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 inEvent, EdsUInt32 inParam, EdsVoid* inContext) {
Camera* c = (Camera*)inContext;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (inEvent) {
case kEdsStateEvent_WillSoonShutDown:
if (camera->mHasOpenSession && camera->mShouldKeepAlive) {
EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to extend shut down timer" << std::endl;
}
}
break;
case kEdsStateEvent_Shutdown:
camera->requestCloseSession();
// send handler and browser removal notices
if (camera->mRemovedHandler) {
camera->mRemovedHandler(camera);
}
CameraBrowser::instance()->removeCamera(camera);
break;
default:
break;
}
return EDS_ERR_OK;
}
}}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: François Faure, INRIA-UJF, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/odesolver/EulerImplicitSolver.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/core/ObjectFactory.h>
#include <math.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
namespace sofa
{
namespace component
{
namespace odesolver
{
using namespace sofa::defaulttype;
using namespace core::componentmodel::behavior;
EulerImplicitSolver::EulerImplicitSolver()
: f_rayleighStiffness( initData(&f_rayleighStiffness,0.1,"rayleighStiffness","Rayleigh damping coefficient related to stiffness") )
, f_rayleighMass( initData(&f_rayleighMass,0.1,"rayleighMass","Rayleigh damping coefficient related to mass"))
, f_velocityDamping( initData(&f_velocityDamping,0.,"vdamping","Velocity decay coefficient (no decay if null)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
{
}
void EulerImplicitSolver::init()
{
if (!this->getTags().empty())
{
sout << "EulerImplicitSolver: responsible for the following objects with tags " << this->getTags() << " :" << sendl;
helper::vector<core::objectmodel::BaseObject*> objs;
this->getContext()->get<core::objectmodel::BaseObject>(&objs,this->getTags(),sofa::core::objectmodel::BaseContext::SearchDown);
for (unsigned int i=0; i<objs.size(); ++i)
sout << " " << objs[i]->getClassName() << ' ' << objs[i]->getName() << sendl;
}
}
void EulerImplicitSolver::solve(double dt, sofa::core::componentmodel::behavior::BaseMechanicalState::VecId xResult, sofa::core::componentmodel::behavior::BaseMechanicalState::VecId vResult)
{
MultiVector pos(this, VecId::position());
MultiVector vel(this, VecId::velocity());
MultiVector f(this, VecId::force());
MultiVector b(this, VecId::V_DERIV);
//MultiVector p(this, VecId::V_DERIV);
//MultiVector q(this, VecId::V_DERIV);
//MultiVector q2(this, VecId::V_DERIV);
//MultiVector r(this, VecId::V_DERIV);
MultiVector x(this, VecId::V_DERIV);
double h = dt;
//const bool printLog = f_printLog.getValue();
const bool verbose = f_verbose.getValue();
//projectResponse(vel); // initial velocities are projected to the constrained space
// compute the right-hand term of the equation system
// accumulation through mappings is disabled as it will be done by addMBKv after all factors are computed
computeForce(b, true, false); // b = f0
// new more powerful visitors
// b += (h+rs)df/dx v - rd M v
// values are not cleared so that contributions from computeForces are kept and accumulated through mappings once at the end
addMBKv(b, (f_rayleighMass.getValue() == 0.0 ? 0.0 : -f_rayleighMass.getValue()), 0, h+f_rayleighStiffness.getValue(), false, true);
b.teq(h); // b = h(f0 + (h+rs)df/dx v - rd M v)
if( verbose )
serr<<"EulerImplicitSolver, f0 = "<< b <<sendl;
projectResponse(b); // b is projected to the constrained space
if( verbose )
serr<<"EulerImplicitSolver, projected f0 = "<< b <<sendl;
MultiMatrix matrix(this);
matrix = MechanicalMatrix::K * (-h*(h+f_rayleighStiffness.getValue())) + MechanicalMatrix::M * (1+h*f_rayleighMass.getValue());
//if( verbose )
// serr<<"EulerImplicitSolver, matrix = "<< (MechanicalMatrix::K * (-h*(h+f_rayleighStiffness.getValue())) + MechanicalMatrix::M * (1+h*f_rayleighMass.getValue())) << " = " << matrix <<sendl;
matrix.solve(x, b);
// projectResponse(x);
// x is the solution of the system
// apply the solution
MultiVector newPos(this, xResult);
MultiVector newVel(this, vResult);
#ifdef SOFA_NO_VMULTIOP // unoptimized version
//vel.peq( x ); // vel = vel + x
newVel.eq(vel, x);
//pos.peq( vel, h ); // pos = pos + h vel
newPos.eq(pos, newVel, h);
#else // single-operation optimization
{
typedef core::componentmodel::behavior::BaseMechanicalState::VMultiOp VMultiOp;
VMultiOp ops;
ops.resize(2);
ops[0].first = (VecId)newVel;
ops[0].second.push_back(std::make_pair((VecId)vel,1.0));
ops[0].second.push_back(std::make_pair((VecId)x,1.0));
ops[1].first = (VecId)newPos;
ops[1].second.push_back(std::make_pair((VecId)pos,1.0));
ops[1].second.push_back(std::make_pair((VecId)newVel,h));
simulation::MechanicalVMultiOpVisitor vmop(ops);
vmop.setTags(this->getTags());
vmop.execute(this->getContext());
}
#endif
addSeparateGravity(dt, newVel); // v += dt*g . Used if mass wants to added G separately from the other forces to v.
if (f_velocityDamping.getValue()!=0.0)
newVel *= exp(-h*f_velocityDamping.getValue());
if( verbose )
{
serr<<"EulerImplicitSolver, final x = "<< newPos <<sendl;
serr<<"EulerImplicitSolver, final v = "<< newVel <<sendl;
}
#ifdef SOFA_HAVE_LAPACK
applyConstraints();
#endif
}
SOFA_DECL_CLASS(EulerImplicitSolver)
int EulerImplicitSolverClass = core::RegisterObject("Implicit time integrator using backward Euler scheme")
.add< EulerImplicitSolver >()
.addAlias("EulerImplicit");
.addAlias("ImplicitEulerSolver");
.addAlias("ImplicitEuler");
;
} // namespace odesolver
} // namespace component
} // namespace sofa
<commit_msg>r4166/sofa-dev : fix compil<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: François Faure, INRIA-UJF, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/odesolver/EulerImplicitSolver.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/core/ObjectFactory.h>
#include <math.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
namespace sofa
{
namespace component
{
namespace odesolver
{
using namespace sofa::defaulttype;
using namespace core::componentmodel::behavior;
EulerImplicitSolver::EulerImplicitSolver()
: f_rayleighStiffness( initData(&f_rayleighStiffness,0.1,"rayleighStiffness","Rayleigh damping coefficient related to stiffness") )
, f_rayleighMass( initData(&f_rayleighMass,0.1,"rayleighMass","Rayleigh damping coefficient related to mass"))
, f_velocityDamping( initData(&f_velocityDamping,0.,"vdamping","Velocity decay coefficient (no decay if null)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
{
}
void EulerImplicitSolver::init()
{
if (!this->getTags().empty())
{
sout << "EulerImplicitSolver: responsible for the following objects with tags " << this->getTags() << " :" << sendl;
helper::vector<core::objectmodel::BaseObject*> objs;
this->getContext()->get<core::objectmodel::BaseObject>(&objs,this->getTags(),sofa::core::objectmodel::BaseContext::SearchDown);
for (unsigned int i=0; i<objs.size(); ++i)
sout << " " << objs[i]->getClassName() << ' ' << objs[i]->getName() << sendl;
}
}
void EulerImplicitSolver::solve(double dt, sofa::core::componentmodel::behavior::BaseMechanicalState::VecId xResult, sofa::core::componentmodel::behavior::BaseMechanicalState::VecId vResult)
{
MultiVector pos(this, VecId::position());
MultiVector vel(this, VecId::velocity());
MultiVector f(this, VecId::force());
MultiVector b(this, VecId::V_DERIV);
//MultiVector p(this, VecId::V_DERIV);
//MultiVector q(this, VecId::V_DERIV);
//MultiVector q2(this, VecId::V_DERIV);
//MultiVector r(this, VecId::V_DERIV);
MultiVector x(this, VecId::V_DERIV);
double h = dt;
//const bool printLog = f_printLog.getValue();
const bool verbose = f_verbose.getValue();
//projectResponse(vel); // initial velocities are projected to the constrained space
// compute the right-hand term of the equation system
// accumulation through mappings is disabled as it will be done by addMBKv after all factors are computed
computeForce(b, true, false); // b = f0
// new more powerful visitors
// b += (h+rs)df/dx v - rd M v
// values are not cleared so that contributions from computeForces are kept and accumulated through mappings once at the end
addMBKv(b, (f_rayleighMass.getValue() == 0.0 ? 0.0 : -f_rayleighMass.getValue()), 0, h+f_rayleighStiffness.getValue(), false, true);
b.teq(h); // b = h(f0 + (h+rs)df/dx v - rd M v)
if( verbose )
serr<<"EulerImplicitSolver, f0 = "<< b <<sendl;
projectResponse(b); // b is projected to the constrained space
if( verbose )
serr<<"EulerImplicitSolver, projected f0 = "<< b <<sendl;
MultiMatrix matrix(this);
matrix = MechanicalMatrix::K * (-h*(h+f_rayleighStiffness.getValue())) + MechanicalMatrix::M * (1+h*f_rayleighMass.getValue());
//if( verbose )
// serr<<"EulerImplicitSolver, matrix = "<< (MechanicalMatrix::K * (-h*(h+f_rayleighStiffness.getValue())) + MechanicalMatrix::M * (1+h*f_rayleighMass.getValue())) << " = " << matrix <<sendl;
matrix.solve(x, b);
// projectResponse(x);
// x is the solution of the system
// apply the solution
MultiVector newPos(this, xResult);
MultiVector newVel(this, vResult);
#ifdef SOFA_NO_VMULTIOP // unoptimized version
//vel.peq( x ); // vel = vel + x
newVel.eq(vel, x);
//pos.peq( vel, h ); // pos = pos + h vel
newPos.eq(pos, newVel, h);
#else // single-operation optimization
{
typedef core::componentmodel::behavior::BaseMechanicalState::VMultiOp VMultiOp;
VMultiOp ops;
ops.resize(2);
ops[0].first = (VecId)newVel;
ops[0].second.push_back(std::make_pair((VecId)vel,1.0));
ops[0].second.push_back(std::make_pair((VecId)x,1.0));
ops[1].first = (VecId)newPos;
ops[1].second.push_back(std::make_pair((VecId)pos,1.0));
ops[1].second.push_back(std::make_pair((VecId)newVel,h));
simulation::MechanicalVMultiOpVisitor vmop(ops);
vmop.setTags(this->getTags());
vmop.execute(this->getContext());
}
#endif
addSeparateGravity(dt, newVel); // v += dt*g . Used if mass wants to added G separately from the other forces to v.
if (f_velocityDamping.getValue()!=0.0)
newVel *= exp(-h*f_velocityDamping.getValue());
if( verbose )
{
serr<<"EulerImplicitSolver, final x = "<< newPos <<sendl;
serr<<"EulerImplicitSolver, final v = "<< newVel <<sendl;
}
#ifdef SOFA_HAVE_LAPACK
applyConstraints();
#endif
}
SOFA_DECL_CLASS(EulerImplicitSolver)
int EulerImplicitSolverClass = core::RegisterObject("Implicit time integrator using backward Euler scheme")
.add< EulerImplicitSolver >()
.addAlias("EulerImplicit")
.addAlias("ImplicitEulerSolver")
.addAlias("ImplicitEuler")
;
} // namespace odesolver
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>#include "math/SIMD.h"
#include "GapsRunner.h"
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::List cogaps_cpp(const Rcpp::NumericMatrix &D,
const Rcpp::NumericMatrix &S, unsigned nFactor, unsigned nEquil,
unsigned nEquilCool, unsigned nSample, unsigned nOutputs, unsigned nSnapshots,
float alphaA, float alphaP, float maxGibbmassA, float maxGibbmassP,
unsigned seed, bool messages, bool singleCellRNASeq, char whichMatrixFixed,
const Rcpp::NumericMatrix &FP, unsigned checkpointInterval,
const std::string &cptFile, unsigned pumpThreshold, unsigned nPumpSamples,
unsigned nCores)
{
// create internal state from parameters and run from there
GapsRunner runner(D, S, nFactor, nEquil, nEquilCool, nSample,
nOutputs, nSnapshots, alphaA, alphaP, maxGibbmassA, maxGibbmassP, seed,
messages, singleCellRNASeq, checkpointInterval, cptFile,
whichMatrixFixed, FP, nCores);
return runner.run();
}
// TODO add checksum to verify D,S matrices
// [[Rcpp::export]]
Rcpp::List cogapsFromCheckpoint_cpp(const Rcpp::NumericMatrix &D,
const Rcpp::NumericMatrix &S, unsigned nFactor, unsigned nEquil,
unsigned nSample, const std::string &fileName, const std::string &cptFile)
{
GapsRunner runner(D, S, nFactor, nEquil, nSample, cptFile);
return runner.run();
}
// used to convert defined macro values into strings
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
// [[Rcpp::export]]
std::string getBuildReport_cpp()
{
#if defined( __clang__ )
std::string compiler = "Compiled with Clang\n";
#elif defined( __INTEL_COMPILER )
std::string compiler = "Compiled with Intel ICC/ICPC\n";
#elif defined( __GNUC__ )
std::string compiler = "Compiled with GCC v" + std::string(STR( __GNUC__ ))
+ "." + std::string(STR( __GNUC_MINOR__ )) + '\n';
#elif defined( _MSC_VER )
std::string compiler = "Compiled with Microsoft Visual Studio\n";
#endif
#if defined( __GAPS_AVX__ )
std::string simd = "AVX enabled\n";
#elif defined( __GAPS_SSE__ )
std::string simd = "SSE enabled\n";
#else
std::string simd = "SIMD not enabled\n";
#endif
#if defined(_OPENMP)
std::string openmp = "Compiled with OpenMP\n";
#else
std::string openmp = "Compiler did not support OpenMP\n";
#endif
return compiler + simd + openmp;
}
<commit_msg>status message about number of cores<commit_after>#include "math/SIMD.h"
#include "GapsRunner.h"
#include <Rcpp.h>
#include <omp.h>
// [[Rcpp::export]]
Rcpp::List cogaps_cpp(const Rcpp::NumericMatrix &D,
const Rcpp::NumericMatrix &S, unsigned nFactor, unsigned nEquil,
unsigned nEquilCool, unsigned nSample, unsigned nOutputs, unsigned nSnapshots,
float alphaA, float alphaP, float maxGibbmassA, float maxGibbmassP,
unsigned seed, bool messages, bool singleCellRNASeq, char whichMatrixFixed,
const Rcpp::NumericMatrix &FP, unsigned checkpointInterval,
const std::string &cptFile, unsigned pumpThreshold, unsigned nPumpSamples,
unsigned nCores)
{
unsigned availableCores = omp_get_max_threads();
Rprintf("Running on %d out of %d available cores\n", nCores, availableCores);
// create internal state from parameters and run from there
GapsRunner runner(D, S, nFactor, nEquil, nEquilCool, nSample,
nOutputs, nSnapshots, alphaA, alphaP, maxGibbmassA, maxGibbmassP, seed,
messages, singleCellRNASeq, checkpointInterval, cptFile,
whichMatrixFixed, FP, nCores);
return runner.run();
}
// TODO add checksum to verify D,S matrices
// [[Rcpp::export]]
Rcpp::List cogapsFromCheckpoint_cpp(const Rcpp::NumericMatrix &D,
const Rcpp::NumericMatrix &S, unsigned nFactor, unsigned nEquil,
unsigned nSample, const std::string &fileName, const std::string &cptFile)
{
GapsRunner runner(D, S, nFactor, nEquil, nSample, cptFile);
return runner.run();
}
// used to convert defined macro values into strings
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
// [[Rcpp::export]]
std::string getBuildReport_cpp()
{
#if defined( __clang__ )
std::string compiler = "Compiled with Clang\n";
#elif defined( __INTEL_COMPILER )
std::string compiler = "Compiled with Intel ICC/ICPC\n";
#elif defined( __GNUC__ )
std::string compiler = "Compiled with GCC v" + std::string(STR( __GNUC__ ))
+ "." + std::string(STR( __GNUC_MINOR__ )) + '\n';
#elif defined( _MSC_VER )
std::string compiler = "Compiled with Microsoft Visual Studio\n";
#endif
#if defined( __GAPS_AVX__ )
std::string simd = "AVX enabled\n";
#elif defined( __GAPS_SSE__ )
std::string simd = "SSE enabled\n";
#else
std::string simd = "SIMD not enabled\n";
#endif
#if defined(_OPENMP)
std::string openmp = "Compiled with OpenMP\n";
#else
std::string openmp = "Compiler did not support OpenMP\n";
#endif
return compiler + simd + openmp;
}
<|endoftext|> |
<commit_before>/**
* @file Config.cpp
* @ingroup LoggerCpp
* @brief Configuration for an Output object
*
* Copyright (c) 2013 Sebastien Rombauts ([email protected])
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "Config.h"
#include "Stream.h"
namespace Log
{
// Constructor
Config::Config(const char* apName) :
mName(apName)
{
}
// Destructor
Config::~Config(void)
{
}
// Get a string value
const std::string& Config::getString(const char* apKey) const
{
Config::Values::const_iterator iValue = mValues.find(apKey);
if (mValues.end() == iValue)
{
/// @todo use a specific Exception class
throw std::runtime_error(Stream() << "Config::getString(\"" << apKey << "\") no existing value");
}
return iValue->second;
}
} // namespace Log
<commit_msg>Fixed Linux compilation<commit_after>/**
* @file Config.cpp
* @ingroup LoggerCpp
* @brief Configuration for an Output object
*
* Copyright (c) 2013 Sebastien Rombauts ([email protected])
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "Config.h"
#include "Stream.h"
#include <stdexcept>
namespace Log
{
// Constructor
Config::Config(const char* apName) :
mName(apName)
{
}
// Destructor
Config::~Config(void)
{
}
// Get a string value
const std::string& Config::getString(const char* apKey) const
{
Config::Values::const_iterator iValue = mValues.find(apKey);
if (mValues.end() == iValue)
{
/// @todo use a specific Exception class
throw std::runtime_error(Stream() << "Config::getString(\"" << apKey << "\") no existing value");
}
return iValue->second;
}
} // namespace Log
<|endoftext|> |
<commit_before>
#include <dronecore/dronecore.h>
#include <iostream>
#include <thread>
#include <chrono>
#include <cstdint>
using std::this_thread::sleep_for;
using std::chrono::milliseconds;
using namespace dronecore;
#define ERROR_CONSOLE_TEXT "\033[31m" //Turn text on console red
#define TELEMETRY_CONSOLE_TEXT "\033[34m" //Turn text on console blue
#define NORMAL_CONSOLE_TEXT "\033[0m" //Restore normal console colour
int main(int /*argc*/, char ** /*argv*/)
{
DroneCore dc;
bool discovered_device = false;
DroneCore::ConnectionResult connection_result = dc.add_udp_connection();
if (connection_result != DroneCore::ConnectionResult::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Connection failed: "
<< DroneCore::connection_result_str(connection_result)
<< NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
std::cout << "Waiting to discover device..." << std::endl;
dc.register_on_discover([&discovered_device](uint64_t uuid) {
std::cout << "Discovered device with UUID: " << uuid << std::endl;
discovered_device = true;
});
// We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds.
std::this_thread::sleep_for(std::chrono::seconds(2));
if (!discovered_device) {
std::cout << ERROR_CONSOLE_TEXT << "No device found, exiting." << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// We don't need to specify the UUID if it's only one device anyway.
// If there were multiple, we could specify it with:
// dc.device(uint64_t uuid);
Device &device = dc.device();
// We want to listen to the altitude of the drone at 1 Hz.
const Telemetry::Result set_rate_result = dc.device().telemetry().set_rate_position(1.0);
if (set_rate_result != Telemetry::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Setting rate failed:" << Telemetry::result_str(
set_rate_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Set up callback to monitor altitude while the vehicle is in flight
device.telemetry().position_async([](Telemetry::Position position) {
std::cout << TELEMETRY_CONSOLE_TEXT // set to blue
<< "Altitude: " << position.relative_altitude_m << " m"
<< NORMAL_CONSOLE_TEXT // set to default color again
<< std::endl;
});
// Check if vehicle is ready to arm
if (device.telemetry().health_all_ok() != true) {
std::cout << ERROR_CONSOLE_TEXT << "Vehicle not ready to arm" << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Arm vehicle
std::cout << "Arming..." << std::endl;
const Action::Result arm_result = device.action().arm();
if (arm_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Arming failed:" << Action::result_str(
arm_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Take off
std::cout << "Taking off..." << std::endl;
const Action::Result takeoff_result = device.action().takeoff();
if (takeoff_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Takeoff failed:" << Action::result_str(
takeoff_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(10));
// Change to FW
const Action::Result fw_result = device.action().transition_to_fixedwing();
if (fw_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Transition to fixed wing failed: " << Action::result_str(
fw_result) << NORMAL_CONSOLE_TEXT << std::endl;
//return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(10));
// Change to VTOL
const Action::Result mc_result = device.action().transition_to_multicopter();
if (mc_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Transition to multi copter failed:" << Action::result_str(
mc_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(5));
// Return to launch
const Action::Result rtl_result = device.action().return_to_launch();
if (rtl_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Returning to launch failed:" << Action::result_str(
rtl_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(20));
// Land
std::cout << "Landing..." << std::endl;
const Action::Result land_result = device.action().land();
if (land_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Land failed:" << Action::result_str(
land_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// We are relying on auto-disarming but let's keep watching the telemetry for a bit longer.
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Finished..." << std::endl;
return 0;
}
<commit_msg>example: added some printfs for what is going on<commit_after>
#include <dronecore/dronecore.h>
#include <iostream>
#include <thread>
#include <chrono>
#include <cstdint>
using std::this_thread::sleep_for;
using std::chrono::milliseconds;
using namespace dronecore;
#define ERROR_CONSOLE_TEXT "\033[31m" //Turn text on console red
#define TELEMETRY_CONSOLE_TEXT "\033[34m" //Turn text on console blue
#define NORMAL_CONSOLE_TEXT "\033[0m" //Restore normal console colour
int main(int /*argc*/, char ** /*argv*/)
{
DroneCore dc;
bool discovered_device = false;
DroneCore::ConnectionResult connection_result = dc.add_udp_connection();
if (connection_result != DroneCore::ConnectionResult::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Connection failed: "
<< DroneCore::connection_result_str(connection_result)
<< NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
std::cout << "Waiting to discover device..." << std::endl;
dc.register_on_discover([&discovered_device](uint64_t uuid) {
std::cout << "Discovered device with UUID: " << uuid << std::endl;
discovered_device = true;
});
// We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds.
std::this_thread::sleep_for(std::chrono::seconds(2));
if (!discovered_device) {
std::cout << ERROR_CONSOLE_TEXT << "No device found, exiting." << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// We don't need to specify the UUID if it's only one device anyway.
// If there were multiple, we could specify it with:
// dc.device(uint64_t uuid);
Device &device = dc.device();
// We want to listen to the altitude of the drone at 1 Hz.
const Telemetry::Result set_rate_result = dc.device().telemetry().set_rate_position(1.0);
if (set_rate_result != Telemetry::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Setting rate failed:" << Telemetry::result_str(
set_rate_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Set up callback to monitor altitude while the vehicle is in flight
device.telemetry().position_async([](Telemetry::Position position) {
std::cout << TELEMETRY_CONSOLE_TEXT // set to blue
<< "Altitude: " << position.relative_altitude_m << " m"
<< NORMAL_CONSOLE_TEXT // set to default color again
<< std::endl;
});
// Check if vehicle is ready to arm
if (device.telemetry().health_all_ok() != true) {
std::cout << ERROR_CONSOLE_TEXT << "Vehicle not ready to arm" << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Arm vehicle
std::cout << "Arming..." << std::endl;
const Action::Result arm_result = device.action().arm();
if (arm_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Arming failed:" << Action::result_str(
arm_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Take off
std::cout << "Taking off..." << std::endl;
const Action::Result takeoff_result = device.action().takeoff();
if (takeoff_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Takeoff failed:" << Action::result_str(
takeoff_result) << NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "Transition to fixedwing..." << std::endl;
const Action::Result fw_result = device.action().transition_to_fixedwing();
if (fw_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Transition to fixed wing failed: " << Action::result_str(
fw_result) << NORMAL_CONSOLE_TEXT << std::endl;
//return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(10));
// Change to VTOL
std::cout << "Transition back to multicopter..." << std::endl;
const Action::Result mc_result = device.action().transition_to_multicopter();
if (mc_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Transition to multi copter failed:" << Action::result_str(
mc_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(5));
// Return to launch
std::cout << "Return to launch..." << std::endl;
const Action::Result rtl_result = device.action().return_to_launch();
if (rtl_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Returning to launch failed:" << Action::result_str(
rtl_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// Wait
std::this_thread::sleep_for(std::chrono::seconds(20));
// Land
std::cout << "Landing..." << std::endl;
const Action::Result land_result = device.action().land();
if (land_result != Action::Result::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT << "Land failed:" << Action::result_str(
land_result) << NORMAL_CONSOLE_TEXT << std::endl;
// return 1;
}
// We are relying on auto-disarming but let's keep watching the telemetry for a bit longer.
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Finished..." << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
namespace {
// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
FILE_PATH_LITERAL("gcswf32.dll");
#else // OS_LINUX, etc.
FILE_PATH_LITERAL("libgcflashplayer.so");
#endif
// File name of the internal PDF plugin on different platforms.
const FilePath::CharType kInternalPDFPluginFileName[] =
#if defined(OS_WIN)
FILE_PATH_LITERAL("pdf.dll");
#elif defined(OS_MACOSX)
FILE_PATH_LITERAL("PDF.plugin");
#else // Linux and Chrome OS
FILE_PATH_LITERAL("libpdf.so");
#endif
// File name of the internal NaCl plugin on different platforms.
const FilePath::CharType kInternalNaClPluginFileName[] =
#if defined(OS_WIN)
FILE_PATH_LITERAL("ppGoogleNaClPluginChrome.dll");
#elif defined(OS_MACOSX)
// TODO(noelallen) Please verify this extention name is correct.
FILE_PATH_LITERAL("ppGoogleNaClPluginChrome.plugin");
#else // Linux and Chrome OS
FILE_PATH_LITERAL("libppGoogleNaClPluginChrome.so");
#endif
} // namespace
namespace chrome {
// Gets the path for internal plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
// If called from Chrome, get internal plugins from a subdirectory of the
// framework.
if (base::mac::AmIBundled()) {
*result = chrome::GetFrameworkBundlePath();
DCHECK(!result->empty());
*result = result->Append("Internet Plug-Ins");
return true;
}
// In tests, just look in the module directory (below).
#endif
// The rest of the world expects plugins in the module directory.
return PathService::Get(base::DIR_MODULE, result);
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifdef NDEBUG
// Release builds write to the data dir
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
// Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
if (!PathService::Get(base::DIR_EXE, result))
return false;
if (base::mac::AmIBundled()) {
// If we're called from chrome, dump it beside the app (outside the
// app bundle), if we're called from a unittest, we'll already
// outside the bundle so use the exe dir.
// exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
*result = result->DirName();
*result = result->DirName();
*result = result->DirName();
}
return true;
#else
return PathService::Get(base::DIR_EXE, result);
#endif // defined(OS_MACOSX)
#endif // NDEBUG
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will not need to create the directory if it does not exist.
// This flag can be set to true for the cases where we want to create it.
bool create_dir = false;
FilePath cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur)) {
NOTREACHED();
return false;
}
create_dir = true;
break;
case chrome::DIR_USER_DOCUMENTS:
if (!GetUserDocumentsDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
if (!GetUserDownloadsDirectorySafe(&cur))
return false;
break;
#else
// Fall through for all other platforms.
#endif
case chrome::DIR_DEFAULT_DOWNLOADS:
if (!GetUserDownloadsDirectory(&cur))
return false;
// Do not create the download directory here, we have done it twice now
// and annoyed a lot of users.
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
create_dir = true;
break;
case chrome::DIR_USER_DESKTOP:
if (!GetUserDesktop(&cur))
return false;
break;
case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
cur = base::mac::MainAppBundlePath();
cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
break;
case chrome::DIR_SHARED_RESOURCES:
if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("shared"));
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
break;
case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_POSIX)
// We can't write into the EXE dir on Linux, so keep dictionaries
// alongside the safe browsing database in the user data dir.
// And we don't want to write into the bundle on the Mac, so push
// it to the user data dir there also.
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
#else
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
#endif
cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
create_dir = true;
break;
case chrome::DIR_USER_DATA_TEMP:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Temp"));
break;
case chrome::DIR_INTERNAL_PLUGINS:
if (!GetInternalPluginsDirectory(&cur))
return false;
break;
case chrome::DIR_MEDIA_LIBS:
#if defined(OS_MACOSX)
*result = base::mac::MainAppBundlePath();
*result = result->Append("Libraries");
return true;
#else
return PathService::Get(chrome::DIR_APP, result);
#endif
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(chrome::kLocalStateFilename);
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("script.log"));
break;
case chrome::FILE_FLASH_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalFlashPluginFileName);
if (!file_util::PathExists(cur))
return false;
break;
case chrome::FILE_PDF_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalPDFPluginFileName);
break;
case chrome::FILE_NACL_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalNaClPluginFileName);
break;
case chrome::FILE_RESOURCES_PACK:
#if defined(OS_MACOSX)
if (base::mac::AmIBundled()) {
cur = base::mac::MainAppBundlePath();
cur = cur.Append(FILE_PATH_LITERAL("Resources"))
.Append(FILE_PATH_LITERAL("resources.pak"));
break;
}
// If we're not bundled on mac, resources.pak should be next to the
// binary (e.g., for unit tests).
#endif
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("resources.pak"));
break;
#if defined(OS_CHROMEOS)
case chrome::FILE_CHROMEOS_API:
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
break;
#endif
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
cur = cur.Append(FILE_PATH_LITERAL("data"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("tools"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
#if defined(OS_POSIX) && !defined(OS_MACOSX)
case chrome::DIR_POLICY_FILES: {
#if defined(GOOGLE_CHROME_BUILD)
cur = FilePath(FILE_PATH_LITERAL("/etc/opt/chrome/policies"));
#else
cur = FilePath(FILE_PATH_LITERAL("/etc/chromium/policies"));
#endif
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
}
#endif
#if defined(OS_MACOSX)
case chrome::DIR_MANAGED_PREFS: {
if (!GetLocalLibraryDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Managed Preferences"));
char* login = getlogin();
if (!login)
return false;
cur = cur.AppendASCII(login);
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
}
#endif
#if defined(OS_CHROMEOS)
case chrome::DIR_USER_EXTERNAL_EXTENSIONS: {
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("External Extensions"));
break;
}
#endif
case chrome::DIR_EXTERNAL_EXTENSIONS:
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
#if defined(OS_MACOSX)
// On Mac, built-in extensions are in Contents/Extensions, a sibling of
// the App dir. If there are none, it may not exist.
cur = cur.DirName();
cur = cur.Append(FILE_PATH_LITERAL("Extensions"));
create_dir = false;
#else
cur = cur.Append(FILE_PATH_LITERAL("extensions"));
create_dir = true;
#endif
break;
default:
return false;
}
if (create_dir && !file_util::PathExists(cur) &&
!file_util::CreateDirectory(cur))
return false;
*result = cur;
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<commit_msg>Restore path chrome::DIR_EXTERNAL_EXTENSIONS to its old path on Mac OS.<commit_after>// Copyright (c) 2011 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/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
namespace {
// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
FILE_PATH_LITERAL("gcswf32.dll");
#else // OS_LINUX, etc.
FILE_PATH_LITERAL("libgcflashplayer.so");
#endif
// File name of the internal PDF plugin on different platforms.
const FilePath::CharType kInternalPDFPluginFileName[] =
#if defined(OS_WIN)
FILE_PATH_LITERAL("pdf.dll");
#elif defined(OS_MACOSX)
FILE_PATH_LITERAL("PDF.plugin");
#else // Linux and Chrome OS
FILE_PATH_LITERAL("libpdf.so");
#endif
// File name of the internal NaCl plugin on different platforms.
const FilePath::CharType kInternalNaClPluginFileName[] =
#if defined(OS_WIN)
FILE_PATH_LITERAL("ppGoogleNaClPluginChrome.dll");
#elif defined(OS_MACOSX)
// TODO(noelallen) Please verify this extention name is correct.
FILE_PATH_LITERAL("ppGoogleNaClPluginChrome.plugin");
#else // Linux and Chrome OS
FILE_PATH_LITERAL("libppGoogleNaClPluginChrome.so");
#endif
} // namespace
namespace chrome {
// Gets the path for internal plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
// If called from Chrome, get internal plugins from a subdirectory of the
// framework.
if (base::mac::AmIBundled()) {
*result = chrome::GetFrameworkBundlePath();
DCHECK(!result->empty());
*result = result->Append("Internet Plug-Ins");
return true;
}
// In tests, just look in the module directory (below).
#endif
// The rest of the world expects plugins in the module directory.
return PathService::Get(base::DIR_MODULE, result);
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifdef NDEBUG
// Release builds write to the data dir
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
// Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
if (!PathService::Get(base::DIR_EXE, result))
return false;
if (base::mac::AmIBundled()) {
// If we're called from chrome, dump it beside the app (outside the
// app bundle), if we're called from a unittest, we'll already
// outside the bundle so use the exe dir.
// exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
*result = result->DirName();
*result = result->DirName();
*result = result->DirName();
}
return true;
#else
return PathService::Get(base::DIR_EXE, result);
#endif // defined(OS_MACOSX)
#endif // NDEBUG
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will not need to create the directory if it does not exist.
// This flag can be set to true for the cases where we want to create it.
bool create_dir = false;
FilePath cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur)) {
NOTREACHED();
return false;
}
create_dir = true;
break;
case chrome::DIR_USER_DOCUMENTS:
if (!GetUserDocumentsDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
if (!GetUserDownloadsDirectorySafe(&cur))
return false;
break;
#else
// Fall through for all other platforms.
#endif
case chrome::DIR_DEFAULT_DOWNLOADS:
if (!GetUserDownloadsDirectory(&cur))
return false;
// Do not create the download directory here, we have done it twice now
// and annoyed a lot of users.
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
create_dir = true;
break;
case chrome::DIR_USER_DESKTOP:
if (!GetUserDesktop(&cur))
return false;
break;
case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
cur = base::mac::MainAppBundlePath();
cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
break;
case chrome::DIR_SHARED_RESOURCES:
if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("shared"));
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
break;
case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_POSIX)
// We can't write into the EXE dir on Linux, so keep dictionaries
// alongside the safe browsing database in the user data dir.
// And we don't want to write into the bundle on the Mac, so push
// it to the user data dir there also.
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
#else
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
#endif
cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
create_dir = true;
break;
case chrome::DIR_USER_DATA_TEMP:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Temp"));
break;
case chrome::DIR_INTERNAL_PLUGINS:
if (!GetInternalPluginsDirectory(&cur))
return false;
break;
case chrome::DIR_MEDIA_LIBS:
#if defined(OS_MACOSX)
*result = base::mac::MainAppBundlePath();
*result = result->Append("Libraries");
return true;
#else
return PathService::Get(chrome::DIR_APP, result);
#endif
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(chrome::kLocalStateFilename);
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("script.log"));
break;
case chrome::FILE_FLASH_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalFlashPluginFileName);
if (!file_util::PathExists(cur))
return false;
break;
case chrome::FILE_PDF_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalPDFPluginFileName);
break;
case chrome::FILE_NACL_PLUGIN:
if (!GetInternalPluginsDirectory(&cur))
return false;
cur = cur.Append(kInternalNaClPluginFileName);
break;
case chrome::FILE_RESOURCES_PACK:
#if defined(OS_MACOSX)
if (base::mac::AmIBundled()) {
cur = base::mac::MainAppBundlePath();
cur = cur.Append(FILE_PATH_LITERAL("Resources"))
.Append(FILE_PATH_LITERAL("resources.pak"));
break;
}
// If we're not bundled on mac, resources.pak should be next to the
// binary (e.g., for unit tests).
#endif
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("resources.pak"));
break;
#if defined(OS_CHROMEOS)
case chrome::FILE_CHROMEOS_API:
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
break;
#endif
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
cur = cur.Append(FILE_PATH_LITERAL("data"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("tools"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
#if defined(OS_POSIX) && !defined(OS_MACOSX)
case chrome::DIR_POLICY_FILES: {
#if defined(GOOGLE_CHROME_BUILD)
cur = FilePath(FILE_PATH_LITERAL("/etc/opt/chrome/policies"));
#else
cur = FilePath(FILE_PATH_LITERAL("/etc/chromium/policies"));
#endif
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
}
#endif
#if defined(OS_MACOSX)
case chrome::DIR_MANAGED_PREFS: {
if (!GetLocalLibraryDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Managed Preferences"));
char* login = getlogin();
if (!login)
return false;
cur = cur.AppendASCII(login);
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
}
#endif
#if defined(OS_CHROMEOS)
case chrome::DIR_USER_EXTERNAL_EXTENSIONS: {
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("External Extensions"));
break;
}
#endif
case chrome::DIR_EXTERNAL_EXTENSIONS:
#if defined(OS_MACOSX)
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
// On Mac, built-in extensions are in Contents/Extensions, a sibling of
// the App dir. If there are none, it may not exist.
// TODO(skerner): Reading external extensions from a file inside the
// app budle causes several problems. Change this path to be outside
// the app bundle. crbug/67203
cur = cur.DirName();
cur = cur.Append(FILE_PATH_LITERAL("Extensions"));
create_dir = false;
#else
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("extensions"));
create_dir = true;
#endif
break;
default:
return false;
}
if (create_dir && !file_util::PathExists(cur) &&
!file_util::CreateDirectory(cur))
return false;
*result = cur;
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
<commit_msg>Fixed what looks like a gcc compiler bug returning true for ':' when function declared as inline rather than static inline.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
<|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/common/pepper_flash.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#if defined(OS_WIN)
#include "base/win/metro.h"
#endif
namespace {
const char* const kFieldTrialName = "ApplyPepperFlash";
const char* const kDisableGroupName = "DisableByDefault";
const char* const kEnableGroupName = "EnableByDefault";
int g_disabled_group_number = -1;
void ActivateFieldTrial() {
// The field trial will expire on Jan 1st, 2014.
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
kFieldTrialName, 1000, kDisableGroupName, 2014, 1, 1,
&g_disabled_group_number));
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kPpapiFlashFieldTrial)) {
std::string switch_value =
command_line->GetSwitchValueASCII(switches::kPpapiFlashFieldTrial);
if (switch_value == switches::kPpapiFlashFieldTrialEnableByDefault) {
trial->AppendGroup(kEnableGroupName, 1000);
return;
} else if (switch_value ==
switches::kPpapiFlashFieldTrialDisableByDefault) {
return;
}
}
// Disable by default if one time randomization is not available.
if (!base::FieldTrialList::IsOneTimeRandomizationEnabled())
return;
trial->UseOneTimeRandomization();
// 50% goes into the enable-by-default group.
trial->AppendGroup(kEnableGroupName, 500);
}
bool IsInFieldTrialGroup() {
static bool activated = false;
if (!activated) {
ActivateFieldTrial();
activated = true;
}
int group = base::FieldTrialList::FindValue(kFieldTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != g_disabled_group_number;
}
} // namespace
bool ConductingPepperFlashFieldTrial() {
#if defined(OS_WIN)
return true;
#elif defined(OS_MACOSX)
// TODO(shess): This is sort of abusive. Initially PepperFlash
// should be present in about:plugins but not enabled in preference
// to NPAPI Flash. Returning |true| here causes
// BrowserProcessImpl::PreMainMessageLoopRun() to find PepperFlash
// after the built-in NPAPI Flash. Returning |false| from
// IsPepperFlashEnabledByDefault() prevents PepperFlash from being
// moved above NPAPI Flash.
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_CANARY)
return true;
// TODO(shess): Don't expose for other channels, yet.
return false;
#else
return false;
#endif
}
bool IsPepperFlashEnabledByDefault() {
#if defined(USE_AURA)
// Pepper Flash is required for Aura (on any OS).
return true;
#elif defined(OS_WIN)
// Pepper Flash is required for Windows 8 Metro mode.
if (base::win::IsMetroProcess())
return true;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_CANARY)
return true;
// For other Windows users, enable only for Dev users in a field trial.
return channel == chrome::VersionInfo::CHANNEL_DEV && IsInFieldTrialGroup();
#elif defined(OS_LINUX)
// For Linux, always try to use it (availability is checked elsewhere).
return true;
#elif defined(OS_MACOSX)
// Don't enable PepperFlash in preference to NPAPI Flash.
return false;
#else
return false;
#endif
}
<commit_msg>[Mac] PepperFlash default on canary, opt-in on dev.<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/common/pepper_flash.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#if defined(OS_WIN)
#include "base/win/metro.h"
#endif
namespace {
const char* const kFieldTrialName = "ApplyPepperFlash";
const char* const kDisableGroupName = "DisableByDefault";
const char* const kEnableGroupName = "EnableByDefault";
int g_disabled_group_number = -1;
void ActivateFieldTrial() {
// The field trial will expire on Jan 1st, 2014.
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
kFieldTrialName, 1000, kDisableGroupName, 2014, 1, 1,
&g_disabled_group_number));
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kPpapiFlashFieldTrial)) {
std::string switch_value =
command_line->GetSwitchValueASCII(switches::kPpapiFlashFieldTrial);
if (switch_value == switches::kPpapiFlashFieldTrialEnableByDefault) {
trial->AppendGroup(kEnableGroupName, 1000);
return;
} else if (switch_value ==
switches::kPpapiFlashFieldTrialDisableByDefault) {
return;
}
}
// Disable by default if one time randomization is not available.
if (!base::FieldTrialList::IsOneTimeRandomizationEnabled())
return;
trial->UseOneTimeRandomization();
// 50% goes into the enable-by-default group.
trial->AppendGroup(kEnableGroupName, 500);
}
bool IsInFieldTrialGroup() {
static bool activated = false;
if (!activated) {
ActivateFieldTrial();
activated = true;
}
int group = base::FieldTrialList::FindValue(kFieldTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != g_disabled_group_number;
}
} // namespace
bool ConductingPepperFlashFieldTrial() {
#if defined(OS_WIN)
return true;
#elif defined(OS_MACOSX)
// Returning |true| here puts PepperFlash in the plugin list, by
// default after the built-in NPAPI Flash. Returning |true| from
// IsPepperFlashEnabledByDefault() puts PepperFlash above NPAPI
// Flash.
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_CANARY)
return true;
if (channel == chrome::VersionInfo::CHANNEL_DEV)
return true;
// TODO(shess): Don't expose for other channels, yet.
return false;
#else
return false;
#endif
}
bool IsPepperFlashEnabledByDefault() {
#if defined(USE_AURA)
// Pepper Flash is required for Aura (on any OS).
return true;
#elif defined(OS_WIN)
// Pepper Flash is required for Windows 8 Metro mode.
if (base::win::IsMetroProcess())
return true;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_CANARY)
return true;
// For other Windows users, enable only for Dev users in a field trial.
return channel == chrome::VersionInfo::CHANNEL_DEV && IsInFieldTrialGroup();
#elif defined(OS_LINUX)
// For Linux, always try to use it (availability is checked elsewhere).
return true;
#elif defined(OS_MACOSX)
// PepperFlash is the default for CANARY.
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_CANARY)
return true;
// PepperFlash is opt-in on any other channels.
return false;
#else
return false;
#endif
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascade Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch >= 161);
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) && (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || ch == '.' || ch == '#' || ch == '!' || ch == '@'))
return true;
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
continue;
}
if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cssWordListDesc[] = {
"Keywords",
"Pseudo classes",
0
};
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc);
<commit_msg>Patch from Jakub Vrana to handle some out of bounds characters and repetitive pseudo-classes.<commit_after>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascade Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch == '_' || ch >= 161); // _ is not in fact correct CSS word-character
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) && (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || ch == '.' || ch == '#' || ch == '!' || ch == '@'))
return true;
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
continue;
}
if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cssWordListDesc[] = {
"Keywords",
"Pseudo classes",
0
};
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc);
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Removed duplicate code.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Kein-Hong Man properly handles + or - as operators in numbers like 1+2.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|> |
<commit_before>#include "Logger.h"
#include <QtGlobal>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDir>
#include <QTime>
#include <fstream>
#include <iostream>
using namespace std;
ofstream logfile;
namespace Logging {
void logHandler(QtMsgType type, const char *msg) {
logfile << QTime::currentTime().toString().toUtf8().data();
switch (type) {
case QtDebugMsg:
logfile << " Debug: " << msg << endl;
break;
case QtCriticalMsg:
logfile << " Critical: " << msg << endl;
break;
case QtWarningMsg:
logfile << " Warning: " << msg << endl;
break;
case QtFatalMsg:
logfile << " Fatal: " << msg << endl;
abort();
}
logfile.flush();
cout << QTime::currentTime().toString().toUtf8().data() << "\t" << msg << endl << flush;
}
QDir
loggingDirectory()
{
#ifdef Q_OS_LINUX
return QDir::home().filePath( ".local/share/Zulip" );
#elif defined(Q_OS_WIN)
return QDir(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
#elif defined(Q_OS_MAC)
return QDir( QDir::homePath() + "/Library/Logs" );
#endif
}
void setupLogging() {
QDir logFileDir = loggingDirectory();
logFileDir.mkpath(logFileDir.absolutePath());
const QString filePath = logFileDir.absoluteFilePath("Zulip.log");
logfile.open( filePath.toLocal8Bit(), ios::app );
cout.flush();
qInstallMsgHandler( logHandler );
}
}
<commit_msg>Hide Warning and Debug messages from console<commit_after>#include "Logger.h"
#include <QtGlobal>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDir>
#include <QTime>
#include <fstream>
#include <iostream>
using namespace std;
ofstream logfile;
namespace Logging {
void logHandler(QtMsgType type, const char *msg) {
logfile << QTime::currentTime().toString().toUtf8().data();
switch (type) {
case QtDebugMsg:
logfile << " Debug: " << msg << endl;
break;
case QtCriticalMsg:
logfile << " Critical: " << msg << endl;
break;
case QtWarningMsg:
logfile << " Warning: " << msg << endl;
break;
case QtFatalMsg:
logfile << " Fatal: " << msg << endl;
abort();
}
logfile.flush();
// Only show Critical and Fatal debug messages on the console
if ((type == QtDebugMsg || type == QtWarningMsg)) {
return;
}
cout << QTime::currentTime().toString().toUtf8().data() << "\t" << msg << endl << flush;
}
QDir
loggingDirectory()
{
#ifdef Q_OS_LINUX
return QDir::home().filePath( ".local/share/Zulip" );
#elif defined(Q_OS_WIN)
return QDir(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
#elif defined(Q_OS_MAC)
return QDir( QDir::homePath() + "/Library/Logs" );
#endif
}
void setupLogging() {
QDir logFileDir = loggingDirectory();
logFileDir.mkpath(logFileDir.absolutePath());
const QString filePath = logFileDir.absoluteFilePath("Zulip.log");
logfile.open( filePath.toLocal8Bit(), ios::app );
cout.flush();
qInstallMsgHandler( logHandler );
}
}
<|endoftext|> |
<commit_before>#include "Logger.hpp"
#include "CAmxDebugManager.hpp"
#include "LogManager.hpp"
#include "amx/amx2.h"
#include <fmt/format.h>
Logger::Logger(std::string modulename) :
_module_name(std::move(modulename))
{
LogConfigReader::Get()->GetLoggerConfig(_module_name, _config);
LogManager::Get()->RegisterLogger(this);
}
Logger::~Logger()
{
LogManager::Get()->UnregisterLogger(this);
}
bool Logger::Log(LogLevel level, const char *msg,
std::vector<samplog::AmxFuncCallInfo> const &call_info)
{
if (!IsLogLevel(level))
return false;
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, level, msg ? msg : "", std::vector<samplog::AmxFuncCallInfo>(call_info))));
return true;
}
bool Logger::Log(LogLevel level, const char *msg)
{
if (!IsLogLevel(level))
return false;
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, level, msg ? msg : "", { })));
return true;
}
bool Logger::LogNativeCall(AMX * const amx, cell * const params,
const char *name, const char *params_format)
{
if (amx == nullptr)
return false;
if (params == nullptr)
return false;
if (name == nullptr || strlen(name) == 0)
return false;
if (params_format == nullptr) // params_format == "" is valid (no parameters)
return false;
if (!IsLogLevel(LogLevel::DEBUG))
return false;
size_t format_len = strlen(params_format);
fmt::MemoryWriter fmt_msg;
fmt_msg << name << '(';
for (int i = 0; i != format_len; ++i)
{
if (i != 0)
fmt_msg << ", ";
cell current_param = params[i + 1];
switch (params_format[i])
{
case 'd': //decimal
case 'i': //integer
fmt_msg << static_cast<int>(current_param);
break;
case 'f': //float
fmt_msg << amx_ctof(current_param);
break;
case 'h': //hexadecimal
case 'x': //
fmt_msg << fmt::hex(current_param);
break;
case 'b': //binary
fmt_msg << fmt::bin(current_param);
break;
case 's': //string
fmt_msg << '"' << amx_GetCppString(amx, current_param) << '"';
break;
case '*': //censored output
fmt_msg << "\"*****\"";
break;
case 'r': //reference
{
cell *addr_dest = nullptr;
amx_GetAddr(amx, current_param, &addr_dest);
fmt_msg << "0x" << fmt::pad(fmt::hexu(reinterpret_cast<unsigned int>(addr_dest)), 8, '0');
} break;
case 'p': //pointer-value
fmt_msg << "0x" << fmt::pad(fmt::hexu(current_param), 8, '0');
break;
default:
return false; //unrecognized format specifier
}
}
fmt_msg << ')';
std::vector<samplog::AmxFuncCallInfo> call_info;
CAmxDebugManager::Get()->GetFunctionCallTrace(amx, call_info);
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, LogLevel::DEBUG, fmt_msg.str(), std::move(call_info))));
return true;
}
samplog::ILogger *samplog_CreateLogger(const char *module)
{
return new Logger(module);
}
<commit_msg>prohibit use of internal log-core logger name<commit_after>#include "Logger.hpp"
#include "CAmxDebugManager.hpp"
#include "LogManager.hpp"
#include "amx/amx2.h"
#include <fmt/format.h>
#include <cstring>
Logger::Logger(std::string modulename) :
_module_name(std::move(modulename))
{
LogConfigReader::Get()->GetLoggerConfig(_module_name, _config);
LogManager::Get()->RegisterLogger(this);
}
Logger::~Logger()
{
LogManager::Get()->UnregisterLogger(this);
}
bool Logger::Log(LogLevel level, const char *msg,
std::vector<samplog::AmxFuncCallInfo> const &call_info)
{
if (!IsLogLevel(level))
return false;
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, level, msg ? msg : "", std::vector<samplog::AmxFuncCallInfo>(call_info))));
return true;
}
bool Logger::Log(LogLevel level, const char *msg)
{
if (!IsLogLevel(level))
return false;
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, level, msg ? msg : "", { })));
return true;
}
bool Logger::LogNativeCall(AMX * const amx, cell * const params,
const char *name, const char *params_format)
{
if (amx == nullptr)
return false;
if (params == nullptr)
return false;
if (name == nullptr || strlen(name) == 0)
return false;
if (params_format == nullptr) // params_format == "" is valid (no parameters)
return false;
if (!IsLogLevel(LogLevel::DEBUG))
return false;
size_t format_len = strlen(params_format);
fmt::MemoryWriter fmt_msg;
fmt_msg << name << '(';
for (int i = 0; i != format_len; ++i)
{
if (i != 0)
fmt_msg << ", ";
cell current_param = params[i + 1];
switch (params_format[i])
{
case 'd': //decimal
case 'i': //integer
fmt_msg << static_cast<int>(current_param);
break;
case 'f': //float
fmt_msg << amx_ctof(current_param);
break;
case 'h': //hexadecimal
case 'x': //
fmt_msg << fmt::hex(current_param);
break;
case 'b': //binary
fmt_msg << fmt::bin(current_param);
break;
case 's': //string
fmt_msg << '"' << amx_GetCppString(amx, current_param) << '"';
break;
case '*': //censored output
fmt_msg << "\"*****\"";
break;
case 'r': //reference
{
cell *addr_dest = nullptr;
amx_GetAddr(amx, current_param, &addr_dest);
fmt_msg << "0x" << fmt::pad(fmt::hexu(reinterpret_cast<unsigned int>(addr_dest)), 8, '0');
} break;
case 'p': //pointer-value
fmt_msg << "0x" << fmt::pad(fmt::hexu(current_param), 8, '0');
break;
default:
return false; //unrecognized format specifier
}
}
fmt_msg << ')';
std::vector<samplog::AmxFuncCallInfo> call_info;
CAmxDebugManager::Get()->GetFunctionCallTrace(amx, call_info);
LogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
_module_name, LogLevel::DEBUG, fmt_msg.str(), std::move(call_info))));
return true;
}
samplog::ILogger *samplog_CreateLogger(const char *module)
{
if (strstr(module, "log-core") != nullptr)
return nullptr;
return new Logger(module);
}
<|endoftext|> |
<commit_before>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Object.h"
#include "Scene.h"
using namespace std;
namespace Magnum {
void Object::setParent(Object* parent) {
if(_parent == parent) return;
/* Set new parent and add the object to new parent children list */
if(parent != nullptr) {
/* Only Fry can be his own grandfather */
Object* p = parent;
while(p != nullptr && p->parent() != p) {
if(p == this) return;
p = p->parent();
}
parent->_children.insert(this);
}
/* Remove the object from old parent children list */
if(_parent != nullptr)
_parent->_children.erase(this);
_parent = parent;
setDirty();
}
Matrix4 Object::absoluteTransformation(Camera* camera) {
Matrix4 t = _transformation;
/* Shortcut for absolute transformation of camera relative to itself */
if(camera == this) return Matrix4();
Object* p = parent();
while(p != nullptr) {
t = p->transformation()*t;
/* We got to the scene, multiply with camera matrix */
if(p->parent() == p) {
if(camera && camera->scene() == scene())
t = camera->cameraMatrix()*t;
break;
}
p = p->parent();
}
return t;
}
Object::~Object() {
/* Remove the object from parent's children */
setParent(nullptr);
/* Delete all children */
for(set<Object*>::const_iterator it = _children.begin(); it != _children.end(); ++it)
delete *it;
}
Scene* Object::scene() const {
/* Goes up the family tree until it finds object which is parent of itself
(that's the scene) */
Object* p = parent();
while(p != nullptr) {
if(p->parent() == p) return static_cast<Scene*>(p);
p = p->parent();
}
return nullptr;
}
void Object::setDirty() {
/* The object (and all its children) are already dirty, nothing to do */
if(dirty) return;
dirty = true;
/* Make all children dirty */
for(set<Object*>::iterator it = _children.begin(); it != _children.end(); ++it)
(*it)->setDirty();
}
void Object::setClean() {
/* The object (and all its parents) is already clean, nothing to do */
if(!dirty) return;
dirty = false;
/* Make all parents clean */
if(_parent != nullptr && _parent != this) _parent->setClean();
}
}
<commit_msg>Fixed crash on deletion of Object children.<commit_after>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Object.h"
#include "Scene.h"
using namespace std;
namespace Magnum {
void Object::setParent(Object* parent) {
if(_parent == parent) return;
/* Set new parent and add the object to new parent children list */
if(parent != nullptr) {
/* Only Fry can be his own grandfather */
Object* p = parent;
while(p != nullptr && p->parent() != p) {
if(p == this) return;
p = p->parent();
}
parent->_children.insert(this);
}
/* Remove the object from old parent children list */
if(_parent != nullptr)
_parent->_children.erase(this);
_parent = parent;
setDirty();
}
Matrix4 Object::absoluteTransformation(Camera* camera) {
Matrix4 t = _transformation;
/* Shortcut for absolute transformation of camera relative to itself */
if(camera == this) return Matrix4();
Object* p = parent();
while(p != nullptr) {
t = p->transformation()*t;
/* We got to the scene, multiply with camera matrix */
if(p->parent() == p) {
if(camera && camera->scene() == scene())
t = camera->cameraMatrix()*t;
break;
}
p = p->parent();
}
return t;
}
Object::~Object() {
/* Remove the object from parent's children */
setParent(nullptr);
/* Delete all children */
while(!_children.empty())
delete *_children.begin();
}
Scene* Object::scene() const {
/* Goes up the family tree until it finds object which is parent of itself
(that's the scene) */
Object* p = parent();
while(p != nullptr) {
if(p->parent() == p) return static_cast<Scene*>(p);
p = p->parent();
}
return nullptr;
}
void Object::setDirty() {
/* The object (and all its children) are already dirty, nothing to do */
if(dirty) return;
dirty = true;
/* Make all children dirty */
for(set<Object*>::iterator it = _children.begin(); it != _children.end(); ++it)
(*it)->setDirty();
}
void Object::setClean() {
/* The object (and all its parents) is already clean, nothing to do */
if(!dirty) return;
dirty = false;
/* Make all parents clean */
if(_parent != nullptr && _parent != this) _parent->setClean();
}
}
<|endoftext|> |
<commit_before>// -*- mode: c++, coding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012 Mattias Andrée ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __GUARD_OBJECT_HPP__
#define __GUARD_OBJECT_HPP__
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <unordered_map>
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <[email protected]>
*/
namespace tbrpg
{
/**
* Master super class
*/
class Object
{
public:
/**
* Class inheritance vector
*/
std::vector<short> class_inheritance;
/**
* Construction
*/
Object();
/**
* Copy constructor
*
* @param original The object to clone
*/
Object(const Object& original);
/**
* Copy constructor
*
* @param original The object to clone
*/
Object(Object& original);
/**
* Move constructor
*
* @param original The object to clone
*/
Object(Object&& original);
/**
* Destructor
*/
virtual ~Object();
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
virtual Object& operator =(const Object& original);
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
virtual Object& operator =(Object& original);
/**
* Move operator
*
* @param original The moved object, its resourced will be moved
* @return The invoked object
*/
virtual Object& operator =(Object&& original);
/**
* Equality evaluator
*
* @param other The other comparand
* @return Whether the instances are equal
*/
virtual bool operator ==(const Object& other) const;
/**
* 'Instance of' evaluator
*
* @param other The other comparand
* @return Whether the left comparand is an instance of the right comparand's class
*/
virtual bool operator >=(const Object& other) const;
/**
* Reversed 'instance of' evaluator
*
* @param other The other comparand
* @return Whether the right comparand is an instance of the left comparand's class
*/
virtual bool operator <=(const Object& other) const;
protected:
/**
* Copy method
*
* @param self The object to modify
* @param original The reference object
*/
static void __copy__(Object& self, const Object& original);
public:
/**
* Hash method
*
* @return The object's hash code
*/
size_t hash() const;
};
}
namespace std
{
template<>
class hash<tbrpg::Object>
{
public:
size_t operator()(const tbrpg::Object& elem) const
{
return elem.hash();
}
};
}
#endif//__GUARD_OBJECT_HPP__
<commit_msg>m<commit_after>// -*- mode: c++, coding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012 Mattias Andrée ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __GUARD_OBJECT_HPP__
#define __GUARD_OBJECT_HPP__
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <unordered_map>
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <[email protected]>
*/
namespace tbrpg
{
/**
* Master super class
*/
class Object
{
public:
/**
* Class inheritance vector
*/
std::vector<short> class_inheritance;
/**
* Construction
*/
Object();
/**
* Copy constructor
*
* @param original The object to clone
*/
Object(const Object& original);
/**
* Copy constructor
*
* @param original The object to clone
*/
Object(Object& original);
/**
* Move constructor
*
* @param original The object to clone
*/
Object(Object&& original);
/**
* Destructor
*/
virtual ~Object();
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
virtual Object& operator =(const Object& original);
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
virtual Object& operator =(Object& original);
/**
* Move operator
*
* @param original The moved object, its resourced will be moved
* @return The invoked object
*/
virtual Object& operator =(Object&& original);
/**
* Equality evaluator
*
* @param other The other comparand
* @return Whether the instances are equal
*/
virtual bool operator ==(const Object& other) const;
/**
* 'Instance of' evaluator
*
* @param other The other comparand
* @return Whether the left comparand is an instance of the right comparand's class
*/
bool operator >=(const Object& other) const;
/**
* Reversed 'instance of' evaluator
*
* @param other The other comparand
* @return Whether the right comparand is an instance of the left comparand's class
*/
bool operator <=(const Object& other) const;
protected:
/**
* Copy method
*
* @param self The object to modify
* @param original The reference object
*/
static void __copy__(Object& self, const Object& original);
public:
/**
* Hash method
*
* @return The object's hash code
*/
size_t hash() const;
};
}
namespace std
{
template<>
class hash<tbrpg::Object>
{
public:
size_t operator()(const tbrpg::Object& elem) const
{
return elem.hash();
}
};
}
#endif//__GUARD_OBJECT_HPP__
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------//
//!
//! \file Utility_TetrahedronHelpers.cpp
//! \author Alex Robinson, Eli Moll
//! \brief Tetrahedron helper functions
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <math.h>
// Trilinos Includes
#include <Teuchos_ScalarTraits.hpp>
// FRENSIE Includes
#include "Utility_TetrahedronHelpers.hpp"
#include "Utility_ContractException.hpp"
#include <moab/Matrix3.hpp>
namespace Utility{
// Calculate the volume of a tetrahedron
double calculateTetrahedronVolume( const double vertex_a[3],
const double vertex_b[3],
const double vertex_c[3],
const double vertex_d[3] )
{
double a1 = vertex_a[0] - vertex_d[0];
double a2 = vertex_a[1] - vertex_d[1];
double a3 = vertex_a[2] - vertex_d[2];
double b1 = vertex_b[0] - vertex_d[0];
double b2 = vertex_b[1] - vertex_d[1];
double b3 = vertex_b[2] - vertex_d[2];
double c1 = vertex_c[0] - vertex_d[0];
double c2 = vertex_c[1] - vertex_d[1];
double c3 = vertex_c[2] - vertex_d[2];
double volume =
fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0;
testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) );
testPostcondition( volume > 0.0 );
return volume;
}
// Calculate the Barycentric Transform Matrix
double* calculateBarycentricTransformMatrix( const double vertex_a[3],
const double vertex_b[3],
const double vertex_c[3],
const double vertex_d[3] )
{
double t1 = 1.0;//vertex_a[0] - vertex_d[0];
double t2 = 5.0;//vertex_b[0] - vertex_d[0];
double t3 = 1.0;//vertex_c[0] - vertex_d[0];
double t4 = 1.0;//vertex_a[1] - vertex_d[1];
double t5 = 1.0;//vertex_b[1] - vertex_d[1];
double t6 = 1.0;//vertex_c[1] - vertex_d[1];
double t7 = 1.0;//vertex_a[2] - vertex_d[2];
double t8 = 1.0;//vertex_b[2] - vertex_d[2];
double t9 = 0.0;//vertex_c[2] - vertex_d[2];
double* t[9] = { t1, t2, t3, t4, t5, t6, t7, t8, t9 };
moab::Matrix3 T( t );
return T.array();
}
} // end Utility namespace
//---------------------------------------------------------------------------//
// end Utility_TetrahedronHelpers.cpp
//---------------------------------------------------------------------------//
<commit_msg>Arraytrans<commit_after>//---------------------------------------------------------------------------//
//!
//! \file Utility_TetrahedronHelpers.cpp
//! \author Alex Robinson, Eli Moll
//! \brief Tetrahedron helper functions
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <math.h>
// Trilinos Includes
#include <Teuchos_ScalarTraits.hpp>
// FRENSIE Includes
#include "Utility_TetrahedronHelpers.hpp"
#include "Utility_ContractException.hpp"
#include <moab/Matrix3.hpp>
namespace Utility{
// Calculate the volume of a tetrahedron
double calculateTetrahedronVolume( const double vertex_a[3],
const double vertex_b[3],
const double vertex_c[3],
const double vertex_d[3] )
{
double a1 = vertex_a[0] - vertex_d[0];
double a2 = vertex_a[1] - vertex_d[1];
double a3 = vertex_a[2] - vertex_d[2];
double b1 = vertex_b[0] - vertex_d[0];
double b2 = vertex_b[1] - vertex_d[1];
double b3 = vertex_b[2] - vertex_d[2];
double c1 = vertex_c[0] - vertex_d[0];
double c2 = vertex_c[1] - vertex_d[1];
double c3 = vertex_c[2] - vertex_d[2];
double volume =
fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0;
testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) );
testPostcondition( volume > 0.0 );
return volume;
}
// Calculate the Barycentric Transform Matrix
double* calculateBarycentricTransformMatrix( const double vertex_a[3],
const double vertex_b[3],
const double vertex_c[3],
const double vertex_d[3] )
{
double t1 = 1.0;//vertex_a[0] - vertex_d[0];
double t2 = 5.0;//vertex_b[0] - vertex_d[0];
double t3 = 1.0;//vertex_c[0] - vertex_d[0];
double t4 = 1.0;//vertex_a[1] - vertex_d[1];
double t5 = 1.0;//vertex_b[1] - vertex_d[1];
double t6 = 1.0;//vertex_c[1] - vertex_d[1];
double t7 = 1.0;//vertex_a[2] - vertex_d[2];
double t8 = 1.0;//vertex_b[2] - vertex_d[2];
double t9 = 1.0;//vertex_c[2] - vertex_d[2];
moab::Matrix3 T( t1, t2, t3, t4, t5, t6, t7, t8, t9 );
return T.array();
}
} // end Utility namespace
//---------------------------------------------------------------------------//
// end Utility_TetrahedronHelpers.cpp
//---------------------------------------------------------------------------//
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* 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
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#define eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/curve/piecewise_creator.hpp"
#include "eli/geom/surface/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
bool create_body_of_revolution(piecewise<bezier, data__, dim__, tol__> &ps,
const eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, dim__, tol__> &pc,
int axis, bool outward_normal)
{
typedef piecewise<bezier, data__, dim__, tol__> piecewise_surface_type;
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, dim__, tol__> piecewise_curve_type;
typedef eli::geom::curve::piecewise_circle_creator<data__, dim__, tol__> circle_creator_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_surface_type::surface_type surface_type;
typedef typename curve_type::point_type point_type;
typedef typename curve_type::data_type data_type;
typedef typename curve_type::index_type index_type;
curve_type c, arc;
surface_type s[4];
piecewise_curve_type pc_circle;
point_type origin, normal, start;
data_type du, dv;
index_type i, j, pp, qq, nu=pc.number_segments(), nv=4, udim, vdim;
// resize the surface
ps.init_uv(nu, nv);
// set the axis of rotation
switch(axis)
{
case(0):
{
normal << 1, 0, 0;
break;
}
case(1):
{
normal << 0, 1, 0;
break;
}
case(2):
{
normal << 0, 0, 1;
break;
}
default:
{
assert(false);
return false;
}
}
if (outward_normal)
{
normal*=-1;
}
// cycle through each curve segment
circle_creator_type circle_creator;
for (pp=0; pp<nu; ++pp)
{
// resize the surface patch
udim=c.dimension();
vdim=3;
pc.get(c, du, pp);
s[0].resize(udim, vdim);
s[1].resize(udim, vdim);
s[2].resize(udim, vdim);
s[3].resize(udim, vdim);
// cycle through each control point in current curve and create patch control points
for (i=0; i<=udim; ++i)
{
// set up the vectors for this circle
start=c.get_control_point(i);
origin=normal.dot(start)*normal;
// get the circle
circle_creator.set(start, origin, normal);
if (!circle_creator.create(pc_circle))
{
assert(false);
return false;
}
// for each segment of circle set the control points
for (qq=0; qq<4; ++qq)
{
pc_circle.get(arc, dv, qq);
for (j=0; j<4; ++j)
{
s[qq].set_control_point(arc.get_control_point(j), i, j);
}
}
}
// set the surface patches
for (qq=0; qq<4; ++qq)
{
ps.set(s[qq], pp, qq);
}
}
return true;
}
}
}
}
#endif
<commit_msg>Pass option to match curve u-parameterization when revolving.<commit_after>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* 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
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#define eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/curve/piecewise_creator.hpp"
#include "eli/geom/surface/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
bool create_body_of_revolution(piecewise<bezier, data__, dim__, tol__> &ps,
const eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, dim__, tol__> &pc,
int axis, bool outward_normal, bool match_uparm = false)
{
typedef piecewise<bezier, data__, dim__, tol__> piecewise_surface_type;
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, dim__, tol__> piecewise_curve_type;
typedef eli::geom::curve::piecewise_circle_creator<data__, dim__, tol__> circle_creator_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_surface_type::surface_type surface_type;
typedef typename curve_type::point_type point_type;
typedef typename curve_type::data_type data_type;
typedef typename curve_type::index_type index_type;
curve_type c, arc;
surface_type s[4];
piecewise_curve_type pc_circle;
point_type origin, normal, start;
data_type du, dv;
index_type i, j, pp, qq, nu=pc.number_segments(), nv=4, udim, vdim;
// resize the surface
if ( match_uparm )
{
vector<data_type> umap, du;
pc.get_pmap( umap );
for ( i = 0; i < nu; i++ )
{
du.push_back( umap[ i + 1 ] - umap[ i ] );
}
ps.init_uv( du.begin(), du.end(), nv, 1, umap[0] );
}
else
{
ps.init_uv(nu, nv);
}
// set the axis of rotation
switch(axis)
{
case(0):
{
normal << 1, 0, 0;
break;
}
case(1):
{
normal << 0, 1, 0;
break;
}
case(2):
{
normal << 0, 0, 1;
break;
}
default:
{
assert(false);
return false;
}
}
if (outward_normal)
{
normal*=-1;
}
// cycle through each curve segment
circle_creator_type circle_creator;
for (pp=0; pp<nu; ++pp)
{
// resize the surface patch
udim=c.dimension();
vdim=3;
pc.get(c, du, pp);
s[0].resize(udim, vdim);
s[1].resize(udim, vdim);
s[2].resize(udim, vdim);
s[3].resize(udim, vdim);
// cycle through each control point in current curve and create patch control points
for (i=0; i<=udim; ++i)
{
// set up the vectors for this circle
start=c.get_control_point(i);
origin=normal.dot(start)*normal;
// get the circle
circle_creator.set(start, origin, normal);
if (!circle_creator.create(pc_circle))
{
assert(false);
return false;
}
// for each segment of circle set the control points
for (qq=0; qq<4; ++qq)
{
pc_circle.get(arc, dv, qq);
for (j=0; j<4; ++j)
{
s[qq].set_control_point(arc.get_control_point(j), i, j);
}
}
}
// set the surface patches
for (qq=0; qq<4; ++qq)
{
ps.set(s[qq], pp, qq);
}
}
return true;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlanchorbindingproxy.h"
#include <qmlanchors.h>
#include <nodeabstractproperty.h>
#include <nodeinstance.h>
#include <QDebug>
namespace QmlDesigner {
class ModelNode;
class NodeState;
namespace Internal {
QmlAnchorBindingProxy::QmlAnchorBindingProxy(QObject *parent) :
QObject(parent)
{
}
QmlAnchorBindingProxy::~QmlAnchorBindingProxy()
{
}
void QmlAnchorBindingProxy::setup(const QmlItemNode &fxItemNode)
{
m_fxItemNode = fxItemNode;
m_verticalTarget = m_horizontalTarget = m_topTarget = m_bottomTarget = m_leftTarget = m_rightTarget = m_fxItemNode.modelNode().parentProperty().parentModelNode();
if (topAnchored())
m_topTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
if (bottomAnchored())
m_bottomTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
if (leftAnchored())
m_leftTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
if (rightAnchored())
m_rightTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
if (verticalCentered())
m_verticalTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
if (horizontalCentered())
m_horizontalTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
emit parentChanged();
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit centeredHChanged();
emit centeredVChanged();
emit anchorsChanged();
if (m_fxItemNode.hasNodeParent()) {
emit itemNodeChanged();
emit topTargetChanged();
emit bottomTargetChanged();
emit leftTargetChanged();
emit rightTargetChanged();
emit verticalTargetChanged();
emit horizontalTargetChanged();
}
}
bool QmlAnchorBindingProxy::hasParent()
{
return m_fxItemNode.isValid() && m_fxItemNode.hasNodeParent();
}
bool QmlAnchorBindingProxy::topAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Top);
}
bool QmlAnchorBindingProxy::bottomAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Bottom);
}
bool QmlAnchorBindingProxy::leftAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Left);
}
bool QmlAnchorBindingProxy::rightAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Right);
}
bool QmlAnchorBindingProxy::hasAnchors()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchors();
}
void QmlAnchorBindingProxy::setTopTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_topTarget)
return;
m_topTarget = newTarget;
calcTopMargin();
emit topTargetChanged();
}
void QmlAnchorBindingProxy::setBottomTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_bottomTarget)
return;
m_bottomTarget = newTarget;
calcBottomMargin();
emit bottomTargetChanged();
}
void QmlAnchorBindingProxy::setLeftTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_leftTarget)
return;
m_leftTarget = newTarget;
calcLeftMargin();
emit leftTargetChanged();
}
void QmlAnchorBindingProxy::setRightTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_rightTarget)
return;
m_rightTarget = newTarget;
calcRightMargin();
emit rightTargetChanged();
}
void QmlAnchorBindingProxy::setVerticalTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_verticalTarget)
return;
m_verticalTarget = newTarget;
m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_verticalTarget, AnchorLine::VerticalCenter);
emit verticalTargetChanged();
}
void QmlAnchorBindingProxy::setHorizontalTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_horizontalTarget)
return;
m_horizontalTarget = newTarget;
m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_horizontalTarget, AnchorLine::HorizontalCenter);
emit horizontalTargetChanged();
}
void QmlAnchorBindingProxy::resetLayout() {
m_fxItemNode.anchors().removeAnchors();
m_fxItemNode.anchors().removeMargins();
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setBottomAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (bottomAnchored() == anchor)
return;
if (!anchor) {
removeBottomAnchor();
} else {
calcBottomMargin();
}
emit bottomAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setLeftAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (leftAnchored() == anchor)
return;
if (!anchor) {
removeLeftAnchor();
} else {
calcLeftMargin();
}
emit leftAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (rightAnchored() == anchor)
return;
if (!anchor) {
removeRightAnchor();
} else {
calcRightMargin();
}
emit rightAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
QRectF QmlAnchorBindingProxy::parentBoundingBox()
{
if (m_fxItemNode.hasInstanceParent())
return m_fxItemNode.instanceParent().toQmlItemNode().instanceBoundingRect();
return QRect();
}
QRectF QmlAnchorBindingProxy::boundingBox(QmlItemNode node)
{
if (node.isValid())
return node.instanceTransform().mapRect(node.instanceBoundingRect());
return QRect();
}
QRectF QmlAnchorBindingProxy::transformedBoundingBox()
{
return m_fxItemNode.instanceTransform().mapRect(m_fxItemNode.instanceBoundingRect());
}
void QmlAnchorBindingProxy::calcTopMargin()
{
if (m_topTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal topMargin = transformedBoundingBox().top() - parentBoundingBox().top();
m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Top);
} else {
qDebug() << boundingBox(m_fxItemNode).top();
qDebug() << boundingBox(m_topTarget).bottom();
qreal topMargin = boundingBox(m_fxItemNode).top() - boundingBox(m_topTarget).bottom();
m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Bottom);
}
}
void QmlAnchorBindingProxy::calcBottomMargin()
{
if (m_bottomTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal bottomMargin = parentBoundingBox().bottom() - transformedBoundingBox().bottom();
m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Bottom);
} else {
qreal bottomMargin = boundingBox(m_fxItemNode).bottom() - boundingBox(m_rightTarget).top();
m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Top);
}
}
void QmlAnchorBindingProxy::calcLeftMargin()
{
if (m_leftTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal leftMargin = transformedBoundingBox().left() - parentBoundingBox().left();
m_fxItemNode.anchors().setMargin(AnchorLine::Left, leftMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Left);
} else {
qreal leftMargin = boundingBox(m_fxItemNode).left() - boundingBox(m_leftTarget).right();
m_fxItemNode.anchors().setMargin( AnchorLine::Left, leftMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Right);
}
}
void QmlAnchorBindingProxy::calcRightMargin()
{
if (m_rightTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal rightMargin = transformedBoundingBox().right() - parentBoundingBox().right();
m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Right);
} else {
qreal rightMargin = boundingBox(m_rightTarget).left() - boundingBox(m_fxItemNode).right();
m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Left);
}
}
void QmlAnchorBindingProxy::setTopAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (topAnchored() == anchor)
return;
if (!anchor) {
removeTopAnchor();
} else {
calcTopMargin();
}
emit topAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::removeTopAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Top);
m_fxItemNode.anchors().removeMargin(AnchorLine::Top);
}
void QmlAnchorBindingProxy::removeBottomAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Bottom);
m_fxItemNode.anchors().removeMargin(AnchorLine::Bottom);
}
void QmlAnchorBindingProxy::removeLeftAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Left);
m_fxItemNode.anchors().removeMargin(AnchorLine::Left);
}
void QmlAnchorBindingProxy::removeRightAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Right);
m_fxItemNode.anchors().removeMargin(AnchorLine::Right);
}
void QmlAnchorBindingProxy::setVerticalCentered(bool centered)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (verticalCentered() == centered)
return;
if (!centered) {
m_fxItemNode.anchors().removeAnchor(AnchorLine::VerticalCenter);
m_fxItemNode.anchors().removeMargin(AnchorLine::VerticalCenter);
} else {
m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::VerticalCenter);
}
emit centeredVChanged();
}
void QmlAnchorBindingProxy::setHorizontalCentered(bool centered)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (horizontalCentered() == centered)
return;
if (!centered) {
m_fxItemNode.anchors().removeAnchor(AnchorLine::HorizontalCenter);
m_fxItemNode.anchors().removeMargin(AnchorLine::HorizontalCenter);
} else {
m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::HorizontalCenter);
}
emit centeredHChanged();
}
bool QmlAnchorBindingProxy::verticalCentered()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::VerticalCenter);
}
bool QmlAnchorBindingProxy::horizontalCentered()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::HorizontalCenter);
}
void QmlAnchorBindingProxy::fill()
{
m_fxItemNode.anchors().fill();
setHorizontalCentered(false);
setVerticalCentered(false);
m_fxItemNode.anchors().setMargin(AnchorLine::Right, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Left, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Top, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Bottom, 0);
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit anchorsChanged();
}
} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner.propertyEditor: fixes bug in marging calulation<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlanchorbindingproxy.h"
#include <qmlanchors.h>
#include <nodeabstractproperty.h>
#include <nodeinstance.h>
#include <QDebug>
namespace QmlDesigner {
class ModelNode;
class NodeState;
namespace Internal {
QmlAnchorBindingProxy::QmlAnchorBindingProxy(QObject *parent) :
QObject(parent)
{
}
QmlAnchorBindingProxy::~QmlAnchorBindingProxy()
{
}
void QmlAnchorBindingProxy::setup(const QmlItemNode &fxItemNode)
{
m_fxItemNode = fxItemNode;
m_verticalTarget = m_horizontalTarget = m_topTarget = m_bottomTarget = m_leftTarget = m_rightTarget = m_fxItemNode.modelNode().parentProperty().parentModelNode();
if (topAnchored())
m_topTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
if (bottomAnchored())
m_bottomTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
if (leftAnchored())
m_leftTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
if (rightAnchored())
m_rightTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
if (verticalCentered())
m_verticalTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
if (horizontalCentered())
m_horizontalTarget = m_fxItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
emit parentChanged();
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit centeredHChanged();
emit centeredVChanged();
emit anchorsChanged();
if (m_fxItemNode.hasNodeParent()) {
emit itemNodeChanged();
emit topTargetChanged();
emit bottomTargetChanged();
emit leftTargetChanged();
emit rightTargetChanged();
emit verticalTargetChanged();
emit horizontalTargetChanged();
}
}
bool QmlAnchorBindingProxy::hasParent()
{
return m_fxItemNode.isValid() && m_fxItemNode.hasNodeParent();
}
bool QmlAnchorBindingProxy::topAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Top);
}
bool QmlAnchorBindingProxy::bottomAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Bottom);
}
bool QmlAnchorBindingProxy::leftAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Left);
}
bool QmlAnchorBindingProxy::rightAnchored()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Right);
}
bool QmlAnchorBindingProxy::hasAnchors()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchors();
}
void QmlAnchorBindingProxy::setTopTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_topTarget)
return;
m_topTarget = newTarget;
calcTopMargin();
emit topTargetChanged();
}
void QmlAnchorBindingProxy::setBottomTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_bottomTarget)
return;
m_bottomTarget = newTarget;
calcBottomMargin();
emit bottomTargetChanged();
}
void QmlAnchorBindingProxy::setLeftTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_leftTarget)
return;
m_leftTarget = newTarget;
calcLeftMargin();
emit leftTargetChanged();
}
void QmlAnchorBindingProxy::setRightTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_rightTarget)
return;
m_rightTarget = newTarget;
calcRightMargin();
emit rightTargetChanged();
}
void QmlAnchorBindingProxy::setVerticalTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_verticalTarget)
return;
m_verticalTarget = newTarget;
m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_verticalTarget, AnchorLine::VerticalCenter);
emit verticalTargetChanged();
}
void QmlAnchorBindingProxy::setHorizontalTarget(const QVariant &target)
{
QmlItemNode newTarget(target.value<ModelNode>());
if (newTarget == m_horizontalTarget)
return;
m_horizontalTarget = newTarget;
m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_horizontalTarget, AnchorLine::HorizontalCenter);
emit horizontalTargetChanged();
}
void QmlAnchorBindingProxy::resetLayout() {
m_fxItemNode.anchors().removeAnchors();
m_fxItemNode.anchors().removeMargins();
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setBottomAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (bottomAnchored() == anchor)
return;
if (!anchor) {
removeBottomAnchor();
} else {
calcBottomMargin();
}
emit bottomAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setLeftAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (leftAnchored() == anchor)
return;
if (!anchor) {
removeLeftAnchor();
} else {
calcLeftMargin();
}
emit leftAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return;
if (rightAnchored() == anchor)
return;
if (!anchor) {
removeRightAnchor();
} else {
calcRightMargin();
}
emit rightAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
QRectF QmlAnchorBindingProxy::parentBoundingBox()
{
if (m_fxItemNode.hasInstanceParent())
return m_fxItemNode.instanceParent().toQmlItemNode().instanceBoundingRect();
return QRect();
}
QRectF QmlAnchorBindingProxy::boundingBox(QmlItemNode node)
{
if (node.isValid())
return node.instanceTransform().mapRect(node.instanceBoundingRect());
return QRect();
}
QRectF QmlAnchorBindingProxy::transformedBoundingBox()
{
return m_fxItemNode.instanceTransform().mapRect(m_fxItemNode.instanceBoundingRect());
}
void QmlAnchorBindingProxy::calcTopMargin()
{
if (m_topTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal topMargin = transformedBoundingBox().top() - parentBoundingBox().top();
m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Top);
} else {
qDebug() << boundingBox(m_fxItemNode).top();
qDebug() << boundingBox(m_topTarget).bottom();
qreal topMargin = boundingBox(m_fxItemNode).top() - boundingBox(m_topTarget).bottom();
m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Bottom);
}
}
void QmlAnchorBindingProxy::calcBottomMargin()
{
if (m_bottomTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal bottomMargin = parentBoundingBox().bottom() - transformedBoundingBox().bottom();
m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Bottom);
} else {
qreal bottomMargin = boundingBox(m_fxItemNode).bottom() - boundingBox(m_rightTarget).top();
m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Top);
}
}
void QmlAnchorBindingProxy::calcLeftMargin()
{
if (m_leftTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal leftMargin = transformedBoundingBox().left() - parentBoundingBox().left();
m_fxItemNode.anchors().setMargin(AnchorLine::Left, leftMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Left);
} else {
qreal leftMargin = boundingBox(m_fxItemNode).left() - boundingBox(m_leftTarget).right();
m_fxItemNode.anchors().setMargin( AnchorLine::Left, leftMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Right);
}
}
void QmlAnchorBindingProxy::calcRightMargin()
{
if (m_rightTarget == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
qreal rightMargin = parentBoundingBox().right() - transformedBoundingBox().right();
m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Right);
} else {
qreal rightMargin = boundingBox(m_rightTarget).left() - boundingBox(m_fxItemNode).right();
m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Left);
}
}
void QmlAnchorBindingProxy::setTopAnchor(bool anchor)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (topAnchored() == anchor)
return;
if (!anchor) {
removeTopAnchor();
} else {
calcTopMargin();
}
emit topAnchorChanged();
if (hasAnchors() != anchor)
emit anchorsChanged();
}
void QmlAnchorBindingProxy::removeTopAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Top);
m_fxItemNode.anchors().removeMargin(AnchorLine::Top);
}
void QmlAnchorBindingProxy::removeBottomAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Bottom);
m_fxItemNode.anchors().removeMargin(AnchorLine::Bottom);
}
void QmlAnchorBindingProxy::removeLeftAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Left);
m_fxItemNode.anchors().removeMargin(AnchorLine::Left);
}
void QmlAnchorBindingProxy::removeRightAnchor() {
m_fxItemNode.anchors().removeAnchor(AnchorLine::Right);
m_fxItemNode.anchors().removeMargin(AnchorLine::Right);
}
void QmlAnchorBindingProxy::setVerticalCentered(bool centered)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (verticalCentered() == centered)
return;
if (!centered) {
m_fxItemNode.anchors().removeAnchor(AnchorLine::VerticalCenter);
m_fxItemNode.anchors().removeMargin(AnchorLine::VerticalCenter);
} else {
m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::VerticalCenter);
}
emit centeredVChanged();
}
void QmlAnchorBindingProxy::setHorizontalCentered(bool centered)
{
if (!m_fxItemNode.hasNodeParent())
return ;
if (horizontalCentered() == centered)
return;
if (!centered) {
m_fxItemNode.anchors().removeAnchor(AnchorLine::HorizontalCenter);
m_fxItemNode.anchors().removeMargin(AnchorLine::HorizontalCenter);
} else {
m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::HorizontalCenter);
}
emit centeredHChanged();
}
bool QmlAnchorBindingProxy::verticalCentered()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::VerticalCenter);
}
bool QmlAnchorBindingProxy::horizontalCentered()
{
return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::HorizontalCenter);
}
void QmlAnchorBindingProxy::fill()
{
m_fxItemNode.anchors().fill();
setHorizontalCentered(false);
setVerticalCentered(false);
m_fxItemNode.anchors().setMargin(AnchorLine::Right, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Left, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Top, 0);
m_fxItemNode.anchors().setMargin(AnchorLine::Bottom, 0);
emit topAnchorChanged();
emit bottomAnchorChanged();
emit leftAnchorChanged();
emit rightAnchorChanged();
emit anchorsChanged();
}
} // namespace Internal
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>#include "card.h"
#include "localization.h"
#include <string>
#include <stdexcept>
#include <sstream>
std::string Card::_outputFormat = DEFAULT_OUTPUT_FORMAT;
Card::Card()
{
_name = CnNone;
_suit = CsNone;
_score = 0;
_outputFormat = DEFAULT_OUTPUT_FORMAT;
}
Card::Card(CardSuit suit, CardName name, unsigned int score)
{
_name = name;
_suit = suit;
SetScore(score);
_outputFormat = DEFAULT_OUTPUT_FORMAT;
}
std::string Card::GetFormattedName() const
{
if (!IsValid()) return "";
std::string temp(_outputFormat);
std::size_t pos = temp.find('N');
temp.erase(temp.begin()+pos);
temp.insert(pos, GetStr((Strings)(_name + 6)));
pos = temp.find('S');
temp.erase(temp.begin()+pos);
temp.insert(pos, GetStr((Strings)(_name + 1)));
return temp;
}
void Card::SetScore(unsigned int score)
{
if (score >= MIN_SCORE && score <= MAX_SCORE)
_score = score;
else
{
throw std::logic_error( "Invalid Score!" );
}
}
<commit_msg>Fixed ShowCard() in card.cpp<commit_after>#include "card.h"
#include "localization.h"
#include <string>
#include <stdexcept>
#include <sstream>
std::string Card::_outputFormat = DEFAULT_OUTPUT_FORMAT;
Card::Card()
{
_name = CnNone;
_suit = CsNone;
_score = 0;
_outputFormat = DEFAULT_OUTPUT_FORMAT;
}
Card::Card(CardSuit suit, CardName name, unsigned int score)
{
_name = name;
_suit = suit;
SetScore(score);
_outputFormat = DEFAULT_OUTPUT_FORMAT;
}
std::string Card::GetFormattedName() const
{
if (!IsValid()) return "";
std::string temp(_outputFormat);
std::size_t pos = temp.find('N');
temp.erase(temp.begin()+pos);
temp.insert(pos, GetStr((Strings)(_name + 6)));
pos = temp.find('S');
temp.erase(temp.begin()+pos);
temp.insert(pos, GetStr((Strings)(_suit + 1)));
return temp;
}
void Card::SetScore(unsigned int score)
{
if (score >= MIN_SCORE && score <= MAX_SCORE)
_score = score;
else
{
throw std::logic_error( "Invalid Score!" );
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImageRegistrationMethodTest_3.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImageRegistrationMethod.h"
#include "itkTranslationTransform.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
/**
* This program test one instantiation of the itk::ImageRegistrationMethod class
*
* Only typedef are tested in this file.
*/
int itkImageRegistrationMethodTest_3(int, char**)
{
bool pass = true;
const unsigned int dimension = 3;
// Fixed Image Type
typedef itk::Image<float,dimension> FixedImageType;
// Moving Image Type
typedef itk::Image<char,dimension> MovingImageType;
// Transform Type
typedef itk::TranslationTransform< double,dimension > TransformType;
// Optimizer Type
typedef itk::GradientDescentOptimizer OptimizerType;
// Metric Type
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Interpolation technique
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Registration Method
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
TransformType::Pointer trasform = TransformType::New();
FixedImageType::Pointer fixedImage = FixedImageType::New();
MovingImageType::Pointer movingImage = MovingImageType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImage );
registration->SetInterpolator( interpolator );
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: A full registration is performed now. Parameters are tunned.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImageRegistrationMethodTest_3.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImageRegistrationMethod.h"
#include "itkTranslationTransform.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
#include "itkCommandIterationUpdate.h"
#include "itkImageRegistrationMethodImageSource.h"
/**
* This program tests one instantiation of the itk::ImageRegistrationMethod class
*
*
*/
int itkImageRegistrationMethodTest_3(int argc, char** argv)
{
bool pass = true;
const unsigned int dimension = 2;
// Fixed Image Type
typedef itk::Image<float,dimension> FixedImageType;
// Moving Image Type
typedef itk::Image<float,dimension> MovingImageType;
// Size Type
typedef MovingImageType::SizeType SizeType;
// ImageSource
typedef itk::testhelper::ImageRegistrationMethodImageSource<
FixedImageType::PixelType,
MovingImageType::PixelType,
dimension > ImageSourceType;
// Transform Type
typedef itk::TranslationTransform< double, dimension > TransformType;
typedef TransformType::ParametersType ParametersType;
// Optimizer Type
typedef itk::GradientDescentOptimizer OptimizerType;
// Metric Type
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Interpolation technique
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Registration Method
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
typedef itk::CommandIterationUpdate<
OptimizerType > CommandIterationType;
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
TransformType::Pointer trasform = TransformType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
ImageSourceType::Pointer imageSource = ImageSourceType::New();
SizeType size;
size[0] = 100;
size[1] = 100;
imageSource->GenerateImages( size );
FixedImageType::ConstPointer fixedImage = imageSource->GetFixedImage();
MovingImageType::ConstPointer movingImage = imageSource->GetMovingImage();
//
// Connect all the components required for Registratio
//
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImage );
registration->SetInterpolator( interpolator );
// Select the Region of Interest over which the Metric will be computed
// Registration time will be proportional to the number of pixels in this region.
metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );
// Instantiate an Observer to report the progress of the Optimization
CommandIterationType::Pointer iterationCommand = CommandIterationType::New();
iterationCommand->SetOptimizer( optimizer.GetPointer() );
// Scale the translation components of the Transform in the Optimizer
OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );
scales.Fill( 1.0 );
unsigned long numberOfIterations = 50;
double translationScale = 1.0;
double learningRate = 1e-2;
if( argc > 1 )
{
numberOfIterations = atol( argv[1] );
std::cout << "numberOfIterations = " << numberOfIterations << std::endl;
}
if( argc > 2 )
{
translationScale = atof( argv[2] );
std::cout << "translationScale = " << translationScale << std::endl;
}
if( argc > 3 )
{
learningRate = atof( argv[3] );
std::cout << "learningRate = " << learningRate << std::endl;
}
for( unsigned int i=0; i<dimension; i++)
{
scales[ i + dimension * dimension ] = translationScale;
}
optimizer->SetScales( scales );
optimizer->SetLearningRate( learningRate );
optimizer->SetNumberOfIterations( numberOfIterations );
// Start from an Identity transform (in a normal case, the user
// can probably provide a better guess than the identity...
transform->SetIdentity();
registration->SetInitialTransformParameters( transform->GetParameters() );
// Initialize the internal connections of the registration method.
// This can potentially throw an exception
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & e )
{
std::cerr << e << std::endl;
pass = false;
}
ParametersType actualParameters = imageSource->GetActualParameters();
ParametersType finalParameters = registration->GetLastTransformParameters();
const unsigned int numbeOfParameters = actualParameters.Size();
const double tolerance = 1.0; // equivalent to 1 pixel.
for(unsigned int i=0; i<numbeOfParameters; i++)
{
// the parameters are negated in order to get the inverse transformation.
// this only works for comparing translation parameters....
std::cout << finalParameters[i] << " == " << -actualParameters[i] << std::endl;
if( fabs ( finalParameters[i] - (-actualParameters[i]) ) > tolerance )
{
std::cout << "Tolerance exceeded at component " << i << std::endl;
pass = false;
}
}
if( !pass )
{
std::cout << "Test FAILED." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* FogLAMP plugin filter class
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Amandeep Singh Arora
*/
#include <filter_pipeline.h>
#include <config_handler.h>
#include <service_handler.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#define JSON_CONFIG_FILTER_ELEM "filter"
#define JSON_CONFIG_PIPELINE_ELEM "pipeline"
using namespace std;
/**
* FilterPipeline class constructor
*
* This class abstracts the filter pipeline interface
*
* @param mgtClient Management client handle
* @param storage Storage client handle
* @param serviceName Name of the service to which this pipeline applies
*/
FilterPipeline::FilterPipeline(ManagementClient* mgtClient, StorageClient& storage, string serviceName) :
mgtClient(mgtClient), storage(storage), serviceName(serviceName)
{
}
/**
* FilterPipeline destructor
*/
FilterPipeline::~FilterPipeline()
{
}
/**
* Load the specified filter plugin
*
* @param filterName The filter plugin to load
* @return Plugin handle on success, NULL otherwise
*
*/
PLUGIN_HANDLE FilterPipeline::loadFilterPlugin(const string& filterName)
{
if (filterName.empty())
{
Logger::getLogger()->error("Unable to fetch filter plugin '%s' from configuration.",
filterName.c_str());
// Failure
return NULL;
}
Logger::getLogger()->info("Loading filter plugin '%s'.", filterName.c_str());
PluginManager* manager = PluginManager::getInstance();
PLUGIN_HANDLE handle;
if ((handle = manager->loadPlugin(filterName, PLUGIN_TYPE_FILTER)) != NULL)
{
// Suceess
Logger::getLogger()->info("Loaded filter plugin '%s'.", filterName.c_str());
}
return handle;
}
/**
* Load all filter plugins in the pipeline
*
* @param categoryName Configuration category name
* @return True if filters are loaded (or no filters at all)
* False otherwise
*/
bool FilterPipeline::loadFilters(const string& categoryName)
{
vector<string> children; // The Child categories of 'Filters'
try
{
// Get the category with values and defaults
ConfigCategory config = mgtClient->getCategory(categoryName);
string filter = config.getValue(JSON_CONFIG_FILTER_ELEM);
Logger::getLogger()->info("FilterPipeline::loadFilters(): categoryName=%s, filters=%s", categoryName.c_str(), filter.c_str());
if (!filter.empty())
{
std::vector<pair<string, PLUGIN_HANDLE>> filterInfo;
// Remove \" and leading/trailing "
// TODO: improve/change this
filter.erase(remove(filter.begin(), filter.end(), '\\' ), filter.end());
size_t i;
while (! (i = filter.find('"')) || (i = filter.rfind('"')) == static_cast<unsigned char>(filter.size() - 1))
{
filter.erase(i, 1);
}
//Parse JSON object for filters
Document theFilters;
theFilters.Parse(filter.c_str());
// The "pipeline" property must be an array
if (theFilters.HasParseError() ||
!theFilters.HasMember(JSON_CONFIG_PIPELINE_ELEM) ||
!theFilters[JSON_CONFIG_PIPELINE_ELEM].IsArray())
{
string errMsg("loadFilters: can not parse JSON '");
errMsg += string(JSON_CONFIG_FILTER_ELEM) + "' property";
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
else
{
const Value& filterList = theFilters[JSON_CONFIG_PIPELINE_ELEM];
if (!filterList.Size())
{
// Empty array, just return true
return true;
}
// Prepare printable list of filters
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
filterList.Accept(writer);
string printableList(buffer.GetString());
string logMsg("loadFilters: found filter(s) ");
logMsg += printableList + " for plugin '";
logMsg += categoryName + "'";
Logger::getLogger()->info(logMsg.c_str());
// Try loading all filter plugins: abort on any error
for (Value::ConstValueIterator itr = filterList.Begin(); itr != filterList.End(); ++itr)
{
// Get "plugin" item fromn filterCategoryName
string filterCategoryName = itr->GetString();
ConfigCategory filterDetails = mgtClient->getCategory(filterCategoryName);
if (!filterDetails.itemExists("plugin"))
{
string errMsg("loadFilters: 'plugin' item not found ");
errMsg += "in " + filterCategoryName + " category";
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
string filterName = filterDetails.getValue("plugin");
PLUGIN_HANDLE filterHandle;
// Load filter plugin only: we don't call any plugin method right now
filterHandle = loadFilterPlugin(filterName);
if (!filterHandle)
{
string errMsg("Cannot load filter plugin '" + filterName + "'");
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
else
{
// Save filter handler: key is filterCategoryName
filterInfo.push_back(pair<string,PLUGIN_HANDLE>
(filterCategoryName, filterHandle));
}
}
// We have kept filter default config in the filterInfo map
// Handle configuration for each filter
PluginManager *pluginManager = PluginManager::getInstance();
for (vector<pair<string, PLUGIN_HANDLE>>::iterator itr = filterInfo.begin();
itr != filterInfo.end();
++itr)
{
// Get plugin default configuration
string filterConfig = pluginManager->getInfo(itr->second)->config;
// Create/Update default filter category items
DefaultConfigCategory filterDefConfig(categoryName + "_" + itr->first, filterConfig);
string filterDescription = "Configuration of '" + itr->first;
filterDescription += "' filter for plugin '" + categoryName + "'";
filterDefConfig.setDescription(filterDescription);
if (!mgtClient->addCategory(filterDefConfig, true))
{
string errMsg("Cannot create/update '" + \
categoryName + "' filter category");
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
children.push_back(categoryName + "_" + itr->first);
// Instantiate the FilterPlugin class
// in order to call plugin entry points
FilterPlugin* currentFilter = new FilterPlugin(itr->first,
itr->second);
// Add filter to filters vector
m_filters.push_back(currentFilter);
}
}
}
/*
* Put all the new catregories in the Filter category parent
* Create an empty South category if one doesn't exist
*/
string parentName = categoryName + " Filters";
DefaultConfigCategory filterConfig(parentName, string("{}"));
filterConfig.setDescription("Filters for " + categoryName);
mgtClient->addCategory(filterConfig, true);
mgtClient->addChildCategories(parentName, children);
vector<string> children1;
children1.push_back(parentName);
mgtClient->addChildCategories(categoryName, children1);
return true;
}
catch (ConfigItemNotFound* e)
{
delete e;
Logger::getLogger()->info("loadFilters: no filters configured for '" + categoryName + "'");
return true;
}
catch (exception& e)
{
Logger::getLogger()->fatal("loadFilters: failed to handle '" + categoryName + "' filters.");
return false;
}
catch (...)
{
Logger::getLogger()->fatal("loadFilters: generic exception while loading '" + categoryName + "' filters.");
return false;
}
}
/**
* Set the filter pipeline
*
* This method calls the method "plugin_init" for all loadad filters.
* Up-to-date filter configurations and Ingest filtering methods
* are passed to "plugin_init"
*
* @param passToOnwardFilter Ptr to function that passes data to next filter
* @param useFilteredData Ptr to function that gets final filtered data
* @param ingest The ingest class handle
* @return True on success,
* False otherwise.
* @thown Any caught exception
*/
bool FilterPipeline::setupFiltersPipeline(void *passToOnwardFilter, void *useFilteredData, void *ingest)
{
bool initErrors = false;
string errMsg = "'plugin_init' failed for filter '";
for (auto it = m_filters.begin(); it != m_filters.end(); ++it)
{
string filterCategoryName = serviceName + "_" + (*it)->getName();
ConfigCategory updatedCfg;
vector<string> children;
try
{
Logger::getLogger()->info("Load plugin categoryName %s", filterCategoryName.c_str());
// Fetch up to date filter configuration
updatedCfg = mgtClient->getCategory(filterCategoryName);
// Add filter category name under service/process config name
children.push_back(filterCategoryName);
mgtClient->addChildCategories(serviceName, children);
ConfigHandler *configHandler = ConfigHandler::getInstance(mgtClient);
configHandler->registerCategory((ServiceHandler *)ingest, filterCategoryName);
m_filterCategories[filterCategoryName] = (*it);
}
// TODO catch specific exceptions
catch (...)
{
throw;
}
// Iterate the load filters set in the Ingest class m_filters member
if ((it + 1) != m_filters.end())
{
// Set next filter pointer as OUTPUT_HANDLE
if (!(*it)->init(updatedCfg,
(OUTPUT_HANDLE *)(*(it + 1)),
filterReadingSetFn(passToOnwardFilter)))
{
errMsg += (*it)->getName() + "'";
initErrors = true;
break;
}
}
else
{
// Set the Ingest class pointer as OUTPUT_HANDLE
if (!(*it)->init(updatedCfg,
(OUTPUT_HANDLE *)(ingest),
filterReadingSetFn(useFilteredData)))
{
errMsg += (*it)->getName() + "'";
initErrors = true;
break;
}
}
if ((*it)->persistData())
{
// Plugin support SP_PERSIST_DATA
// Instantiate the PluginData class
(*it)->m_plugin_data = new PluginData(&storage);
// Load plugin data from storage layer
string pluginStoredData = (*it)->m_plugin_data->loadStoredData(serviceName + (*it)->getName());
//call 'plugin_start' with plugin data: startData()
(*it)->startData(pluginStoredData);
}
else
{
// We don't call simple plugin_start for filters right now
}
}
if (initErrors)
{
// Failure
Logger::getLogger()->fatal("%s error: %s", __FUNCTION__, errMsg.c_str());
return false;
}
//Success
return true;
}
/**
* Cleanup all the loaded filters
*
* Call "plugin_shutdown" method and free the FilterPlugin object
*
* @param categoryName Configuration category name
*
*/
void FilterPipeline::cleanupFilters(const string& categoryName)
{
// Cleanup filters
for (auto it = m_filters.begin(); it != m_filters.end(); ++it)
{
FilterPlugin* filter = *it;
//string filterCategoryName = categoryName + "_" + filter->getName();
//mgtClient->unregisterCategory(filterCategoryName);
//Logger::getLogger()->info("FilterPipeline::cleanupFilters(): unregistered category %s", filterCategoryName.c_str());
// If plugin has SP_PERSIST_DATA option:
if (filter->m_plugin_data)
{
// 1- call shutdownSaveData and get up-to-date plugin data.
string saveData = filter->shutdownSaveData();
// 2- store returned data: key is service/task categoryName + pluginName
string key(categoryName + filter->getName());
if (!filter->m_plugin_data->persistPluginData(key, saveData))
{
Logger::getLogger()->error("Filter plugin %s has failed to save data [%s] for key %s",
filter->getName().c_str(),
saveData.c_str(),
key.c_str());
}
}
else
{
// Call filter plugin shutdown
(*it)->shutdown();
}
// Free filter
delete filter;
}
}
/**
* Configuration change for one of the filters. Lookup the category name and
* find the plugin to call. Call the reconfigure method of that plugin with
* the new configuration.
*
* @param category The name of the configuration category
* @param newConfig The new category contents
*/
void FilterPipeline::configChange(const string& category, const string& newConfig)
{
auto it = m_filterCategories.find(category);
if (it != m_filterCategories.end())
{
it->second->reconfigure(newConfig);
}
}
<commit_msg>FOGK-3146: Cleanup filters pipeline fix: use reverse order (#1643)<commit_after>/*
* FogLAMP plugin filter class
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Amandeep Singh Arora
*/
#include <filter_pipeline.h>
#include <config_handler.h>
#include <service_handler.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#define JSON_CONFIG_FILTER_ELEM "filter"
#define JSON_CONFIG_PIPELINE_ELEM "pipeline"
using namespace std;
/**
* FilterPipeline class constructor
*
* This class abstracts the filter pipeline interface
*
* @param mgtClient Management client handle
* @param storage Storage client handle
* @param serviceName Name of the service to which this pipeline applies
*/
FilterPipeline::FilterPipeline(ManagementClient* mgtClient, StorageClient& storage, string serviceName) :
mgtClient(mgtClient), storage(storage), serviceName(serviceName)
{
}
/**
* FilterPipeline destructor
*/
FilterPipeline::~FilterPipeline()
{
}
/**
* Load the specified filter plugin
*
* @param filterName The filter plugin to load
* @return Plugin handle on success, NULL otherwise
*
*/
PLUGIN_HANDLE FilterPipeline::loadFilterPlugin(const string& filterName)
{
if (filterName.empty())
{
Logger::getLogger()->error("Unable to fetch filter plugin '%s' from configuration.",
filterName.c_str());
// Failure
return NULL;
}
Logger::getLogger()->info("Loading filter plugin '%s'.", filterName.c_str());
PluginManager* manager = PluginManager::getInstance();
PLUGIN_HANDLE handle;
if ((handle = manager->loadPlugin(filterName, PLUGIN_TYPE_FILTER)) != NULL)
{
// Suceess
Logger::getLogger()->info("Loaded filter plugin '%s'.", filterName.c_str());
}
return handle;
}
/**
* Load all filter plugins in the pipeline
*
* @param categoryName Configuration category name
* @return True if filters are loaded (or no filters at all)
* False otherwise
*/
bool FilterPipeline::loadFilters(const string& categoryName)
{
vector<string> children; // The Child categories of 'Filters'
try
{
// Get the category with values and defaults
ConfigCategory config = mgtClient->getCategory(categoryName);
string filter = config.getValue(JSON_CONFIG_FILTER_ELEM);
Logger::getLogger()->info("FilterPipeline::loadFilters(): categoryName=%s, filters=%s", categoryName.c_str(), filter.c_str());
if (!filter.empty())
{
std::vector<pair<string, PLUGIN_HANDLE>> filterInfo;
// Remove \" and leading/trailing "
// TODO: improve/change this
filter.erase(remove(filter.begin(), filter.end(), '\\' ), filter.end());
size_t i;
while (! (i = filter.find('"')) || (i = filter.rfind('"')) == static_cast<unsigned char>(filter.size() - 1))
{
filter.erase(i, 1);
}
//Parse JSON object for filters
Document theFilters;
theFilters.Parse(filter.c_str());
// The "pipeline" property must be an array
if (theFilters.HasParseError() ||
!theFilters.HasMember(JSON_CONFIG_PIPELINE_ELEM) ||
!theFilters[JSON_CONFIG_PIPELINE_ELEM].IsArray())
{
string errMsg("loadFilters: can not parse JSON '");
errMsg += string(JSON_CONFIG_FILTER_ELEM) + "' property";
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
else
{
const Value& filterList = theFilters[JSON_CONFIG_PIPELINE_ELEM];
if (!filterList.Size())
{
// Empty array, just return true
return true;
}
// Prepare printable list of filters
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
filterList.Accept(writer);
string printableList(buffer.GetString());
string logMsg("loadFilters: found filter(s) ");
logMsg += printableList + " for plugin '";
logMsg += categoryName + "'";
Logger::getLogger()->info(logMsg.c_str());
// Try loading all filter plugins: abort on any error
for (Value::ConstValueIterator itr = filterList.Begin(); itr != filterList.End(); ++itr)
{
// Get "plugin" item fromn filterCategoryName
string filterCategoryName = itr->GetString();
ConfigCategory filterDetails = mgtClient->getCategory(filterCategoryName);
if (!filterDetails.itemExists("plugin"))
{
string errMsg("loadFilters: 'plugin' item not found ");
errMsg += "in " + filterCategoryName + " category";
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
string filterName = filterDetails.getValue("plugin");
PLUGIN_HANDLE filterHandle;
// Load filter plugin only: we don't call any plugin method right now
filterHandle = loadFilterPlugin(filterName);
if (!filterHandle)
{
string errMsg("Cannot load filter plugin '" + filterName + "'");
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
else
{
// Save filter handler: key is filterCategoryName
filterInfo.push_back(pair<string,PLUGIN_HANDLE>
(filterCategoryName, filterHandle));
}
}
// We have kept filter default config in the filterInfo map
// Handle configuration for each filter
PluginManager *pluginManager = PluginManager::getInstance();
for (vector<pair<string, PLUGIN_HANDLE>>::iterator itr = filterInfo.begin();
itr != filterInfo.end();
++itr)
{
// Get plugin default configuration
string filterConfig = pluginManager->getInfo(itr->second)->config;
// Create/Update default filter category items
DefaultConfigCategory filterDefConfig(categoryName + "_" + itr->first, filterConfig);
string filterDescription = "Configuration of '" + itr->first;
filterDescription += "' filter for plugin '" + categoryName + "'";
filterDefConfig.setDescription(filterDescription);
if (!mgtClient->addCategory(filterDefConfig, true))
{
string errMsg("Cannot create/update '" + \
categoryName + "' filter category");
Logger::getLogger()->fatal(errMsg.c_str());
throw runtime_error(errMsg);
}
children.push_back(categoryName + "_" + itr->first);
// Instantiate the FilterPlugin class
// in order to call plugin entry points
FilterPlugin* currentFilter = new FilterPlugin(itr->first,
itr->second);
// Add filter to filters vector
m_filters.push_back(currentFilter);
}
}
}
/*
* Put all the new catregories in the Filter category parent
* Create an empty South category if one doesn't exist
*/
string parentName = categoryName + " Filters";
DefaultConfigCategory filterConfig(parentName, string("{}"));
filterConfig.setDescription("Filters for " + categoryName);
mgtClient->addCategory(filterConfig, true);
mgtClient->addChildCategories(parentName, children);
vector<string> children1;
children1.push_back(parentName);
mgtClient->addChildCategories(categoryName, children1);
return true;
}
catch (ConfigItemNotFound* e)
{
delete e;
Logger::getLogger()->info("loadFilters: no filters configured for '" + categoryName + "'");
return true;
}
catch (exception& e)
{
Logger::getLogger()->fatal("loadFilters: failed to handle '" + categoryName + "' filters.");
return false;
}
catch (...)
{
Logger::getLogger()->fatal("loadFilters: generic exception while loading '" + categoryName + "' filters.");
return false;
}
}
/**
* Set the filter pipeline
*
* This method calls the method "plugin_init" for all loadad filters.
* Up-to-date filter configurations and Ingest filtering methods
* are passed to "plugin_init"
*
* @param passToOnwardFilter Ptr to function that passes data to next filter
* @param useFilteredData Ptr to function that gets final filtered data
* @param ingest The ingest class handle
* @return True on success,
* False otherwise.
* @thown Any caught exception
*/
bool FilterPipeline::setupFiltersPipeline(void *passToOnwardFilter, void *useFilteredData, void *ingest)
{
bool initErrors = false;
string errMsg = "'plugin_init' failed for filter '";
for (auto it = m_filters.begin(); it != m_filters.end(); ++it)
{
string filterCategoryName = serviceName + "_" + (*it)->getName();
ConfigCategory updatedCfg;
vector<string> children;
try
{
Logger::getLogger()->info("Load plugin categoryName %s", filterCategoryName.c_str());
// Fetch up to date filter configuration
updatedCfg = mgtClient->getCategory(filterCategoryName);
// Add filter category name under service/process config name
children.push_back(filterCategoryName);
mgtClient->addChildCategories(serviceName, children);
ConfigHandler *configHandler = ConfigHandler::getInstance(mgtClient);
configHandler->registerCategory((ServiceHandler *)ingest, filterCategoryName);
m_filterCategories[filterCategoryName] = (*it);
}
// TODO catch specific exceptions
catch (...)
{
throw;
}
// Iterate the load filters set in the Ingest class m_filters member
if ((it + 1) != m_filters.end())
{
// Set next filter pointer as OUTPUT_HANDLE
if (!(*it)->init(updatedCfg,
(OUTPUT_HANDLE *)(*(it + 1)),
filterReadingSetFn(passToOnwardFilter)))
{
errMsg += (*it)->getName() + "'";
initErrors = true;
break;
}
}
else
{
// Set the Ingest class pointer as OUTPUT_HANDLE
if (!(*it)->init(updatedCfg,
(OUTPUT_HANDLE *)(ingest),
filterReadingSetFn(useFilteredData)))
{
errMsg += (*it)->getName() + "'";
initErrors = true;
break;
}
}
if ((*it)->persistData())
{
// Plugin support SP_PERSIST_DATA
// Instantiate the PluginData class
(*it)->m_plugin_data = new PluginData(&storage);
// Load plugin data from storage layer
string pluginStoredData = (*it)->m_plugin_data->loadStoredData(serviceName + (*it)->getName());
//call 'plugin_start' with plugin data: startData()
(*it)->startData(pluginStoredData);
}
else
{
// We don't call simple plugin_start for filters right now
}
}
if (initErrors)
{
// Failure
Logger::getLogger()->fatal("%s error: %s", __FUNCTION__, errMsg.c_str());
return false;
}
//Success
return true;
}
/**
* Cleanup all the loaded filters
*
* Call "plugin_shutdown" method and free the FilterPlugin object
*
* @param categoryName Configuration category name
*
*/
void FilterPipeline::cleanupFilters(const string& categoryName)
{
// Cleanup filters, in reverse order
for (auto it = m_filters.rbegin(); it != m_filters.rend(); ++it)
{
FilterPlugin* filter = *it;
//string filterCategoryName = categoryName + "_" + filter->getName();
//mgtClient->unregisterCategory(filterCategoryName);
//Logger::getLogger()->info("FilterPipeline::cleanupFilters(): unregistered category %s", filterCategoryName.c_str());
// If plugin has SP_PERSIST_DATA option:
if (filter->m_plugin_data)
{
// 1- call shutdownSaveData and get up-to-date plugin data.
string saveData = filter->shutdownSaveData();
// 2- store returned data: key is service/task categoryName + pluginName
string key(categoryName + filter->getName());
if (!filter->m_plugin_data->persistPluginData(key, saveData))
{
Logger::getLogger()->error("Filter plugin %s has failed to save data [%s] for key %s",
filter->getName().c_str(),
saveData.c_str(),
key.c_str());
}
}
else
{
// Call filter plugin shutdown
(*it)->shutdown();
}
// Free filter
delete filter;
}
}
/**
* Configuration change for one of the filters. Lookup the category name and
* find the plugin to call. Call the reconfigure method of that plugin with
* the new configuration.
*
* @param category The name of the configuration category
* @param newConfig The new category contents
*/
void FilterPipeline::configChange(const string& category, const string& newConfig)
{
auto it = m_filterCategories.find(category);
if (it != m_filterCategories.end())
{
it->second->reconfigure(newConfig);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#include "otbGenericRSResampleImageFilter.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include <ogr_spatialref.h>
// Default value
#include "itkPixelBuilder.h"
// Extract ROI
#include "otbMultiChannelExtractROI.h"
// Images definition
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef ImageType::SizeType SizeType;
typedef otb::GenericRSResampleImageFilter<ImageType,
ImageType> ImageResamplerType;
typedef ImageResamplerType::OriginType OriginType;
typedef ImageResamplerType::SpacingType SpacingType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
int otbGenericRSResampleImageFilterNew(int argc, char* argv[])
{
// SmartPointer instanciation
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
int otbGenericRSResampleImageFilter(int argc, char* argv[])
{
// SmartPointer instanciation
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
const char * infname = argv[1];
const char * outfname = argv[6];
unsigned int isize = atoi(argv[2]);
double iGridSpacing = atof(argv[3]);
int useInRpc = atoi(argv[4]);
int useOutRpc = atoi(argv[5]);
ReaderType::Pointer reader = ReaderType::New();
// Read the input image
reader->SetFileName(infname);
reader->UpdateOutputInformation();
// Fill the output size with the user selection
SizeType size;
size.Fill(isize);
// Set the origin & the spacing of the output
OriginType origin;
origin[0] = 367340;
origin[1] = 4.83467e+06;
SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
// Build the ouput projection ref : UTM ref
OGRSpatialReference oSRS;
oSRS.SetProjCS("UTM");
oSRS.SetUTM(31, true);
char * utmRef = NULL;
oSRS.exportToWkt(&utmRef);
// Deformation Field spacing
SpacingType gridSpacing;
gridSpacing[0] = iGridSpacing;
gridSpacing[1] = -iGridSpacing;
// Default value builder
ImageType::PixelType defaultValue;
itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
reader->GetOutput()->GetNumberOfComponentsPerPixel());
// Set the Resampler Parameters
resampler->SetInput(reader->GetOutput());
resampler->SetDeformationFieldSpacing(gridSpacing);
resampler->SetOutputOrigin(origin);
resampler->SetOutputSize(size);
resampler->SetOutputSpacing(spacing);
resampler->SetOutputProjectionRef(utmRef);
resampler->SetEdgePaddingValue(defaultValue);
if (useInRpc)
{
resampler->SetInputRpcGridSize(20);
resampler->EstimateInputRpcModelOn();
}
if (useOutRpc)
{
resampler->SetOutputRpcGridSize(20);
resampler->EstimateOutputRpcModelOn();
}
// Write the resampled image
WriterType::Pointer writer= WriterType::New();
writer->SetNumberOfDivisionsTiledStreaming(4);
writer->SetFileName(outfname);
writer->SetInput(resampler->GetOutput());
writer->Update();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
int otbGenericRSResampleImageFilterFromMap(int argc, char* argv[])
{
typedef otb::MultiChannelExtractROI<PixelType, PixelType> ExtractROIType;
// SmartPointer instanciation
ExtractROIType::Pointer extractor = ExtractROIType::New();
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
const char * infname = argv[1];
const char * outfname = argv[4];
double iGridSpacing = atof(argv[2]);
int useInRpc = atoi(argv[3]);
// Reader Instanciation
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->UpdateOutputInformation();
SpacingType spacing;
spacing[0] = 2.5;
spacing[1] = -2.5;
// Deformation Field spacing
SpacingType gridSpacing;
gridSpacing[0] = iGridSpacing;
gridSpacing[1] = -iGridSpacing;
// Default value builder
ImageType::PixelType defaultValue;
itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
reader->GetOutput()->GetNumberOfComponentsPerPixel());
// Extract a roi centered on the input center
ImageType::RegionType roi;
ImageType::IndexType roiIndex;
SizeType roiSize;
// Fill the size
roiSize.Fill(500);
// Fill the start index
roiIndex[0] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] - roiSize[0]) /2);
roiIndex[1] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] - roiSize[1]) /2);
roi.SetIndex(roiIndex);
roi.SetSize(roiSize);
extractor->SetExtractionRegion(roi);
extractor->SetInput(reader->GetOutput());
extractor->UpdateOutputInformation();
// Set the Resampler Parameters
resampler->SetInput(extractor->GetOutput());
resampler->SetDeformationFieldSpacing(gridSpacing);
resampler->SetOutputParametersFromMap("UTM", spacing);
if (useInRpc)
{
resampler->SetInputRpcGridSize(20);
resampler->EstimateInputRpcModelOn();
}
// Write the resampled image
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer= WriterType::New();
writer->SetAutomaticTiledStreaming();
writer->SetFileName(outfname);
writer->SetInput(resampler->GetOutput());
writer->Update();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: reduce the size of the output image to be able to test the WordView sensor<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#include "otbGenericRSResampleImageFilter.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include <ogr_spatialref.h>
// Default value
#include "itkPixelBuilder.h"
// Extract ROI
#include "otbMultiChannelExtractROI.h"
// Images definition
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef ImageType::SizeType SizeType;
typedef otb::GenericRSResampleImageFilter<ImageType,
ImageType> ImageResamplerType;
typedef ImageResamplerType::OriginType OriginType;
typedef ImageResamplerType::SpacingType SpacingType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
int otbGenericRSResampleImageFilterNew(int argc, char* argv[])
{
// SmartPointer instanciation
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
int otbGenericRSResampleImageFilter(int argc, char* argv[])
{
// SmartPointer instanciation
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
const char * infname = argv[1];
const char * outfname = argv[6];
unsigned int isize = atoi(argv[2]);
double iGridSpacing = atof(argv[3]);
int useInRpc = atoi(argv[4]);
int useOutRpc = atoi(argv[5]);
ReaderType::Pointer reader = ReaderType::New();
// Read the input image
reader->SetFileName(infname);
reader->UpdateOutputInformation();
// Fill the output size with the user selection
SizeType size;
size.Fill(isize);
// Set the origin & the spacing of the output
OriginType origin;
origin[0] = 367340;
origin[1] = 4.83467e+06;
SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
// Build the ouput projection ref : UTM ref
OGRSpatialReference oSRS;
oSRS.SetProjCS("UTM");
oSRS.SetUTM(31, true);
char * utmRef = NULL;
oSRS.exportToWkt(&utmRef);
// Deformation Field spacing
SpacingType gridSpacing;
gridSpacing[0] = iGridSpacing;
gridSpacing[1] = -iGridSpacing;
// Default value builder
ImageType::PixelType defaultValue;
itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
reader->GetOutput()->GetNumberOfComponentsPerPixel());
// Set the Resampler Parameters
resampler->SetInput(reader->GetOutput());
resampler->SetDeformationFieldSpacing(gridSpacing);
resampler->SetOutputOrigin(origin);
resampler->SetOutputSize(size);
resampler->SetOutputSpacing(spacing);
resampler->SetOutputProjectionRef(utmRef);
resampler->SetEdgePaddingValue(defaultValue);
if (useInRpc)
{
resampler->SetInputRpcGridSize(20);
resampler->EstimateInputRpcModelOn();
}
if (useOutRpc)
{
resampler->SetOutputRpcGridSize(20);
resampler->EstimateOutputRpcModelOn();
}
// Write the resampled image
WriterType::Pointer writer= WriterType::New();
writer->SetNumberOfDivisionsTiledStreaming(4);
writer->SetFileName(outfname);
writer->SetInput(resampler->GetOutput());
writer->Update();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
int otbGenericRSResampleImageFilterFromMap(int argc, char* argv[])
{
typedef otb::MultiChannelExtractROI<PixelType, PixelType> ExtractROIType;
// SmartPointer instanciation
ExtractROIType::Pointer extractor = ExtractROIType::New();
ImageResamplerType::Pointer resampler = ImageResamplerType::New();
const char * infname = argv[1];
const char * outfname = argv[4];
double iGridSpacing = atof(argv[2]);
int useInRpc = atoi(argv[3]);
// Reader Instanciation
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->UpdateOutputInformation();
SpacingType spacing;
spacing[0] = 2.5;
spacing[1] = -2.5;
// Deformation Field spacing
SpacingType gridSpacing;
gridSpacing[0] = iGridSpacing;
gridSpacing[1] = -iGridSpacing;
// Default value builder
ImageType::PixelType defaultValue;
itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
reader->GetOutput()->GetNumberOfComponentsPerPixel());
// Extract a roi centered on the input center
ImageType::RegionType roi;
ImageType::IndexType roiIndex;
SizeType roiSize;
// Fill the size
roiSize.Fill(250);
// Fill the start index
roiIndex[0] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] - roiSize[0]) /2);
roiIndex[1] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] - roiSize[1]) /2);
roi.SetIndex(roiIndex);
roi.SetSize(roiSize);
extractor->SetExtractionRegion(roi);
extractor->SetInput(reader->GetOutput());
extractor->UpdateOutputInformation();
// Set the Resampler Parameters
resampler->SetInput(extractor->GetOutput());
resampler->SetDeformationFieldSpacing(gridSpacing);
resampler->SetOutputParametersFromMap("UTM", spacing);
if (useInRpc)
{
resampler->SetInputRpcGridSize(20);
resampler->EstimateInputRpcModelOn();
}
// Write the resampled image
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer= WriterType::New();
writer->SetAutomaticTiledStreaming();
writer->SetFileName(outfname);
writer->SetInput(resampler->GetOutput());
writer->Update();
std::cout << resampler << std::endl;
return EXIT_SUCCESS;
}
<|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 <time.h>
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkChangeLabelImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SmallRegionsMerging : public Application
{
public:
typedef SmallRegionsMerging Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
//typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<ImageType, LabelImageType> StatisticsMapFromLabelImageFilterType;
typedef otb::LabelImageSmallRegionMergingFilter<LabelImageType> LabelImageSmallRegionMergingFilterType;
typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType> ChangeLabelImageFilterType;
itkNewMacro(Self);
itkTypeMacro(Merging, otb::Application);
private:
ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter;
void DoInit() override
{
SetName("SmallRegionsMerging");
SetDescription("This application merges small regions of a segmentation result to connected region.");
SetDocName("Small Region Merging");
SetDocLongDescription("Given a segmentation result and the original image, it will"
" merge segments whose size in pixels is lower than minsize parameter"
" with the adjacent segments with the adjacent segment with closest"
" radiometry and acceptable size.\n\n"
"Small segments will be processed by increasing size: first all segments"
" for which area is equal to 1 pixel will be merged with adjacent"
" segments, then all segments of area equal to 2 pixels will be processed,"
" until segments of area minsize."
" \n\n");
SetDocLimitations("This application is more efficient if the labels are contiguous, starting from 0.");
SetDocAuthors("OTB-Team");
SetDocSeeAlso( "Segmentation");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription( "in", "The input image, containing initial spectral signatures corresponding to the segmented image (inseg)." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", "Segmented image where each pixel value is the unique integer label of the segment it belongs to." );
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "The output image. The output image is the segmented image where the minimal segments have been merged." );
SetDefaultOutputPixelType("out",ImagePixelType_uint32);
AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
SetParameterDescription("minsize", "Minimum Segment Size. If, after the segmentation, a segment is of size strictly lower than this criterion, the segment is merged with the segment that has the closest sepctral signature.");
SetDefaultParameterInt("minsize", 50);
SetMinimumParameterIntValue("minsize", 1);
MandatoryOff("minsize");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in","smooth.tif");
SetDocExampleParameterValue("inseg","segmentation.tif");
SetDocExampleParameterValue("out","merged.tif");
SetDocExampleParameterValue("minsize","50");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
clock_t tic = clock();
unsigned int minSize = GetParameterInt("minsize");
//Acquisition of the input image dimensions
ImageType::Pointer imageIn = GetParameterImage("in");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
// Compute statistics for each segment
auto labelStatsFilter = StatisticsMapFromLabelImageFilterType::New();
labelStatsFilter->SetInput(imageIn);
labelStatsFilter->SetInputLabelImage(labelIn);
AddProcess(labelStatsFilter->GetStreamer() , "Computing stats on input image ...");
labelStatsFilter->Update();
// Convert Map to Unordered map
auto labelPopulationMap = labelStatsFilter->GetLabelPopulationMap();
std::unordered_map< unsigned int,double> labelPopulation;
for (auto population : labelPopulationMap)
{
labelPopulation[population.first]=population.second;
}
auto meanValueMap = labelStatsFilter->GetMeanValueMap();
std::unordered_map< unsigned int, itk::VariableLengthVector<double> > meanValues;
for (const auto & mean : meanValueMap)
{
meanValues[mean.first] = mean.second;
}
// Compute the LUT from the original label image to the merged output label image.
auto regionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
regionMergingFilter->SetInput( labelIn );
regionMergingFilter->SetLabelPopulation( labelPopulation );
regionMergingFilter->SetLabelStatistic( meanValues );
regionMergingFilter->SetMinSize( minSize);
AddProcess(regionMergingFilter, "Computing LUT ...");
regionMergingFilter->Update();
// Relabelling using the LUT
auto changeLabelFilter = ChangeLabelImageFilterType::New();
changeLabelFilter->SetInput(labelIn);
const auto & LUT = regionMergingFilter->GetLUT();
for (auto label : LUT)
{
if (label.first != label.second)
{
changeLabelFilter->SetChange(label.first, label.second);
}
}
SetParameterOutputImage("out", changeLabelFilter->GetOutput());
RegisterPipeline();
clock_t toc = clock();
otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SmallRegionsMerging)
<commit_msg>DOC : Long description should not end with a newline<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 <time.h>
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkChangeLabelImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SmallRegionsMerging : public Application
{
public:
typedef SmallRegionsMerging Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
//typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<ImageType, LabelImageType> StatisticsMapFromLabelImageFilterType;
typedef otb::LabelImageSmallRegionMergingFilter<LabelImageType> LabelImageSmallRegionMergingFilterType;
typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType> ChangeLabelImageFilterType;
itkNewMacro(Self);
itkTypeMacro(Merging, otb::Application);
private:
ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter;
void DoInit() override
{
SetName("SmallRegionsMerging");
SetDescription("This application merges small regions of a segmentation result to connected region.");
SetDocName("Small Region Merging");
SetDocLongDescription("Given a segmentation result and the original image, it will"
" merge segments whose size in pixels is lower than minsize parameter"
" with the adjacent segments with the adjacent segment with closest"
" radiometry and acceptable size.\n\n"
"Small segments will be processed by increasing size: first all segments"
" for which area is equal to 1 pixel will be merged with adjacent"
" segments, then all segments of area equal to 2 pixels will be processed,"
" until segments of area minsize.");
SetDocLimitations("This application is more efficient if the labels are contiguous, starting from 0.");
SetDocAuthors("OTB-Team");
SetDocSeeAlso( "Segmentation");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription( "in", "The input image, containing initial spectral signatures corresponding to the segmented image (inseg)." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", "Segmented image where each pixel value is the unique integer label of the segment it belongs to." );
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "The output image. The output image is the segmented image where the minimal segments have been merged." );
SetDefaultOutputPixelType("out",ImagePixelType_uint32);
AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
SetParameterDescription("minsize", "Minimum Segment Size. If, after the segmentation, a segment is of size strictly lower than this criterion, the segment is merged with the segment that has the closest sepctral signature.");
SetDefaultParameterInt("minsize", 50);
SetMinimumParameterIntValue("minsize", 1);
MandatoryOff("minsize");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in","smooth.tif");
SetDocExampleParameterValue("inseg","segmentation.tif");
SetDocExampleParameterValue("out","merged.tif");
SetDocExampleParameterValue("minsize","50");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
clock_t tic = clock();
unsigned int minSize = GetParameterInt("minsize");
//Acquisition of the input image dimensions
ImageType::Pointer imageIn = GetParameterImage("in");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
// Compute statistics for each segment
auto labelStatsFilter = StatisticsMapFromLabelImageFilterType::New();
labelStatsFilter->SetInput(imageIn);
labelStatsFilter->SetInputLabelImage(labelIn);
AddProcess(labelStatsFilter->GetStreamer() , "Computing stats on input image ...");
labelStatsFilter->Update();
// Convert Map to Unordered map
auto labelPopulationMap = labelStatsFilter->GetLabelPopulationMap();
std::unordered_map< unsigned int,double> labelPopulation;
for (auto population : labelPopulationMap)
{
labelPopulation[population.first]=population.second;
}
auto meanValueMap = labelStatsFilter->GetMeanValueMap();
std::unordered_map< unsigned int, itk::VariableLengthVector<double> > meanValues;
for (const auto & mean : meanValueMap)
{
meanValues[mean.first] = mean.second;
}
// Compute the LUT from the original label image to the merged output label image.
auto regionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
regionMergingFilter->SetInput( labelIn );
regionMergingFilter->SetLabelPopulation( labelPopulation );
regionMergingFilter->SetLabelStatistic( meanValues );
regionMergingFilter->SetMinSize( minSize);
AddProcess(regionMergingFilter, "Computing LUT ...");
regionMergingFilter->Update();
// Relabelling using the LUT
auto changeLabelFilter = ChangeLabelImageFilterType::New();
changeLabelFilter->SetInput(labelIn);
const auto & LUT = regionMergingFilter->GetLUT();
for (auto label : LUT)
{
if (label.first != label.second)
{
changeLabelFilter->SetChange(label.first, label.second);
}
}
SetParameterOutputImage("out", changeLabelFilter->GetOutput());
RegisterPipeline();
clock_t toc = clock();
otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SmallRegionsMerging)
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Disa Mhembere ([email protected])
*
* This file is part of FlashMatrix.
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kmeans.h"
#define OMP_MAX_THREADS 32
#define KM_TEST 0
namespace {
bool updated = false;
static unsigned NEV;
static size_t K;
static unsigned NUM_ROWS;
static omp_lock_t writelock;
static struct timeval start, end;
/**
* \brief Print an arry of some length `len`.
* \param len The length of the array.
*/
template <typename T>
static void print_arr(T* arr, unsigned len) {
printf("[ ");
for (unsigned i = 0; i < len; i++) {
std::cout << arr[i] << " ";
}
printf("]\n");
}
/*
* \Internal
* \brief Simple helper used to print a vector.
* \param v The vector to print.
*/
template <typename T>
static void print_vector(typename std::vector<T>& v)
{
std::cout << "[";
typename std::vector<T>::iterator itr = v.begin();
for (; itr != v.end(); itr++) {
std::cout << " "<< *itr;
}
std::cout << " ]\n";
}
/**
* \brief Get the squared distance given two values.
* \param arg1 the first value.
* \param arg2 the second value.
* \return the squared distance.
*/
static double dist_sq(double arg1, double arg2)
{
double diff = arg1 - arg2;
return diff*diff;
}
/**
* \brief This initializes clusters by randomly choosing sample
* membership in a cluster.
* See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods
* \param cluster_assignments Which cluster each sample falls into.
*/
static void random_partition_init(unsigned* cluster_assignments)
{
BOOST_LOG_TRIVIAL(info) << "Random init start";
// #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)
for (unsigned vid = 0; vid < NUM_ROWS; vid++) {
size_t assigned_cluster = random() % K; // 0...K
cluster_assignments[vid] = assigned_cluster;
}
// NOTE: M-Step is called in compute func to update cluster counts & centers
#if 0
printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS);
#endif
BOOST_LOG_TRIVIAL(info) << "Random init end\n";
}
/**
* \brief Forgy init takes `K` random samples from the matrix
* and uses them as cluster centers.
* \param matrix the flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
*/
static void forgy_init(const double* matrix, double* clusters) {
BOOST_LOG_TRIVIAL(info) << "Forgy init start";
for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K
unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1)
memcpy(&clusters[clust_idx*NEV], &matrix[rand_idx*NEV], sizeof(clusters[0])*NEV);
}
BOOST_LOG_TRIVIAL(info) << "Forgy init end";
}
/**
* \brief A parallel version of the kmeans++ initialization alg.
*/
static void kmeanspp_init()
{
BOOST_LOG_TRIVIAL(fatal) << "kmeanspp not yet implemented";
exit(-1);
}
/*\Internal
* \brief print a col wise matrix of type double / double.
* Used for testing only.
* \param matrix The col wise matrix.
* \param rows The number of rows in the mat
* \param cols The number of cols in the mat
*/
template <typename T>
static void print_mat(T* matrix, const unsigned rows, const unsigned cols) {
for (unsigned row = 0; row < rows; row++) {
std::cout << "[";
for (unsigned col = 0; col < cols; col++) {
std::cout << " " << matrix[row*cols + col];
}
std::cout << " ]\n";
}
}
/**
* \brief Update the cluster assignments while recomputing distance matrix.
* \param matrix The flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void E_step(const double* matrix, double* clusters,
unsigned* cluster_assignments, unsigned* cluster_assignment_counts)
{
gettimeofday(&start, NULL);
// Create per thread vectors
std::vector<std::vector<unsigned>> pt_cl_as_cnt; // K * OMP_MAX_THREADS
std::vector<std::vector<double>> pt_cl; // K * nev * OMP_MAX_THREADS
pt_cl_as_cnt.resize(OMP_MAX_THREADS);
pt_cl.resize(OMP_MAX_THREADS);
for (int i = 0; i < OMP_MAX_THREADS; i++) {
pt_cl_as_cnt[i].resize(K); // C++ default is 0 value in all
pt_cl[i].resize(K*NEV);
}
#pragma omp parallel for firstprivate(matrix, clusters) shared(pt_cl_as_cnt, cluster_assignments)
for (unsigned row = 0; row < NUM_ROWS; row++) {
size_t asgnd_clust = std::numeric_limits<size_t>::max();
double best = std::numeric_limits<double>::max();
for (size_t clust_idx = 0; clust_idx < K; clust_idx++) {
double sum = 0;
for (unsigned col = 0; col < NEV; col++) {
sum += dist_sq(matrix[(row*NEV) + col], clusters[clust_idx*NEV + col]);
}
if (sum < best) {
best = sum;
asgnd_clust = clust_idx;
}
}
if (asgnd_clust != cluster_assignments[row]) {
// We must avoid the possible race condition on the `updated` variable
// Cheap because it only happens a max of once per iteration.
if (!updated) {
omp_set_lock(&writelock);
updated = true;
omp_unset_lock(&writelock);
}
}
cluster_assignments[row] = asgnd_clust;
pt_cl_as_cnt[omp_get_thread_num()][asgnd_clust]++; // Add to local copy
// Accumulate for local copies
for (unsigned col = 0; col < NEV; col++) {
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] =
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] + matrix[row*NEV + col];
}
}
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
// Serial aggreate of OMP_MAX_THREADS vectors
for (int i = 0; i < OMP_MAX_THREADS; i++) {
// Counts
for (unsigned j = 0; j < K; j++) {
cluster_assignment_counts[j] += pt_cl_as_cnt[i][j];
}
// Summation for cluster centers
#pragma omp parallel for firstprivate(pt_cl) shared(clusters)
for (unsigned row = 0; row < K; row++) { /* ClusterID */
for (unsigned col = 0; col < NEV; col++) { /* Features */
clusters[row*NEV+col] = pt_cl[i][row*NEV + col] + clusters[row*NEV + col];
}
}
}
gettimeofday(&end, NULL);
BOOST_LOG_TRIVIAL(info) << "E-step time taken = " << time_diff(start, end) << " sec";
#if KM_TEST
printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K);
printf("Cluster assignments:\n"); print_arr(cluster_assignments, NUM_ROWS);
#endif
}
/**
* \brief Update the cluster means
* \param matrix The matrix who's rows are being clustered.
* \param clusters The cluster centers (means).
* \param cluster_assignment_counts How many members each cluster has.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void M_step(const double* matrix, double* clusters, unsigned*
cluster_assignment_counts, const unsigned* cluster_assignments, bool init=false)
{
BOOST_LOG_TRIVIAL(info) << "M_step start";
if (init) {
BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ...";
memset(clusters, 0, sizeof(clusters[0])*K*NEV);
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
for (unsigned vid = 0; vid < NUM_ROWS; vid++) {
unsigned asgnd_clust = cluster_assignments[vid];
cluster_assignment_counts[asgnd_clust]++;
for (unsigned col = 0; col < NEV; col++) {
clusters[asgnd_clust*NEV + col] =
clusters[asgnd_clust*NEV + col] + matrix[vid*NEV + col];
}
}
}
// Take the mean of all added means
BOOST_LOG_TRIVIAL(info) << " Div by in place ...";
for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {
if (cluster_assignment_counts[clust_idx] > 0) { // Avoid div by 0
// #pragma omp parallel for firstprivate(cluster_assignment_counts, NEV) shared(clusters)
for (unsigned col = 0; col < NEV; col++) {
clusters[clust_idx*NEV + col] =
clusters[clust_idx*NEV + col] / cluster_assignment_counts[clust_idx];
}
}
}
# if KM_TEST
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
}
}
namespace fg
{
unsigned compute_kmeans(const double* matrix, double* clusters,
unsigned* cluster_assignments, unsigned* cluster_assignment_counts,
const unsigned num_rows, const unsigned nev, const size_t k, const unsigned MAX_ITERS,
const std::string init)
{
NEV = nev;
K = k;
NUM_ROWS = num_rows;
if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) {
BOOST_LOG_TRIVIAL(fatal)
<< "'k' must be between 2 and the number of rows in the matrix";
exit(-1);
}
if (init.compare("random") != 0 && init.compare("kmeanspp") != 0 &&
init.compare("forgy") != 0) {
BOOST_LOG_TRIVIAL(fatal)
<< "[ERROR]: param init must be one of: 'random', 'kmeanspp'.It is '"
<< init << "'";
exit(-1);
}
#ifdef PROFILER
ProfilerStart(PROF_FILE_LOC);
#endif
/*** Begin VarInit of data structures ***/
memset(cluster_assignments, -1,
sizeof(cluster_assignments[0])*NUM_ROWS);
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
omp_init_lock(&writelock);
/*** End VarInit ***/
if (init == "random") {
BOOST_LOG_TRIVIAL(info) << "Init is random_partition \n";
random_partition_init(cluster_assignments);
// We must now update cluster centers before we begin
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments, true);
}
if (init == "forgy") {
BOOST_LOG_TRIVIAL(info) << "Init is forgy";
forgy_init(matrix, clusters);
}
else {
if (init == "kmeanspp") {
kmeanspp_init(); // TODO: kmeanspp
}
}
BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ...";
bool converged = false;
std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ?
"until convergence ...":
std::to_string(MAX_ITERS) + " iterations ...";
BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters;
unsigned iter = 1;
while (iter < MAX_ITERS) {
// Hold cluster assignment counter
BOOST_LOG_TRIVIAL(info) << "\nE-step Iteration " << iter <<
" . Computing cluster assignments ...";
E_step(matrix, clusters, cluster_assignments, cluster_assignment_counts);
if (!updated) {
converged = true;
break;
} else { updated = false; }
BOOST_LOG_TRIVIAL(info) << "M-step Updating cluster means ...";
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments);
iter++;
}
omp_destroy_lock(&writelock);
#ifdef PROFILER
ProfilerStop();
#endif
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
if (converged) {
BOOST_LOG_TRIVIAL(info) <<
"K-means converged in " << iter << " iterations";
} else {
BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in "
<< iter << " iterations";
}
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
return iter;
}
}
<commit_msg>[Matrix]: Using libcommon omp method to determine the number of threads on the machine<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Disa Mhembere ([email protected])
*
* This file is part of FlashMatrix.
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kmeans.h"
#define KM_TEST 0
namespace {
bool updated = false;
static unsigned NEV;
static size_t K;
static unsigned NUM_ROWS;
static omp_lock_t writelock;
short OMP_MAX_THREADS;
static struct timeval start, end;
/**
* \brief Print an arry of some length `len`.
* \param len The length of the array.
*/
template <typename T>
static void print_arr(T* arr, unsigned len) {
printf("[ ");
for (unsigned i = 0; i < len; i++) {
std::cout << arr[i] << " ";
}
printf("]\n");
}
/*
* \Internal
* \brief Simple helper used to print a vector.
* \param v The vector to print.
*/
template <typename T>
static void print_vector(typename std::vector<T>& v)
{
std::cout << "[";
typename std::vector<T>::iterator itr = v.begin();
for (; itr != v.end(); itr++) {
std::cout << " "<< *itr;
}
std::cout << " ]\n";
}
/**
* \brief Get the squared distance given two values.
* \param arg1 the first value.
* \param arg2 the second value.
* \return the squared distance.
*/
static double dist_sq(double arg1, double arg2)
{
double diff = arg1 - arg2;
return diff*diff;
}
/**
* \brief This initializes clusters by randomly choosing sample
* membership in a cluster.
* See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods
* \param cluster_assignments Which cluster each sample falls into.
*/
static void random_partition_init(unsigned* cluster_assignments)
{
BOOST_LOG_TRIVIAL(info) << "Random init start";
// #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)
for (unsigned vid = 0; vid < NUM_ROWS; vid++) {
size_t assigned_cluster = random() % K; // 0...K
cluster_assignments[vid] = assigned_cluster;
}
// NOTE: M-Step is called in compute func to update cluster counts & centers
#if 0
printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS);
#endif
BOOST_LOG_TRIVIAL(info) << "Random init end\n";
}
/**
* \brief Forgy init takes `K` random samples from the matrix
* and uses them as cluster centers.
* \param matrix the flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
*/
static void forgy_init(const double* matrix, double* clusters) {
BOOST_LOG_TRIVIAL(info) << "Forgy init start";
for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K
unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1)
memcpy(&clusters[clust_idx*NEV], &matrix[rand_idx*NEV], sizeof(clusters[0])*NEV);
}
BOOST_LOG_TRIVIAL(info) << "Forgy init end";
}
/**
* \brief A parallel version of the kmeans++ initialization alg.
*/
static void kmeanspp_init()
{
BOOST_LOG_TRIVIAL(fatal) << "kmeanspp not yet implemented";
exit(-1);
}
/*\Internal
* \brief print a col wise matrix of type double / double.
* Used for testing only.
* \param matrix The col wise matrix.
* \param rows The number of rows in the mat
* \param cols The number of cols in the mat
*/
template <typename T>
static void print_mat(T* matrix, const unsigned rows, const unsigned cols) {
for (unsigned row = 0; row < rows; row++) {
std::cout << "[";
for (unsigned col = 0; col < cols; col++) {
std::cout << " " << matrix[row*cols + col];
}
std::cout << " ]\n";
}
}
/**
* \brief Update the cluster assignments while recomputing distance matrix.
* \param matrix The flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void E_step(const double* matrix, double* clusters,
unsigned* cluster_assignments, unsigned* cluster_assignment_counts)
{
gettimeofday(&start, NULL);
// Create per thread vectors
std::vector<std::vector<unsigned>> pt_cl_as_cnt; // K * OMP_MAX_THREADS
std::vector<std::vector<double>> pt_cl; // K * nev * OMP_MAX_THREADS
pt_cl_as_cnt.resize(OMP_MAX_THREADS);
pt_cl.resize(OMP_MAX_THREADS);
for (int i = 0; i < OMP_MAX_THREADS; i++) {
pt_cl_as_cnt[i].resize(K); // C++ default is 0 value in all
pt_cl[i].resize(K*NEV);
}
#pragma omp parallel for firstprivate(matrix, clusters) shared(pt_cl_as_cnt, cluster_assignments)
for (unsigned row = 0; row < NUM_ROWS; row++) {
size_t asgnd_clust = std::numeric_limits<size_t>::max();
double best = std::numeric_limits<double>::max();
for (size_t clust_idx = 0; clust_idx < K; clust_idx++) {
double sum = 0;
for (unsigned col = 0; col < NEV; col++) {
sum += dist_sq(matrix[(row*NEV) + col], clusters[clust_idx*NEV + col]);
}
if (sum < best) {
best = sum;
asgnd_clust = clust_idx;
}
}
if (asgnd_clust != cluster_assignments[row]) {
// We must avoid the possible race condition on the `updated` variable
// Cheap because it only happens a max of once per iteration.
if (!updated) {
omp_set_lock(&writelock);
updated = true;
omp_unset_lock(&writelock);
}
}
cluster_assignments[row] = asgnd_clust;
pt_cl_as_cnt[omp_get_thread_num()][asgnd_clust]++; // Add to local copy
// Accumulate for local copies
for (unsigned col = 0; col < NEV; col++) {
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] =
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] + matrix[row*NEV + col];
}
}
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
// Serial aggreate of OMP_MAX_THREADS vectors
for (int i = 0; i < OMP_MAX_THREADS; i++) {
// Counts
for (unsigned j = 0; j < K; j++) {
cluster_assignment_counts[j] += pt_cl_as_cnt[i][j];
}
// Summation for cluster centers
#pragma omp parallel for firstprivate(pt_cl) shared(clusters)
for (unsigned row = 0; row < K; row++) { /* ClusterID */
for (unsigned col = 0; col < NEV; col++) { /* Features */
clusters[row*NEV+col] = pt_cl[i][row*NEV + col] + clusters[row*NEV + col];
}
}
}
gettimeofday(&end, NULL);
BOOST_LOG_TRIVIAL(info) << "E-step time taken = " << time_diff(start, end) << " sec";
#if KM_TEST
printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K);
printf("Cluster assignments:\n"); print_arr(cluster_assignments, NUM_ROWS);
#endif
}
/**
* \brief Update the cluster means
* \param matrix The matrix who's rows are being clustered.
* \param clusters The cluster centers (means).
* \param cluster_assignment_counts How many members each cluster has.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void M_step(const double* matrix, double* clusters, unsigned*
cluster_assignment_counts, const unsigned* cluster_assignments, bool init=false)
{
BOOST_LOG_TRIVIAL(info) << "M_step start";
if (init) {
BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ...";
memset(clusters, 0, sizeof(clusters[0])*K*NEV);
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
for (unsigned vid = 0; vid < NUM_ROWS; vid++) {
unsigned asgnd_clust = cluster_assignments[vid];
cluster_assignment_counts[asgnd_clust]++;
for (unsigned col = 0; col < NEV; col++) {
clusters[asgnd_clust*NEV + col] =
clusters[asgnd_clust*NEV + col] + matrix[vid*NEV + col];
}
}
}
// Take the mean of all added means
BOOST_LOG_TRIVIAL(info) << " Div by in place ...";
for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {
if (cluster_assignment_counts[clust_idx] > 0) { // Avoid div by 0
// #pragma omp parallel for firstprivate(cluster_assignment_counts, NEV) shared(clusters)
for (unsigned col = 0; col < NEV; col++) {
clusters[clust_idx*NEV + col] =
clusters[clust_idx*NEV + col] / cluster_assignment_counts[clust_idx];
}
}
}
# if KM_TEST
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
}
}
namespace fg
{
unsigned compute_kmeans(const double* matrix, double* clusters,
unsigned* cluster_assignments, unsigned* cluster_assignment_counts,
const unsigned num_rows, const unsigned nev, const size_t k, const unsigned MAX_ITERS,
const std::string init)
{
NEV = nev;
K = k;
NUM_ROWS = num_rows;
OMP_MAX_THREADS = get_num_omp_threads();
if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) {
BOOST_LOG_TRIVIAL(fatal)
<< "'k' must be between 2 and the number of rows in the matrix";
exit(-1);
}
if (init.compare("random") != 0 && init.compare("kmeanspp") != 0 &&
init.compare("forgy") != 0) {
BOOST_LOG_TRIVIAL(fatal)
<< "[ERROR]: param init must be one of: 'random', 'kmeanspp'.It is '"
<< init << "'";
exit(-1);
}
#ifdef PROFILER
ProfilerStart(PROF_FILE_LOC);
#endif
/*** Begin VarInit of data structures ***/
memset(cluster_assignments, -1,
sizeof(cluster_assignments[0])*NUM_ROWS);
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
omp_init_lock(&writelock);
/*** End VarInit ***/
if (init == "random") {
BOOST_LOG_TRIVIAL(info) << "Init is random_partition \n";
random_partition_init(cluster_assignments);
// We must now update cluster centers before we begin
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments, true);
}
if (init == "forgy") {
BOOST_LOG_TRIVIAL(info) << "Init is forgy";
forgy_init(matrix, clusters);
}
else {
if (init == "kmeanspp") {
kmeanspp_init(); // TODO: kmeanspp
}
}
BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ...";
bool converged = false;
std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ?
"until convergence ...":
std::to_string(MAX_ITERS) + " iterations ...";
BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters;
unsigned iter = 1;
while (iter < MAX_ITERS) {
// Hold cluster assignment counter
BOOST_LOG_TRIVIAL(info) << "\nE-step Iteration " << iter <<
" . Computing cluster assignments ...";
E_step(matrix, clusters, cluster_assignments, cluster_assignment_counts);
if (!updated) {
converged = true;
break;
} else { updated = false; }
BOOST_LOG_TRIVIAL(info) << "M-step Updating cluster means ...";
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments);
iter++;
}
omp_destroy_lock(&writelock);
#ifdef PROFILER
ProfilerStop();
#endif
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
if (converged) {
BOOST_LOG_TRIVIAL(info) <<
"K-means converged in " << iter << " iterations";
} else {
BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in "
<< iter << " iterations";
}
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
return iter;
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <wchar.h>
#include "XSData.h"
#include "Tab.h"
#include "Parser.h"
#include "Scanner.h"
namespace CocoXml{
struct options_s enum_options[]={
{"UNKNOWN_NAMESPACE", UNKNOWN_NAMESPACE},
{"END_UNKNOWN_NAMESPACE", END_UNKNOWN_NAMESPACE},
{"UNKNOWN_TAG", UNKNOWN_TAG},
{"END_UNKNOWN_TAG", END_UNKNOWN_TAG},
{"UNKNOWN_ATTR_NAMESPACE", UNKNOWN_ATTR_NAMESPACE},
{"UNKNOWN_ATTR", UNKNOWN_ATTR},
{"UNKNOWN_PROCESSING_INSTRUCTION", UNKNOWN_PROCESSING_INSTRUCTION},
// For the nodes in common status.
{"TEXT", TEXT},
{"CDATA", CDATA},
{"COMMENT", COMMENT},
{"WHITESPACE", WHITESPACE},
// For the nodes in Unknown namespaces.
{"UNS_TEXT", UNS_TEXT},
{"UNS_CDATA", UNS_CDATA},
{"UNS_COMMENT", UNS_COMMENT},
{"UNS_WHITESPACE", UNS_WHITESPACE},
// For the nodes in Unknown tags.
{"UT_TEXT", UT_TEXT},
{"UT_CDATA", UT_CDATA},
{"UT_COMMENT", UT_COMMENT},
{"UT_WHITESPACE", UT_WHITESPACE},
{NULL, -1}
};
map<const wchar_t*, int, wcharCmp> optionsMap;
XmlLangDefinition::XmlLangDefinition(Tab *tab, Errors *errors){
int i;
this->tab = tab;
this->errors = errors;
for (i=0; enum_options[i].value>=0; i++){
optionsMap.insert(make_pair(coco_string_create(enum_options[i].name), enum_options[i].value));
}
useVector.resize(optionsMap.size());
}
void XmlLangDefinition::AddOption(const wchar_t* optname, int line){
int optval; Symbol* sym;
map<const wchar_t*, int>::iterator it = optionsMap.find(optname);
if(it != optionsMap.end()){
/* find it */
optval = it->second;
}else{
wchar_t fmt[200];
coco_swprintf(fmt, 200, L"Unsupported option '%ls' encountered. Line(%d)\n", optname, line);
for(it=optionsMap.begin();it!=optionsMap.end();it++){
wprintf(L"Options:%ls,%d\n", it->first, it->second);
}
/* unsupported option */
errors->Exception(fmt);
return;
}
useVector[optval] = true;
sym = tab->FindSym(optname);
if (sym == NULL) tab->NewSym(Node::t, optname, line);
}
int XmlLangDefinition::addUniqueToken(const wchar_t* tokenName, const wchar_t* typeName, int line){
Symbol *sym = tab->FindSym(tokenName);
if (sym != NULL){
wprintf(L"typeName '%ls' declared twice\n", tokenName);
errors->count ++;
}
sym = tab->NewSym(Node::t, tokenName, line);
return sym->n;
}
void XmlLangDefinition::AddTag(const wchar_t* tagname, wchar_t* tokenname, int line){
TagInfo *tinfo = new TagInfo();
wchar_t tmp[200];
tinfo->startToken = addUniqueToken(tokenname, L"Tag", line);
coco_swprintf(tmp, 200, L"END_%ls", tokenname);
tinfo->endToken = addUniqueToken(tmp, L"Tag", line);
map<const wchar_t*, TagInfo*>::iterator it = Tags.find(tagname);
if (it != Tags.end()){
wprintf(L"Tag '%ls' declared twice\n", tagname);
errors->count ++;
}
Tags.insert(make_pair(tagname, tinfo));
}
void XmlLangDefinition::AddAttr(const wchar_t* attrname, const wchar_t* tokenname, int line){
int value = addUniqueToken(tokenname, L"Attribute", line);
map<const wchar_t*, int>::iterator it = Attrs.find(attrname);
if (it!=Attrs.end()){
wprintf(L"Attribute '%ls' declared twice\n", attrname);
errors->count ++;
}
Attrs.insert(make_pair(attrname, value));
}
void XmlLangDefinition::AddProcessingInstruction(const wchar_t* pinstruction, const wchar_t* tokenname, int line){
int value = addUniqueToken(tokenname, L"Processing instruction", line);
map<const wchar_t*, int>::iterator it = PInstructions.find(pinstruction);
if (it!=PInstructions.end()){
wprintf(L"Processing Instruction '%ls' declared twice\n", pinstruction);
errors->count ++;
}
PInstructions.insert(make_pair(pinstruction, value));
}
void XmlLangDefinition::Write(FILE* gen){
int option;
for (option = 0; option < useVector.size(); ++option)
if (useVector[option]){
const char *optionname = enum_options[option].name;
map<const wchar_t*, int>::iterator iter=optionsMap.find(coco_string_create(optionname));
if(iter!=optionsMap.end()){
fwprintf(gen, L"\tcurXLDef.useVector[%d] = true; // %ls", option, iter->first);
}else{
errors->Exception(L"Why come here? it MUST have some error in somwhere?\n");
}
}
map<const wchar_t*, TagInfo*>::iterator iter;
for (iter=Tags.begin(); iter!=Tags.end(); ++iter)
fwprintf(gen, L"\tcurXLDef.AddTag(%ls, %d, %d);",
iter->first, iter->second->startToken, iter->second->endToken);
map<const wchar_t*, int>::iterator iter1;
for (iter1=Attrs.begin(); iter1!=Attrs.end(); ++iter1)
fwprintf(gen, L"\tcurXLDef.AddAttr(%ls, %d);", iter1->first, iter1->second);
map<const wchar_t*, int>::iterator iter2;
for (iter2=PInstructions.begin(); iter2!=PInstructions.end(); ++iter2)
fwprintf(gen, L"\tcurXLDef.AddProcessInstruction(%ls, %d);", iter2->first, iter2->second);
}
XmlScannerData::XmlScannerData(Parser *parser){
this->tab = parser->tab;
this->errors = parser->errors;
}
void XmlScannerData::Add(const wchar_t* NamespaceURI, XmlLangDefinition *xldef){
map<const wchar_t*, XmlLangDefinition*>::iterator it=XmlLangMap.find(NamespaceURI);
if (it != XmlLangMap.end()){
wchar_t fmt[200];
coco_swprintf(fmt, 200, L"Namespace '%ls' declared twice.", NamespaceURI);
/* unsupported option */
errors->Exception(fmt);
}
XmlLangMap.insert(make_pair(NamespaceURI, xldef));
}
void XmlScannerData::OpenGen(const wchar_t *genName, bool backUp) { /* pdt */
wchar_t *fn = coco_string_create_append(tab->outDir, genName); /* pdt */
char *chFn = coco_string_create_char(fn);
FILE* tmp;
if (backUp && ((tmp = fopen(chFn, "r")) != NULL)) {
fclose(tmp);
wchar_t *oldName = coco_string_create_append(fn, L".old");
char *chOldName = coco_string_create_char(oldName);
remove(chOldName); rename(chFn, chOldName); // copy with overwrite
coco_string_delete(chOldName);
coco_string_delete(oldName);
}
if ((gen = fopen(chFn, "w")) == NULL) {
errors->Exception(L"-- Cannot generate scanner file");
}
coco_string_delete(chFn);
coco_string_delete(fn);
}
void XmlScannerData::CopyFramePart(const wchar_t * stop){
wchar_t startCh = stop[0];
int endOfStopString = coco_string_length(stop)-1;
wchar_t ch = 0;
fwscanf(fram, L"%lc", &ch); //fram.ReadByte();
while (!feof(fram)) // ch != EOF
if (ch == startCh) {
int i = 0;
do {
if (i == endOfStopString) return; // stop[0..i] found
fwscanf(fram, L"%lc", &ch); i++;
} while (ch == stop[i]);
// stop[0..i-1] found; continue with last read character
wchar_t *subStop = coco_string_create(stop, 0, i);
fwprintf(gen, L"%ls", subStop);
coco_string_delete(subStop);
} else {
fwprintf(gen, L"%lc", ch);
fwscanf(fram, L"%lc", &ch);
}
wprintf(L"CopyFramePart:[%ls]\n", stop);
errors->Exception(L" -- incomplete or corrupt scanner frame file\n");
}
void XmlScannerData::WriteOptions(){
fwprintf(gen, L" public enum Options {");
map<const wchar_t*, int>::iterator iter;
for (iter=optionsMap.begin(); iter!=optionsMap.end(); iter++)
fwprintf(gen, L" %ls,", iter->first);
fwprintf(gen, L" };");
fwprintf(gen, L" public const int numOptions = %d;", optionsMap.size());
}
void XmlScannerData::WriteDeclarations(){
Symbol *sym;
fwprintf(gen, L" static readonly int[] useKindVector = new int[] {");
map<const wchar_t*, int>::iterator iter;
for (iter=optionsMap.begin(); iter!=optionsMap.end(); ++iter){
sym = tab->FindSym(iter->first);
fwprintf(gen, L" %d, // %ls", sym == NULL ? -1 : sym->n, iter->first);
}
fwprintf(gen, L" };");
}
void XmlScannerData::WriteInitialization(){
map<const wchar_t *, XmlLangDefinition*>::iterator iter;
for (iter=XmlLangMap.begin(); iter!=XmlLangMap.end(); ++iter){
fwprintf(gen, L"\tcurXLDef = new XmlLangDefinition();");
iter->second->Write(gen);
fwprintf(gen, L"\tXmlLangMap.Add(\"%ls\", curXLDef);", iter->first);
}
}
int XmlScannerData::GenNamespaceOpen(const wchar_t *nsName) {
if (nsName == NULL || coco_string_length(nsName) == 0) {
return 0;
}
int len = coco_string_length(nsName);
int startPos = 0, endPos;
int nrOfNs = 0;
do {
endPos = coco_string_indexof(nsName + startPos, COCO_CPP_NAMESPACE_SEPARATOR);
if (endPos == -1) { endPos = len; }
wchar_t *curNs = coco_string_create(nsName, startPos, endPos - startPos);
fwprintf(gen, L"namespace %ls {\n", curNs);
coco_string_delete(curNs);
startPos = endPos + 1;
++nrOfNs;
} while (startPos < len);
return nrOfNs;
}
void XmlScannerData::GenNamespaceClose(int nrOfNs) {
for (int i = 0; i < nrOfNs; ++i) {
fwprintf(gen, L"}; // namespace\n");
}
}
void XmlScannerData::WriteXmlScanner(){
wchar_t *fr = coco_string_create_append(tab->srcDir, L"XmlScanner.frame");
char *chFr = coco_string_create_char(fr);
FILE* tmp;
if ((tmp = fopen(chFr, "r")) == NULL) {
if (coco_string_length(tab->frameDir) != 0) {
delete [] fr;
fr = coco_string_create(tab->frameDir);
coco_string_merge(fr, L"/");
coco_string_merge(fr, L"XmlScanner.frame");
}
coco_string_delete(chFr);
chFr = coco_string_create_char(fr);
if ((tmp = fopen(chFr, "r")) == NULL) {
errors->Exception(L"-- Cannot find XmlScanner.frame\n");
} else {
fclose(tmp);
}
} else {
fclose(tmp);
}
if ((fram = fopen(chFr, "r")) == NULL) {
errors->Exception(L"-- Cannot open XmlScanner.frame.\n");
}
coco_string_delete(chFr);
coco_string_delete(fr);
/* to generate header file */
{
OpenGen(L"XmlScanner.h", true);
CopyFramePart(L"/*---- Namespace Begin ----*/");
int nrOfNs = GenNamespaceOpen(tab->nsName);
CopyFramePart(L"/*---- Options ----*/"); WriteOptions();
CopyFramePart(L"/*---- Declarations ----*/"); WriteDeclarations();
CopyFramePart(L"/*---- Namespace End ----*/");
GenNamespaceClose(nrOfNs);
CopyFramePart(L"/*---- Implementation ----*/");
fclose(gen);
}
/* to generate source file */
{
OpenGen(L"XmlScanner.cpp", true);
CopyFramePart(L"/*---- Begin ----*/");
fwprintf(gen, L"// THIS FILE IS GENERATED BY CocoXml AUTOMATICALLY, DO NOT EDIT IT MANUALLY.");
CopyFramePart(L"/*---- Namespace Begin ----*/");
int nrOfNs = GenNamespaceOpen(tab->nsName);
CopyFramePart(L"/*---- Initialization ----*/"); WriteInitialization();
CopyFramePart(L"/*---- Namespace End ----*/");
CopyFramePart(L"/*---- $$$ ----*/");
GenNamespaceClose(nrOfNs);
fclose(gen);
}
}
} //namespace
<commit_msg>add line character<commit_after>#include <stdlib.h>
#include <wchar.h>
#include "XSData.h"
#include "Tab.h"
#include "Parser.h"
#include "Scanner.h"
namespace CocoXml{
struct options_s enum_options[]={
{"UNKNOWN_NAMESPACE", UNKNOWN_NAMESPACE},
{"END_UNKNOWN_NAMESPACE", END_UNKNOWN_NAMESPACE},
{"UNKNOWN_TAG", UNKNOWN_TAG},
{"END_UNKNOWN_TAG", END_UNKNOWN_TAG},
{"UNKNOWN_ATTR_NAMESPACE", UNKNOWN_ATTR_NAMESPACE},
{"UNKNOWN_ATTR", UNKNOWN_ATTR},
{"UNKNOWN_PROCESSING_INSTRUCTION", UNKNOWN_PROCESSING_INSTRUCTION},
// For the nodes in common status.
{"TEXT", TEXT},
{"CDATA", CDATA},
{"COMMENT", COMMENT},
{"WHITESPACE", WHITESPACE},
// For the nodes in Unknown namespaces.
{"UNS_TEXT", UNS_TEXT},
{"UNS_CDATA", UNS_CDATA},
{"UNS_COMMENT", UNS_COMMENT},
{"UNS_WHITESPACE", UNS_WHITESPACE},
// For the nodes in Unknown tags.
{"UT_TEXT", UT_TEXT},
{"UT_CDATA", UT_CDATA},
{"UT_COMMENT", UT_COMMENT},
{"UT_WHITESPACE", UT_WHITESPACE},
{NULL, -1}
};
map<const wchar_t*, int, wcharCmp> optionsMap;
XmlLangDefinition::XmlLangDefinition(Tab *tab, Errors *errors){
int i;
this->tab = tab;
this->errors = errors;
for (i=0; enum_options[i].value>=0; i++){
optionsMap.insert(make_pair(coco_string_create(enum_options[i].name), enum_options[i].value));
}
useVector.resize(optionsMap.size());
}
void XmlLangDefinition::AddOption(const wchar_t* optname, int line){
int optval; Symbol* sym;
map<const wchar_t*, int>::iterator it = optionsMap.find(optname);
if(it != optionsMap.end()){
/* find it */
optval = it->second;
}else{
wchar_t fmt[200];
coco_swprintf(fmt, 200, L"Unsupported option '%ls' encountered. Line(%d)\n", optname, line);
for(it=optionsMap.begin();it!=optionsMap.end();it++){
wprintf(L"Options:%ls,%d\n", it->first, it->second);
}
/* unsupported option */
errors->Exception(fmt);
return;
}
useVector[optval] = true;
sym = tab->FindSym(optname);
if (sym == NULL) tab->NewSym(Node::t, optname, line);
}
int XmlLangDefinition::addUniqueToken(const wchar_t* tokenName, const wchar_t* typeName, int line){
Symbol *sym = tab->FindSym(tokenName);
if (sym != NULL){
wprintf(L"typeName '%ls' declared twice\n", tokenName);
errors->count ++;
}
sym = tab->NewSym(Node::t, tokenName, line);
return sym->n;
}
void XmlLangDefinition::AddTag(const wchar_t* tagname, wchar_t* tokenname, int line){
TagInfo *tinfo = new TagInfo();
wchar_t tmp[200];
tinfo->startToken = addUniqueToken(tokenname, L"Tag", line);
coco_swprintf(tmp, 200, L"END_%ls", tokenname);
tinfo->endToken = addUniqueToken(tmp, L"Tag", line);
map<const wchar_t*, TagInfo*>::iterator it = Tags.find(tagname);
if (it != Tags.end()){
wprintf(L"Tag '%ls' declared twice\n", tagname);
errors->count ++;
}
Tags.insert(make_pair(tagname, tinfo));
}
void XmlLangDefinition::AddAttr(const wchar_t* attrname, const wchar_t* tokenname, int line){
int value = addUniqueToken(tokenname, L"Attribute", line);
map<const wchar_t*, int>::iterator it = Attrs.find(attrname);
if (it!=Attrs.end()){
wprintf(L"Attribute '%ls' declared twice\n", attrname);
errors->count ++;
}
Attrs.insert(make_pair(attrname, value));
}
void XmlLangDefinition::AddProcessingInstruction(const wchar_t* pinstruction, const wchar_t* tokenname, int line){
int value = addUniqueToken(tokenname, L"Processing instruction", line);
map<const wchar_t*, int>::iterator it = PInstructions.find(pinstruction);
if (it!=PInstructions.end()){
wprintf(L"Processing Instruction '%ls' declared twice\n", pinstruction);
errors->count ++;
}
PInstructions.insert(make_pair(pinstruction, value));
}
void XmlLangDefinition::Write(FILE* gen){
int option;
for (option = 0; option < useVector.size(); ++option)
if (useVector[option]){
const char *optionname = enum_options[option].name;
map<const wchar_t*, int>::iterator iter=optionsMap.find(coco_string_create(optionname));
if(iter!=optionsMap.end()){
fwprintf(gen, L" curXLDef.useVector[%d] = true; // %ls\n", option, iter->first);
}else{
errors->Exception(L"Why come here? it MUST have some error in somwhere?\n");
}
}
map<const wchar_t*, TagInfo*>::iterator iter;
for (iter=Tags.begin(); iter!=Tags.end(); ++iter)
fwprintf(gen, L" curXLDef.AddTag(L%ls, %d, %d);\n",
iter->first, iter->second->startToken, iter->second->endToken);
map<const wchar_t*, int>::iterator iter1;
for (iter1=Attrs.begin(); iter1!=Attrs.end(); ++iter1)
fwprintf(gen, L" curXLDef.AddAttr(L%ls, %d);\n", iter1->first, iter1->second);
map<const wchar_t*, int>::iterator iter2;
for (iter2=PInstructions.begin(); iter2!=PInstructions.end(); ++iter2)
fwprintf(gen, L" curXLDef.AddProcessInstruction(L%ls, %d);\n", iter2->first, iter2->second);
}
XmlScannerData::XmlScannerData(Parser *parser){
this->tab = parser->tab;
this->errors = parser->errors;
}
void XmlScannerData::Add(const wchar_t* NamespaceURI, XmlLangDefinition *xldef){
map<const wchar_t*, XmlLangDefinition*>::iterator it=XmlLangMap.find(NamespaceURI);
if (it != XmlLangMap.end()){
wchar_t fmt[200];
coco_swprintf(fmt, 200, L"Namespace '%ls' declared twice.", NamespaceURI);
/* unsupported option */
errors->Exception(fmt);
}
XmlLangMap.insert(make_pair(NamespaceURI, xldef));
}
void XmlScannerData::OpenGen(const wchar_t *genName, bool backUp) { /* pdt */
wchar_t *fn = coco_string_create_append(tab->outDir, genName); /* pdt */
char *chFn = coco_string_create_char(fn);
FILE* tmp;
if (backUp && ((tmp = fopen(chFn, "r")) != NULL)) {
fclose(tmp);
wchar_t *oldName = coco_string_create_append(fn, L".old");
char *chOldName = coco_string_create_char(oldName);
remove(chOldName); rename(chFn, chOldName); // copy with overwrite
coco_string_delete(chOldName);
coco_string_delete(oldName);
}
if ((gen = fopen(chFn, "w")) == NULL) {
errors->Exception(L"-- Cannot generate scanner file");
}
coco_string_delete(chFn);
coco_string_delete(fn);
}
void XmlScannerData::CopyFramePart(const wchar_t * stop){
wchar_t startCh = stop[0];
int endOfStopString = coco_string_length(stop)-1;
wchar_t ch = 0;
fwscanf(fram, L"%lc", &ch); //fram.ReadByte();
while (!feof(fram)) // ch != EOF
if (ch == startCh) {
int i = 0;
do {
if (i == endOfStopString) return; // stop[0..i] found
fwscanf(fram, L"%lc", &ch); i++;
} while (ch == stop[i]);
// stop[0..i-1] found; continue with last read character
wchar_t *subStop = coco_string_create(stop, 0, i);
fwprintf(gen, L"%ls", subStop);
coco_string_delete(subStop);
} else {
fwprintf(gen, L"%lc", ch);
fwscanf(fram, L"%lc", &ch);
}
wprintf(L"CopyFramePart:[%ls]\n", stop);
errors->Exception(L" -- incomplete or corrupt scanner frame file\n");
}
void XmlScannerData::WriteOptions(){
fwprintf(gen, L" enum Options {\n");
map<const wchar_t*, int>::iterator iter;
for (iter=optionsMap.begin(); iter!=optionsMap.end(); iter++)
fwprintf(gen, L" %ls,\n", iter->first);
fwprintf(gen, L" };\n");
fwprintf(gen, L" const int numOptions = %d;\n", optionsMap.size());
}
void XmlScannerData::WriteDeclarations(){
Symbol *sym;
fwprintf(gen, L" int[] useKindVector = new int[] {\n");
map<const wchar_t*, int>::iterator iter;
for (iter=optionsMap.begin(); iter!=optionsMap.end(); ++iter){
sym = tab->FindSym(iter->first);
fwprintf(gen, L" %d, // %ls\n", sym == NULL ? -1 : sym->n, iter->first);
}
fwprintf(gen, L" };\n");
}
void XmlScannerData::WriteInitialization(){
map<const wchar_t *, XmlLangDefinition*>::iterator iter;
for (iter=XmlLangMap.begin(); iter!=XmlLangMap.end(); ++iter){
fwprintf(gen, L" curXLDef = new XmlLangDefinition();\n");
iter->second->Write(gen);
fwprintf(gen, L" XmlLangMap.Add(\"%ls\", curXLDef);\n", iter->first);
}
}
int XmlScannerData::GenNamespaceOpen(const wchar_t *nsName) {
if (nsName == NULL || coco_string_length(nsName) == 0) {
return 0;
}
int len = coco_string_length(nsName);
int startPos = 0, endPos;
int nrOfNs = 0;
do {
endPos = coco_string_indexof(nsName + startPos, COCO_CPP_NAMESPACE_SEPARATOR);
if (endPos == -1) { endPos = len; }
wchar_t *curNs = coco_string_create(nsName, startPos, endPos - startPos);
fwprintf(gen, L"namespace %ls {\n", curNs);
coco_string_delete(curNs);
startPos = endPos + 1;
++nrOfNs;
} while (startPos < len);
return nrOfNs;
}
void XmlScannerData::GenNamespaceClose(int nrOfNs) {
for (int i = 0; i < nrOfNs; ++i) {
fwprintf(gen, L"}; // namespace\n");
}
}
void XmlScannerData::WriteXmlScanner(){
wchar_t *fr = coco_string_create_append(tab->srcDir, L"XmlScanner.frame");
char *chFr = coco_string_create_char(fr);
FILE* tmp;
if ((tmp = fopen(chFr, "r")) == NULL) {
if (coco_string_length(tab->frameDir) != 0) {
delete [] fr;
fr = coco_string_create(tab->frameDir);
coco_string_merge(fr, L"/");
coco_string_merge(fr, L"XmlScanner.frame");
}
coco_string_delete(chFr);
chFr = coco_string_create_char(fr);
if ((tmp = fopen(chFr, "r")) == NULL) {
errors->Exception(L"-- Cannot find XmlScanner.frame\n");
} else {
fclose(tmp);
}
} else {
fclose(tmp);
}
if ((fram = fopen(chFr, "r")) == NULL) {
errors->Exception(L"-- Cannot open XmlScanner.frame.\n");
}
coco_string_delete(chFr);
coco_string_delete(fr);
/* to generate header file */
{
OpenGen(L"XmlScanner.h", true);
CopyFramePart(L"/*---- Namespace Begin ----*/");
int nrOfNs = GenNamespaceOpen(tab->nsName);
CopyFramePart(L"/*---- Options ----*/"); WriteOptions();
CopyFramePart(L"/*---- Declarations ----*/"); WriteDeclarations();
CopyFramePart(L"/*---- Namespace End ----*/");
GenNamespaceClose(nrOfNs);
CopyFramePart(L"/*---- Implementation ----*/");
fclose(gen);
}
/* to generate source file */
{
OpenGen(L"XmlScanner.cpp", true);
CopyFramePart(L"/*---- Begin ----*/");
fwprintf(gen, L"// THIS FILE IS GENERATED BY CocoXml AUTOMATICALLY, DO NOT EDIT IT MANUALLY.\n");
CopyFramePart(L"/*---- Namespace Begin ----*/");
int nrOfNs = GenNamespaceOpen(tab->nsName);
CopyFramePart(L"/*---- Initialization ----*/"); WriteInitialization();
CopyFramePart(L"/*---- Namespace End ----*/");
CopyFramePart(L"/*---- $$$ ----*/");
GenNamespaceClose(nrOfNs);
fclose(gen);
}
}
} //namespace
<|endoftext|> |
<commit_before>// Copyright 2014 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 "base/prefs/pref_service.h"
#include "chrome/browser/browsing_data/browsing_data_remover_test_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/options/options_ui_browsertest.h"
#include "chrome/common/url_constants.h"
#include "content/public/test/browser_test_utils.h"
namespace options {
class ClearBrowserDataBrowserTest : public OptionsUIBrowserTest {
protected:
void ClickElement(const std::string& selector) {
bool element_enabled = false;
ASSERT_NO_FATAL_FAILURE(GetElementEnabledState(selector, &element_enabled));
ASSERT_TRUE(element_enabled);
ASSERT_TRUE(content::ExecuteScript(
GetSettingsFrame(),
"document.querySelector('" + selector + "').click();"));
}
bool IsElementEnabled(const std::string& selector) {
bool element_enabled = false;
GetElementEnabledState(selector, &element_enabled);
return element_enabled;
}
bool IsElementInFocus(const std::string& selector) {
bool element_in_focus = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
GetSettingsFrame(),
"window.domAutomationController.send(document.querySelector('" +
selector + "') == document.activeElement);",
&element_in_focus));
return element_in_focus;
}
private:
void GetElementEnabledState(
const std::string& selector,
bool* enabled) {
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
GetSettingsFrame(),
"window.domAutomationController.send(!document.querySelector('" +
selector + "').disabled);",
enabled));
}
};
IN_PROC_BROWSER_TEST_F(ClearBrowserDataBrowserTest,
CommitButtonDisabledWhileDeletionInProgress) {
const char kTimePeriodSelectorId[] = "#clear-browser-data-time-period";
const char kCommitButtonId[] = "#clear-browser-data-commit";
BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
// Navigate to the Clear Browsing Data dialog to ensure that the commit button
// is initially enabled, usable, and gets disabled after having been pressed.
// Furthermore, verify that the time period combo-box gets the initial focus.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_TRUE(IsElementInFocus(kTimePeriodSelectorId));
ASSERT_NO_FATAL_FAILURE(ClickElement(kCommitButtonId));
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
completion_inhibitor.BlockUntilNearCompletion();
// Simulate a reload while the previous removal is still running, and verify
// that the button is still disabled.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
completion_inhibitor.ContinueToCompletion();
// However, the button should be enabled again once the process has finished.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_TRUE(IsElementEnabled(kCommitButtonId));
}
IN_PROC_BROWSER_TEST_F(ClearBrowserDataBrowserTest,
CommitButtonDisabledWhenNoDataTypesSelected) {
const char kCommitButtonId[] = "#clear-browser-data-commit";
const char* kDataTypes[] = {"browser.clear_data.browsing_history",
"browser.clear_data.download_history",
"browser.clear_data.cache",
"browser.clear_data.cookies",
"browser.clear_data.passwords",
"browser.clear_data.form_data",
"browser.clear_data.hosted_apps_data",
"browser.clear_data.content_licenses"};
PrefService* prefs = browser()->profile()->GetPrefs();
for (size_t i = 0; i < arraysize(kDataTypes); ++i) {
prefs->SetBoolean(kDataTypes[i], false);
}
// Navigate to the Clear Browsing Data dialog to ensure that the commit button
// is disabled if clearing is not requested for any of the data types.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
// However, expect the commit button to be re-enabled if any of the data types
// gets selected to be cleared.
for (size_t i = 0; i < arraysize(kDataTypes); ++i) {
prefs->SetBoolean(kDataTypes[i], true);
EXPECT_TRUE(IsElementEnabled(kCommitButtonId));
prefs->SetBoolean(kDataTypes[i], false);
}
}
} // namespace options
<commit_msg>DisabledClearBrowserDataBrowserTest.CommitButtonDisabledWhileDeletionInProgress.<commit_after>// Copyright 2014 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 "base/prefs/pref_service.h"
#include "chrome/browser/browsing_data/browsing_data_remover_test_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/options/options_ui_browsertest.h"
#include "chrome/common/url_constants.h"
#include "content/public/test/browser_test_utils.h"
namespace options {
class ClearBrowserDataBrowserTest : public OptionsUIBrowserTest {
protected:
void ClickElement(const std::string& selector) {
bool element_enabled = false;
ASSERT_NO_FATAL_FAILURE(GetElementEnabledState(selector, &element_enabled));
ASSERT_TRUE(element_enabled);
ASSERT_TRUE(content::ExecuteScript(
GetSettingsFrame(),
"document.querySelector('" + selector + "').click();"));
}
bool IsElementEnabled(const std::string& selector) {
bool element_enabled = false;
GetElementEnabledState(selector, &element_enabled);
return element_enabled;
}
bool IsElementInFocus(const std::string& selector) {
bool element_in_focus = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
GetSettingsFrame(),
"window.domAutomationController.send(document.querySelector('" +
selector + "') == document.activeElement);",
&element_in_focus));
return element_in_focus;
}
private:
void GetElementEnabledState(
const std::string& selector,
bool* enabled) {
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
GetSettingsFrame(),
"window.domAutomationController.send(!document.querySelector('" +
selector + "').disabled);",
enabled));
}
};
// Fails flakily. http://crbug.com/379574
IN_PROC_BROWSER_TEST_F(ClearBrowserDataBrowserTest,
DISABLED_CommitButtonDisabledWhileDeletionInProgress) {
const char kTimePeriodSelectorId[] = "#clear-browser-data-time-period";
const char kCommitButtonId[] = "#clear-browser-data-commit";
BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
// Navigate to the Clear Browsing Data dialog to ensure that the commit button
// is initially enabled, usable, and gets disabled after having been pressed.
// Furthermore, verify that the time period combo-box gets the initial focus.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_TRUE(IsElementInFocus(kTimePeriodSelectorId));
ASSERT_NO_FATAL_FAILURE(ClickElement(kCommitButtonId));
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
completion_inhibitor.BlockUntilNearCompletion();
// Simulate a reload while the previous removal is still running, and verify
// that the button is still disabled.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
completion_inhibitor.ContinueToCompletion();
// However, the button should be enabled again once the process has finished.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_TRUE(IsElementEnabled(kCommitButtonId));
}
IN_PROC_BROWSER_TEST_F(ClearBrowserDataBrowserTest,
CommitButtonDisabledWhenNoDataTypesSelected) {
const char kCommitButtonId[] = "#clear-browser-data-commit";
const char* kDataTypes[] = {"browser.clear_data.browsing_history",
"browser.clear_data.download_history",
"browser.clear_data.cache",
"browser.clear_data.cookies",
"browser.clear_data.passwords",
"browser.clear_data.form_data",
"browser.clear_data.hosted_apps_data",
"browser.clear_data.content_licenses"};
PrefService* prefs = browser()->profile()->GetPrefs();
for (size_t i = 0; i < arraysize(kDataTypes); ++i) {
prefs->SetBoolean(kDataTypes[i], false);
}
// Navigate to the Clear Browsing Data dialog to ensure that the commit button
// is disabled if clearing is not requested for any of the data types.
NavigateToSettingsSubpage(chrome::kClearBrowserDataSubPage);
EXPECT_FALSE(IsElementEnabled(kCommitButtonId));
// However, expect the commit button to be re-enabled if any of the data types
// gets selected to be cleared.
for (size_t i = 0; i < arraysize(kDataTypes); ++i) {
prefs->SetBoolean(kDataTypes[i], true);
EXPECT_TRUE(IsElementEnabled(kCommitButtonId));
prefs->SetBoolean(kDataTypes[i], false);
}
}
} // namespace options
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
XCodecDecoder::XCodecDecoder(XCodecCache *cache)
: log_("/xcodec/decoder"),
cache_(cache),
window_()
{ }
XCodecDecoder::~XCodecDecoder()
{ }
/*
* XXX These comments are out-of-date.
*
* Decode an XCodec-encoded stream. Returns false if there was an
* inconsistency, error or unrecoverable condition in the stream.
* Returns true if we were able to process the stream entirely or
* expect to be able to finish processing it once more data arrives.
* The input buffer is cleared of anything we can parse right now.
*
* Since some events later in the stream (i.e. ASK or LEARN) may need
* to be processed before some earlier in the stream (i.e. REF), we
* parse the stream into a list of actions to take, performing them
* as we go if possible, otherwise queueing them to occur until the
* action that is blocking the stream has been satisfied or the stream
* has been closed.
*
* XXX For now we will ASK in every stream where an unknown hash has
* occurred and expect a LEARN in all of them. In the future, it is
* desirable to optimize this. Especially once we start putting an
* instance UUID in the HELLO message and can tell which streams
* share an originator.
*/
bool
XCodecDecoder::decode(Buffer *output, Buffer *input, std::set<uint64_t>& unknown_hashes)
{
while (!input->empty()) {
unsigned off;
if (!input->find(XCODEC_MAGIC, &off)) {
output->append(input);
input->clear();
break;
}
if (off != 0) {
output->append(input, off);
input->skip(off);
}
ASSERT(!input->empty());
/*
* Need the following byte at least.
*/
if (input->length() == 1)
break;
uint8_t op;
input->extract(&op, sizeof XCODEC_MAGIC);
switch (op) {
case XCODEC_OP_ESCAPE:
output->append(XCODEC_MAGIC);
input->skip(sizeof XCODEC_MAGIC + sizeof op);
break;
case XCODEC_OP_EXTRACT:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + XCODEC_SEGMENT_LENGTH)
goto done;
else {
input->skip(sizeof XCODEC_MAGIC + sizeof op);
BufferSegment *seg;
input->copyout(&seg, XCODEC_SEGMENT_LENGTH);
input->skip(XCODEC_SEGMENT_LENGTH);
uint64_t hash = XCodecHash::hash(seg->data());
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
if (oseg->equal(seg)) {
seg->unref();
seg = oseg;
} else {
ERROR(log_) << "Collision in <EXTRACT>.";
seg->unref();
return (false);
}
} else {
cache_->enter(hash, seg);
}
window_.declare(hash, seg);
output->append(seg);
seg->unref();
}
break;
case XCODEC_OP_REF:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + sizeof (uint64_t))
goto done;
else {
uint64_t behash;
input->extract(&behash, sizeof XCODEC_MAGIC + sizeof op);
input->skip(sizeof XCODEC_MAGIC + sizeof op + sizeof behash);
uint64_t hash = BigEndian::decode(behash);
BufferSegment *oseg = cache_->lookup(hash);
if (oseg == NULL) {
if (unknown_hashes.find(hash) == unknown_hashes.end()) {
DEBUG(log_) << "Sending <ASK>, waiting for <LEARN>.";
unknown_hashes.insert(hash);
} else {
DEBUG(log_) << "Already sent <ASK>, waiting for <LEARN>.";
}
return (true);
} else {
window_.declare(hash, oseg);
output->append(oseg);
oseg->unref();
}
}
break;
case XCODEC_OP_BACKREF:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + sizeof (uint8_t))
goto done;
else {
uint8_t idx;
input->moveout(&idx, sizeof XCODEC_MAGIC + sizeof op, sizeof idx);
BufferSegment *oseg = window_.dereference(idx);
if (oseg == NULL) {
ERROR(log_) << "Index not present in <BACKREF> window: " << (unsigned)idx;
return (false);
}
output->append(oseg);
oseg->unref();
}
break;
default:
ERROR(log_) << "Unsupported XCodec opcode " << (unsigned)op << ".";
return (false);
}
}
done: return (true);
}
<commit_msg>Don't skip a reference if we're sending an ASK for it. If we do that, we can decode a subsequent reference, but the backref window will be wrong.<commit_after>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
XCodecDecoder::XCodecDecoder(XCodecCache *cache)
: log_("/xcodec/decoder"),
cache_(cache),
window_()
{ }
XCodecDecoder::~XCodecDecoder()
{ }
/*
* XXX These comments are out-of-date.
*
* Decode an XCodec-encoded stream. Returns false if there was an
* inconsistency, error or unrecoverable condition in the stream.
* Returns true if we were able to process the stream entirely or
* expect to be able to finish processing it once more data arrives.
* The input buffer is cleared of anything we can parse right now.
*
* Since some events later in the stream (i.e. ASK or LEARN) may need
* to be processed before some earlier in the stream (i.e. REF), we
* parse the stream into a list of actions to take, performing them
* as we go if possible, otherwise queueing them to occur until the
* action that is blocking the stream has been satisfied or the stream
* has been closed.
*
* XXX For now we will ASK in every stream where an unknown hash has
* occurred and expect a LEARN in all of them. In the future, it is
* desirable to optimize this. Especially once we start putting an
* instance UUID in the HELLO message and can tell which streams
* share an originator.
*/
bool
XCodecDecoder::decode(Buffer *output, Buffer *input, std::set<uint64_t>& unknown_hashes)
{
while (!input->empty()) {
unsigned off;
if (!input->find(XCODEC_MAGIC, &off)) {
output->append(input);
input->clear();
break;
}
if (off != 0) {
output->append(input, off);
input->skip(off);
}
ASSERT(!input->empty());
/*
* Need the following byte at least.
*/
if (input->length() == 1)
break;
uint8_t op;
input->extract(&op, sizeof XCODEC_MAGIC);
switch (op) {
case XCODEC_OP_ESCAPE:
output->append(XCODEC_MAGIC);
input->skip(sizeof XCODEC_MAGIC + sizeof op);
break;
case XCODEC_OP_EXTRACT:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + XCODEC_SEGMENT_LENGTH)
goto done;
else {
input->skip(sizeof XCODEC_MAGIC + sizeof op);
BufferSegment *seg;
input->copyout(&seg, XCODEC_SEGMENT_LENGTH);
input->skip(XCODEC_SEGMENT_LENGTH);
uint64_t hash = XCodecHash::hash(seg->data());
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
if (oseg->equal(seg)) {
seg->unref();
seg = oseg;
} else {
ERROR(log_) << "Collision in <EXTRACT>.";
seg->unref();
return (false);
}
} else {
cache_->enter(hash, seg);
}
window_.declare(hash, seg);
output->append(seg);
seg->unref();
}
break;
case XCODEC_OP_REF:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + sizeof (uint64_t))
goto done;
else {
uint64_t behash;
input->extract(&behash, sizeof XCODEC_MAGIC + sizeof op);
uint64_t hash = BigEndian::decode(behash);
BufferSegment *oseg = cache_->lookup(hash);
if (oseg == NULL) {
if (unknown_hashes.find(hash) == unknown_hashes.end()) {
DEBUG(log_) << "Sending <ASK>, waiting for <LEARN>.";
unknown_hashes.insert(hash);
} else {
DEBUG(log_) << "Already sent <ASK>, waiting for <LEARN>.";
}
return (true);
}
input->skip(sizeof XCODEC_MAGIC + sizeof op + sizeof behash);
window_.declare(hash, oseg);
output->append(oseg);
oseg->unref();
}
break;
case XCODEC_OP_BACKREF:
if (input->length() < sizeof XCODEC_MAGIC + sizeof op + sizeof (uint8_t))
goto done;
else {
uint8_t idx;
input->moveout(&idx, sizeof XCODEC_MAGIC + sizeof op, sizeof idx);
BufferSegment *oseg = window_.dereference(idx);
if (oseg == NULL) {
ERROR(log_) << "Index not present in <BACKREF> window: " << (unsigned)idx;
return (false);
}
output->append(oseg);
oseg->unref();
}
break;
default:
ERROR(log_) << "Unsupported XCodec opcode " << (unsigned)op << ".";
return (false);
}
}
done: return (true);
}
<|endoftext|> |
<commit_before>/**
*
* @file State.cpp
* Definitions for the class State, that manages the independent variables of temperature, mass density,
* and species mass/mole fraction that define the thermodynamic state (see \ref phases and
* class \link Cantera::State State\endlink).
*
*/
/*
* $Author$
* $Date$
* $Revision$
*
* Copyright 2003-2004 California Institute of Technology
* See file License.txt for licensing information
*
*/
#include "utilities.h"
#include "ctexceptions.h"
#include "stringUtils.h"
#include "State.h"
//#ifdef DARWIN
//#include <Accelerate.h>
//#endif
using namespace std;
namespace Cantera {
State::State() : m_kk(0), m_temp(0.0), m_dens(0.001), m_mmw(0.0) {}
State::~State() {}
State::State(const State& right) :
m_kk(0),
m_temp(0.0),
m_dens(0.001),
m_mmw(0.0) {
/*
* Call the assignment operator.
*/
*this = operator=(right);
}
/*
* Assignment operator for the State Class
*/
State& State::operator=(const State& right) {
/*
* Check for self assignment.
*/
if (this == &right) return *this;
/*
* We do a straight assignment operator on all of the
* data. The vectors are copied.
*/
m_kk = right.m_kk;
m_temp = right.m_temp;
m_dens = right.m_dens;
m_mmw = right.m_mmw;
m_ym = right.m_ym;
m_y = right.m_y;
m_molwts = right.m_molwts;
m_rmolwts = right.m_rmolwts;
/*
* Return the reference to the current object
*/
return *this;
}
doublereal State::moleFraction(int k) const {
if (k >= 0 && k < m_kk) {
return m_ym[k] * m_mmw;
}
else {
throw CanteraError("State:moleFraction",
"illegal species index number");
}
}
void State::setMoleFractions(const doublereal* x) {
doublereal sum = 0.0, norm = 0.0;
sum = dot(x, x + m_kk, m_molwts.begin());
doublereal rsum = 1.0/sum;
transform(x, x + m_kk, m_ym.begin(), timesConstant<double>(rsum));
transform(m_ym.begin(), m_ym.begin() + m_kk, m_molwts.begin(),
m_y.begin(), multiplies<double>());
norm = accumulate(x, x + m_kk, 0.0);
//for (k = 0; k != m_kk; ++k) {
// m_ym[k] = x[k] / sum;
// m_y[k] = m_molwts[k]*m_ym[k];
// norm += x[k];
//}
m_mmw = sum/norm;
}
void State::setMoleFractions_NoNorm(const doublereal* x) {
m_mmw = dot(x, x + m_kk, m_molwts.begin());
doublereal rmmw = 1.0/m_mmw;
transform(x, x + m_kk, m_ym.begin(), timesConstant<double>(rmmw));
transform(m_y.begin(), m_y.begin() + m_kk, m_molwts.begin(),
m_y.begin(), multiplies<double>());
}
doublereal State::massFraction(int k) const {
if (k >= 0 && k < m_kk) {
return m_y[k];
}
else {
throw CanteraError("State:massFraction",
"illegal species index number");
}
}
doublereal State::concentration(int k) const {
if (k >= 0 && k < m_kk) {
return m_y[k] * m_dens * m_rmolwts[k] ;
}
else {
throw CanteraError("State:massFraction",
"illegal species index number");
}
}
void State::setMassFractions(const doublereal* y) {
doublereal norm = 0.0, sum = 0.0;
//cblas_dcopy(m_kk, y, 1, m_y.begin(), 1);
norm = accumulate(y, y + m_kk, 0.0);
copy(y, y + m_kk, m_y.begin());
scale(y, y + m_kk, m_y.begin(), 1.0/norm);
// for (k = 0; k != m_kk; ++k) {
// norm += y[k];
// m_y[k] = y[k];
//}
//scale(m_kk, 1.0/norm, m_y.begin());
transform(m_y.begin(), m_y.begin() + m_kk, m_rmolwts.begin(),
m_ym.begin(), multiplies<double>());
sum = accumulate(m_ym.begin(), m_ym.begin() + m_kk, 0.0);
// for (k = 0; k != m_kk; ++k) {
// m_ym[k] = m_y[k] * m_rmolwts[k];
// sum += m_ym[k];
//}
m_mmw = 1.0/sum;
}
void State::setMassFractions_NoNorm(const doublereal* y) {
doublereal sum = 0.0;
copy(y, y + m_kk, m_y.begin());
transform(m_y.begin(), m_y.end(), m_rmolwts.begin(), m_ym.begin(),
multiplies<double>());
sum = accumulate(m_ym.begin(), m_ym.end(), 0.0);
//for (k = 0; k != m_kk; ++k) {
// m_y[k] = y[k];
// m_ym[k] = m_y[k] * m_rmolwts[k];
// sum += m_ym[k];
//}
m_mmw = 1.0/sum;
}
doublereal State::sum_xlogx() const {
return m_mmw* Cantera::sum_xlogx(m_ym.begin(), m_ym.end()) + log(m_mmw);
}
doublereal State::sum_xlogQ(doublereal* Q) const {
return m_mmw * Cantera::sum_xlogQ(m_ym.begin(), m_ym.end(), Q);
}
void State::setConcentrations(const doublereal* c) {
int k;
doublereal sum = 0.0, norm = 0.0;
for (k = 0; k != m_kk; ++k) {
sum += c[k]*m_molwts[k];
norm += c[k];
}
m_mmw = sum/norm;
setDensity(sum);
doublereal rsum = 1.0/sum;
for (k = 0; k != m_kk; ++k) {
m_ym[k] = c[k] * rsum;
m_y[k] = m_ym[k] * m_molwts[k];
}
}
void State::getConcentrations(doublereal* c) const {
scale(m_ym.begin(), m_ym.end(), c, m_dens);
}
doublereal State::mean_Y(const doublereal* Q) const {
return dot(m_y.begin(), m_y.end(), Q);
}
void State::getMoleFractions(doublereal* x) const {
scale(m_ym.begin(), m_ym.end(), x, m_mmw);
}
void State::getMassFractions(doublereal* y) const {
copy(m_y.begin(), m_y.end(), y);
}
void State::init(const array_fp& mw) {
m_kk = mw.size();
m_molwts.resize(m_kk);
m_rmolwts.resize(m_kk);
m_y.resize(m_kk, 0.0);
m_ym.resize(m_kk, 0.0);
copy(mw.begin(), mw.end(), m_molwts.begin());
for (int k = 0; k < m_kk; k++) {
if (m_molwts[k] < 0.0) {
throw CanteraError("State::init",
"negative molecular weight for species number "+int2str(k));
}
/*
* Some surface phases may define species representing
* empty sites that have zero molecular weight. Give them
* a very small molecular weight to avoid dividing by
* zero.
*/
if (m_molwts[k] < Tiny) m_molwts[k] = Tiny;
m_rmolwts[k] = 1.0/m_molwts[k];
}
/*
* Now that we have resized the State object, let's fill it with
* a valid mass fraction vector that sums to one. The State object
* should never have a mass fraction vector that doesn't sum to one.
* We will assume that species 0 has a mass fraction of 1.0 and
* mass fraction of all other species is 0.0.
*/
m_y[0] = 1.0;
m_ym[0] = m_y[0] * m_rmolwts[0];
m_mmw = 1.0 / m_ym[0];
}
}
<commit_msg>Fixed an error in the function setMoleFractions_NoNorm(). The error was introduced in v. 1.2 of this file on 5/4/07, and lead to bad values for output mass fractions.<commit_after>/**
* @file State.cpp
* Definitions for the class State, that manages the independent variables of temperature, mass density,
* and species mass/mole fraction that define the thermodynamic state (see \ref phases and
* class \link Cantera::State State\endlink).
*/
/*
* $Author$
* $Date$
* $Revision$
*
* Copyright 2003-2004 California Institute of Technology
* See file License.txt for licensing information
*
*/
#include "utilities.h"
#include "ctexceptions.h"
#include "stringUtils.h"
#include "State.h"
//#ifdef DARWIN
//#include <Accelerate.h>
//#endif
using namespace std;
namespace Cantera {
State::State() : m_kk(0), m_temp(0.0), m_dens(0.001), m_mmw(0.0) {}
State::~State() {}
State::State(const State& right) :
m_kk(0),
m_temp(0.0),
m_dens(0.001),
m_mmw(0.0) {
/*
* Call the assignment operator.
*/
*this = operator=(right);
}
/*
* Assignment operator for the State Class
*/
State& State::operator=(const State& right) {
/*
* Check for self assignment.
*/
if (this == &right) return *this;
/*
* We do a straight assignment operator on all of the
* data. The vectors are copied.
*/
m_kk = right.m_kk;
m_temp = right.m_temp;
m_dens = right.m_dens;
m_mmw = right.m_mmw;
m_ym = right.m_ym;
m_y = right.m_y;
m_molwts = right.m_molwts;
m_rmolwts = right.m_rmolwts;
/*
* Return the reference to the current object
*/
return *this;
}
doublereal State::moleFraction(int k) const {
if (k >= 0 && k < m_kk) {
return m_ym[k] * m_mmw;
}
else {
throw CanteraError("State:moleFraction",
"illegal species index number");
}
}
void State::setMoleFractions(const doublereal* x) {
doublereal sum = 0.0, norm = 0.0;
sum = dot(x, x + m_kk, m_molwts.begin());
doublereal rsum = 1.0/sum;
transform(x, x + m_kk, m_ym.begin(), timesConstant<double>(rsum));
transform(m_ym.begin(), m_ym.begin() + m_kk, m_molwts.begin(),
m_y.begin(), multiplies<double>());
norm = accumulate(x, x + m_kk, 0.0);
//for (k = 0; k != m_kk; ++k) {
// m_ym[k] = x[k] / sum;
// m_y[k] = m_molwts[k]*m_ym[k];
// norm += x[k];
//}
m_mmw = sum/norm;
}
void State::setMoleFractions_NoNorm(const doublereal* x) {
m_mmw = dot(x, x + m_kk, m_molwts.begin());
doublereal rmmw = 1.0/m_mmw;
transform(x, x + m_kk, m_ym.begin(), timesConstant<double>(rmmw));
transform(m_ym.begin(), m_ym.begin() + m_kk, m_molwts.begin(),
m_y.begin(), multiplies<double>());
}
doublereal State::massFraction(int k) const {
if (k >= 0 && k < m_kk) {
return m_y[k];
}
else {
throw CanteraError("State:massFraction",
"illegal species index number");
}
}
doublereal State::concentration(int k) const {
if (k >= 0 && k < m_kk) {
return m_y[k] * m_dens * m_rmolwts[k] ;
}
else {
throw CanteraError("State:massFraction",
"illegal species index number");
}
}
void State::setMassFractions(const doublereal* y) {
doublereal norm = 0.0, sum = 0.0;
//cblas_dcopy(m_kk, y, 1, m_y.begin(), 1);
norm = accumulate(y, y + m_kk, 0.0);
copy(y, y + m_kk, m_y.begin());
scale(y, y + m_kk, m_y.begin(), 1.0/norm);
// for (k = 0; k != m_kk; ++k) {
// norm += y[k];
// m_y[k] = y[k];
//}
//scale(m_kk, 1.0/norm, m_y.begin());
transform(m_y.begin(), m_y.begin() + m_kk, m_rmolwts.begin(),
m_ym.begin(), multiplies<double>());
sum = accumulate(m_ym.begin(), m_ym.begin() + m_kk, 0.0);
// for (k = 0; k != m_kk; ++k) {
// m_ym[k] = m_y[k] * m_rmolwts[k];
// sum += m_ym[k];
//}
m_mmw = 1.0/sum;
}
void State::setMassFractions_NoNorm(const doublereal* y) {
doublereal sum = 0.0;
copy(y, y + m_kk, m_y.begin());
transform(m_y.begin(), m_y.end(), m_rmolwts.begin(), m_ym.begin(),
multiplies<double>());
sum = accumulate(m_ym.begin(), m_ym.end(), 0.0);
//for (k = 0; k != m_kk; ++k) {
// m_y[k] = y[k];
// m_ym[k] = m_y[k] * m_rmolwts[k];
// sum += m_ym[k];
//}
m_mmw = 1.0/sum;
}
doublereal State::sum_xlogx() const {
return m_mmw* Cantera::sum_xlogx(m_ym.begin(), m_ym.end()) + log(m_mmw);
}
doublereal State::sum_xlogQ(doublereal* Q) const {
return m_mmw * Cantera::sum_xlogQ(m_ym.begin(), m_ym.end(), Q);
}
void State::setConcentrations(const doublereal* c) {
int k;
doublereal sum = 0.0, norm = 0.0;
for (k = 0; k != m_kk; ++k) {
sum += c[k]*m_molwts[k];
norm += c[k];
}
m_mmw = sum/norm;
setDensity(sum);
doublereal rsum = 1.0/sum;
for (k = 0; k != m_kk; ++k) {
m_ym[k] = c[k] * rsum;
m_y[k] = m_ym[k] * m_molwts[k];
}
}
void State::getConcentrations(doublereal* c) const {
scale(m_ym.begin(), m_ym.end(), c, m_dens);
}
doublereal State::mean_Y(const doublereal* Q) const {
return dot(m_y.begin(), m_y.end(), Q);
}
void State::getMoleFractions(doublereal* x) const {
scale(m_ym.begin(), m_ym.end(), x, m_mmw);
}
void State::getMassFractions(doublereal* y) const {
copy(m_y.begin(), m_y.end(), y);
}
void State::init(const array_fp& mw) {
m_kk = mw.size();
m_molwts.resize(m_kk);
m_rmolwts.resize(m_kk);
m_y.resize(m_kk, 0.0);
m_ym.resize(m_kk, 0.0);
copy(mw.begin(), mw.end(), m_molwts.begin());
for (int k = 0; k < m_kk; k++) {
if (m_molwts[k] < 0.0) {
throw CanteraError("State::init",
"negative molecular weight for species number "+int2str(k));
}
/*
* Some surface phases may define species representing
* empty sites that have zero molecular weight. Give them
* a very small molecular weight to avoid dividing by
* zero.
*/
if (m_molwts[k] < Tiny) m_molwts[k] = Tiny;
m_rmolwts[k] = 1.0/m_molwts[k];
}
/*
* Now that we have resized the State object, let's fill it with
* a valid mass fraction vector that sums to one. The State object
* should never have a mass fraction vector that doesn't sum to one.
* We will assume that species 0 has a mass fraction of 1.0 and
* mass fraction of all other species is 0.0.
*/
m_y[0] = 1.0;
m_ym[0] = m_y[0] * m_rmolwts[0];
m_mmw = 1.0 / m_ym[0];
}
}
<|endoftext|> |
<commit_before>// Original Work Copyright (c) 2010 Amit J Patel, Modified Work Copyright (c) 2016 Jay M Stevens
#include "PolygonalMapGeneratorPrivatePCH.h"
#include "DrawDebugHelpers.h"
#include "Maps/MapDataHelper.h"
#include "PolygonalMapHeightmap.h"
FMapData UPolygonalMapHeightmap::MakeMapPoint(FVector2D PixelPosition, TArray<FMapData> MapData, UBiomeManager* BiomeManager)
{
TArray<FMapData> closestPoints;
// Iterate over the entire mapData array to find how many points we need to average
for (int i = 0; i < MapData.Num(); i++)
{
if (closestPoints.Num() == 0)
{
closestPoints.Add(MapData[i]);
continue;
}
float distance = FVector2D::DistSquared(PixelPosition, MapData[i].Point);
// This will hold the index of first point we find that's further away than our point
int addPointIndex = -1;
for (int j = 0; j < closestPoints.Num(); j++)
{
// Get the distance of this point
float pointDist = FVector2D::DistSquared(PixelPosition, closestPoints[j].Point);
if (distance < pointDist)
{
addPointIndex = j;
break;
}
}
// If we found a point that's further away than our point, place it in the array and move everything else down
if (addPointIndex >= 0)
{
FMapData last = MapData[i];
for (int j = addPointIndex; j < closestPoints.Num(); j++)
{
FMapData temp = closestPoints[j];
closestPoints[j] = last;
last = temp;
}
// If we are below the number of points we need to add, then add the furthest point to the end
if (closestPoints.Num() < NumberOfPointsToAverage)
{
closestPoints.Add(last);
}
}
else if (closestPoints.Num() < NumberOfPointsToAverage)
{
closestPoints.Add(MapData[i]);
}
}
// Cache the distances
TArray<float> closestPointDistances;
float totalDistance = 0.0f;
for (int i = 0; i < closestPoints.Num(); i++)
{
float distance = FVector2D::DistSquared(PixelPosition, closestPoints[i].Point);
totalDistance += distance;
closestPointDistances.Add(distance);
}
float inversePercentageTotal = 0.0f;
for (int i = 0; i < closestPoints.Num(); i++)
{
// Get the total percentage that this point contributed to the overall distance
float percentageOfDistance = closestPointDistances[i] / totalDistance;
// Take the inverse of the distance percentage -- points which are closer get a larger weight
float inversePercentage = 1.0f - percentageOfDistance;
// We re-add the inverse percentage to the array so we can make sure it all totals up to 1
closestPointDistances[i] = inversePercentage;
inversePercentageTotal += inversePercentage;
}
// Now gather the weighted distance for each point
TArray<TPair<FMapData, float>> pointWeights;
for (int i = 0; i < closestPoints.Num(); i++)
{
TPair<FMapData, float> weight;
weight.Key = closestPoints[i];
weight.Value = closestPointDistances[i] / inversePercentageTotal;
pointWeights.Add(weight);
}
/*float isBorder = 0.0f;
float isWater = 0.0f;
float isOcean = 0.0f;
float isCoast = 0.0f;
float isRiver = 0.0f;*/
float elevation = 0.0f;
float moisture = 0.0f;
TMap<FName, float> tagWeights;
for (int i = 0; i < pointWeights.Num(); i++)
{
FMapData curPoint = pointWeights[i].Key;
float weight = pointWeights[i].Value;
/*if (UMapDataHelper::IsBorder(curPoint))
{
isBorder += weight;
}
if (curPoint.bIsCoast)
{
isCoast += weight;
}
if (curPoint.bIsOcean)
{
isOcean += weight;
}
if (curPoint.bIsRiver)
{
isRiver += weight;
}
if (curPoint.bIsWater)
{
isWater += weight;
}*/
elevation += (curPoint.Elevation * weight);
moisture += (curPoint.Moisture * weight);
for (int j = 0; j < curPoint.Tags.Num(); j++)
{
FName tag = curPoint.Tags[j];
float currentTagWeight = tagWeights.FindOrAdd(tag);
currentTagWeight += weight;
tagWeights[tag] = currentTagWeight;
}
}
FMapData pixelData;
pixelData.Point = PixelPosition;
/*pixelData.bIsBorder = isBorder >= 0.5f;
pixelData.bIsCoast = isCoast >= 0.5f;
pixelData.bIsOcean = isOcean >= 0.5f;
pixelData.bIsRiver = isRiver >= 0.5f;
pixelData.bIsWater = isWater >= 0.5f;*/
for (auto& elem : tagWeights)
{
if (elem.Value >= 0.1f)
{
pixelData.Tags.Add(elem.Key);
}
}
pixelData.Elevation = elevation;
pixelData.Moisture = moisture;
pixelData.Biome = BiomeManager->DetermineBiome(pixelData);
return pixelData;
}
void UPolygonalMapHeightmap::CreateHeightmap(UPolygonMap* PolygonMap, UBiomeManager* BiomeManager, int32 Size)
{
if (PolygonMap == NULL)
{
return;
}
HeightmapSize = Size;
TArray<FMapData> graph = PolygonMap->GetAllMapData();
for (int x = 0; x < HeightmapSize; x++)
{
for (int y = 0; y < HeightmapSize; y++)
{
FVector2D point = FVector2D(x, y);
HeightmapData.Add(MakeMapPoint(point,graph, BiomeManager));
}
}
}
TArray<FMapData> UPolygonalMapHeightmap::GetMapData()
{
return HeightmapData;
}
FMapData UPolygonalMapHeightmap::GetMapPoint(int32 x, int32 y)
{
int32 index = x + (y * HeightmapSize);
if (index < 0 || HeightmapData.Num() <= index)
{
UE_LOG(LogWorldGen, Warning, TEXT("Tried to fetch a pixel at %d, %d, but no pixel was found."), x, y);
return FMapData();
}
else
{
return HeightmapData[index];
}
}
void UPolygonalMapHeightmap::DrawDebugPixelGrid(UWorld* world, float PixelSize)
{
if (world == NULL)
{
UE_LOG(LogWorldGen, Error, TEXT("World was null!"));
return;
}
float elevationScale = 3100.0f;
FVector offset = FVector(0.0f, 0.0f, 0.0f);
for (int32 x = 0; x < HeightmapSize; x++)
{
for (int32 y = 0; y < HeightmapSize; y++)
{
FMapData mapData = GetMapPoint(x,y);
FColor color = FColor(255, 255, 255);
if (UMapDataHelper::IsOcean(mapData))
{
color = FColor(0, 0, 255);
}
else if (UMapDataHelper::IsCoast(mapData))
{
color = FColor(255, 255, 0);
}
else if (UMapDataHelper::IsWater(mapData))
{
color = FColor(0, 255, 255);
}
FVector v0 = offset + FVector(mapData.Point.X * PixelSize, mapData.Point.Y * PixelSize, mapData.Elevation * elevationScale);
FVector v1 = FVector(v0.X, v0.Y + PixelSize, v0.Z);
FVector v2 = FVector(v0.X + PixelSize, v0.Y, v0.Z);
FVector v3 = FVector(v2.X, v1.Y, v0.Z);
DrawDebugSphere(world, v0, 100, 4, color, true);
DrawDebugLine(world, v0, v1, color, true);
DrawDebugLine(world, v0, v2, color, true);
}
}
}<commit_msg>Adjusted heightmap tag weight value to something more reasonable.<commit_after>// Original Work Copyright (c) 2010 Amit J Patel, Modified Work Copyright (c) 2016 Jay M Stevens
#include "PolygonalMapGeneratorPrivatePCH.h"
#include "DrawDebugHelpers.h"
#include "Maps/MapDataHelper.h"
#include "PolygonalMapHeightmap.h"
FMapData UPolygonalMapHeightmap::MakeMapPoint(FVector2D PixelPosition, TArray<FMapData> MapData, UBiomeManager* BiomeManager)
{
TArray<FMapData> closestPoints;
// Iterate over the entire mapData array to find how many points we need to average
for (int i = 0; i < MapData.Num(); i++)
{
if (closestPoints.Num() == 0)
{
closestPoints.Add(MapData[i]);
continue;
}
float distance = FVector2D::DistSquared(PixelPosition, MapData[i].Point);
// This will hold the index of first point we find that's further away than our point
int addPointIndex = -1;
for (int j = 0; j < closestPoints.Num(); j++)
{
// Get the distance of this point
float pointDist = FVector2D::DistSquared(PixelPosition, closestPoints[j].Point);
if (distance < pointDist)
{
addPointIndex = j;
break;
}
}
// If we found a point that's further away than our point, place it in the array and move everything else down
if (addPointIndex >= 0)
{
FMapData last = MapData[i];
for (int j = addPointIndex; j < closestPoints.Num(); j++)
{
FMapData temp = closestPoints[j];
closestPoints[j] = last;
last = temp;
}
// If we are below the number of points we need to add, then add the furthest point to the end
if (closestPoints.Num() < NumberOfPointsToAverage)
{
closestPoints.Add(last);
}
}
else if (closestPoints.Num() < NumberOfPointsToAverage)
{
closestPoints.Add(MapData[i]);
}
}
// Cache the distances
TArray<float> closestPointDistances;
float totalDistance = 0.0f;
for (int i = 0; i < closestPoints.Num(); i++)
{
float distance = FVector2D::DistSquared(PixelPosition, closestPoints[i].Point);
totalDistance += distance;
closestPointDistances.Add(distance);
}
float inversePercentageTotal = 0.0f;
for (int i = 0; i < closestPoints.Num(); i++)
{
// Get the total percentage that this point contributed to the overall distance
float percentageOfDistance = closestPointDistances[i] / totalDistance;
// Take the inverse of the distance percentage -- points which are closer get a larger weight
float inversePercentage = 1.0f - percentageOfDistance;
// We re-add the inverse percentage to the array so we can make sure it all totals up to 1
closestPointDistances[i] = inversePercentage;
inversePercentageTotal += inversePercentage;
}
// Now gather the weighted distance for each point
TArray<TPair<FMapData, float>> pointWeights;
for (int i = 0; i < closestPoints.Num(); i++)
{
TPair<FMapData, float> weight;
weight.Key = closestPoints[i];
weight.Value = closestPointDistances[i] / inversePercentageTotal;
pointWeights.Add(weight);
}
/*float isBorder = 0.0f;
float isWater = 0.0f;
float isOcean = 0.0f;
float isCoast = 0.0f;
float isRiver = 0.0f;*/
float elevation = 0.0f;
float moisture = 0.0f;
TMap<FName, float> tagWeights;
for (int i = 0; i < pointWeights.Num(); i++)
{
FMapData curPoint = pointWeights[i].Key;
float weight = pointWeights[i].Value;
/*if (UMapDataHelper::IsBorder(curPoint))
{
isBorder += weight;
}
if (curPoint.bIsCoast)
{
isCoast += weight;
}
if (curPoint.bIsOcean)
{
isOcean += weight;
}
if (curPoint.bIsRiver)
{
isRiver += weight;
}
if (curPoint.bIsWater)
{
isWater += weight;
}*/
elevation += (curPoint.Elevation * weight);
moisture += (curPoint.Moisture * weight);
for (int j = 0; j < curPoint.Tags.Num(); j++)
{
FName tag = curPoint.Tags[j];
float currentTagWeight = tagWeights.FindOrAdd(tag);
currentTagWeight += weight;
tagWeights[tag] = currentTagWeight;
}
}
FMapData pixelData;
pixelData.Point = PixelPosition;
/*pixelData.bIsBorder = isBorder >= 0.5f;
pixelData.bIsCoast = isCoast >= 0.5f;
pixelData.bIsOcean = isOcean >= 0.5f;
pixelData.bIsRiver = isRiver >= 0.5f;
pixelData.bIsWater = isWater >= 0.5f;*/
for (auto& elem : tagWeights)
{
if (elem.Value >= 0.5f)
{
pixelData.Tags.Add(elem.Key);
}
}
pixelData.Elevation = elevation;
pixelData.Moisture = moisture;
pixelData.Biome = BiomeManager->DetermineBiome(pixelData);
return pixelData;
}
void UPolygonalMapHeightmap::CreateHeightmap(UPolygonMap* PolygonMap, UBiomeManager* BiomeManager, int32 Size)
{
if (PolygonMap == NULL)
{
return;
}
HeightmapSize = Size;
TArray<FMapData> graph = PolygonMap->GetAllMapData();
for (int x = 0; x < HeightmapSize; x++)
{
for (int y = 0; y < HeightmapSize; y++)
{
FVector2D point = FVector2D(x, y);
HeightmapData.Add(MakeMapPoint(point,graph, BiomeManager));
}
}
}
TArray<FMapData> UPolygonalMapHeightmap::GetMapData()
{
return HeightmapData;
}
FMapData UPolygonalMapHeightmap::GetMapPoint(int32 x, int32 y)
{
int32 index = x + (y * HeightmapSize);
if (index < 0 || HeightmapData.Num() <= index)
{
UE_LOG(LogWorldGen, Warning, TEXT("Tried to fetch a pixel at %d, %d, but no pixel was found."), x, y);
return FMapData();
}
else
{
return HeightmapData[index];
}
}
void UPolygonalMapHeightmap::DrawDebugPixelGrid(UWorld* world, float PixelSize)
{
if (world == NULL)
{
UE_LOG(LogWorldGen, Error, TEXT("World was null!"));
return;
}
float elevationScale = 3100.0f;
FVector offset = FVector(0.0f, 0.0f, 0.0f);
for (int32 x = 0; x < HeightmapSize; x++)
{
for (int32 y = 0; y < HeightmapSize; y++)
{
FMapData mapData = GetMapPoint(x,y);
FColor color = FColor(255, 255, 255);
if (UMapDataHelper::IsOcean(mapData))
{
color = FColor(0, 0, 255);
}
else if (UMapDataHelper::IsCoast(mapData))
{
color = FColor(255, 255, 0);
}
else if (UMapDataHelper::IsWater(mapData))
{
color = FColor(0, 255, 255);
}
FVector v0 = offset + FVector(mapData.Point.X * PixelSize, mapData.Point.Y * PixelSize, mapData.Elevation * elevationScale);
FVector v1 = FVector(v0.X, v0.Y + PixelSize, v0.Z);
FVector v2 = FVector(v0.X + PixelSize, v0.Y, v0.Z);
FVector v3 = FVector(v2.X, v1.Y, v0.Z);
DrawDebugSphere(world, v0, 100, 4, color, true);
DrawDebugLine(world, v0, v1, color, true);
DrawDebugLine(world, v0, v2, color, true);
}
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.
#include <string.h>
#include "rescle.h"
bool print_error(const char* message) {
fprintf(stderr, "Fatal error: %s\n", message);
return 1;
}
bool print_warning(const char* message) {
fprintf(stderr, "Warning: %s\n", message);
return 1;
}
bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) {
*v1 = *v2 = *v3 = *v4 = 0;
if (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4)
return true;
if (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3)
return true;
if (swscanf_s(str, L"%hu.%hu", v1, v2) == 2)
return true;
if (swscanf_s(str, L"%hu", v1) == 1)
return true;
return false;
}
int wmain(int argc, const wchar_t* argv[]) {
bool loaded = false;
rescle::ResourceUpdater updater;
for (int i = 1; i < argc; ++i) {
if (wcscmp(argv[i], L"--set-version-string") == 0 ||
wcscmp(argv[i], L"-svs") == 0) {
if (argc - i < 3)
return print_error("--set-version-string requires 'Key' and 'Value'");
const wchar_t* key = argv[++i];
const wchar_t* value = argv[++i];
if (!updater.SetVersionString(key, value))
return print_error("Unable to change version string");
} else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
wcscmp(argv[i], L"-sfv") == 0) {
if (argc - i < 2)
return print_error("--set-file-version requires a version string");
unsigned short v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string for FileVersion");
if (!updater.SetFileVersion(v1, v2, v3, v4))
return print_error("Unable to change file version");
if (!updater.SetVersionString(L"FileVersion", argv[i]))
return print_error("Unable to change FileVersion string");
} else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
wcscmp(argv[i], L"-spv") == 0) {
if (argc - i < 2)
return print_error("--set-product-version requires a version string");
unsigned short v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string for ProductVersion");
if (!updater.SetProductVersion(v1, v2, v3, v4))
return print_error("Unable to change product version");
if (!updater.SetVersionString(L"ProductVersion", argv[i]))
return print_error("Unable to change ProductVersion string");
} else if (wcscmp(argv[i], L"--set-icon") == 0 ||
wcscmp(argv[i], L"-si") == 0) {
if (argc - i < 2)
return print_error("--set-icon requires path to the icon");
if (!updater.SetIcon(argv[++i]))
return print_error("Unable to set icon");
} else if (wcscmp(argv[i], L"--set-requested-execution-level") == 0 ||
wcscmp(argv[i], L"-sel") == 0) {
if (argc - i < 2)
return print_error("--set-requested-execution-level requires asInvoker, highestAvailable or requireAdministrator");
if (updater.IsApplicationManifestSet())
{
print_warning("--set-requested-execution-level is ignored if --application-manifest is set");
}
if (!updater.SetExecutionLevel(argv[++i]))
return print_error("Unable to set execution level");
} else if (wcscmp(argv[i], L"--application-manifest") == 0 ||
wcscmp(argv[i], L"-am") == 0) {
if (argc - i < 2)
return print_error("--application-manifest requires local path");
if (updater.IsExecutionLevelSet())
{
print_warning("--set-requested-execution-level is ignored if --application-manifest is set");
}
if (!updater.SetApplicationManifest(argv[++i]))
return print_error("Unable to set application manifest");
} else if (wcscmp(argv[i], L"--set-resource-string") == 0 ||
wcscmp(argv[i], L"--srs") == 0) {
if (argc - i < 3)
return print_error("--set-resource-string requires int 'Key' and string 'Value'");
const wchar_t* key = argv[++i];
unsigned int key_id = 0;
if (swscanf_s(key, L"%d", &key_id) != 1)
return print_error("Unable to parse id");
const wchar_t* value = argv[++i];
if (!updater.ChangeString(key_id, value))
return print_error("Unable to change string");
} else {
if (loaded)
return print_error("Unexpected trailing arguments");
loaded = true;
if (!updater.Load(argv[i]))
return print_error("Unable to load file");
}
}
if (!loaded)
return print_error("You should specify a exe/dll file");
if (!updater.Commit())
return print_error("Unable to commit changes");
return 0;
}
<commit_msg>Add missing r to short option<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.
#include <string.h>
#include "rescle.h"
bool print_error(const char* message) {
fprintf(stderr, "Fatal error: %s\n", message);
return 1;
}
bool print_warning(const char* message) {
fprintf(stderr, "Warning: %s\n", message);
return 1;
}
bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) {
*v1 = *v2 = *v3 = *v4 = 0;
if (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4)
return true;
if (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3)
return true;
if (swscanf_s(str, L"%hu.%hu", v1, v2) == 2)
return true;
if (swscanf_s(str, L"%hu", v1) == 1)
return true;
return false;
}
int wmain(int argc, const wchar_t* argv[]) {
bool loaded = false;
rescle::ResourceUpdater updater;
for (int i = 1; i < argc; ++i) {
if (wcscmp(argv[i], L"--set-version-string") == 0 ||
wcscmp(argv[i], L"-svs") == 0) {
if (argc - i < 3)
return print_error("--set-version-string requires 'Key' and 'Value'");
const wchar_t* key = argv[++i];
const wchar_t* value = argv[++i];
if (!updater.SetVersionString(key, value))
return print_error("Unable to change version string");
} else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
wcscmp(argv[i], L"-sfv") == 0) {
if (argc - i < 2)
return print_error("--set-file-version requires a version string");
unsigned short v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string for FileVersion");
if (!updater.SetFileVersion(v1, v2, v3, v4))
return print_error("Unable to change file version");
if (!updater.SetVersionString(L"FileVersion", argv[i]))
return print_error("Unable to change FileVersion string");
} else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
wcscmp(argv[i], L"-spv") == 0) {
if (argc - i < 2)
return print_error("--set-product-version requires a version string");
unsigned short v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string for ProductVersion");
if (!updater.SetProductVersion(v1, v2, v3, v4))
return print_error("Unable to change product version");
if (!updater.SetVersionString(L"ProductVersion", argv[i]))
return print_error("Unable to change ProductVersion string");
} else if (wcscmp(argv[i], L"--set-icon") == 0 ||
wcscmp(argv[i], L"-si") == 0) {
if (argc - i < 2)
return print_error("--set-icon requires path to the icon");
if (!updater.SetIcon(argv[++i]))
return print_error("Unable to set icon");
} else if (wcscmp(argv[i], L"--set-requested-execution-level") == 0 ||
wcscmp(argv[i], L"-srel") == 0) {
if (argc - i < 2)
return print_error("--set-requested-execution-level requires asInvoker, highestAvailable or requireAdministrator");
if (updater.IsApplicationManifestSet())
{
print_warning("--set-requested-execution-level is ignored if --application-manifest is set");
}
if (!updater.SetExecutionLevel(argv[++i]))
return print_error("Unable to set execution level");
} else if (wcscmp(argv[i], L"--application-manifest") == 0 ||
wcscmp(argv[i], L"-am") == 0) {
if (argc - i < 2)
return print_error("--application-manifest requires local path");
if (updater.IsExecutionLevelSet())
{
print_warning("--set-requested-execution-level is ignored if --application-manifest is set");
}
if (!updater.SetApplicationManifest(argv[++i]))
return print_error("Unable to set application manifest");
} else if (wcscmp(argv[i], L"--set-resource-string") == 0 ||
wcscmp(argv[i], L"--srs") == 0) {
if (argc - i < 3)
return print_error("--set-resource-string requires int 'Key' and string 'Value'");
const wchar_t* key = argv[++i];
unsigned int key_id = 0;
if (swscanf_s(key, L"%d", &key_id) != 1)
return print_error("Unable to parse id");
const wchar_t* value = argv[++i];
if (!updater.ChangeString(key_id, value))
return print_error("Unable to change string");
} else {
if (loaded)
return print_error("Unexpected trailing arguments");
loaded = true;
if (!updater.Load(argv[i]))
return print_error("Unable to load file");
}
}
if (!loaded)
return print_error("You should specify a exe/dll file");
if (!updater.Commit())
return print_error("Unable to commit changes");
return 0;
}
<|endoftext|> |
<commit_before>#ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP
#define TOPPRA_PIECEWISE_POLY_PATH_HPP
#include <toppra/geometric_path.hpp>
#include <toppra/toppra.hpp>
namespace toppra {
/// Boundary condition
typedef struct {
int order;
Vector values;
} BoundaryCond;
/**
* \brief Piecewise polynomial geometric path.
*
* An implementation of a piecewise polynomial geometric path.
*
* The coefficient vector has shape (N, P, D), where N is the number
* segments. For each segment, the i-th row (P index) denotes the
* power, while the j-th column is the degree of freedom. In
* particular,
*
* coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3)
*
*
*/
class PiecewisePolyPath : public GeometricPath {
public:
PiecewisePolyPath() = default;
/**
* \brief Construct new piecewise polynomial.
*
* See class docstring for details.
*
* @param coefficients Polynomial coefficients.
* @param breakpoints Vector of breakpoints.
*/
PiecewisePolyPath(const Matrices &coefficients, std::vector<value_type> breakpoints);
/**
* \brief Construct a new piecewise 3rd degree polynomial.
* @param positions Vectors of path positions at given times.
* @param times Vector of times in a strictly increasing order.
* @param bc_type Boundary conditions at the curve start and end.
*/
PiecewisePolyPath(const Vectors &positions, const Vector ×, const std::array<BoundaryCond, 2> &bc_type);
/**
* /brief Evaluate the path at given position.
*/
Vector eval_single(value_type, int order = 0) const override;
/**
* /brief Evaluate the path at given positions (vector).
*/
Vectors eval(const Vector &, int order = 0) const override;
/**
* Return the starting and ending path positions.
*/
Bound pathInterval() const override;
void serialize(std::ostream &O) const override;
void deserialize(std::istream &I) override;
/**
* \brief Construct a new Hermite polynomial.
*/
static PiecewisePolyPath constructHermite(const Vectors &positions,
const Vectors &velocities,
const std::vector<value_type> times);
protected:
void initAsHermite(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
void computeCubicSplineCoefficients(const Vectors &positions, const Vector ×,
const std::array<BoundaryCond, 2> &bc_type, Matrices &coefficients);
void reset();
size_t findSegmentIndex(value_type pos) const;
void checkInputArgs();
void checkInputArgs(const Vectors &positions, const Vector ×,
const std::array<BoundaryCond, 2> &bc_type);
void computeDerivativesCoefficients();
const Matrix &getCoefficient(size_t seg_index, int order) const;
Matrices m_coefficients, m_coefficients_1, m_coefficients_2;
std::vector<value_type> m_breakpoints;
int m_degree;
};
} // namespace toppra
#endif
<commit_msg>doc: Improve PiecewisePolyPath constructor docstring<commit_after>#ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP
#define TOPPRA_PIECEWISE_POLY_PATH_HPP
#include <toppra/geometric_path.hpp>
#include <toppra/toppra.hpp>
namespace toppra {
/// Boundary condition
typedef struct {
int order;
Vector values;
} BoundaryCond;
/**
* \brief Piecewise polynomial geometric path.
*
* An implementation of a piecewise polynomial geometric path.
*
* The coefficient vector has shape (N, P, D), where N is the number
* segments. For each segment, the i-th row (P index) denotes the
* power, while the j-th column is the degree of freedom. In
* particular,
*
* coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3)
*
*
*/
class PiecewisePolyPath : public GeometricPath {
public:
PiecewisePolyPath() = default;
/**
* \brief Construct new piecewise polynomial.
*
* See class docstring for details.
*
* @param coefficients Polynomial coefficients.
* @param breakpoints Vector of breakpoints.
*/
PiecewisePolyPath(const Matrices &coefficients, std::vector<value_type> breakpoints);
/**
* \brief Construct a new piecewise 3rd degree polynomial.
* @param positions Vectors of path positions at given times.
* @param times Vector of times in a strictly increasing order.
* @param bc_type Boundary conditions at the curve start and end.
*/
PiecewisePolyPath(const Vectors &positions, const Vector ×, const std::array<BoundaryCond, 2> &bc_type);
/**
* /brief Evaluate the path at given position.
*/
Vector eval_single(value_type, int order = 0) const override;
/**
* /brief Evaluate the path at given positions (vector).
*/
Vectors eval(const Vector &, int order = 0) const override;
/**
* Return the starting and ending path positions.
*/
Bound pathInterval() const override;
void serialize(std::ostream &O) const override;
void deserialize(std::istream &I) override;
/**
* @brief Construct a piecewise Cubic Hermite polynomial.
*
* See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for a good
* description of this interplation scheme.
*
* This function is implemented based on scipy.interpolate.CubicHermiteSpline.
*
* Note that path generates by this function is not guaranteed to have
* continuous acceleration, or the path second-order derivative.
*
* @param positions Robot joints corresponding to the given times. Must have
* the same size as times.
* @param velocities Robot joint velocities.
* @param times Path positions or times. This is the independent variable.
* @return PiecewisePolyPath
*/
static PiecewisePolyPath constructHermite(const Vectors &positions,
const Vectors &velocities,
const std::vector<value_type> times);
/**
* @brief Construct a cubic spline.
*
* Interpolate the given joint positions with a spline that is twice
* continuously differentiable. This means the position, velocity and
* acceleration are guaranteed to be continous but not jerk.
*
* This method is modelled after scipy.interpolate.CubicSpline.
*
* @param positions Robot joints corresponding to the given times.
* @param times Path positions or times. This is the independent variable.
* @param bc_type Boundary condition.
* @return PiecewisePolyPath
*/
static PiecewisePolyPath CubicSpline(const Vectors &positions, const Vector ×, const std::array<BoundaryCond, 2> &bc_type){
return PiecewisePolyPath(positions, times, bc_type);
}
protected:
void initAsHermite(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
void computeCubicSplineCoefficients(const Vectors &positions, const Vector ×,
const std::array<BoundaryCond, 2> &bc_type, Matrices &coefficients);
void reset();
size_t findSegmentIndex(value_type pos) const;
void checkInputArgs();
void checkInputArgs(const Vectors &positions, const Vector ×,
const std::array<BoundaryCond, 2> &bc_type);
void computeDerivativesCoefficients();
const Matrix &getCoefficient(size_t seg_index, int order) const;
Matrices m_coefficients, m_coefficients_1, m_coefficients_2;
std::vector<value_type> m_breakpoints;
int m_degree;
};
} // namespace toppra
#endif
<|endoftext|> |
<commit_before>/**
* This file defines the `getter` functor.
*/
#ifndef D2_DETAIL_GETTER_HPP
#define D2_DETAIL_GETTER_HPP
namespace d2 {
namespace detail {
/**
* Functor fetching a member inside an object.
*/
template <typename Type, typename Tag>
class getter {
typedef Type Tag::* Ptr;
Ptr ptr_;
public:
explicit getter(Ptr ptr) : ptr_(ptr) { }
template <typename Sig>
struct result;
template <typename This>
struct result<This(Tag&)> {
typedef Type& type;
};
template <typename This>
struct result<This(Tag const&)> {
typedef Type const& type;
};
typename result<getter(Tag&)>::type operator()(Tag& t) const {
return t.*ptr_;
}
typename result<getter(Tag const&)>::type operator()(Tag const& t) const {
return t.*ptr_;
}
};
/**
* `getter` of a member specified at compile time.
*/
template <typename Type, typename Tag, Type Tag::* ptr>
struct fixed_getter : getter<Type, Tag> {
fixed_getter() : getter<Type, Tag>(ptr) { }
};
/**
* Helper function to create a `getter`.
*/
template <typename Type, typename Tag>
getter<Type, Tag> get(Type Tag::*ptr) {
return getter<Type, Tag>(ptr);
}
} // end namespace detail
} // end namespace d2
#endif // !D2_DETAIL_GETTER_HPP
<commit_msg>Remove useless file (functionally equivalent to mem_fn).<commit_after><|endoftext|> |
<commit_before>#ifndef slic3r_LOG_HPP
#define slic3r_LOG_HPP
#include <string>
namespace Slic3r {
class Log {
public:
static void fatal_error(std::string topic, std::wstring message) {
std::cerr << topic << ": ";
std::wcerr << message << std::endl;
}
static void info(std::string topic, std::wstring message) {
std::clog << topic << ": ";
std::wclog << message << std::endl;
}
static void warn(std::string topic, std::wstring message) {
std::cerr << topic << ": ";
std::wcerr << message << std::endl;
}
};
}
#endif // slic3r_LOG_HPP
<commit_msg>Added generic error message to Log; print error type to console.<commit_after>#ifndef slic3r_LOG_HPP
#define slic3r_LOG_HPP
#include <string>
namespace Slic3r {
class Log {
public:
static void fatal_error(std::string topic, std::wstring message) {
std::cerr << topic << " FERR" << ": ";
std::wcerr << message << std::endl;
}
static void error(std::string topic, std::wstring message) {
std::cerr << topic << " ERR" << ": ";
std::wcerr << message << std::endl;
}
static void info(std::string topic, std::wstring message) {
std::clog << topic << " INFO" << ": ";
std::wclog << message << std::endl;
}
static void warn(std::string topic, std::wstring message) {
std::cerr << topic << " WARN" << ": ";
std::wcerr << message << std::endl;
}
};
}
#endif // slic3r_LOG_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <vector>
#include "gtest/gtest.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/metrics/video_metrics.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_file_based_comparison_tests.h"
#include "webrtc/video_engine/test/auto_test/primitives/framedrop_primitives.h"
#include "webrtc/video_engine/test/libvietest/include/tb_external_transport.h"
#include "webrtc/video_engine/test/libvietest/include/vie_to_file_renderer.h"
namespace {
// The input file must be QCIF since I420 gets scaled to that in the tests
// (it is so bandwidth-heavy we have no choice). Our comparison algorithms
// wouldn't like scaling, so this will work when we compare with the original.
const int kInputWidth = 176;
const int kInputHeight = 144;
class ViEVideoVerificationTest : public testing::Test {
protected:
void SetUp() {
input_file_ = webrtc::test::ResourcePath("paris_qcif", "yuv");
local_file_renderer_ = NULL;
remote_file_renderer_ = NULL;
}
void InitializeFileRenderers() {
local_file_renderer_ = new ViEToFileRenderer();
remote_file_renderer_ = new ViEToFileRenderer();
SetUpLocalFileRenderer(local_file_renderer_);
SetUpRemoteFileRenderer(remote_file_renderer_);
}
void SetUpLocalFileRenderer(ViEToFileRenderer* file_renderer) {
SetUpFileRenderer(file_renderer, "-local-preview.yuv");
}
void SetUpRemoteFileRenderer(ViEToFileRenderer* file_renderer) {
SetUpFileRenderer(file_renderer, "-remote.yuv");
}
// Must be called manually inside the tests.
void StopRenderers() {
local_file_renderer_->StopRendering();
remote_file_renderer_->StopRendering();
}
void CompareFiles(const std::string& reference_file,
const std::string& test_file,
double* psnr_result, double *ssim_result) {
webrtc::test::QualityMetricsResult psnr;
int error = I420PSNRFromFiles(reference_file.c_str(), test_file.c_str(),
kInputWidth, kInputHeight, &psnr);
EXPECT_EQ(0, error) << "PSNR routine failed - output files missing?";
*psnr_result = psnr.average;
webrtc::test::QualityMetricsResult ssim;
error = I420SSIMFromFiles(reference_file.c_str(), test_file.c_str(),
kInputWidth, kInputHeight, &ssim);
EXPECT_EQ(0, error) << "SSIM routine failed - output files missing?";
*ssim_result = ssim.average;
ViETest::Log("Results: PSNR is %f (dB; 48 is max), "
"SSIM is %f (1 is perfect)",
psnr.average, ssim.average);
}
// Note: must call AFTER CompareFiles.
void TearDownFileRenderers() {
TearDownFileRenderer(local_file_renderer_);
TearDownFileRenderer(remote_file_renderer_);
}
std::string input_file_;
ViEToFileRenderer* local_file_renderer_;
ViEToFileRenderer* remote_file_renderer_;
ViEFileBasedComparisonTests tests_;
private:
void SetUpFileRenderer(ViEToFileRenderer* file_renderer,
const std::string& suffix) {
std::string output_path = ViETest::GetResultOutputPath();
std::string filename = "render_output" + suffix;
if (!file_renderer->PrepareForRendering(output_path, filename)) {
FAIL() << "Could not open output file " << filename <<
" for writing.";
}
}
void TearDownFileRenderer(ViEToFileRenderer* file_renderer) {
assert(file_renderer);
bool test_failed = ::testing::UnitTest::GetInstance()->
current_test_info()->result()->Failed();
if (test_failed) {
// Leave the files for analysis if the test failed.
file_renderer->SaveOutputFile("failed-");
}
delete file_renderer;
}
};
class ParameterizedFullStackTest : public ViEVideoVerificationTest,
public ::testing::WithParamInterface<int> {
public:
static const int kNumFullStackInstances = 4;
protected:
struct TestParameters {
NetworkParameters network;
std::string file_name;
int width;
int height;
int bitrate;
double avg_psnr_threshold;
double avg_ssim_threshold;
ProtectionMethod protection_method;
std::string test_label;
};
void SetUp() {
for (int i = 0; i < kNumFullStackInstances; ++i) {
parameter_table_[i].file_name = webrtc::test::ResourcePath("foreman_cif",
"yuv");
parameter_table_[i].width = 352;
parameter_table_[i].height = 288;
}
int i = 0;
parameter_table_[i].protection_method = kNack;
// Uniform loss => Setting burst length to -1.
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 0;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 0;
parameter_table_[i].network.std_dev_one_way_delay = 0;
parameter_table_[i].bitrate = 300;
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
parameter_table_[i].test_label = "net_delay_0_0_plr_0";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 5;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 50;
parameter_table_[i].network.std_dev_one_way_delay = 5;
parameter_table_[i].bitrate = 300;
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
parameter_table_[i].test_label = "net_delay_50_5_plr_5";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 0;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 100;
parameter_table_[i].network.std_dev_one_way_delay = 10;
parameter_table_[i].bitrate = 300;
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
parameter_table_[i].test_label = "net_delay_100_10_plr_0";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kGilbertElliotLoss;
parameter_table_[i].network.packet_loss_rate = 5;
parameter_table_[i].network.burst_length = 3;
parameter_table_[i].network.mean_one_way_delay = 100;
parameter_table_[i].network.std_dev_one_way_delay = 10;
parameter_table_[i].bitrate = 300;
// Thresholds disabled for now. This is being run mainly to get a graph.
parameter_table_[i].avg_psnr_threshold = 0;
parameter_table_[i].avg_ssim_threshold = 0.0;
parameter_table_[i].test_label = "net_delay_100_10_plr_5_gilbert_elliot";
ASSERT_EQ(kNumFullStackInstances - 1, i);
}
TestParameters parameter_table_[kNumFullStackInstances];
};
TEST_F(ViEVideoVerificationTest, RunsBaseStandardTestWithoutErrors) {
// I420 is lossless, so the I420 test should obviously get perfect results -
// the local preview and remote output files should be bit-exact. This test
// runs on external transport to ensure we do not drop packets.
// However, it's hard to make 100% stringent requirements on the video engine
// since for instance the jitter buffer has non-deterministic elements. If it
// breaks five times in a row though, you probably introduced a bug.
const double kReasonablePsnr = webrtc::test::kMetricsPerfectPSNR - 2.0f;
const double kReasonableSsim = 0.99f;
const int kNumAttempts = 5;
for (int attempt = 0; attempt < kNumAttempts; ++attempt) {
InitializeFileRenderers();
ASSERT_TRUE(tests_.TestCallSetup(input_file_, kInputWidth, kInputHeight,
local_file_renderer_,
remote_file_renderer_));
std::string remote_file = remote_file_renderer_->GetFullOutputPath();
std::string local_preview = local_file_renderer_->GetFullOutputPath();
StopRenderers();
double actual_psnr = 0;
double actual_ssim = 0;
CompareFiles(local_preview, remote_file, &actual_psnr, &actual_ssim);
TearDownFileRenderers();
if (actual_psnr > kReasonablePsnr && actual_ssim > kReasonableSsim) {
// Test successful.
return;
} else {
ViETest::Log("Retrying; attempt %d of %d.", attempt + 1, kNumAttempts);
}
}
FAIL() << "Failed to achieve near-perfect PSNR and SSIM results after " <<
kNumAttempts << " attempts.";
}
// Runs a whole stack processing with tracking of which frames are dropped
// in the encoder. Tests show that they start at the same frame, which is
// the important thing when doing frame-to-frame comparison with PSNR/SSIM.
TEST_P(ParameterizedFullStackTest, RunsFullStackWithoutErrors) {
// Using CIF here since it's a more common resolution than QCIF, and higher
// resolutions shouldn't be a problem for a test using VP8.
input_file_ = parameter_table_[GetParam()].file_name;
FrameDropDetector detector;
local_file_renderer_ = new ViEToFileRenderer();
remote_file_renderer_ = new FrameDropMonitoringRemoteFileRenderer(&detector);
SetUpLocalFileRenderer(local_file_renderer_);
SetUpRemoteFileRenderer(remote_file_renderer_);
// Set a low bit rate so the encoder budget will be tight, causing it to drop
// frames every now and then.
const int kBitRateKbps = parameter_table_[GetParam()].bitrate;
const NetworkParameters network = parameter_table_[GetParam()].network;
int width = parameter_table_[GetParam()].width;
int height = parameter_table_[GetParam()].height;
ProtectionMethod protection_method =
parameter_table_[GetParam()].protection_method;
ViETest::Log("Bit rate : %5d kbps", kBitRateKbps);
ViETest::Log("Packet loss : %5d %%", network.packet_loss_rate);
ViETest::Log("Network delay: mean=%dms std dev=%d ms",
network.mean_one_way_delay, network.std_dev_one_way_delay);
tests_.TestFullStack(input_file_, width, height, kBitRateKbps,
protection_method, network, local_file_renderer_,
remote_file_renderer_, &detector);
const std::string reference_file = local_file_renderer_->GetFullOutputPath();
const std::string output_file = remote_file_renderer_->GetFullOutputPath();
StopRenderers();
detector.CalculateResults();
detector.PrintReport(parameter_table_[GetParam()].test_label);
if (detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kRendered) >
detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kDecoded)) {
detector.PrintDebugDump();
}
ASSERT_GE(detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kRendered),
detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kDecoded))
<< "The number of dropped frames on the decode and render steps are not "
"equal. This may be because we have a major problem in the buffers of "
"the ViEToFileRenderer?";
// We may have dropped frames during the processing, which means the output
// file does not contain all the frames that are present in the input file.
// To make the quality measurement correct, we must adjust the output file to
// that by copying the last successful frame into the place where the dropped
// frame would be, for all dropped frames.
const int frame_length_in_bytes = 3 * width * height / 2;
ViETest::Log("Frame length: %d bytes", frame_length_in_bytes);
std::vector<Frame*> all_frames = detector.GetAllFrames();
FixOutputFileForComparison(output_file, frame_length_in_bytes, all_frames);
// Verify all sent frames are present in the output file.
size_t output_file_size = webrtc::test::GetFileSize(output_file);
EXPECT_EQ(all_frames.size(), output_file_size / frame_length_in_bytes)
<< "The output file size is incorrect. It should be equal to the number "
"of frames multiplied by the frame size. This will likely affect "
"PSNR/SSIM calculations in a bad way.";
TearDownFileRenderers();
// We are running on a lower bitrate here so we need to settle for somewhat
// lower PSNR and SSIM values.
double actual_psnr = 0;
double actual_ssim = 0;
CompareFiles(reference_file, output_file, &actual_psnr, &actual_ssim);
const double kExpectedMinimumPSNR =
parameter_table_[GetParam()].avg_psnr_threshold;
const double kExpectedMinimumSSIM =
parameter_table_[GetParam()].avg_ssim_threshold;
EXPECT_GE(actual_psnr, kExpectedMinimumPSNR);
EXPECT_GE(actual_ssim, kExpectedMinimumSSIM);
}
INSTANTIATE_TEST_CASE_P(FullStackTests, ParameterizedFullStackTest,
::testing::Range(0, ParameterizedFullStackTest::kNumFullStackInstances));
} // namespace
<commit_msg>Disable full stack PSNR/SSIM triggers on Mac and Win for now due to flakiness. Adding plots of PSNR and SSIM.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <vector>
#include "gtest/gtest.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/test/testsupport/metrics/video_metrics.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_file_based_comparison_tests.h"
#include "webrtc/video_engine/test/auto_test/primitives/framedrop_primitives.h"
#include "webrtc/video_engine/test/libvietest/include/tb_external_transport.h"
#include "webrtc/video_engine/test/libvietest/include/vie_to_file_renderer.h"
namespace {
// The input file must be QCIF since I420 gets scaled to that in the tests
// (it is so bandwidth-heavy we have no choice). Our comparison algorithms
// wouldn't like scaling, so this will work when we compare with the original.
const int kInputWidth = 176;
const int kInputHeight = 144;
class ViEVideoVerificationTest : public testing::Test {
protected:
void SetUp() {
input_file_ = webrtc::test::ResourcePath("paris_qcif", "yuv");
local_file_renderer_ = NULL;
remote_file_renderer_ = NULL;
}
void InitializeFileRenderers() {
local_file_renderer_ = new ViEToFileRenderer();
remote_file_renderer_ = new ViEToFileRenderer();
SetUpLocalFileRenderer(local_file_renderer_);
SetUpRemoteFileRenderer(remote_file_renderer_);
}
void SetUpLocalFileRenderer(ViEToFileRenderer* file_renderer) {
SetUpFileRenderer(file_renderer, "-local-preview.yuv");
}
void SetUpRemoteFileRenderer(ViEToFileRenderer* file_renderer) {
SetUpFileRenderer(file_renderer, "-remote.yuv");
}
// Must be called manually inside the tests.
void StopRenderers() {
local_file_renderer_->StopRendering();
remote_file_renderer_->StopRendering();
}
void CompareFiles(const std::string& reference_file,
const std::string& test_file,
double* psnr_result, double *ssim_result) {
webrtc::test::QualityMetricsResult psnr;
int error = I420PSNRFromFiles(reference_file.c_str(), test_file.c_str(),
kInputWidth, kInputHeight, &psnr);
EXPECT_EQ(0, error) << "PSNR routine failed - output files missing?";
*psnr_result = psnr.average;
webrtc::test::QualityMetricsResult ssim;
error = I420SSIMFromFiles(reference_file.c_str(), test_file.c_str(),
kInputWidth, kInputHeight, &ssim);
EXPECT_EQ(0, error) << "SSIM routine failed - output files missing?";
*ssim_result = ssim.average;
ViETest::Log("Results: PSNR is %f (dB; 48 is max), "
"SSIM is %f (1 is perfect)",
psnr.average, ssim.average);
}
// Note: must call AFTER CompareFiles.
void TearDownFileRenderers() {
TearDownFileRenderer(local_file_renderer_);
TearDownFileRenderer(remote_file_renderer_);
}
std::string input_file_;
ViEToFileRenderer* local_file_renderer_;
ViEToFileRenderer* remote_file_renderer_;
ViEFileBasedComparisonTests tests_;
private:
void SetUpFileRenderer(ViEToFileRenderer* file_renderer,
const std::string& suffix) {
std::string output_path = ViETest::GetResultOutputPath();
std::string filename = "render_output" + suffix;
if (!file_renderer->PrepareForRendering(output_path, filename)) {
FAIL() << "Could not open output file " << filename <<
" for writing.";
}
}
void TearDownFileRenderer(ViEToFileRenderer* file_renderer) {
assert(file_renderer);
bool test_failed = ::testing::UnitTest::GetInstance()->
current_test_info()->result()->Failed();
if (test_failed) {
// Leave the files for analysis if the test failed.
file_renderer->SaveOutputFile("failed-");
}
delete file_renderer;
}
};
class ParameterizedFullStackTest : public ViEVideoVerificationTest,
public ::testing::WithParamInterface<int> {
public:
static const int kNumFullStackInstances = 4;
protected:
struct TestParameters {
NetworkParameters network;
std::string file_name;
int width;
int height;
int bitrate;
double avg_psnr_threshold;
double avg_ssim_threshold;
ProtectionMethod protection_method;
std::string test_label;
};
void SetUp() {
for (int i = 0; i < kNumFullStackInstances; ++i) {
parameter_table_[i].file_name = webrtc::test::ResourcePath("foreman_cif",
"yuv");
parameter_table_[i].width = 352;
parameter_table_[i].height = 288;
}
int i = 0;
parameter_table_[i].protection_method = kNack;
// Uniform loss => Setting burst length to -1.
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 0;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 0;
parameter_table_[i].network.std_dev_one_way_delay = 0;
parameter_table_[i].bitrate = 300;
// TODO(holmer): Enable for Win and Mac when the file rendering has been
// moved to a separate thread.
#ifdef WEBRTC_LINUX
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
#else
parameter_table_[i].avg_psnr_threshold = 0;
parameter_table_[i].avg_ssim_threshold = 0.0;
#endif
parameter_table_[i].test_label = "net_delay_0_0_plr_0";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 5;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 50;
parameter_table_[i].network.std_dev_one_way_delay = 5;
parameter_table_[i].bitrate = 300;
// TODO(holmer): Enable for Win and Mac when the file rendering has been
// moved to a separate thread.
#ifdef WEBRTC_LINUX
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
#else
parameter_table_[i].avg_psnr_threshold = 0;
parameter_table_[i].avg_ssim_threshold = 0.0;
#endif
parameter_table_[i].test_label = "net_delay_50_5_plr_5";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kUniformLoss;
parameter_table_[i].network.packet_loss_rate = 0;
parameter_table_[i].network.burst_length = -1;
parameter_table_[i].network.mean_one_way_delay = 100;
parameter_table_[i].network.std_dev_one_way_delay = 10;
parameter_table_[i].bitrate = 300;
// TODO(holmer): Enable for Win and Mac when the file rendering has been
// moved to a separate thread.
#ifdef WEBRTC_LINUX
parameter_table_[i].avg_psnr_threshold = 35;
parameter_table_[i].avg_ssim_threshold = 0.96;
#else
parameter_table_[i].avg_psnr_threshold = 0;
parameter_table_[i].avg_ssim_threshold = 0.0;
#endif
parameter_table_[i].test_label = "net_delay_100_10_plr_0";
++i;
parameter_table_[i].protection_method = kNack;
parameter_table_[i].network.loss_model = kGilbertElliotLoss;
parameter_table_[i].network.packet_loss_rate = 5;
parameter_table_[i].network.burst_length = 3;
parameter_table_[i].network.mean_one_way_delay = 100;
parameter_table_[i].network.std_dev_one_way_delay = 10;
parameter_table_[i].bitrate = 300;
// Thresholds disabled for now. This is being run mainly to get a graph.
parameter_table_[i].avg_psnr_threshold = 0;
parameter_table_[i].avg_ssim_threshold = 0.0;
parameter_table_[i].test_label = "net_delay_100_10_plr_5_gilbert_elliot";
ASSERT_EQ(kNumFullStackInstances - 1, i);
}
TestParameters parameter_table_[kNumFullStackInstances];
};
TEST_F(ViEVideoVerificationTest, RunsBaseStandardTestWithoutErrors) {
// I420 is lossless, so the I420 test should obviously get perfect results -
// the local preview and remote output files should be bit-exact. This test
// runs on external transport to ensure we do not drop packets.
// However, it's hard to make 100% stringent requirements on the video engine
// since for instance the jitter buffer has non-deterministic elements. If it
// breaks five times in a row though, you probably introduced a bug.
const double kReasonablePsnr = webrtc::test::kMetricsPerfectPSNR - 2.0f;
const double kReasonableSsim = 0.99f;
const int kNumAttempts = 5;
for (int attempt = 0; attempt < kNumAttempts; ++attempt) {
InitializeFileRenderers();
ASSERT_TRUE(tests_.TestCallSetup(input_file_, kInputWidth, kInputHeight,
local_file_renderer_,
remote_file_renderer_));
std::string remote_file = remote_file_renderer_->GetFullOutputPath();
std::string local_preview = local_file_renderer_->GetFullOutputPath();
StopRenderers();
double actual_psnr = 0;
double actual_ssim = 0;
CompareFiles(local_preview, remote_file, &actual_psnr, &actual_ssim);
TearDownFileRenderers();
if (actual_psnr > kReasonablePsnr && actual_ssim > kReasonableSsim) {
// Test successful.
return;
} else {
ViETest::Log("Retrying; attempt %d of %d.", attempt + 1, kNumAttempts);
}
}
FAIL() << "Failed to achieve near-perfect PSNR and SSIM results after " <<
kNumAttempts << " attempts.";
}
// Runs a whole stack processing with tracking of which frames are dropped
// in the encoder. Tests show that they start at the same frame, which is
// the important thing when doing frame-to-frame comparison with PSNR/SSIM.
TEST_P(ParameterizedFullStackTest, RunsFullStackWithoutErrors) {
// Using CIF here since it's a more common resolution than QCIF, and higher
// resolutions shouldn't be a problem for a test using VP8.
input_file_ = parameter_table_[GetParam()].file_name;
FrameDropDetector detector;
local_file_renderer_ = new ViEToFileRenderer();
remote_file_renderer_ = new FrameDropMonitoringRemoteFileRenderer(&detector);
SetUpLocalFileRenderer(local_file_renderer_);
SetUpRemoteFileRenderer(remote_file_renderer_);
// Set a low bit rate so the encoder budget will be tight, causing it to drop
// frames every now and then.
const int kBitRateKbps = parameter_table_[GetParam()].bitrate;
const NetworkParameters network = parameter_table_[GetParam()].network;
int width = parameter_table_[GetParam()].width;
int height = parameter_table_[GetParam()].height;
ProtectionMethod protection_method =
parameter_table_[GetParam()].protection_method;
ViETest::Log("Bit rate : %5d kbps", kBitRateKbps);
ViETest::Log("Packet loss : %5d %%", network.packet_loss_rate);
ViETest::Log("Network delay: mean=%dms std dev=%d ms",
network.mean_one_way_delay, network.std_dev_one_way_delay);
tests_.TestFullStack(input_file_, width, height, kBitRateKbps,
protection_method, network, local_file_renderer_,
remote_file_renderer_, &detector);
const std::string reference_file = local_file_renderer_->GetFullOutputPath();
const std::string output_file = remote_file_renderer_->GetFullOutputPath();
StopRenderers();
detector.CalculateResults();
detector.PrintReport(parameter_table_[GetParam()].test_label);
if (detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kRendered) >
detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kDecoded)) {
detector.PrintDebugDump();
}
ASSERT_GE(detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kRendered),
detector.GetNumberOfFramesDroppedAt(FrameDropDetector::kDecoded))
<< "The number of dropped frames on the decode and render steps are not "
"equal. This may be because we have a major problem in the buffers of "
"the ViEToFileRenderer?";
// We may have dropped frames during the processing, which means the output
// file does not contain all the frames that are present in the input file.
// To make the quality measurement correct, we must adjust the output file to
// that by copying the last successful frame into the place where the dropped
// frame would be, for all dropped frames.
const int frame_length_in_bytes = 3 * width * height / 2;
ViETest::Log("Frame length: %d bytes", frame_length_in_bytes);
std::vector<Frame*> all_frames = detector.GetAllFrames();
FixOutputFileForComparison(output_file, frame_length_in_bytes, all_frames);
// Verify all sent frames are present in the output file.
size_t output_file_size = webrtc::test::GetFileSize(output_file);
EXPECT_EQ(all_frames.size(), output_file_size / frame_length_in_bytes)
<< "The output file size is incorrect. It should be equal to the number "
"of frames multiplied by the frame size. This will likely affect "
"PSNR/SSIM calculations in a bad way.";
TearDownFileRenderers();
// We are running on a lower bitrate here so we need to settle for somewhat
// lower PSNR and SSIM values.
double actual_psnr = 0;
double actual_ssim = 0;
CompareFiles(reference_file, output_file, &actual_psnr, &actual_ssim);
const double kExpectedMinimumPSNR =
parameter_table_[GetParam()].avg_psnr_threshold;
const double kExpectedMinimumSSIM =
parameter_table_[GetParam()].avg_ssim_threshold;
EXPECT_GE(actual_psnr, kExpectedMinimumPSNR);
EXPECT_GE(actual_ssim, kExpectedMinimumSSIM);
webrtc::test::PrintResult(
"psnr", "", parameter_table_[GetParam()].test_label,
actual_psnr, "dB", false);
webrtc::test::PrintResult(
"ssim", "", parameter_table_[GetParam()].test_label,
actual_ssim, "", false);
}
INSTANTIATE_TEST_CASE_P(FullStackTests, ParameterizedFullStackTest,
::testing::Range(0, ParameterizedFullStackTest::kNumFullStackInstances));
} // namespace
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ — Engine (PLACEHOLDER)
*
* This is a placeholder for future functionality. Do not use.
*
* @author Christopher Alfeld <[email protected]>
*/
#ifndef __IBPP__ENGINE__
#define __IBPP__ENGINE__
#include <ironbeepp/common_semantics.hpp>
#include <iostream>
// IronBee C
typedef struct ib_engine_t ib_engine_t;
namespace IronBee {
/**
* Const Engine; equivalent to a const pointer to ib_engine_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* See Engine for discussion of the engine.
*
* @sa Engine
* @sa ironbeepp
* @sa ib_engine_t
* @nosubgrouping
**/
class ConstEngine :
public CommonSemantics<ConstEngine>
{
public:
/**
* Construct singular ConstEngine.
*
* All behavior of a singular ConstEngine is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstEngine();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_engine_t accessor.
// Intentionally inlined.
const ib_engine_t* ib() const
{
return m_ib;
}
//! Construct Engine from ib_engine_t.
explicit
ConstEngine(const ib_engine_t* ib_engine);
///@}
private:
const ib_engine_t* m_ib;
};
/**
* Engine; equivalent to a pointer to ib_engine_t.
*
* An Engine can be treated as a ConstEngine. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* XXX
*
* @sa ironbeepp
* @sa ib_engine_t
* @sa ConstEngine
* @nosubgrouping
**/
class Engine :
public ConstEngine
{
public:
/**
* Remove the constness of a ConstEngine.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] bs ConstEngine to remove const from.
* @returns Engine pointing to same underlying byte string as @a bs.
**/
static Engine remove_const(ConstEngine engine);
/**
* Construct singular Engine.
*
* All behavior of a singular Engine is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
Engine();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_engine_t accessor.
// Intentionally inlined.
ib_engine_t* ib() const
{
return m_ib;
}
//! Construct Engine from ib_engine_t.
explicit
Engine(ib_engine_t* ib_engine);
///@}
private:
ib_engine_t* m_ib;
};
/**
* Output operator for Engine.
*
* Outputs Engine[@e value] to @a o where @e value is replaced with
* the value of the bytestring.
*
* @param[in] o Ostream to output to.
* @param[in] byte_string Engine to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstEngine& engine);
} // IronBee
#endif
<commit_msg>IronBee++/Engine: API documentation.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ — Engine
*
* This code is under construction. Do not use yet.
*
* @author Christopher Alfeld <[email protected]>
*/
#ifndef __IBPP__ENGINE__
#define __IBPP__ENGINE__
#include <ironbeepp/common_semantics.hpp>
#include <iostream>
// IronBee C
typedef struct ib_engine_t ib_engine_t;
namespace IronBee {
/**
* Const Engine; equivalent to a const pointer to ib_engine_t.
*
* Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
* singularity via CommonSemantics.
*
* See Engine for discussion of the engine.
*
* @sa Engine
* @sa ironbeepp
* @sa ib_engine_t
* @nosubgrouping
**/
class ConstEngine :
public CommonSemantics<ConstEngine>
{
public:
/**
* Construct singular ConstEngine.
*
* All behavior of a singular ConstEngine is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
ConstEngine();
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_engine_t accessor.
// Intentionally inlined.
const ib_engine_t* ib() const
{
return m_ib;
}
//! Construct Engine from ib_engine_t.
explicit
ConstEngine(const ib_engine_t* ib_engine);
///@}
private:
const ib_engine_t* m_ib;
};
/**
* Engine; equivalent to a pointer to ib_engine_t.
*
* An Engine can be treated as a ConstEngine. See @ref ironbeepp for
* details on IronBee++ object semantics.
*
* The IronBee Engine is the central component of IronBee that processes
* inputs and calls hooks. It is a complex state machine. See
* IronBeeEngineState.
*
* This class provides some of the C API functionality. In particular, it
* allows module writers to register hooks with the engine and provides
* logging functionality.
*
* @sa ironbeepp
* @sa IronBeeEngineState
* @sa ib_engine_t
* @sa ConstEngine
* @nosubgrouping
**/
class Engine :
public ConstEngine
{
public:
/**
* Remove the constness of a ConstEngine.
*
* @warning This is as dangerous as a @c const_cast, use carefully.
*
* @param[in] bs ConstEngine to remove const from.
* @returns Engine pointing to same underlying byte string as @a bs.
**/
static Engine remove_const(ConstEngine engine);
/**
* Construct singular Engine.
*
* All behavior of a singular Engine is undefined except for
* assignment, copying, comparison, and evaluate-as-bool.
**/
Engine();
/**
* @name Hooks
* Methods to register hooks.
*
* See IronBeeEngineState for details on the states and transitions.
**/
///@{
///@}
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! const ib_engine_t accessor.
// Intentionally inlined.
ib_engine_t* ib() const
{
return m_ib;
}
//! Construct Engine from ib_engine_t.
explicit
Engine(ib_engine_t* ib_engine);
///@}
private:
ib_engine_t* m_ib;
};
/**
* Output operator for Engine.
*
* Outputs Engine[@e value] to @a o where @e value is replaced with
* the value of the bytestring.
*
* @param[in] o Ostream to output to.
* @param[in] byte_string Engine to output.
* @return @a o
**/
std::ostream& operator<<(std::ostream& o, const ConstEngine& engine);
} // IronBee
#endif
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <set>
#include "onnxruntime_extensions.h"
#include "ocos.h"
class ExternalCustomOps {
public:
ExternalCustomOps() {
}
static ExternalCustomOps& instance() {
static ExternalCustomOps g_instance;
return g_instance;
}
void Add(const OrtCustomOp* c_op) {
op_array_.push_back(c_op);
}
const OrtCustomOp* GetNextOp(size_t& idx) {
if (idx >= op_array_.size()) {
return nullptr;
}
return op_array_[idx++];
}
ExternalCustomOps(ExternalCustomOps const&) = delete;
void operator=(ExternalCustomOps const&) = delete;
private:
std::vector<const OrtCustomOp*> op_array_;
};
extern "C" bool ORT_API_CALL AddExternalCustomOp(const OrtCustomOp* c_op) {
ExternalCustomOps::instance().Add(c_op);
return true;
}
extern "C" OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api) {
OrtCustomOpDomain* domain = nullptr;
const OrtApi* ortApi = api->GetApi(ORT_API_VERSION);
std::set<std::string> pyop_nameset;
OrtStatus* status = nullptr;
#if defined(PYTHON_OP_SUPPORT)
if (status = RegisterPythonDomainAndOps(options, ortApi)){
return status;
}
#endif // PYTHON_OP_SUPPORT
if (status = ortApi->CreateCustomOpDomain(c_OpDomain, &domain)) {
return status;
}
#if defined(PYTHON_OP_SUPPORT)
size_t count = 0;
const OrtCustomOp* c_ops = FetchPyCustomOps(count);
while (c_ops != nullptr) {
if (status = ortApi->CustomOpDomain_Add(domain, c_ops)) {
return status;
} else {
pyop_nameset.emplace(c_ops->GetName(c_ops));
}
++count;
c_ops = FetchPyCustomOps(count);
}
#endif
static std::vector<FxLoadCustomOpFactory> c_factories = {
LoadCustomOpClasses<CustomOpClassBegin>
#if defined(ENABLE_TF_STRING)
, LoadCustomOpClasses_Text
#endif // ENABLE_TF_STRING
#if defined(ENABLE_MATH)
, LoadCustomOpClasses_Math
#endif
#if defined(ENABLE_TOKENIZER)
, LoadCustomOpClasses_Tokenizer
#endif
};
for (auto fx : c_factories) {
auto ops = fx();
while (*ops != nullptr) {
if (pyop_nameset.find((*ops)->GetName(*ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, *ops)) {
return status;
}
}
++ops;
}
}
size_t idx = 0;
const OrtCustomOp* e_ops = ExternalCustomOps::instance().GetNextOp(idx);
while (e_ops != nullptr) {
if (pyop_nameset.find(e_ops->GetName(e_ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, e_ops)) {
return status;
}
e_ops = ExternalCustomOps::instance().GetNextOp(idx);
}
}
return ortApi->AddCustomOpDomain(options, domain);
}
<commit_msg>Ensure custom op domain is released (#234)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <mutex>
#include <set>
#include "onnxruntime_extensions.h"
#include "ocos.h"
struct OrtCustomOpDomainDeleter {
explicit OrtCustomOpDomainDeleter(const OrtApi* ort_api) {
ort_api_ = ort_api;
}
void operator()(OrtCustomOpDomain* domain) const {
ort_api_->ReleaseCustomOpDomain(domain);
}
const OrtApi* ort_api_;
};
using OrtCustomOpDomainUniquePtr = std::unique_ptr<OrtCustomOpDomain, OrtCustomOpDomainDeleter>;
static std::vector<OrtCustomOpDomainUniquePtr> ort_custom_op_domain_container;
static std::mutex ort_custom_op_domain_mutex;
static void AddOrtCustomOpDomainToContainer(OrtCustomOpDomain* domain, const OrtApi* ort_api) {
std::lock_guard<std::mutex> lock(ort_custom_op_domain_mutex);
auto ptr = std::unique_ptr<OrtCustomOpDomain, OrtCustomOpDomainDeleter>(domain, OrtCustomOpDomainDeleter(ort_api));
ort_custom_op_domain_container.push_back(std::move(ptr));
}
class ExternalCustomOps {
public:
ExternalCustomOps() {
}
static ExternalCustomOps& instance() {
static ExternalCustomOps g_instance;
return g_instance;
}
void Add(const OrtCustomOp* c_op) {
op_array_.push_back(c_op);
}
const OrtCustomOp* GetNextOp(size_t& idx) {
if (idx >= op_array_.size()) {
return nullptr;
}
return op_array_[idx++];
}
ExternalCustomOps(ExternalCustomOps const&) = delete;
void operator=(ExternalCustomOps const&) = delete;
private:
std::vector<const OrtCustomOp*> op_array_;
};
extern "C" bool ORT_API_CALL AddExternalCustomOp(const OrtCustomOp* c_op) {
ExternalCustomOps::instance().Add(c_op);
return true;
}
extern "C" OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api) {
OrtCustomOpDomain* domain = nullptr;
const OrtApi* ortApi = api->GetApi(ORT_API_VERSION);
std::set<std::string> pyop_nameset;
OrtStatus* status = nullptr;
#if defined(PYTHON_OP_SUPPORT)
if (status = RegisterPythonDomainAndOps(options, ortApi)){
return status;
}
#endif // PYTHON_OP_SUPPORT
if (status = ortApi->CreateCustomOpDomain(c_OpDomain, &domain)) {
return status;
}
AddOrtCustomOpDomainToContainer(domain, ortApi);
#if defined(PYTHON_OP_SUPPORT)
size_t count = 0;
const OrtCustomOp* c_ops = FetchPyCustomOps(count);
while (c_ops != nullptr) {
if (status = ortApi->CustomOpDomain_Add(domain, c_ops)) {
return status;
} else {
pyop_nameset.emplace(c_ops->GetName(c_ops));
}
++count;
c_ops = FetchPyCustomOps(count);
}
#endif
static std::vector<FxLoadCustomOpFactory> c_factories = {
LoadCustomOpClasses<CustomOpClassBegin>
#if defined(ENABLE_TF_STRING)
, LoadCustomOpClasses_Text
#endif // ENABLE_TF_STRING
#if defined(ENABLE_MATH)
, LoadCustomOpClasses_Math
#endif
#if defined(ENABLE_TOKENIZER)
, LoadCustomOpClasses_Tokenizer
#endif
};
for (auto fx : c_factories) {
auto ops = fx();
while (*ops != nullptr) {
if (pyop_nameset.find((*ops)->GetName(*ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, *ops)) {
return status;
}
}
++ops;
}
}
size_t idx = 0;
const OrtCustomOp* e_ops = ExternalCustomOps::instance().GetNextOp(idx);
while (e_ops != nullptr) {
if (pyop_nameset.find(e_ops->GetName(e_ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, e_ops)) {
return status;
}
e_ops = ExternalCustomOps::instance().GetNextOp(idx);
}
}
return ortApi->AddCustomOpDomain(options, domain);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef LIBPORT_TYPE_INFO_HH
# define LIBPORT_TYPE_INFO_HH
namespace libport
{
class TypeInfo
{
public:
TypeInfo(const ::std::type_info& info);
template <typename T>
explicit TypeInfo(const T& obj);
bool operator <(const TypeInfo& other) const;
bool operator==(const TypeInfo& other) const;
std::string name() const;
private:
const ::std::type_info* info_;
};
std::ostream& operator << (std::ostream& out, const TypeInfo& info);
}
# include <libport/type-info.hxx>
#endif
<commit_msg>Add missing include.<commit_after>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef LIBPORT_TYPE_INFO_HH
# define LIBPORT_TYPE_INFO_HH
# include <string>
namespace libport
{
class TypeInfo
{
public:
TypeInfo(const ::std::type_info& info);
template <typename T>
explicit TypeInfo(const T& obj);
bool operator <(const TypeInfo& other) const;
bool operator==(const TypeInfo& other) const;
std::string name() const;
private:
const ::std::type_info* info_;
};
std::ostream& operator << (std::ostream& out, const TypeInfo& info);
}
# include <libport/type-info.hxx>
#endif
<|endoftext|> |
<commit_before>/*
* predixy - A high performance and full features proxy for redis.
* Copyright (C) 2017 Joyield, Inc. <[email protected]>
* All rights reserved.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include "Socket.h"
#include "Util.h"
#include "Logger.h"
#include "Timer.h"
Socket::Socket(int fd):
mClassType(RawType),
mFd(fd),
mEvts(0),
mStatus(fd >= 0 ? Normal : None)
{
}
Socket::Socket(int domain, int type, int protocol):
mClassType(RawType),
mFd(Socket::socket(domain, type, protocol)),
mStatus(Normal)
{
}
Socket::~Socket()
{
close();
}
void Socket::close()
{
if (mFd >= 0) {
::close(mFd);
mFd = -1;
mEvts = 0;
mStatus = None;
}
}
void Socket::attach(int fd)
{
close();
mFd = fd;
mEvts = 0;
mStatus = fd >= 0 ? Normal : None;
}
void Socket::detach()
{
mFd = -1;
mEvts = 0;
mStatus = None;
}
const char* Socket::statusStr() const
{
static const char* strs[] = {
"Normal",
"None",
"End",
"IOError",
"EventError",
"ExceptError"
};
return mStatus < CustomStatus ? strs[mStatus] : "Custom";
}
int Socket::socket(int domain, int type, int protocol)
{
int fd = ::socket(domain, type, protocol);
if (fd < 0) {
Throw(SocketCallFail, "%s", StrError());
}
return fd;
}
void Socket::getFirstAddr(const char* addr, int type, int protocol, sockaddr* res, socklen_t* len)
{
if (*addr == '/') { //unix socket
struct sockaddr_un sun;
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
strncpy(sun.sun_path, addr, sizeof(sun.sun_path));
if (*len < sizeof(sun)) {
*len = sizeof(sun);
Throw(AddrLenTooShort, "result address space too short");
}
*len = sizeof(sun);
memcpy(res, &sun, *len);
} else {
std::string tmp;
const char* host = addr;
const char* port = strchr(addr, ':');
if (port) {
tmp.append(addr, port - addr);
host = tmp.c_str();
port++;
}
struct addrinfo hints;
struct addrinfo *dst;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = type;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = protocol;
int s = getaddrinfo(host, port, &hints, &dst);
if (s != 0) {
Throw(InvalidAddr, "invalid addr %s:%s", addr, gai_strerror(s));
}
if (!dst) {
Throw(InvalidAddr, "invalid addr %s", addr);
}
if (*len < dst->ai_addrlen) {
*len = dst->ai_addrlen;
Throw(AddrLenTooShort, "result address space too short");
}
*len = dst->ai_addrlen;
memcpy(res, dst->ai_addr, *len);
freeaddrinfo(dst);
}
}
bool Socket::setNonBlock(bool val)
{
int flags = fcntl(mFd, F_GETFL, NULL);
if (flags < 0) {
return false;
}
if (val) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int ret = fcntl(mFd, F_SETFL, flags);
return ret == 0;
}
bool Socket::setTcpNoDelay(bool val)
{
int nodelay = val ? 1 : 0;
socklen_t len = sizeof(nodelay);
int ret = setsockopt(mFd, IPPROTO_TCP, TCP_NODELAY, &nodelay, len);
return ret == 0;
}
bool Socket::setTcpKeepAlive(int interval)
{
int val = 1;
int ret = setsockopt(mFd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
if (ret != 0) {
return false;
}
#ifdef __linux__
val = interval;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val));
if (ret != 0) {
return false;
}
val = interval / 3;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val));
if (ret != 0) {
return false;
}
val = 3;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val));
if (ret != 0) {
return false;
}
#else
((void)interval); //Avoid unused var warning for non Linux systems
#endif
return true;
}
int Socket::read(void* buf, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::read(mFd, buf, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
} else if (n == 0) {
mStatus = End;
}
return n;
}
return 0;
}
int Socket::write(const void* buf, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::write(mFd, buf, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
}
return n;
}
return 0;
}
int Socket::writev(const struct iovec* vecs, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::writev(mFd, vecs, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
}
return n;
}
return 0;
}
<commit_msg>[fix] ipv6 address parsing<commit_after>/*
* predixy - A high performance and full features proxy for redis.
* Copyright (C) 2017 Joyield, Inc. <[email protected]>
* All rights reserved.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include "Socket.h"
#include "Util.h"
#include "Logger.h"
#include "Timer.h"
Socket::Socket(int fd):
mClassType(RawType),
mFd(fd),
mEvts(0),
mStatus(fd >= 0 ? Normal : None)
{
}
Socket::Socket(int domain, int type, int protocol):
mClassType(RawType),
mFd(Socket::socket(domain, type, protocol)),
mStatus(Normal)
{
}
Socket::~Socket()
{
close();
}
void Socket::close()
{
if (mFd >= 0) {
::close(mFd);
mFd = -1;
mEvts = 0;
mStatus = None;
}
}
void Socket::attach(int fd)
{
close();
mFd = fd;
mEvts = 0;
mStatus = fd >= 0 ? Normal : None;
}
void Socket::detach()
{
mFd = -1;
mEvts = 0;
mStatus = None;
}
const char* Socket::statusStr() const
{
static const char* strs[] = {
"Normal",
"None",
"End",
"IOError",
"EventError",
"ExceptError"
};
return mStatus < CustomStatus ? strs[mStatus] : "Custom";
}
int Socket::socket(int domain, int type, int protocol)
{
int fd = ::socket(domain, type, protocol);
if (fd < 0) {
Throw(SocketCallFail, "%s", StrError());
}
return fd;
}
void Socket::getFirstAddr(const char* addr, int type, int protocol, sockaddr* res, socklen_t* len)
{
if (*addr == '/') { //unix socket
struct sockaddr_un sun;
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
strncpy(sun.sun_path, addr, sizeof(sun.sun_path));
if (*len < sizeof(sun)) {
*len = sizeof(sun);
Throw(AddrLenTooShort, "result address space too short");
}
*len = sizeof(sun);
memcpy(res, &sun, *len);
} else {
std::string tmp;
const char* host = addr;
const char* port = strrchr(addr, ':');
if (port) {
tmp.append(addr, port - addr);
host = tmp.c_str();
port++;
}
struct addrinfo hints;
struct addrinfo *dst;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = type;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = protocol;
int s = getaddrinfo(host, port, &hints, &dst);
if (s != 0) {
Throw(InvalidAddr, "invalid addr %s:%s", addr, gai_strerror(s));
}
if (!dst) {
Throw(InvalidAddr, "invalid addr %s", addr);
}
if (*len < dst->ai_addrlen) {
*len = dst->ai_addrlen;
Throw(AddrLenTooShort, "result address space too short");
}
*len = dst->ai_addrlen;
memcpy(res, dst->ai_addr, *len);
freeaddrinfo(dst);
}
}
bool Socket::setNonBlock(bool val)
{
int flags = fcntl(mFd, F_GETFL, NULL);
if (flags < 0) {
return false;
}
if (val) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int ret = fcntl(mFd, F_SETFL, flags);
return ret == 0;
}
bool Socket::setTcpNoDelay(bool val)
{
int nodelay = val ? 1 : 0;
socklen_t len = sizeof(nodelay);
int ret = setsockopt(mFd, IPPROTO_TCP, TCP_NODELAY, &nodelay, len);
return ret == 0;
}
bool Socket::setTcpKeepAlive(int interval)
{
int val = 1;
int ret = setsockopt(mFd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
if (ret != 0) {
return false;
}
#ifdef __linux__
val = interval;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val));
if (ret != 0) {
return false;
}
val = interval / 3;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val));
if (ret != 0) {
return false;
}
val = 3;
ret = setsockopt(mFd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val));
if (ret != 0) {
return false;
}
#else
((void)interval); //Avoid unused var warning for non Linux systems
#endif
return true;
}
int Socket::read(void* buf, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::read(mFd, buf, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
} else if (n == 0) {
mStatus = End;
}
return n;
}
return 0;
}
int Socket::write(const void* buf, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::write(mFd, buf, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
}
return n;
}
return 0;
}
int Socket::writev(const struct iovec* vecs, int cnt)
{
FuncCallTimer();
while (cnt > 0) {
int n = ::writev(mFd, vecs, cnt);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
} else if (errno == EINTR) {
continue;
}
mStatus = IOError;
}
return n;
}
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_ATTRIBUTE_HPP
#define MAPNIK_ATTRIBUTE_HPP
// mapnik
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
// stl
#include <string>
#include <unordered_map>
namespace mapnik {
struct attribute
{
std::string name_;
explicit attribute(std::string const& name)
: name_(name) {}
template <typename V ,typename F>
V const& value(F const& f) const
{
return f.get(name_);
}
std::string const& name() const { return name_;}
};
struct geometry_type_attribute
{
template <typename V, typename F>
V value(F const& f) const
{
mapnik::value_integer type = 0;
//for (auto const& geom : f.paths())
//{
// if (type != 0 && geom.type() != type)
// {
// return value_integer(4); // Collection
// }
// type = geom.type();
//}
// FIXME
return type;
}
};
struct global_attribute
{
std::string name;
explicit global_attribute(std::string const& name_)
: name(name_) {}
template <typename V, typename C>
V const& operator() (C const& ctx)
{
return ctx.get(name);
}
};
using attributes = std::unordered_map<std::string, value>;
}
#endif // MAPNIK_ATTRIBUTE_HPP
<commit_msg>return geometry_type(geom)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_ATTRIBUTE_HPP
#define MAPNIK_ATTRIBUTE_HPP
// mapnik
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
#include <mapnik/geometry_type.hpp>
// stl
#include <string>
#include <unordered_map>
namespace mapnik {
struct attribute
{
std::string name_;
explicit attribute(std::string const& name)
: name_(name) {}
template <typename V ,typename F>
V const& value(F const& f) const
{
return f.get(name_);
}
std::string const& name() const { return name_;}
};
struct geometry_type_attribute
{
template <typename V, typename F>
V value(F const& f) const
{
return new_geometry::geometry_type(f.get_geometry());
}
};
struct global_attribute
{
std::string name;
explicit global_attribute(std::string const& name_)
: name(name_) {}
template <typename V, typename C>
V const& operator() (C const& ctx)
{
return ctx.get(name);
}
};
using attributes = std::unordered_map<std::string, value>;
}
#endif // MAPNIK_ATTRIBUTE_HPP
<|endoftext|> |
<commit_before>/*
* Koder is a code editor for Haiku based on Scintilla.
*
* Copyright (C) 2014-2015 Kacper Kasper <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Styler.h"
#include <cstdlib>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <String.h>
#include "Editor.h"
#include "XmlDocument.h"
#include "XmlNode.h"
Styler::Styler(const char* path)
:
fDocument(new XmlDocument(path))
{
}
Styler::~Styler()
{
delete fDocument;
}
void
Styler::ApplyGlobal(Editor* editor)
{
uint32 count;
XmlNode* defaultStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle[@styleID='32']", &count);
int id, fg, bg, fs;
_GetAttributesFromNode(defaultStyle[0], &id, &fg, &bg, &fs);
font_family fixed;
be_fixed_font->GetFamilyAndStyle(&fixed, NULL);
editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) fixed);
_SetAttributesInEditor(editor, id, fg, bg, fs);
editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
delete []defaultStyle;
XmlNode* globalStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle", &count);
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(globalStyle[i], &id, &fg, &bg, &fs);
if(id != 0 && id != 2069) {
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
else
{
BString name = globalStyle[i].GetAttribute("name");
if(name == "Current line background colour") {
editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
}
else if(name == "White space symbol") {
if(fg != -1) {
editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
}
}
else if(name == "Selected text colour") {
if(fg != -1) {
editor->SendMessage(SCI_SETSELFORE, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETSELBACK, true, bg);
}
}
else if(name == "Caret colour") {
editor->SendMessage(SCI_SETCARETFORE, fg, 0);
}
else if(name == "Edge colour") {
editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
}
else if(name == "Fold") {
if(fg != -1) {
editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, bg);
}
}
}
}
delete []globalStyle;
}
void
Styler::ApplyLanguage(Editor* editor, const char* lang)
{
BString xpath("/NotepadPlus/LexerStyles/LexerType[@name='%s']/WordsStyle");
xpath.ReplaceFirst("%s", lang);
uint32 count;
XmlNode* nodes = fDocument->GetNodesByXPath(xpath.String(), &count);
int id, fg, bg, fs;
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(nodes[i], &id, &fg, &bg, &fs);
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
delete []nodes;
}
void
Styler::_GetAttributesFromNode(XmlNode &node, int* styleId, int* fgColor, int* bgColor, int* fontStyle)
{
*styleId = -1;
*fgColor = -1;
*bgColor = -1;
*fontStyle = -1;
BString temp;
temp = node.GetAttribute("styleID");
if(temp.IsEmpty() == false) {
*styleId = strtol(temp.String(), NULL, 10);
}
temp = node.GetAttribute("fgColor");
if(temp.IsEmpty() == false) {
*fgColor = strtol(temp.String(), NULL, 16);
}
temp = node.GetAttribute("bgColor");
if(temp.IsEmpty() == false) {
*bgColor = strtol(temp.String(), NULL, 16);
}
temp = node.GetAttribute("fontStyle");
if(temp.IsEmpty() == false) {
*fontStyle = strtol(temp.String(), NULL, 10);
}
}
void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor, int bgColor, int fontStyle)
{
if(fgColor != -1) {
editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
}
if(bgColor != -1) {
editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
}
if(fontStyle != -1) {
if(fontStyle & 1) {
editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
}
if(fontStyle & 2) {
editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
}
if(fontStyle & 4) {
editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
}
}
}
<commit_msg>Get font size from system settings.<commit_after>/*
* Koder is a code editor for Haiku based on Scintilla.
*
* Copyright (C) 2014-2015 Kacper Kasper <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Styler.h"
#include <cstdlib>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <String.h>
#include "Editor.h"
#include "XmlDocument.h"
#include "XmlNode.h"
Styler::Styler(const char* path)
:
fDocument(new XmlDocument(path))
{
}
Styler::~Styler()
{
delete fDocument;
}
void
Styler::ApplyGlobal(Editor* editor)
{
uint32 count;
XmlNode* defaultStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle[@styleID='32']", &count);
int id, fg, bg, fs;
_GetAttributesFromNode(defaultStyle[0], &id, &fg, &bg, &fs);
font_family fixed;
be_fixed_font->GetFamilyAndStyle(&fixed, NULL);
editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) fixed);
editor->SendMessage(SCI_STYLESETSIZE, id, (sptr_t) be_fixed_font->Size());
_SetAttributesInEditor(editor, id, fg, bg, fs);
editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
delete []defaultStyle;
XmlNode* globalStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle", &count);
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(globalStyle[i], &id, &fg, &bg, &fs);
if(id != 0 && id != 2069) {
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
else
{
BString name = globalStyle[i].GetAttribute("name");
if(name == "Current line background colour") {
editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
}
else if(name == "White space symbol") {
if(fg != -1) {
editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
}
}
else if(name == "Selected text colour") {
if(fg != -1) {
editor->SendMessage(SCI_SETSELFORE, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETSELBACK, true, bg);
}
}
else if(name == "Caret colour") {
editor->SendMessage(SCI_SETCARETFORE, fg, 0);
}
else if(name == "Edge colour") {
editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
}
else if(name == "Fold") {
if(fg != -1) {
editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, fg);
}
if(bg != -1) {
editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, bg);
}
}
}
}
delete []globalStyle;
}
void
Styler::ApplyLanguage(Editor* editor, const char* lang)
{
BString xpath("/NotepadPlus/LexerStyles/LexerType[@name='%s']/WordsStyle");
xpath.ReplaceFirst("%s", lang);
uint32 count;
XmlNode* nodes = fDocument->GetNodesByXPath(xpath.String(), &count);
int id, fg, bg, fs;
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(nodes[i], &id, &fg, &bg, &fs);
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
delete []nodes;
}
void
Styler::_GetAttributesFromNode(XmlNode &node, int* styleId, int* fgColor, int* bgColor, int* fontStyle)
{
*styleId = -1;
*fgColor = -1;
*bgColor = -1;
*fontStyle = -1;
BString temp;
temp = node.GetAttribute("styleID");
if(temp.IsEmpty() == false) {
*styleId = strtol(temp.String(), NULL, 10);
}
temp = node.GetAttribute("fgColor");
if(temp.IsEmpty() == false) {
*fgColor = strtol(temp.String(), NULL, 16);
}
temp = node.GetAttribute("bgColor");
if(temp.IsEmpty() == false) {
*bgColor = strtol(temp.String(), NULL, 16);
}
temp = node.GetAttribute("fontStyle");
if(temp.IsEmpty() == false) {
*fontStyle = strtol(temp.String(), NULL, 10);
}
}
void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor, int bgColor, int fontStyle)
{
if(fgColor != -1) {
editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
}
if(bgColor != -1) {
editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
}
if(fontStyle != -1) {
if(fontStyle & 1) {
editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
}
if(fontStyle & 2) {
editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
}
if(fontStyle & 4) {
editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ObjectUtils/CoffFile.h"
#include <absl/strings/str_format.h>
#include <llvm/Demangle/Demangle.h>
#include <llvm/Object/Binary.h>
#include <llvm/Object/COFF.h>
#include <llvm/Object/ObjectFile.h>
#include "OrbitBase/Logging.h"
#include "OrbitBase/Result.h"
#include "symbol.pb.h"
namespace orbit_object_utils {
namespace {
using orbit_grpc_protos::ModuleSymbols;
using orbit_grpc_protos::SymbolInfo;
class CoffFileImpl : public CoffFile {
public:
CoffFileImpl(std::filesystem::path file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& owning_binary);
[[nodiscard]] ErrorMessageOr<orbit_grpc_protos::ModuleSymbols> LoadDebugSymbols() override;
[[nodiscard]] bool HasDebugSymbols() const override;
[[nodiscard]] std::string GetName() const override;
[[nodiscard]] const std::filesystem::path& GetFilePath() const override;
[[nodiscard]] bool IsElf() const override;
[[nodiscard]] bool IsCoff() const override;
private:
ErrorMessageOr<uint64_t> GetSectionOffsetForSymbol(const llvm::object::SymbolRef& symbol_ref);
ErrorMessageOr<SymbolInfo> CreateSymbolInfo(const llvm::object::SymbolRef& symbol_ref);
const std::filesystem::path file_path_;
llvm::object::OwningBinary<llvm::object::ObjectFile> owning_binary_;
llvm::object::COFFObjectFile* object_file_;
bool has_symbol_table_;
};
CoffFileImpl::CoffFileImpl(std::filesystem::path file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& owning_binary)
: file_path_(std::move(file_path)),
owning_binary_(std::move(owning_binary)),
has_symbol_table_(false) {
object_file_ = llvm::dyn_cast<llvm::object::COFFObjectFile>(owning_binary_.getBinary());
// Per specification, a COFF file has a symbol table if the pointer to the symbol table is not 0.
has_symbol_table_ = (object_file_->getSymbolTable() != 0);
}
ErrorMessageOr<uint64_t> CoffFileImpl::GetSectionOffsetForSymbol(
const llvm::object::SymbolRef& symbol_ref) {
// Symbol addresses are relative virtual addresses (RVAs) that are relative to the
// start of the section. To get the address relative to the start of the object
// file, we need to find the section and add the base address of the section.
llvm::object::COFFSymbolRef coff_symbol_ref = object_file_->getCOFFSymbol(symbol_ref);
int32_t section_id = coff_symbol_ref.getSectionNumber();
const llvm::object::coff_section* section = nullptr;
std::error_code err = object_file_->getSection(section_id, section);
if (err) {
return ErrorMessage(absl::StrFormat("Section of symbol not found: %s", err.message()));
}
return section->VirtualAddress;
}
ErrorMessageOr<SymbolInfo> CoffFileImpl::CreateSymbolInfo(
const llvm::object::SymbolRef& symbol_ref) {
if ((symbol_ref.getFlags() & llvm::object::BasicSymbolRef::SF_Undefined) != 0) {
return ErrorMessage("Symbol is defined in another object file (SF_Undefined flag is set).");
}
const std::string name = symbol_ref.getName() ? symbol_ref.getName().get() : "";
// Unknown type - skip and generate a warning.
if (!symbol_ref.getType()) {
LOG("WARNING: Type is not set for symbol \"%s\" in \"%s\", skipping.", name,
file_path_.string());
return ErrorMessage(absl::StrFormat(R"(Type is not set for symbol "%s" in "%s", skipping.)",
name, file_path_.string()));
}
// Limit list of symbols to functions. Ignore sections and variables.
if (symbol_ref.getType().get() != llvm::object::SymbolRef::ST_Function) {
return ErrorMessage("Symbol is not a function.");
}
auto section_offset = GetSectionOffsetForSymbol(symbol_ref);
if (section_offset.has_error()) {
return ErrorMessage(absl::StrFormat("Error retrieving section offset for symbol \"%s\": %s",
name, section_offset.error().message()));
}
SymbolInfo symbol_info;
symbol_info.set_name(name);
symbol_info.set_demangled_name(llvm::demangle(name));
symbol_info.set_address(symbol_ref.getValue() + section_offset.value());
symbol_info.set_size(symbol_ref.getCommonSize());
return symbol_info;
}
ErrorMessageOr<ModuleSymbols> CoffFileImpl::LoadDebugSymbols() {
if (!has_symbol_table_) {
return ErrorMessage("COFF file does not have a symbol table.");
}
ModuleSymbols module_symbols;
module_symbols.set_symbols_file_path(file_path_.string());
for (const auto& symbol_ref : object_file_->symbols()) {
auto symbol_or_error = CreateSymbolInfo(symbol_ref);
if (symbol_or_error.has_value()) {
*module_symbols.add_symbol_infos() = std::move(symbol_or_error.value());
}
}
if (module_symbols.symbol_infos_size() == 0) {
return ErrorMessage(
"Unable to load symbols from object file, not even a single symbol of "
"type function found.");
}
return module_symbols;
}
bool CoffFileImpl::HasDebugSymbols() const { return has_symbol_table_; }
const std::filesystem::path& CoffFileImpl::GetFilePath() const { return file_path_; }
std::string CoffFileImpl::GetName() const { return file_path_.filename().string(); }
bool CoffFileImpl::IsElf() const { return false; }
bool CoffFileImpl::IsCoff() const { return true; }
} // namespace
ErrorMessageOr<std::unique_ptr<CoffFile>> CreateCoffFile(const std::filesystem::path& file_path) {
// TODO(hebecker): Remove this explicit construction of StringRef when we
// switch to LLVM10.
const std::string file_path_str = file_path.string();
const llvm::StringRef file_path_llvm{file_path_str};
llvm::Expected<llvm::object::OwningBinary<llvm::object::ObjectFile>> object_file_or_error =
llvm::object::ObjectFile::createObjectFile(file_path_llvm);
if (!object_file_or_error) {
return ErrorMessage(absl::StrFormat("Unable to load COFF file \"%s\": %s", file_path.string(),
llvm::toString(object_file_or_error.takeError())));
}
llvm::object::OwningBinary<llvm::object::ObjectFile>& file = object_file_or_error.get();
return CreateCoffFile(file_path, std::move(file));
}
ErrorMessageOr<std::unique_ptr<CoffFile>> CreateCoffFile(
const std::filesystem::path& file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& file) {
llvm::object::ObjectFile* object_file = file.getBinary();
if (llvm::dyn_cast<llvm::object::COFFObjectFile>(object_file) != nullptr) {
return std::unique_ptr<CoffFile>(new CoffFileImpl(file_path, std::move(file)));
} else {
return ErrorMessage(absl::StrFormat("Unable to load object file \"%s\":", file_path.string()));
}
}
} // namespace orbit_object_utils
<commit_msg>Fix tripping assert in CoffFileImpl::LoadDebugSymbols<commit_after>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ObjectUtils/CoffFile.h"
#include <absl/strings/str_format.h>
#include <llvm/Demangle/Demangle.h>
#include <llvm/Object/Binary.h>
#include <llvm/Object/COFF.h>
#include <llvm/Object/ObjectFile.h>
#include "OrbitBase/Logging.h"
#include "OrbitBase/Result.h"
#include "symbol.pb.h"
namespace orbit_object_utils {
namespace {
using orbit_grpc_protos::ModuleSymbols;
using orbit_grpc_protos::SymbolInfo;
class CoffFileImpl : public CoffFile {
public:
CoffFileImpl(std::filesystem::path file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& owning_binary);
[[nodiscard]] ErrorMessageOr<orbit_grpc_protos::ModuleSymbols> LoadDebugSymbols() override;
[[nodiscard]] bool HasDebugSymbols() const override;
[[nodiscard]] std::string GetName() const override;
[[nodiscard]] const std::filesystem::path& GetFilePath() const override;
[[nodiscard]] bool IsElf() const override;
[[nodiscard]] bool IsCoff() const override;
private:
ErrorMessageOr<uint64_t> GetSectionOffsetForSymbol(const llvm::object::SymbolRef& symbol_ref);
ErrorMessageOr<SymbolInfo> CreateSymbolInfo(const llvm::object::SymbolRef& symbol_ref);
const std::filesystem::path file_path_;
llvm::object::OwningBinary<llvm::object::ObjectFile> owning_binary_;
llvm::object::COFFObjectFile* object_file_;
bool has_symbol_table_;
};
CoffFileImpl::CoffFileImpl(std::filesystem::path file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& owning_binary)
: file_path_(std::move(file_path)),
owning_binary_(std::move(owning_binary)),
has_symbol_table_(false) {
object_file_ = llvm::dyn_cast<llvm::object::COFFObjectFile>(owning_binary_.getBinary());
// Per specification, a COFF file has a symbol table if the pointer to the symbol table is not 0.
has_symbol_table_ = (object_file_->getSymbolTable() != 0);
}
ErrorMessageOr<uint64_t> CoffFileImpl::GetSectionOffsetForSymbol(
const llvm::object::SymbolRef& symbol_ref) {
// Symbol addresses are relative virtual addresses (RVAs) that are relative to the
// start of the section. To get the address relative to the start of the object
// file, we need to find the section and add the base address of the section.
llvm::object::COFFSymbolRef coff_symbol_ref = object_file_->getCOFFSymbol(symbol_ref);
int32_t section_id = coff_symbol_ref.getSectionNumber();
const llvm::object::coff_section* section = nullptr;
std::error_code err = object_file_->getSection(section_id, section);
if (err) {
return ErrorMessage(absl::StrFormat("Section of symbol not found: %s", err.message()));
}
return section->VirtualAddress;
}
ErrorMessageOr<SymbolInfo> CoffFileImpl::CreateSymbolInfo(
const llvm::object::SymbolRef& symbol_ref) {
if ((symbol_ref.getFlags() & llvm::object::BasicSymbolRef::SF_Undefined) != 0) {
return ErrorMessage("Symbol is defined in another object file (SF_Undefined flag is set).");
}
const std::string name = symbol_ref.getName() ? symbol_ref.getName().get() : "";
// Unknown type - skip and generate a warning.
if (!symbol_ref.getType()) {
LOG("WARNING: Type is not set for symbol \"%s\" in \"%s\", skipping.", name,
file_path_.string());
return ErrorMessage(absl::StrFormat(R"(Type is not set for symbol "%s" in "%s", skipping.)",
name, file_path_.string()));
}
// Limit list of symbols to functions. Ignore sections and variables.
if (symbol_ref.getType().get() != llvm::object::SymbolRef::ST_Function) {
return ErrorMessage("Symbol is not a function.");
}
auto section_offset = GetSectionOffsetForSymbol(symbol_ref);
if (section_offset.has_error()) {
return ErrorMessage(absl::StrFormat("Error retrieving section offset for symbol \"%s\": %s",
name, section_offset.error().message()));
}
SymbolInfo symbol_info;
symbol_info.set_name(name);
symbol_info.set_demangled_name(llvm::demangle(name));
symbol_info.set_address(symbol_ref.getValue() + section_offset.value());
llvm::object::COFFSymbolRef coff_symbol_ref = object_file_->getCOFFSymbol(symbol_ref);
symbol_info.set_size(coff_symbol_ref.getValue());
return symbol_info;
}
ErrorMessageOr<ModuleSymbols> CoffFileImpl::LoadDebugSymbols() {
if (!has_symbol_table_) {
return ErrorMessage("COFF file does not have a symbol table.");
}
ModuleSymbols module_symbols;
module_symbols.set_symbols_file_path(file_path_.string());
for (const auto& symbol_ref : object_file_->symbols()) {
auto symbol_or_error = CreateSymbolInfo(symbol_ref);
if (symbol_or_error.has_value()) {
*module_symbols.add_symbol_infos() = std::move(symbol_or_error.value());
}
}
if (module_symbols.symbol_infos_size() == 0) {
return ErrorMessage(
"Unable to load symbols from object file, not even a single symbol of "
"type function found.");
}
return module_symbols;
}
bool CoffFileImpl::HasDebugSymbols() const { return has_symbol_table_; }
const std::filesystem::path& CoffFileImpl::GetFilePath() const { return file_path_; }
std::string CoffFileImpl::GetName() const { return file_path_.filename().string(); }
bool CoffFileImpl::IsElf() const { return false; }
bool CoffFileImpl::IsCoff() const { return true; }
} // namespace
ErrorMessageOr<std::unique_ptr<CoffFile>> CreateCoffFile(const std::filesystem::path& file_path) {
// TODO(hebecker): Remove this explicit construction of StringRef when we
// switch to LLVM10.
const std::string file_path_str = file_path.string();
const llvm::StringRef file_path_llvm{file_path_str};
llvm::Expected<llvm::object::OwningBinary<llvm::object::ObjectFile>> object_file_or_error =
llvm::object::ObjectFile::createObjectFile(file_path_llvm);
if (!object_file_or_error) {
return ErrorMessage(absl::StrFormat("Unable to load COFF file \"%s\": %s", file_path.string(),
llvm::toString(object_file_or_error.takeError())));
}
llvm::object::OwningBinary<llvm::object::ObjectFile>& file = object_file_or_error.get();
return CreateCoffFile(file_path, std::move(file));
}
ErrorMessageOr<std::unique_ptr<CoffFile>> CreateCoffFile(
const std::filesystem::path& file_path,
llvm::object::OwningBinary<llvm::object::ObjectFile>&& file) {
llvm::object::ObjectFile* object_file = file.getBinary();
if (llvm::dyn_cast<llvm::object::COFFObjectFile>(object_file) != nullptr) {
return std::unique_ptr<CoffFile>(new CoffFileImpl(file_path, std::move(file)));
} else {
return ErrorMessage(absl::StrFormat("Unable to load object file \"%s\":", file_path.string()));
}
}
} // namespace orbit_object_utils
<|endoftext|> |
<commit_before>/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk>
* Please see website for licensing terms.
*/
#include "config/stm32plus.h"
#include "config/flash/spi.h"
#include "config/sdcard.h"
#include "config/usart.h"
#include "config/filesystem.h"
#include "memory/scoped_ptr.h"
#include <vector>
#include <string>
using namespace stm32plus;
/**
* This example programs a SPI flash device from files stored on an SD card and outputs
* progress messages to a USART terminal. This programmer only requires the standard SPI
* commands so it uses the 'StandardSpiFlashDevice' template. Other templates are available
* that mixin commands specific to those devices.
*
* The SD card must contain an "index.txt" file in the "/spiflash" folder. "/spiflash/index.txt"
* contains one line per file to flash The line is of the form:
*
* <filename>=<start-address-in-flash-in-decimal>
*
* For example:
*
* /spiflash/graphic1.bin=0
* /spiflash/graphic2.bin=16384
* /spiflash/assets/line.bin=24576
*
* Whitespace is not permitted anywhere on the text lines. It is important that each address
* is a multiple of the device page size (usually 256 bytes). If it's not then you will get
* data corruption. A chip-erase command is used to wipe the device before
* programming.
*
* An example "spiflash" directory is included with this example that can be copied to
* the root of your SD card. See the related 'flash_spi_reader' example for a demo that
* reads back the example graphic files and displays them on an LCD.
*
* The default peripherals for this demo are SPI2, USART1, Winbond W25Q16DW 16Mbit flash. All
* of these are customisable by you. The device identification code reported by the W25Q16DW
* should be "ef6015".
*
* Compatible MCU:
* STM32F1
* STM32F4
*
* Tested on devices:
* STM32F103ZET6
* STM32F407VGT6
*/
class FlashSpiProgram {
// these are the peripherals we will use
typedef Spi2<> MySpi;
typedef Usart1<> MyUsart;
typedef spiflash::StandardSpiFlashDevice<MySpi> MyFlash;
// declare the peripheral pointers
MyUsart *_usart;
MySpi *_spi;
MyFlash *_flash;
SdioDmaSdCard *_sdcard;
FileSystem *_fs;
UsartPollingOutputStream *_usartStream;
// declare the program variables
struct FlashEntry {
char *filename;
uint32_t length;
uint32_t offset;
};
std::vector<FlashEntry> _flashEntries;
public:
void run() {
// initialise the USART
_usart=new MyUsart(57600);
_usartStream=new UsartPollingOutputStream(*_usart);
status("Initialising SD card.");
// initialise the SD card
_sdcard=new SdioDmaSdCard;
if(errorProvider.hasError())
error("SD card could not be initialised");
// initialise the filesystem on the card
NullTimeProvider timeProvider;
if(!FileSystem::getInstance(*_sdcard,timeProvider,_fs))
error("The file system on the SD card could not be initialised");
// Initialise the SPI peripheral in master mode. The SPI speed is bus/4
// Make sure that this is not too fast for your device.
MySpi::Parameters spiParams;
spiParams.spi_mode=SPI_Mode_Master;
spiParams.spi_baudRatePrescaler=SPI_BaudRatePrescaler_4;
spiParams.spi_cpol=SPI_CPOL_Low;
spiParams.spi_cpha=SPI_CPHA_1Edge;
_spi=new MySpi(spiParams);
// initialise the flash device
_flash=new MyFlash(*_spi);
// show the device identifier
showDeviceIdentifier();
// read the index file
readIndexFile();
// erase the flash device
eraseFlash();
// write each file
for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++)
writeFile(*it);
// verify each file
for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++)
verifyFile(*it);
// done
status("Success");
for(;;);
}
/*
* Show the flash device id
*/
void showDeviceIdentifier() {
uint8_t id[3];
char output[7];
if(!_flash->readJedecId(id,sizeof(id)))
error("Unable to read the flash id code");
StringUtil::toHex(id,sizeof(id),output);
output[sizeof(output)-1]='\0';
*_usartStream << "Flash id = " << output << "\r\n";
}
/*
* Erase the entire device
*/
void eraseFlash() {
status("Erasing the entire flash device");
if(!_flash->writeEnable())
error("Unable to enable write access");
if(!_flash->chipErase())
error("Unable to execute the erase command");
if(!_flash->waitForIdle())
error("Failed to wait for the flash device to be idle");
status("Erase completed");
}
/*
* Write the file to the flash device
*/
void writeFile(const FlashEntry& fe) {
uint8_t page[MyFlash::PAGE_SIZE];
scoped_ptr<File> file;
uint32_t remaining,actuallyRead,address;
*_usartStream << "Programming " << fe.filename << "\r\n";
if(!_fs->openFile(fe.filename,file.address()))
error("Failed to open file");
address=fe.offset;
for(remaining=fe.length;remaining;remaining-=actuallyRead) {
// read a page from the file
if(!file->read(page,sizeof(page),actuallyRead))
error("Failed to read from file");
// cannot hit EOF here
if(!actuallyRead)
error("Unexpected end of file");
// wait for the device to go idle
if(!_flash->waitForIdle())
error("Failed to wait for the device to become idle");
// enable writing
if(!_flash->writeEnable())
error("Unable to enable write access");
if(!_flash->waitForIdle())
error("Failed to wait for the device to become idle");
// program the page
if(!_flash->pageProgram(address,page,actuallyRead))
error("Failed to program the page");
// update for next
address+=actuallyRead;
}
}
/*
* Verify the file just written to the device
*/
void verifyFile(const FlashEntry& fe) {
uint8_t filePage[MyFlash::PAGE_SIZE],flashPage[MyFlash::PAGE_SIZE];
scoped_ptr<File> file;
uint32_t remaining,actuallyRead,address;
*_usartStream << "Verifying " << fe.filename << "\r\n";
if(!_fs->openFile(fe.filename,file.address()))
error("Failed to open file");
address=fe.offset;
for(remaining=fe.length;remaining;remaining-=actuallyRead) {
// read a page from the file
if(!file->read(filePage,sizeof(filePage),actuallyRead))
error("Failed to read from file");
// cannot hit EOF here
if(!actuallyRead)
error("Unexpected end of file");
// read the page from the flash device
if(!_flash->fastRead(address,flashPage,actuallyRead))
error("Failed to read from the flash device");
// compare it
if(memcmp(filePage,flashPage,actuallyRead)!=0)
error("Verify error: programming failed");
// update for next
address+=actuallyRead;
}
}
/*
* Read index.txt
*/
void readIndexFile() {
scoped_ptr<File> file;
char line[200],*ptr;
status("Reading index file.");
// open the file
if(!_fs->openFile("/spiflash/index.txt",file.address()))
error("Cannot open /index.txt");
// attach a reader and read each line
FileReader reader(*file);
while(reader.available()) {
scoped_ptr<File> dataFile;
// read line
if(!reader.readLine(line,sizeof(line)))
error("Failed to read line from file");
// search for the = separator and break the text line at it
if((ptr=strchr(line,'='))==nullptr)
error("Badly formatted index.txt line - cannot find = symbol");
*ptr='\0';
// ensure this file can be opened
if(!_fs->openFile(line,dataFile.address()))
error("Cannot open data file");
FlashEntry fe;
fe.filename=strdup(line);
fe.offset=atoi(ptr+1);
fe.length=dataFile->getLength();
_flashEntries.push_back(fe);
*_usartStream << "Parsed " << fe.filename
<< " offset " << StringUtil::Ascii(fe.offset)
<< " length " << StringUtil::Ascii(fe.length)
<< "\r\n";
}
*_usartStream << "Finished reading index, "
<< StringUtil::Ascii(_flashEntries.size()) << ", entries read\r\n";
}
/*
* Unrecoverable error
*/
void error(const char *text) {
status(text);
for(;;);
}
/*
* Write a status string to the usart
*/
void status(const char *text) {
*_usartStream << text << "\r\n";
}
};
/*
* Main entry point
*/
int main() {
MillisecondTimer::initialise();
FlashSpiProgram test;
test.run();
// not reached
return 0;
}
<commit_msg>adding SPI pinout to comments in example<commit_after>/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk>
* Please see website for licensing terms.
*/
#include "config/stm32plus.h"
#include "config/flash/spi.h"
#include "config/sdcard.h"
#include "config/usart.h"
#include "config/filesystem.h"
#include "memory/scoped_ptr.h"
#include <vector>
#include <string>
using namespace stm32plus;
/**
* This example programs a SPI flash device from files stored on an SD card and outputs
* progress messages to a USART terminal. This programmer only requires the standard SPI
* commands so it uses the 'StandardSpiFlashDevice' template. Other templates are available
* that mixin commands specific to those devices.
*
* The SD card must contain an "index.txt" file in the "/spiflash" folder. "/spiflash/index.txt"
* contains one line per file to flash The line is of the form:
*
* <filename>=<start-address-in-flash-in-decimal>
*
* For example:
*
* /spiflash/graphic1.bin=0
* /spiflash/graphic2.bin=16384
* /spiflash/assets/line.bin=24576
*
* Whitespace is not permitted anywhere on the text lines. It is important that each address
* is a multiple of the device page size (usually 256 bytes). If it's not then you will get
* data corruption. A chip-erase command is used to wipe the device before
* programming.
*
* An example "spiflash" directory is included with this example that can be copied to
* the root of your SD card. See the related 'flash_spi_reader' example for a demo that
* reads back the example graphic files and displays them on an LCD.
*
* The default peripherals for this demo are SPI2, USART1, Winbond W25Q16DW 16Mbit flash. All
* of these are customisable by you. The device identification code reported by the W25Q16DW
* should be "ef6015".
*
* The pinout for SPI2 is:
*
* NSS = PB12
* SCK = PB13
* MISO = PB14
* MOSI = PB15
*
* Compatible MCU:
* STM32F1
* STM32F4
*
* Tested on devices:
* STM32F103ZET6
* STM32F407VGT6
*/
class FlashSpiProgram {
// these are the peripherals we will use
typedef Spi2<> MySpi;
typedef Usart1<> MyUsart;
typedef spiflash::StandardSpiFlashDevice<MySpi> MyFlash;
// declare the peripheral pointers
MyUsart *_usart;
MySpi *_spi;
MyFlash *_flash;
SdioDmaSdCard *_sdcard;
FileSystem *_fs;
UsartPollingOutputStream *_usartStream;
// declare the program variables
struct FlashEntry {
char *filename;
uint32_t length;
uint32_t offset;
};
std::vector<FlashEntry> _flashEntries;
public:
void run() {
// initialise the USART
_usart=new MyUsart(57600);
_usartStream=new UsartPollingOutputStream(*_usart);
status("Initialising SD card.");
// initialise the SD card
_sdcard=new SdioDmaSdCard;
if(errorProvider.hasError())
error("SD card could not be initialised");
// initialise the filesystem on the card
NullTimeProvider timeProvider;
if(!FileSystem::getInstance(*_sdcard,timeProvider,_fs))
error("The file system on the SD card could not be initialised");
// Initialise the SPI peripheral in master mode. The SPI speed is bus/4
// Make sure that this is not too fast for your device.
MySpi::Parameters spiParams;
spiParams.spi_mode=SPI_Mode_Master;
spiParams.spi_baudRatePrescaler=SPI_BaudRatePrescaler_4;
spiParams.spi_cpol=SPI_CPOL_Low;
spiParams.spi_cpha=SPI_CPHA_1Edge;
_spi=new MySpi(spiParams);
// initialise the flash device
_flash=new MyFlash(*_spi);
// show the device identifier
showDeviceIdentifier();
// read the index file
readIndexFile();
// erase the flash device
eraseFlash();
// write each file
for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++)
writeFile(*it);
// verify each file
for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++)
verifyFile(*it);
// done
status("Success");
for(;;);
}
/*
* Show the flash device id
*/
void showDeviceIdentifier() {
uint8_t id[3];
char output[7];
if(!_flash->readJedecId(id,sizeof(id)))
error("Unable to read the flash id code");
StringUtil::toHex(id,sizeof(id),output);
output[sizeof(output)-1]='\0';
*_usartStream << "Flash id = " << output << "\r\n";
}
/*
* Erase the entire device
*/
void eraseFlash() {
status("Erasing the entire flash device");
if(!_flash->writeEnable())
error("Unable to enable write access");
if(!_flash->chipErase())
error("Unable to execute the erase command");
if(!_flash->waitForIdle())
error("Failed to wait for the flash device to be idle");
status("Erase completed");
}
/*
* Write the file to the flash device
*/
void writeFile(const FlashEntry& fe) {
uint8_t page[MyFlash::PAGE_SIZE];
scoped_ptr<File> file;
uint32_t remaining,actuallyRead,address;
*_usartStream << "Programming " << fe.filename << "\r\n";
if(!_fs->openFile(fe.filename,file.address()))
error("Failed to open file");
address=fe.offset;
for(remaining=fe.length;remaining;remaining-=actuallyRead) {
// read a page from the file
if(!file->read(page,sizeof(page),actuallyRead))
error("Failed to read from file");
// cannot hit EOF here
if(!actuallyRead)
error("Unexpected end of file");
// wait for the device to go idle
if(!_flash->waitForIdle())
error("Failed to wait for the device to become idle");
// enable writing
if(!_flash->writeEnable())
error("Unable to enable write access");
if(!_flash->waitForIdle())
error("Failed to wait for the device to become idle");
// program the page
if(!_flash->pageProgram(address,page,actuallyRead))
error("Failed to program the page");
// update for next
address+=actuallyRead;
}
}
/*
* Verify the file just written to the device
*/
void verifyFile(const FlashEntry& fe) {
uint8_t filePage[MyFlash::PAGE_SIZE],flashPage[MyFlash::PAGE_SIZE];
scoped_ptr<File> file;
uint32_t remaining,actuallyRead,address;
*_usartStream << "Verifying " << fe.filename << "\r\n";
if(!_fs->openFile(fe.filename,file.address()))
error("Failed to open file");
address=fe.offset;
for(remaining=fe.length;remaining;remaining-=actuallyRead) {
// read a page from the file
if(!file->read(filePage,sizeof(filePage),actuallyRead))
error("Failed to read from file");
// cannot hit EOF here
if(!actuallyRead)
error("Unexpected end of file");
// read the page from the flash device
if(!_flash->fastRead(address,flashPage,actuallyRead))
error("Failed to read from the flash device");
// compare it
if(memcmp(filePage,flashPage,actuallyRead)!=0)
error("Verify error: programming failed");
// update for next
address+=actuallyRead;
}
}
/*
* Read index.txt
*/
void readIndexFile() {
scoped_ptr<File> file;
char line[200],*ptr;
status("Reading index file.");
// open the file
if(!_fs->openFile("/spiflash/index.txt",file.address()))
error("Cannot open /index.txt");
// attach a reader and read each line
FileReader reader(*file);
while(reader.available()) {
scoped_ptr<File> dataFile;
// read line
if(!reader.readLine(line,sizeof(line)))
error("Failed to read line from file");
// search for the = separator and break the text line at it
if((ptr=strchr(line,'='))==nullptr)
error("Badly formatted index.txt line - cannot find = symbol");
*ptr='\0';
// ensure this file can be opened
if(!_fs->openFile(line,dataFile.address()))
error("Cannot open data file");
FlashEntry fe;
fe.filename=strdup(line);
fe.offset=atoi(ptr+1);
fe.length=dataFile->getLength();
_flashEntries.push_back(fe);
*_usartStream << "Parsed " << fe.filename
<< " offset " << StringUtil::Ascii(fe.offset)
<< " length " << StringUtil::Ascii(fe.length)
<< "\r\n";
}
*_usartStream << "Finished reading index, "
<< StringUtil::Ascii(_flashEntries.size()) << ", entries read\r\n";
}
/*
* Unrecoverable error
*/
void error(const char *text) {
status(text);
for(;;);
}
/*
* Write a status string to the usart
*/
void status(const char *text) {
*_usartStream << text << "\r\n";
}
};
/*
* Main entry point
*/
int main() {
MillisecondTimer::initialise();
FlashSpiProgram test;
test.run();
// not reached
return 0;
}
<|endoftext|> |
<commit_before>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns
//Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)
//as published by the Free Software Foundation.
// Simple example of use of Producer::RenderSurface
// The myGraphics class is a simple sample of how one would implement
// graphics drawing with Producer::RenderSurface
#include <osgUtil/UpdateVisitor>
#include <osgDB/ReadFile>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osgProducer/Viewer>
#include "DepthPartitionNode.h"
const double r_earth = 6378.137;
const double r_sun = 695990.0;
const double AU = 149697900.0;
osg::Node* createScene()
{
// Create the Earth, in blue
osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;
osg::Sphere* earth_sphere = new osg::Sphere;
earth_sphere->setRadius(r_earth);
earth_sd->setShape(earth_sphere);
earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));
osg::Geode* earth = new osg::Geode;
earth->setName("earth");
earth->addDrawable(earth_sd);
// Create the Sun, in yellow
osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;
osg::Sphere* sun_sphere = new osg::Sphere;
sun_sphere->setRadius(r_sun);
sun_sd->setShape(sun_sphere);
sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));
osg::Geode* sun = new osg::Geode;
sun->setName("sun");
sun->addDrawable(sun_sd);
// Move the sun behind the earth
osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3d(0.0, AU, 0.0));
osg::Group* scene = new osg::Group;
scene->addChild(earth);
scene->addChild(pat);
pat->addChild(sun);
return scene;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard example of using osgProducer::CameraGroup.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
bool needToSetHomePosition = false;
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
// if one hasn't been loaded create an earth and sun test model.
if (!scene)
{
scene = createScene();
needToSetHomePosition = true;
}
// Create a DepthPartitionNode to manage partitioning of the scene
osg::ref_ptr<DepthPartitionNode> dpn = new DepthPartitionNode;
dpn->addChild(scene.get());
dpn->setActive(true); // Control whether the node analyzes the scene
// pass the loaded scene graph to the viewer.
viewer.setSceneData(dpn.get());
if (needToSetHomePosition)
{
viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// run a clean up frame to delete all OpenGL objects.
viewer.cleanup_frame();
// wait for all the clean up frame to complete.
viewer.sync();
return 0;
}
<commit_msg>From Keith Steffen, changed instance of sun to sun_geode to avoid Solaris10 build issue with it defining "sun"?#!<commit_after>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns
//Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)
//as published by the Free Software Foundation.
// Simple example of use of Producer::RenderSurface
// The myGraphics class is a simple sample of how one would implement
// graphics drawing with Producer::RenderSurface
#include <osgUtil/UpdateVisitor>
#include <osgDB/ReadFile>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osgProducer/Viewer>
#include "DepthPartitionNode.h"
const double r_earth = 6378.137;
const double r_sun = 695990.0;
const double AU = 149697900.0;
osg::Node* createScene()
{
// Create the Earth, in blue
osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;
osg::Sphere* earth_sphere = new osg::Sphere;
earth_sphere->setRadius(r_earth);
earth_sd->setShape(earth_sphere);
earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));
osg::Geode* earth = new osg::Geode;
earth->setName("earth");
earth->addDrawable(earth_sd);
// Create the Sun, in yellow
osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;
osg::Sphere* sun_sphere = new osg::Sphere;
sun_sphere->setRadius(r_sun);
sun_sd->setShape(sun_sphere);
sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));
osg::Geode* sun_geode = new osg::Geode;
sun_geode->setName("sun");
sun_geode->addDrawable(sun_sd);
// Move the sun behind the earth
osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3d(0.0, AU, 0.0));
osg::Group* scene = new osg::Group;
scene->addChild(earth);
scene->addChild(pat);
pat->addChild(sun_geode);
return scene;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard example of using osgProducer::CameraGroup.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
bool needToSetHomePosition = false;
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
// if one hasn't been loaded create an earth and sun test model.
if (!scene)
{
scene = createScene();
needToSetHomePosition = true;
}
// Create a DepthPartitionNode to manage partitioning of the scene
osg::ref_ptr<DepthPartitionNode> dpn = new DepthPartitionNode;
dpn->addChild(scene.get());
dpn->setActive(true); // Control whether the node analyzes the scene
// pass the loaded scene graph to the viewer.
viewer.setSceneData(dpn.get());
if (needToSetHomePosition)
{
viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// run a clean up frame to delete all OpenGL objects.
viewer.cleanup_frame();
// wait for all the clean up frame to complete.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <include/grassmann_pca_with_trimming.hpp>
#include <include/private/boost_ublas_external_storage.hpp>
#include <include/private/boost_ublas_row_iterator.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <string>
#include <fstream>
static std::string movielocation = "/is/ps/shared/users/jonas/movies/";
static std::string eigenvectorslocation = "./";
void number2filename(size_t file_number, char *filename)
{
const char *fn_template = (movielocation + "starwars_%.3u/frame%.7u.png").c_str();
const size_t dir_num = file_number / 10000;
sprintf(filename, fn_template, dir_num, file_number);
}
//! An container over the content of a cvMat, addressable
//! in a vector fashion.
template <class T>
struct cvMatAsVector
{
cvMatAsVector(const cv::Mat& image_) :
image(image_),
width(image_.size().width),
height(image_.size().height)
{}
T operator()(std::size_t index) const
{
int colorchannel = index % 3;
index /= 3;
int column = index % width;
index /= width;
return image.at<cv::Vec3b>(index, column)[colorchannel];
}
struct internal_iterator
{
cvMatAsVector<T> &outer_instance;
internal_iterator() : current_index(0){}
internal_iterator(size_t index) : current_index(index) {}
T const& operator*() const
{
return outer_instance[current_index];
}
internal_iterator& operator++()
{
current_index++;
return *this;
}
size_t current_index;
};
internal_iterator begin() const
{
return internal_iterator(0);
}
internal_iterator end() const
{
return internal_iterator(size());
}
size_t size() const
{
return width * height * 3;
}
const cv::Mat& image;
const size_t width;
const size_t height;
};
//! An iterator that will load the images on demand instead of storing everything on memory
template <class T>
class iterator_on_image_files :
public boost::iterator_facade<
iterator_on_image_files<T>
, boost::numeric::ublas::vector<T>
, std::random_access_iterator_tag
, boost::numeric::ublas::vector<T> const& // const reference
>
{
public:
typedef iterator_on_image_files<T> this_type;
typedef boost::numeric::ublas::vector<T> image_vector_type;
iterator_on_image_files() : m_index(std::numeric_limits<size_t>::max())
{}
explicit iterator_on_image_files(size_t index)
: m_index(index)
{}
private:
friend class boost::iterator_core_access;
typename this_type::difference_type distance_to(this_type const& r) const
{
return typename this_type::difference_type(r.m_index) - typename this_type::difference_type(m_index); // sign promotion
}
void increment()
{
m_index++;
image_vector.clear();
}
bool equal(this_type const& other) const
{
return this->m_index == other.m_index;
}
image_vector_type const& dereference() const
{
if(image_vector.empty())
{
read_image();
}
return image_vector;
}
void read_image() const
{
char filename[MAX_PATH];
number2filename(m_index, filename);
std::cout << "Reading " << filename << std::endl;
cv::Mat image = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
if(!image.data)
{
std::ostringstream o;
o << "error: could not load image '" << filename << "'";
std::cerr << o.str() << std::endl;
throw std::runtime_error(o.str());
}
const int w = image.size().width;
const int h = image.size().height;
image_vector.resize(w * h * 3);
typename boost::numeric::ublas::vector<T>::iterator it = image_vector.begin();
for(int y = 0; y < h; y++)
{
for(int x = 0; x < w; x++)
{
cv::Vec3b pixel = image.at<cv::Vec3b>(y, x);
*it++ = pixel[0];
*it++ = pixel[1];
*it++ = pixel[2];
}
}
}
void advance(typename this_type::difference_type n)
{
if(n < 0)
{
assert((-n) <= static_cast<typename this_type::difference_type>(m_index));
m_index -= n;
}
else
{
//assert(n + index <= matrix->size1());
m_index += n;
}
if(n != 0)
{
image_vector.clear();
}
}
size_t m_index;
mutable boost::numeric::ublas::vector<T> image_vector;
};
//! An output vector that also writes to a file
template <class data_iterator_t>
class iterator_on_output_data :
public boost::iterator_facade<
iterator_on_output_data<data_iterator_t>
, typename data_iterator_t::value_type
, std::random_access_iterator_tag
, typename data_iterator_t::reference
>
{
public:
typedef typename data_iterator_t::reference reference;
typedef iterator_on_output_data<data_iterator_t> this_type;
iterator_on_output_data() :
m_index(std::numeric_limits<size_t>::max()),
m_max_element_per_line(100),
internal_it()
{}
explicit iterator_on_output_data(size_t index, data_iterator_t it_) :
m_index(index),
m_max_element_per_line(100),
internal_it(it_)
{}
void save_eigenvector()
{
char filename[MAX_PATH];
const char * eigen_vector_template = "eigenvector_%.7d.txt";
sprintf(filename, eigen_vector_template, m_index);
std::ofstream f(filename);
if(!f.is_open())
{
std::cerr << "Cannot open the file " << filename << " for writing" << std::endl;
return;
}
std::cout << "Writing eigenvector file " << filename << std::endl;
typedef typename data_iterator_t::value_type::iterator element_iterator;
element_iterator itelement(internal_it->begin());
for(int i = 0; i < internal_it->size(); i++, ++itelement)
{
if((i + 1) % m_max_element_per_line == 0)
{
f << std::endl;
}
f << *itelement;
}
f.close();
std::cout << "Writing eigenvector file " << filename << " -- ok " << std::endl;
}
private:
friend class boost::iterator_core_access;
typename this_type::difference_type distance_to(this_type const& r) const
{
return typename this_type::difference_type(r.m_index) - typename this_type::difference_type(m_index); // sign promotion
}
void increment() {
// here we save before going further, except if it has not been changed
save_eigenvector();
m_index++;
++internal_it;
}
void advance(typename this_type::difference_type n)
{
if(n < 0)
{
assert((-n) <= static_cast<typename this_type::difference_type>(m_index));
m_index -= n;
}
else
{
//assert(n + index <= matrix->size1());
m_index += n;
}
}
bool equal(this_type const& other) const
{
return this->internal_it == other.internal_it;
}
reference dereference() const
{
return *internal_it;
}
size_t m_index;
// max number of element on one line during the save
size_t m_max_element_per_line;
data_iterator_t internal_it;
};
#if 0
template <class data_t>
class data_and_save : data_t
{
size_t index;
//! sets the index that will determine the filename to which this eigenvector will
//! be saved.
void set_index(size_t index_)
{
index = index_;
}
data_t& operator*()
};
#endif
int main(int argc, char *argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("nb-frames,f", po::value<int>(), "number of frames in the movie")
("movie,m", po::value<std::string>(), "full path to the movie location")
("max-dimensions,d", po::value<int>(), "requested number of components for the computation of the trimmed grassmann average")
("max-iterations", po::value<int>(), "maximum number of iterations (defaults to the number of frames)")
("nb-pca-steps", po::value<int>(), "number of pca steps")
("trimming-percentage", po::value<float>(), "percentage of trimming")
("nb-processors", po::value<int>(), "number of processors used (defaults to 1)")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
if(!vm.count("trimming-percentage"))
{
std::cerr << "the parameter 'trimming-percentage' should be set, now exiting...\n";
return 1;
}
const float trimming_percentage = vm["trimming-percentage"].as<float>();
size_t num_frames = 100; //179415;
if(vm.count("nb-frames"))
{
std::cout << "The movie contains #" << vm["nb-frames"].as<int>() << " frames.\n";
num_frames = vm["nb-frames"].as<int>();
}
else
{
std::cout << "Nb of frames not set, setting it to" << num_frames << "\n";
}
size_t max_dimension = 30;
if(vm.count("max-dimensions"))
{
std::cout << "Number of components requested #" << vm["max-dimensions"].as<int>() << "\n";
max_dimension = vm["max-dimensions"].as<int>();
}
else
{
std::cout << "Nb of components not set, setting it to" << max_dimension << "\n";
}
size_t max_iterations = num_frames;
if(vm.count("max-iterations"))
{
std::cout << "Maximum number of iterations #" << vm["max-iterations"].as<int>() << "\n";
max_iterations = vm["max-iterations"].as<int>();
}
size_t nb_pca_steps = 3;
if(vm.count("nb-pca-steps"))
{
std::cout << "Number of PCA steps #" << vm["nb-pca-steps"].as<int>() << "\n";
nb_pca_steps = vm["nb-pca-steps"].as<int>();
}
else
{
std::cout << "Number of PCA steps not set, setting it to" << nb_pca_steps << "\n";
}
int nb_processors = 0;
if(vm.count("nb-processors"))
{
std::cout << "Number of processors #" << vm["nb-processors"].as<int>() << "\n";
nb_processors = vm["nb-processors"].as<int>();
}
size_t rows(0);
size_t cols(0);
{
char filename[MAX_PATH];
// Read first image to get image size
number2filename(1, filename);
cv::Mat image = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
cv::Size image_size = image.size();
rows = image_size.height;
cols = image_size.width;
}
// Allocate data
std::cout << "=== Allocate ===" << std::endl;
std::cout << " Number of images: " << num_frames << std::endl;
std::cout << " Image size: " << cols << "x" << rows << " (RGB)" << std::endl;
std::cout << " Data size: " << (num_frames*rows*cols * 3) / (1024 * 1024) << " MB" << std::endl;
iterator_on_image_files<float> iterator_file_begin(1);
iterator_on_image_files<float> iterator_file_end(num_frames + 1);
// Compute trimmed Grassmann Average
// XXX: Ask Raffi for help here
// XXX: We need to time this computation
namespace ub = boost::numeric::ublas;
// type for the final eigen vectors
typedef ub::vector<double> data_t;
using namespace grassmann_averages_pca;
using namespace grassmann_averages_pca::details::ublas_helpers;
typedef double input_array_type;
const size_t dimension = rows * cols;
const size_t nb_elements = num_frames;
// this is the form of the data extracted from the storage
typedef ub::vector<input_array_type> data_t;
typedef grassmann_pca_with_trimming< data_t > grassmann_pca_with_trimming_t;
// main instance
grassmann_pca_with_trimming_t instance(trimming_percentage / 100);
typedef std::vector<data_t> output_eigenvector_collection_t;
output_eigenvector_collection_t v_output_eigenvectors(nb_elements);
if(nb_processors > 0)
{
if(!instance.set_nb_processors(nb_processors))
{
std::cerr << "[configuration]" << "Incorrect number of processors. Please consult the documentation (was " << nb_processors << ")" << std::endl;
return 1;
}
}
if(!instance.set_nb_steps_pca(nb_pca_steps))
{
std::cerr << "[configuration]" << "Incorrect number of regular PCA steps. Please consult the documentation (was " << nb_pca_steps << ")" << std::endl;
return false;
}
bool ret = instance.batch_process(
max_iterations,
max_dimension,
iterator_file_begin,
iterator_file_end,
iterator_on_output_data<output_eigenvector_collection_t::iterator>(0, v_output_eigenvectors.begin()));
// Save resulting components
// XXX: Ask Raffi for help here
return 0;
}
<commit_msg>small changes and cleanup now all float instead of double<commit_after>#include <cstdio>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <include/grassmann_pca_with_trimming.hpp>
#include <include/private/boost_ublas_external_storage.hpp>
#include <include/private/boost_ublas_row_iterator.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <string>
#include <fstream>
#ifndef MAX_PATH
// "funny" differences win32/posix
#define MAX_PATH PATH_MAX
#endif
static std::string movielocation = "/is/ps/shared/users/jonas/movies/";
static std::string eigenvectorslocation = "./";
void number2filename(size_t file_number, char *filename)
{
const char *fn_template = (movielocation + "starwars_%.3u/frame%.7u.png").c_str();
const size_t dir_num = file_number / 10000;
sprintf(filename, fn_template, dir_num, file_number);
}
//! An iterator that will load the images on demand instead of storing everything on memory
template <class T>
class iterator_on_image_files :
public boost::iterator_facade<
iterator_on_image_files<T>
, boost::numeric::ublas::vector<T>
, std::random_access_iterator_tag
, boost::numeric::ublas::vector<T> const& // const reference
>
{
public:
typedef iterator_on_image_files<T> this_type;
typedef boost::numeric::ublas::vector<T> image_vector_type;
iterator_on_image_files() : m_index(std::numeric_limits<size_t>::max())
{}
explicit iterator_on_image_files(size_t index)
: m_index(index)
{}
private:
friend class boost::iterator_core_access;
typename this_type::difference_type distance_to(this_type const& r) const
{
return typename this_type::difference_type(r.m_index) - typename this_type::difference_type(m_index); // sign promotion
}
void increment()
{
m_index++;
image_vector.clear();
}
bool equal(this_type const& other) const
{
return this->m_index == other.m_index;
}
image_vector_type const& dereference() const
{
if(image_vector.empty())
{
read_image();
}
return image_vector;
}
void read_image() const
{
char filename[MAX_PATH];
number2filename(m_index, filename);
std::cout << "Reading " << filename << std::endl;
cv::Mat image = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
if(!image.data)
{
std::ostringstream o;
o << "error: could not load image '" << filename << "'";
std::cerr << o.str() << std::endl;
throw std::runtime_error(o.str());
}
const int w = image.size().width;
const int h = image.size().height;
image_vector.resize(w * h * 3);
typename boost::numeric::ublas::vector<T>::iterator it = image_vector.begin();
for(int y = 0; y < h; y++)
{
for(int x = 0; x < w; x++)
{
cv::Vec3b pixel = image.at<cv::Vec3b>(y, x);
*it++ = pixel[0];
*it++ = pixel[1];
*it++ = pixel[2];
}
}
}
void advance(typename this_type::difference_type n)
{
if(n < 0)
{
assert((-n) <= static_cast<typename this_type::difference_type>(m_index));
m_index -= n;
}
else
{
//assert(n + index <= matrix->size1());
m_index += n;
}
if(n != 0)
{
image_vector.clear();
}
}
size_t m_index;
mutable boost::numeric::ublas::vector<T> image_vector;
};
//! An output vector that also writes to a file
template <class data_iterator_t>
class iterator_on_output_data :
public boost::iterator_facade<
iterator_on_output_data<data_iterator_t>
, typename data_iterator_t::value_type
, std::random_access_iterator_tag
, typename data_iterator_t::reference
>
{
public:
typedef typename data_iterator_t::reference reference;
typedef iterator_on_output_data<data_iterator_t> this_type;
iterator_on_output_data() :
m_index(std::numeric_limits<size_t>::max()),
m_max_element_per_line(100),
internal_it()
{}
explicit iterator_on_output_data(size_t index, data_iterator_t it_) :
m_index(index),
m_max_element_per_line(100),
internal_it(it_)
{}
void save_eigenvector()
{
char filename[MAX_PATH];
const char * eigen_vector_template = "eigenvector_%.7d.txt";
sprintf(filename, eigen_vector_template, m_index);
std::ofstream f(filename);
if(!f.is_open())
{
std::cerr << "Cannot open the file " << filename << " for writing" << std::endl;
return;
}
std::cout << "Writing eigenvector file " << filename << std::endl;
typedef typename data_iterator_t::value_type::iterator element_iterator;
element_iterator itelement(internal_it->begin());
for(int i = 0; i < internal_it->size(); i++, ++itelement)
{
if((i + 1) % m_max_element_per_line == 0)
{
f << std::endl;
}
f << *itelement;
}
f.close();
std::cout << "Writing eigenvector file " << filename << " -- ok " << std::endl;
}
private:
friend class boost::iterator_core_access;
typename this_type::difference_type distance_to(this_type const& r) const
{
return typename this_type::difference_type(r.m_index) - typename this_type::difference_type(m_index); // sign promotion
}
void increment() {
// here we save before going further, except if it has not been changed
save_eigenvector();
m_index++;
++internal_it;
}
void advance(typename this_type::difference_type n)
{
if(n < 0)
{
assert((-n) <= static_cast<typename this_type::difference_type>(m_index));
m_index -= n;
}
else
{
//assert(n + index <= matrix->size1());
m_index += n;
}
}
bool equal(this_type const& other) const
{
return this->internal_it == other.internal_it;
}
reference dereference() const
{
return *internal_it;
}
size_t m_index;
// max number of element on one line during the save
size_t m_max_element_per_line;
data_iterator_t internal_it;
};
int main(int argc, char *argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("nb-frames,f", po::value<int>(), "number of frames in the movie")
("movie,m", po::value<std::string>(), "full path to the movie location")
("max-dimensions,d", po::value<int>(), "requested number of components for the computation of the trimmed grassmann average")
("max-iterations", po::value<int>(), "maximum number of iterations (defaults to the number of frames)")
("nb-pca-steps", po::value<int>(), "number of pca steps")
("trimming-percentage", po::value<float>(), "percentage of trimming")
("nb-processors", po::value<int>(), "number of processors used (defaults to 1)")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
if(!vm.count("trimming-percentage"))
{
std::cerr << "the parameter 'trimming-percentage' should be set, now exiting...\n";
return 1;
}
const float trimming_percentage = vm["trimming-percentage"].as<float>();
size_t num_frames = 100; //179415;
if(vm.count("nb-frames"))
{
std::cout << "The movie contains #" << vm["nb-frames"].as<int>() << " frames.\n";
num_frames = vm["nb-frames"].as<int>();
}
else
{
std::cout << "Nb of frames not set, setting it to" << num_frames << "\n";
}
if(vm.count("movie"))
{
std::cout << "Directory of the movie #" << vm["movie"].as<std::string>() << "\n";
movielocation = vm["movie"].as<std::string>();
}
size_t max_dimension = 30;
if(vm.count("max-dimensions"))
{
std::cout << "Number of components requested #" << vm["max-dimensions"].as<int>() << "\n";
max_dimension = vm["max-dimensions"].as<int>();
}
else
{
std::cout << "Nb of components not set, setting it to" << max_dimension << "\n";
}
size_t max_iterations = num_frames;
if(vm.count("max-iterations"))
{
std::cout << "Maximum number of iterations #" << vm["max-iterations"].as<int>() << "\n";
max_iterations = vm["max-iterations"].as<int>();
}
size_t nb_pca_steps = 3;
if(vm.count("nb-pca-steps"))
{
std::cout << "Number of PCA steps #" << vm["nb-pca-steps"].as<int>() << "\n";
nb_pca_steps = vm["nb-pca-steps"].as<int>();
}
else
{
std::cout << "Number of PCA steps not set, setting it to" << nb_pca_steps << "\n";
}
int nb_processors = 0;
if(vm.count("nb-processors"))
{
std::cout << "Number of processors #" << vm["nb-processors"].as<int>() << "\n";
nb_processors = vm["nb-processors"].as<int>();
}
size_t rows(0);
size_t cols(0);
{
char filename[MAX_PATH];
// Read first image to get image size
number2filename(1, filename);
cv::Mat image = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
cv::Size image_size = image.size();
rows = image_size.height;
cols = image_size.width;
}
// Allocate data
std::cout << "=== Allocate ===" << std::endl;
std::cout << " Number of images: " << num_frames << std::endl;
std::cout << " Image size: " << cols << "x" << rows << " (RGB)" << std::endl;
std::cout << " Data size: " << (num_frames*rows*cols * 3) / (1024 * 1024) << " MB" << std::endl;
iterator_on_image_files<float> iterator_file_begin(1);
iterator_on_image_files<float> iterator_file_end(num_frames + 1);
// Compute trimmed Grassmann Average
// XXX: Ask Raffi for help here
// XXX: We need to time this computation
namespace ub = boost::numeric::ublas;
using namespace grassmann_averages_pca;
using namespace grassmann_averages_pca::details::ublas_helpers;
// type of the scalars manipulated by the algorithm
typedef float input_array_type;
//const size_t dimension = rows * cols;
const size_t nb_elements = num_frames;
// this is the form of the data extracted from the storage
typedef ub::vector<input_array_type> data_t;
typedef grassmann_pca_with_trimming< data_t > grassmann_pca_with_trimming_t;
// main instance
grassmann_pca_with_trimming_t instance(trimming_percentage / 100);
typedef std::vector<data_t> output_eigenvector_collection_t;
output_eigenvector_collection_t v_output_eigenvectors(nb_elements);
if(nb_processors > 0)
{
if(!instance.set_nb_processors(nb_processors))
{
std::cerr << "[configuration]" << "Incorrect number of processors. Please consult the documentation (was " << nb_processors << ")" << std::endl;
return 1;
}
}
if(!instance.set_nb_steps_pca(nb_pca_steps))
{
std::cerr << "[configuration]" << "Incorrect number of regular PCA steps. Please consult the documentation (was " << nb_pca_steps << ")" << std::endl;
return false;
}
bool ret = instance.batch_process(
max_iterations,
max_dimension,
iterator_file_begin,
iterator_file_end,
iterator_on_output_data<output_eigenvector_collection_t::iterator>(0, v_output_eigenvectors.begin()));
// Save resulting components
// XXX: Ask Raffi for help here
if(!ret)
{
std::cerr << "The process returned an error" << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <string>
// http://www.programcreek.com/2013/02/longest-substring-which-contains-2-unique-characters/
// Given a string, find the longest substring that contains only two unique characters.
// For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
// Algorithm to be tested:
// std::size_t longest_size(std::string const& in);
// Running tests
TEST(TEST_NAME, EmptyString)
{
ASSERT_EQ(0, longest_size(""));
}
TEST(TEST_NAME, UniqueCharacter)
{
ASSERT_EQ(5, longest_size("aaaaa"));
}
TEST(TEST_NAME, TwoCharacters)
{
ASSERT_EQ(7, longest_size("abbaaba"));
}
TEST(TEST_NAME, SubstringOfMainString)
{
ASSERT_EQ(10, longest_size("abcbbbbcccbdddadacb"));
}
RC_GTEST_PROP(TEST_NAME, RandomData, (char c1, char c2))
{
RC_PRE(c1 != c2);
std::string answer_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(rc::gen::element<char>(char(c1), char(c2))))
.as("longest part with 2 different chars");
RC_PRE(answer_str.find(c1) != std::string::npos);
RC_PRE(answer_str.find(c2) != std::string::npos);
std::size_t pre_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())
.as("length for the part before longest");
std::string pre_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(pre_length, rc::gen::arbitrary<char>()))
.as("before longest chars");
RC_PRE(pre_str.size() == std::size_t() || (pre_str.back() != c1 && pre_str.back() != c2));
RC_PRE(pre_str.size() < std::size_t(2) || pre_str[pre_str.size() -1] != pre_str[pre_str.size() -2]);
std::size_t post_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())
.as("length of the part after longest");
std::string post_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(post_length, rc::gen::arbitrary<char>()))
.as("after longest chars");
RC_PRE(post_str.size() == std::size_t() || (post_str.front() != c1 && post_str.front() != c2));
RC_PRE(post_str.size() < std::size_t(2) || post_str[0] != post_str[1]);
std::string data = pre_str + answer_str + post_str;
RC_ASSERT(answer_str.size() == longest_size(data));
}
<commit_msg>[visual studio] Fix compile issue in longest-substr-2-uniques<commit_after>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <string>
// http://www.programcreek.com/2013/02/longest-substring-which-contains-2-unique-characters/
// Given a string, find the longest substring that contains only two unique characters.
// For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
// Algorithm to be tested:
// std::size_t longest_size(std::string const& in);
// Running tests
TEST(TEST_NAME, EmptyString)
{
ASSERT_EQ(0, longest_size(""));
}
TEST(TEST_NAME, UniqueCharacter)
{
ASSERT_EQ(5, longest_size("aaaaa"));
}
TEST(TEST_NAME, TwoCharacters)
{
ASSERT_EQ(7, longest_size("abbaaba"));
}
TEST(TEST_NAME, SubstringOfMainString)
{
ASSERT_EQ(10, longest_size("abcbbbbcccbdddadacb"));
}
RC_GTEST_PROP(TEST_NAME, RandomData, (char c1, char c2))
{
RC_PRE(c1 != c2);
char moved_c1 = c1, moved_c2 = c2;
std::string answer_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(rc::gen::element<char>(std::move(moved_c1), std::move(moved_c2))))
.as("longest part with 2 different chars");
RC_PRE(answer_str.find(c1) != std::string::npos);
RC_PRE(answer_str.find(c2) != std::string::npos);
std::size_t pre_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())
.as("length for the part before longest");
std::string pre_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(pre_length, rc::gen::arbitrary<char>()))
.as("before longest chars");
RC_PRE(pre_str.size() == std::size_t() || (pre_str.back() != c1 && pre_str.back() != c2));
RC_PRE(pre_str.size() < std::size_t(2) || pre_str[pre_str.size() -1] != pre_str[pre_str.size() -2]);
std::size_t post_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())
.as("length of the part after longest");
std::string post_str = *rc::gen::apply(
[](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }
, rc::gen::container<std::vector<char>>(post_length, rc::gen::arbitrary<char>()))
.as("after longest chars");
RC_PRE(post_str.size() == std::size_t() || (post_str.front() != c1 && post_str.front() != c2));
RC_PRE(post_str.size() < std::size_t(2) || post_str[0] != post_str[1]);
std::string data = pre_str + answer_str + post_str;
RC_ASSERT(answer_str.size() == longest_size(data));
}
<|endoftext|> |
<commit_before>/*!
* \brief Short Time Fourier Transform.
* \author Thomas Hamboeck, Austrian Kangaroos 2014
*/
#include "STFT.h"
#include <limits>
#include <complex>
#include <iostream>
// 0, params.nWindowSize, params.nWindowSkipping, params.nWindowSizePadded, spectrumHandler
STFT::STFT(const int channelOffset, const int windowTime, const int windowTimeStep, const int windowFrequency, SpectrumHandler *handler)
: offset(channelOffset),
windowTime(windowTime),
windowTimeStep(windowTimeStep),
windowFrequency(windowFrequency),
windowFrequencyHalf(windowFrequency / 2 + 1),
handler(handler),
nOverflow(0), overflownData(NULL), input(NULL), output(NULL), outputMag(NULL)
{
overflownData = new int16_t[windowTime]; /* actually a max of (windowTime - 1) */
input = static_cast<double*>(fftw_malloc(sizeof(double) * windowFrequency));
output = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * windowFrequencyHalf));
outputMag = new double[windowFrequencyHalf];
//WARN(windowFrequency >= windowTime, "Frequency window must be greater than Time Window.");
for(int i = 0; i < windowFrequency; ++i) {
input[i] = 0.0;
}
plan = fftw_plan_dft_r2c_1d(windowFrequency, input, output, FFTW_MEASURE);
}
STFT::~STFT()
{
if(overflownData) {
delete[] overflownData;
}
if(input) {
fftw_free(input);
}
if(output) {
fftw_free(output);
}
if(outputMag) {
delete[] outputMag;
}
if(plan) {
fftw_destroy_plan(plan);
}
}
void STFT::intToFloat(const int16_t &in, double &out)
{
out = static_cast<double>(in) / static_cast<double>(std::numeric_limits<int16_t>::max() + 1);
}
void STFT::newData(const int16_t *data, int length, short channels)
{
int iBegin, iEnd, iDataChannel, iBuffer;
iBuffer = 0;
/* for each overflown data */
while(iBuffer < nOverflow) {
intToFloat(overflownData[iBuffer], input[iBuffer]);
++iBuffer;
}
iBegin = 0;
while(true)
{
iEnd = iBegin * channels + windowTime*channels;
if(iEnd > length) {
break;
}
// copy the data fro the window
iDataChannel = iBegin * channels + offset;
while(iBuffer < windowTime) {
intToFloat(data[iDataChannel], input[iBuffer]);
++iBuffer;
iDataChannel += channels;
}
/* and the rest is zero */
fftw_execute(plan);
/* calc magnitude */
for(int i = 0; i < windowFrequencyHalf; ++i) {
outputMag[i] = std::sqrt(output[i][0]*output[i][0] + output[i][1]*output[i][1]);
}
if(handler != NULL) {
handler->handle(outputMag, windowFrequencyHalf);
}
/* next cycle */
iBegin += windowTimeStep;
iBuffer = 0;
}
nOverflow = 0;
iDataChannel = iBegin * channels + offset;
while(iDataChannel < length) {
/* copy to overflow buffer */
overflownData[nOverflow] = data[iDataChannel];
++nOverflow;
iDataChannel += channels;
}
}
<commit_msg>fix value overflow?<commit_after>/*!
* \brief Short Time Fourier Transform.
* \author Thomas Hamboeck, Austrian Kangaroos 2014
*/
#include "STFT.h"
#include <limits>
#include <complex>
#include <iostream>
// 0, params.nWindowSize, params.nWindowSkipping, params.nWindowSizePadded, spectrumHandler
STFT::STFT(const int channelOffset, const int windowTime, const int windowTimeStep, const int windowFrequency, SpectrumHandler *handler)
: offset(channelOffset),
windowTime(windowTime),
windowTimeStep(windowTimeStep),
windowFrequency(windowFrequency),
windowFrequencyHalf(windowFrequency / 2 + 1),
handler(handler),
nOverflow(0), overflownData(NULL), input(NULL), output(NULL), outputMag(NULL)
{
overflownData = new int16_t[windowTime]; /* actually a max of (windowTime - 1) */
input = static_cast<double*>(fftw_malloc(sizeof(double) * windowFrequency));
output = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * windowFrequencyHalf));
outputMag = new double[windowFrequencyHalf];
//WARN(windowFrequency >= windowTime, "Frequency window must be greater than Time Window.");
for(int i = 0; i < windowFrequency; ++i) {
input[i] = 0.0;
}
plan = fftw_plan_dft_r2c_1d(windowFrequency, input, output, FFTW_MEASURE);
}
STFT::~STFT()
{
if(overflownData) {
delete[] overflownData;
}
if(input) {
fftw_free(input);
}
if(output) {
fftw_free(output);
}
if(outputMag) {
delete[] outputMag;
}
if(plan) {
fftw_destroy_plan(plan);
}
}
void STFT::intToFloat(const int16_t &in, double &out)
{
out = static_cast<double>(in) / (static_cast<double>(std::numeric_limits<int16_t>::max()) + 1.0);
}
void STFT::newData(const int16_t *data, int length, short channels)
{
int iBegin, iEnd, iDataChannel, iBuffer;
iBuffer = 0;
/* for each overflown data */
while(iBuffer < nOverflow) {
intToFloat(overflownData[iBuffer], input[iBuffer]);
++iBuffer;
}
iBegin = 0;
while(true)
{
iEnd = iBegin * channels + windowTime*channels;
if(iEnd > length) {
break;
}
// copy the data fro the window
iDataChannel = iBegin * channels + offset;
while(iBuffer < windowTime) {
intToFloat(data[iDataChannel], input[iBuffer]);
++iBuffer;
iDataChannel += channels;
}
/* and the rest is zero */
fftw_execute(plan);
/* calc magnitude */
for(int i = 0; i < windowFrequencyHalf; ++i) {
outputMag[i] = std::sqrt(output[i][0]*output[i][0] + output[i][1]*output[i][1]);
}
if(handler != NULL) {
handler->handle(outputMag, windowFrequencyHalf);
}
/* next cycle */
iBegin += windowTimeStep;
iBuffer = 0;
}
nOverflow = 0;
iDataChannel = iBegin * channels + offset;
while(iDataChannel < length) {
/* copy to overflow buffer */
overflownData[nOverflow] = data[iDataChannel];
++nOverflow;
iDataChannel += channels;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <vtkObjectFactory.h>
// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"
// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>
// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
return refNode->IsA("vtkMRMLSpatialObjectsNode");
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjectsNode =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
if(Superclass::ReadDataInternal(refNode) != 0)
{
return 0;
}
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("ReadData: File name not specified");
return 0;
}
// compute file prefix
std::string name(fullName);
std::string::size_type loc = name.find_last_of(".");
if( loc == std::string::npos )
{
vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
return 0;
}
std::string extension = name.substr(loc);
vtkDebugMacro("ReadData: extension = " << extension.c_str());
int result = 1;
try
{
if(extension == std::string(".tre"))
{
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(fullName);
reader->Update();
// WARNING : Should we check if the tube contains less than 2 points...
char childName[] = "Tube";
TubeNetType::ChildrenListType* tubeList =
reader->GetGroup()->GetChildren(reader->GetGroup()->GetMaximumDepth(), childName);
// -----------------------------------------------------------------------
// Copy skeleton points from vessels into polydata structure
// -----------------------------------------------------------------------
// Initialize the SpatialObject
// Count number of points && remove dupplicate
int totalNumberOfPoints = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end();
++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
if(currTube->GetNumberOfPoints() < 2)
continue;
totalNumberOfPoints += currTube->GetNumberOfPoints();
}
// Create the points
vtkNew<vtkPoints> vesselsPoints;
vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);
// Create the Lines
vtkNew<vtkCellArray> vesselLinesCA;
// Create scalar array that indicates the radius at each
// centerline point.
vtkNew<vtkDoubleArray> tubeRadius;
tubeRadius->SetName("TubeRadius");
tubeRadius->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates TubeID.
vtkNew<vtkDoubleArray> tubeIDs;
tubeIDs->SetName("TubeIDs");
tubeIDs->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates both tangeantes at each
// centerline point.
vtkNew<vtkDoubleArray> tan1;
tan1->SetName("Tan1");
tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
tan1->SetNumberOfComponents(3);
vtkNew<vtkDoubleArray> tan2;
tan2->SetName("Tan2");
tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
tan2->SetNumberOfComponents(3);
// Create scalar array that indicates Ridgness and medialness at each
// centerline point.
bool containsMidialnessInfo = false;
vtkNew<vtkDoubleArray> medialness;
medialness->SetName("Medialness");
medialness->SetNumberOfTuples(totalNumberOfPoints);
bool containsRidgnessInfo = false;
vtkNew<vtkDoubleArray> ridgeness;
ridgeness->SetName("Ridgeness");
ridgeness->SetNumberOfTuples(totalNumberOfPoints);
int pointID = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end(); ++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
int tubeSize = currTube->GetNumberOfPoints();
if(tubeSize < 2)
continue;
currTube->ComputeTangentAndNormals();
// Create a pointID list [linear for a polyline]
vtkIdType* pointIDs = new vtkIdType[tubeSize];
vtkNew<vtkPolyLine> vesselLine;
// Get the tube element spacing information.
const double* axesRatio = currTube->GetSpacing();
int index = 0;
std::vector<TubePointType>::iterator tubePointIterator;
for(tubePointIterator = currTube->GetPoints().begin();
tubePointIterator != currTube->GetPoints().end();
++tubePointIterator, ++pointID, ++index)
{
PointType inputPoint = tubePointIterator->GetPosition();
pointIDs[index] = pointID;
// Insert points using the element spacing information.
vesselsPoints->SetPoint(pointID,
inputPoint[0],
inputPoint[1] * axesRatio[1] / axesRatio[0],
inputPoint[2] * axesRatio[2] / axesRatio[0]);
// TubeID
tubeIDs->SetTuple1(pointID, currTube->GetId());
// Radius
tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());
// Tangeantes
tan1->SetTuple3(pointID,
(*tubePointIterator).GetNormal1()[0],
(*tubePointIterator).GetNormal1()[1],
(*tubePointIterator).GetNormal1()[2]);
tan2->SetTuple3(pointID,
(*tubePointIterator).GetNormal2()[0],
(*tubePointIterator).GetNormal2()[1],
(*tubePointIterator).GetNormal2()[2]);
// Medialness & Ridgness
if(tubePointIterator->GetMedialness() != 0)
{
containsMidialnessInfo = true;
}
medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());
if(tubePointIterator->GetRidgeness() != 0)
{
containsRidgnessInfo = true;
}
ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
}
vesselLine->Initialize(tubeSize,
pointIDs,
vesselsPoints.GetPointer());
vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
delete [] pointIDs;
}
// Convert spatial objects to a PolyData
vtkNew<vtkPolyData> vesselsPD;
vesselsPD->SetLines(vesselLinesCA.GetPointer());
vesselsPD->SetPoints(vesselsPoints.GetPointer());
// Add the Radius information
vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");
// Add the TudeID information
vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());
// Add Tangeantes information
vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
vesselsPD->GetPointData()->AddArray(tan2.GetPointer());
// Add Medialness & Ridgness if contains information
if(containsMidialnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
}
if(containsRidgnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
}
// Remove any duplicate points from polydata.
// The tubes generation will fails if any duplicates points are present.
// Cleaned before, could create degeneration problems with the cells
//vtkNew<vtkCleanPolyData> cleanedVesselPD;
//cleanedVesselPD->SetInput(vesselsPD.GetPointer());
vtkDebugMacro("Points: " << totalNumberOfPoints);
spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
spatialObjectsNode->SetSpatialObject(reader->GetGroup());
delete tubeList;
}
}
catch(...)
{
result = 0;
}
if(spatialObjectsNode->GetPolyData() != NULL)
{
// is there an active scalar array?
if(spatialObjectsNode->GetDisplayNode())
{
double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
if(scalarRange)
{
vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
<< ", " << scalarRange[1]);
spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
}
}
spatialObjectsNode->GetPolyData()->Modified();
}
return result;
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjects =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("vtkMRMLModelNode: File name not specified");
return 0;
}
std::string extension =
itksys::SystemTools::GetFilenameLastExtension(fullName);
int result = 1;
if(extension == ".tre")
{
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(fullName.c_str());
writer->SetInput(spatialObjects->GetSpatialObject());
writer->Update();
}
catch(...)
{
result = 0;
vtkErrorMacro("Error occured writing Spatial Objects: "
<< fullName.c_str());
}
}
else
{
result = 0;
vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
}
return result;
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
return "tre";
}
<commit_msg>STYLE: Const correctness and types in vtkMRMLSpatialObjectsStorageNode.cxx.<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <vtkObjectFactory.h>
// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"
// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>
// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
return refNode->IsA("vtkMRMLSpatialObjectsNode");
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjectsNode =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
if(Superclass::ReadDataInternal(refNode) != 0)
{
return 0;
}
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("ReadData: File name not specified");
return 0;
}
// compute file prefix
std::string name(fullName);
std::string::size_type loc = name.find_last_of(".");
if( loc == std::string::npos )
{
vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
return 0;
}
std::string extension = name.substr(loc);
vtkDebugMacro("ReadData: extension = " << extension.c_str());
int result = 1;
try
{
if(extension == std::string(".tre"))
{
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(fullName);
reader->Update();
// WARNING : Should we check if the tube contains less than 2 points...
char childName[] = "Tube";
TubeNetType::ChildrenListType* tubeList =
reader->GetGroup()->GetChildren(reader->GetGroup()->GetMaximumDepth(), childName);
// -----------------------------------------------------------------------
// Copy skeleton points from vessels into polydata structure
// -----------------------------------------------------------------------
// Initialize the SpatialObject
// Count number of points && remove dupplicate
int totalNumberOfPoints = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end();
++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
const itk::SizeValueType numberOfPoints = currTube->GetNumberOfPoints();
if( numberOfPoints < 2 )
{
continue;
}
totalNumberOfPoints += numberOfPoints;
}
// Create the points
vtkNew<vtkPoints> vesselsPoints;
vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);
// Create the Lines
vtkNew<vtkCellArray> vesselLinesCA;
// Create scalar array that indicates the radius at each
// centerline point.
vtkNew<vtkDoubleArray> tubeRadius;
tubeRadius->SetName("TubeRadius");
tubeRadius->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates TubeID.
vtkNew<vtkDoubleArray> tubeIDs;
tubeIDs->SetName("TubeIDs");
tubeIDs->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates both tangents at each
// centerline point.
vtkNew<vtkDoubleArray> tan1;
tan1->SetName("Tan1");
tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
tan1->SetNumberOfComponents(3);
vtkNew<vtkDoubleArray> tan2;
tan2->SetName("Tan2");
tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
tan2->SetNumberOfComponents(3);
// Create scalar array that indicates Ridgness and medialness at each
// centerline point.
bool containsMidialnessInfo = false;
vtkNew<vtkDoubleArray> medialness;
medialness->SetName("Medialness");
medialness->SetNumberOfTuples(totalNumberOfPoints);
bool containsRidgnessInfo = false;
vtkNew<vtkDoubleArray> ridgeness;
ridgeness->SetName("Ridgeness");
ridgeness->SetNumberOfTuples(totalNumberOfPoints);
int pointID = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end(); ++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
const itk::SizeValueType tubeSize = currTube->GetNumberOfPoints();
if( tubeSize < 2 )
{
continue;
}
currTube->ComputeTangentAndNormals();
// Create a pointID list [linear for a polyline]
vtkIdType* pointIDs = new vtkIdType[tubeSize];
vtkNew<vtkPolyLine> vesselLine;
// Get the tube element spacing information.
const double* axesRatio = currTube->GetSpacing();
int index = 0;
std::vector<TubePointType>::iterator tubePointIterator;
for(tubePointIterator = currTube->GetPoints().begin();
tubePointIterator != currTube->GetPoints().end();
++tubePointIterator, ++pointID, ++index)
{
PointType inputPoint = tubePointIterator->GetPosition();
pointIDs[index] = pointID;
// Insert points using the element spacing information.
vesselsPoints->SetPoint(pointID,
inputPoint[0],
inputPoint[1] * axesRatio[1] / axesRatio[0],
inputPoint[2] * axesRatio[2] / axesRatio[0]);
// TubeID
tubeIDs->SetTuple1(pointID, currTube->GetId());
// Radius
tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());
// Tangeantes
tan1->SetTuple3(pointID,
(*tubePointIterator).GetNormal1()[0],
(*tubePointIterator).GetNormal1()[1],
(*tubePointIterator).GetNormal1()[2]);
tan2->SetTuple3(pointID,
(*tubePointIterator).GetNormal2()[0],
(*tubePointIterator).GetNormal2()[1],
(*tubePointIterator).GetNormal2()[2]);
// Medialness & Ridgness
if(tubePointIterator->GetMedialness() != 0)
{
containsMidialnessInfo = true;
}
medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());
if(tubePointIterator->GetRidgeness() != 0)
{
containsRidgnessInfo = true;
}
ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
}
vesselLine->Initialize(tubeSize,
pointIDs,
vesselsPoints.GetPointer());
vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
delete [] pointIDs;
}
// Convert spatial objects to a PolyData
vtkNew<vtkPolyData> vesselsPD;
vesselsPD->SetLines(vesselLinesCA.GetPointer());
vesselsPD->SetPoints(vesselsPoints.GetPointer());
// Add the Radius information
vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");
// Add the TudeID information
vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());
// Add Tangeantes information
vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
vesselsPD->GetPointData()->AddArray(tan2.GetPointer());
// Add Medialness & Ridgness if contains information
if(containsMidialnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
}
if(containsRidgnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
}
// Remove any duplicate points from polydata.
// The tubes generation will fails if any duplicates points are present.
// Cleaned before, could create degeneration problems with the cells
//vtkNew<vtkCleanPolyData> cleanedVesselPD;
//cleanedVesselPD->SetInput(vesselsPD.GetPointer());
vtkDebugMacro("Points: " << totalNumberOfPoints);
spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
spatialObjectsNode->SetSpatialObject(reader->GetGroup());
delete tubeList;
}
}
catch(...)
{
result = 0;
}
if(spatialObjectsNode->GetPolyData() != NULL)
{
// is there an active scalar array?
if(spatialObjectsNode->GetDisplayNode())
{
double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
if(scalarRange)
{
vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
<< ", " << scalarRange[1]);
spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
}
}
spatialObjectsNode->GetPolyData()->Modified();
}
return result;
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjects =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
const std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("vtkMRMLModelNode: File name not specified");
return 0;
}
const std::string extension =
itksys::SystemTools::GetFilenameLastExtension(fullName);
int result = 1;
if(extension == ".tre")
{
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(fullName.c_str());
writer->SetInput(spatialObjects->GetSpatialObject());
writer->Update();
}
catch(...)
{
result = 0;
vtkErrorMacro("Error occured writing Spatial Objects: "
<< fullName.c_str());
}
}
else
{
result = 0;
vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
}
return result;
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
return "tre";
}
<|endoftext|> |
<commit_before>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"
#include "libnanocv/functions/function_trid.h"
#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_powell.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_sum_squares.h"
#include "libnanocv/functions/function_dixon_price.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
const size_t trials = 1024;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 1024;
const scalar_t epsilon = 1e-6;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
// batch_optimizer::GD,
// batch_optimizer::CGD_CD,
// batch_optimizer::CGD_DY,
// batch_optimizer::CGD_FR,
// batch_optimizer::CGD_HS,
// batch_optimizer::CGD_LS,
batch_optimizer::CGD_PRP,
batch_optimizer::CGD_N,
batch_optimizer::CGD_DYCD,
batch_optimizer::CGD_DYHS,
batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optimize::ls_initializer::unit,
optimize::ls_initializer::quadratic,
optimize::ls_initializer::consistent
};
const auto ls_strategies =
{
// optimize::ls_strategy::backtrack_armijo,
// optimize::ls_strategy::backtrack_wolfe,
// optimize::ls_strategy::backtrack_strong_wolfe,
// optimize::ls_strategy::interpolation_bisection,
// optimize::ls_strategy::interpolation_cubic,
optimize::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (batch_optimizer optimizer : optimizers)
for (optimize::ls_initializer ls_initializer : ls_initializers)
for (optimize::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// check gradients
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
if (problem.grad_accuracy(x0) > math::epsilon2<scalar_t>())
{
const thread_pool_t::lock_t lock(mutex);
log_error() << "invalid gradient for problem [" << problem_name << "]!";
}
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(!state.converged(epsilon) ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
table.sort_as_number_ascending(3);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int argc, char *argv[])
{
using namespace ncv;
check_problems(ncv::make_beale_funcs());
check_problems(ncv::make_booth_funcs());
check_problems(ncv::make_matyas_funcs());
check_problems(ncv::make_trid_funcs(128));
check_problems(ncv::make_sphere_funcs(128));
check_problems(ncv::make_powell_funcs(128));
check_problems(ncv::make_mccormick_funcs());
check_problems(ncv::make_himmelblau_funcs());
check_problems(ncv::make_rosenbrock_funcs(7));
check_problems(ncv::make_3hump_camel_funcs());
check_problems(ncv::make_dixon_price_funcs(128));
check_problems(ncv::make_sum_squares_funcs(128));
check_problems(ncv::make_goldstein_price_funcs());
check_problems(ncv::make_rotated_ellipsoid_funcs(128));
// show global statistics
tabulator_t table(text::resize("optimizer", 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum())
<< stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
table.sort_as_number_ascending(3);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<commit_msg>update unit test<commit_after>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"
#include "libnanocv/functions/function_trid.h"
#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_powell.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_sum_squares.h"
#include "libnanocv/functions/function_dixon_price.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
const size_t trials = 1024;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 1024;
const scalar_t epsilon = 1e-6;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
// batch_optimizer::GD,
// batch_optimizer::CGD_CD,
// batch_optimizer::CGD_DY,
// batch_optimizer::CGD_FR,
// batch_optimizer::CGD_HS,
// batch_optimizer::CGD_LS,
batch_optimizer::CGD_PRP,
batch_optimizer::CGD_N,
batch_optimizer::CGD_DYCD,
batch_optimizer::CGD_DYHS,
batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optimize::ls_initializer::unit,
optimize::ls_initializer::quadratic,
optimize::ls_initializer::consistent
};
const auto ls_strategies =
{
// optimize::ls_strategy::backtrack_armijo,
// optimize::ls_strategy::backtrack_wolfe,
// optimize::ls_strategy::backtrack_strong_wolfe,
// optimize::ls_strategy::interpolation_bisection,
optimize::ls_strategy::interpolation_cubic,
optimize::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (batch_optimizer optimizer : optimizers)
for (optimize::ls_initializer ls_initializer : ls_initializers)
for (optimize::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// check gradients
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
if (problem.grad_accuracy(x0) > math::epsilon2<scalar_t>())
{
const thread_pool_t::lock_t lock(mutex);
log_error() << "invalid gradient for problem [" << problem_name << "]!";
}
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(!state.converged(epsilon) ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
table.sort_as_number_ascending(3);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int argc, char *argv[])
{
using namespace ncv;
// check_problems(ncv::make_beale_funcs());
check_problems(ncv::make_booth_funcs());
check_problems(ncv::make_matyas_funcs());
check_problems(ncv::make_trid_funcs(128));
check_problems(ncv::make_sphere_funcs(128));
check_problems(ncv::make_powell_funcs(128));
check_problems(ncv::make_mccormick_funcs());
check_problems(ncv::make_himmelblau_funcs());
check_problems(ncv::make_rosenbrock_funcs(7));
check_problems(ncv::make_3hump_camel_funcs());
check_problems(ncv::make_dixon_price_funcs(128));
check_problems(ncv::make_sum_squares_funcs(128));
// check_problems(ncv::make_goldstein_price_funcs());
check_problems(ncv::make_rotated_ellipsoid_funcs(128));
// show global statistics
tabulator_t table(text::resize("optimizer", 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum())
<< stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
table.sort_as_number_ascending(3);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>void MakeADQAParamEntry(const char *outputCDB = "local://$ALICE_ROOT/OCDB") {
//========================================================================
//
// Steering macro for AD reconstruction parameters
//
// Author: Michal Broz
//
//========================================================================
const char* macroname = "MakeADQAParamEntry.C";
// Activate CDB storage and load geometry from CDB
AliCDBManager* cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage(outputCDB);
cdb->SetRun(0);
AliADQAParam * ADQAParam = new AliADQAParam();
ADQAParam->SetMaxPedDiff(1);
ADQAParam->SetMaxPedWidth(1.5);
ADQAParam->SetSatMed(0.1);
ADQAParam->SetSatHigh(0.3);
ADQAParam->SetSatHuge(0.7);
ADQAParam->SetAsynchronBB(0.5);
ADQAParam->SetAsynchronBG(1.0);
ADQAParam->SetMaxBBVariation(0.2);
ADQAParam->SetMaxBGVariation(0.2);
ADQAParam->SetChargeChannelZoomMin(0);
ADQAParam->SetChargeChannelZoomMax(50);
ADQAParam->SetNTdcTimeBins(3062);
ADQAParam->SetTdcTimeMin(0.976562);
ADQAParam->SetTdcTimeMax(300.0);
ADQAParam->SetNChargeChannelBins(7000);
ADQAParam->SetChargeChannelMin(0);
ADQAParam->SetChargeChannelMax(7000);
ADQAParam->SetNChargeSideBins(5000);
ADQAParam->SetChargeSideMin(10);
ADQAParam->SetChargeSideMax(50000);
// save in CDB storage
AliCDBMetaData *md= new AliCDBMetaData();
md->SetResponsible("Michal Broz");
md->SetComment("Reconstruction parameters for AD");
//md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
//md->SetBeamPeriod(0);
AliCDBId id("AD/Calib/QAParam", 0, AliCDBRunRange::Infinity());
cdb->Put(ADQAParam, id, md);
return;
}
<commit_msg>Updated QA params<commit_after>void MakeADQAParamEntry(const char *outputCDB = "local://$ALICE_ROOT/OCDB") {
//========================================================================
//
// Steering macro for AD reconstruction parameters
//
// Author: Michal Broz
//
//========================================================================
const char* macroname = "MakeADQAParamEntry.C";
// Activate CDB storage and load geometry from CDB
AliCDBManager* cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage(outputCDB);
cdb->SetRun(0);
AliADQAParam * ADQAParam = new AliADQAParam();
ADQAParam->SetMaxPedDiff(5);
ADQAParam->SetMaxPedWidth(1.5);
ADQAParam->SetSatMed(0.7);
ADQAParam->SetSatHigh(0.9);
ADQAParam->SetSatHuge(0.99);
ADQAParam->SetAsynchronBB(5.0);
ADQAParam->SetAsynchronBG(10.0);
ADQAParam->SetMaxBBVariation(0.2);
ADQAParam->SetMaxBGVariation(0.2);
ADQAParam->SetMaxNoFlagRate(0.2);
ADQAParam->SetChargeChannelZoomMin(0);
ADQAParam->SetChargeChannelZoomMax(50);
ADQAParam->SetNTdcTimeBins(3062);
ADQAParam->SetTdcTimeMin(0.976562);
ADQAParam->SetTdcTimeMax(300.0);
ADQAParam->SetNChargeChannelBins(10000);
ADQAParam->SetChargeChannelMin(0);
ADQAParam->SetChargeChannelMax(10000);
ADQAParam->SetNChargeSideBins(7000);
ADQAParam->SetChargeSideMin(10);
ADQAParam->SetChargeSideMax(70000);
// save in CDB storage
AliCDBMetaData *md= new AliCDBMetaData();
md->SetResponsible("Michal Broz");
md->SetComment("Reconstruction parameters for AD");
//md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
//md->SetBeamPeriod(0);
AliCDBId id("AD/Calib/QAParam", 0, AliCDBRunRange::Infinity());
cdb->Put(ADQAParam, id, md);
return;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "PvpPotion.h"
#include "../../Common/ETypes.h"
#include "../../Common/Helpers/RapidHelper.hpp"
#include <ATF/global.hpp>
namespace GameServer
{
namespace Addon
{
#define CheckEffLimType(x, y) \
(x == y && x != -1 && y != -1)
bool CPvpPotion::m_bActivated = false;
CPvpPotion::TempEffectFunc_Cont CPvpPotion::g_TempEffectFunc;
void CPvpPotion::load()
{
TempEffectFunc_Ptr* origTempEffectFunc = (TempEffectFunc_Ptr*)0x14096CDF0L;
for (int i = 0; i < detail::count_orig_effect_func; ++i)
{
g_TempEffectFunc[i] = origTempEffectFunc[i];
}
::std::vector<::std::pair<int, TempEffectFunc_Ptr>> vecNewFunc{
{ 182, &AlterMoneyPotion<e_money_type::cp> },
{ 183, &AlterMoneyPotion<e_money_type::gold> },
{ 184, &AlterMoneyPotion<e_money_type::pvp_point> },
{ 185, &AlterMoneyPotion<e_money_type::pvp_point_2> },
{ 186, &AlterMoneyPotion<e_money_type::processing_point> },
{ 187, &AlterMoneyPotion<e_money_type::hunter_point> },
{ 188, &AlterMoneyPotion<e_money_type::gold_point> }
};
for (auto& kv : vecNewFunc)
{
g_TempEffectFunc[kv.first] = kv.second;
}
enable_hook(&ATF::CPotionMgr::ApplyPotion, &CPvpPotion::ApplyPotion);
}
void CPvpPotion::unload()
{
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CPvpPotion::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "addons.pvp_potion";
return name;
}
void CPvpPotion::configure(const rapidjson::Value & nodeConfig)
{
CPvpPotion::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false);
}
int CPvpPotion::ApplyPotion(
ATF::CPotionMgr* pObj,
ATF::CPlayer* pUsePlayer,
ATF::CPlayer* pApplyPlayer,
ATF::_skill_fld* pEffecFld,
ATF::_CheckPotion_fld* pCheckFld,
ATF::_PotionItem_fld* pfB,
bool bCommonPotion,
ATF::Info::CPotionMgrApplyPotion2_ptr next)
{
if (!CPvpPotion::m_bActivated)
return next(pObj, pUsePlayer, pApplyPlayer, pEffecFld, pCheckFld, pfB, bCommonPotion);
if (!pUsePlayer || !pApplyPlayer || !pEffecFld)
return -1;
if (pCheckFld)
{
for (auto& i : pCheckFld->m_CheckEffectCode)
{
if (!ATF::Global::_CheckPotionData(&i, pApplyPlayer))
return 19;
}
}
int nContEffectResult = -1;
int nResult = -1;
if (pEffecFld->m_nContEffectType != -1 && bCommonPotion)
{
int indxDelBuff = 0;
bool bExpiresBuff = false;
for (int k = 0; k < _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData); ++k)
{
int n = pUsePlayer->m_PotionParam.m_ContCommonPotionData[k].GetEffectIndex();
auto pPotionFld = (ATF::_PotionItem_fld*)ATF::Global::g_MainThread
->m_tblItemData[(int)e_code_item_table::tbl_code_potion].GetRecord(n);
auto pCurrFld = (ATF::_skill_fld*)pObj->m_tblPotionEffectData.GetRecord(n);
if (!pCurrFld)
continue;
if (CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType) ||
CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType2) ||
CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType) ||
CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType2))
{
if (pPotionFld)
{
if (pPotionFld->m_nPotionCheck <= pfB->m_nPotionCheck)
{
bExpiresBuff = true;
indxDelBuff = k;
}
}
}
}
if (pApplyPlayer->m_PotionBufUse.IsExtPotionUse())
{
if (!bExpiresBuff)
indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, true, false);
}
else
{
indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, false, false);
}
if (indxDelBuff > _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData))
return 25;
nContEffectResult = pObj->InsertPotionContEffect(
pApplyPlayer,
&pUsePlayer->m_PotionParam.m_ContCommonPotionData[indxDelBuff],
pEffecFld,
pEffecFld->m_nContEffectSec[0]);
}
if (pEffecFld->m_nTempEffectType != -1)
{
if (pEffecFld->m_nTempEffectType >= 150 &&
pEffecFld->m_nTempEffectType < 182)
{
nResult = -1;
}
else
{
float fValue = 0.0;
if (ATF::Global::_GetTempEffectValue(pEffecFld, pEffecFld->m_nTempEffectType, &fValue))
{
char nRet = -1;
auto fnEffect = CPvpPotion::g_TempEffectFunc[pEffecFld->m_nTempEffectType];
if (fnEffect && fnEffect(pUsePlayer, pApplyPlayer, fValue, &nRet))
nResult = 0;
else
nResult = nRet;
}
else
{
nResult = -1;
}
}
}
int result;
if (nContEffectResult && nResult)
result = nContEffectResult;
else
result = 0;
return result;
}
}
}
<commit_msg>Updated addon with pvp potion<commit_after>#include "stdafx.h"
#include "PvpPotion.h"
#include "../../Common/ETypes.h"
#include "../../Common/Helpers/RapidHelper.hpp"
#include <ATF/global.hpp>
namespace GameServer
{
namespace Addon
{
#define CheckEffLimType(x, y) \
(x == y && x != -1 && y != -1)
bool CPvpPotion::m_bActivated = false;
CPvpPotion::TempEffectFunc_Cont CPvpPotion::g_TempEffectFunc;
void CPvpPotion::load()
{
TempEffectFunc_Ptr* origTempEffectFunc = (TempEffectFunc_Ptr*)0x14096CDF0L;
for (int i = 0; i < detail::count_orig_effect_func; ++i)
{
g_TempEffectFunc[i] = origTempEffectFunc[i];
}
::std::vector<::std::pair<int, TempEffectFunc_Ptr>> vecNewFunc{
{ 182, &AlterMoneyPotion<e_money_type::cp> },
{ 183, &AlterMoneyPotion<e_money_type::gold> },
{ 184, &AlterMoneyPotion<e_money_type::pvp_point> },
{ 185, &AlterMoneyPotion<e_money_type::pvp_point_2> },
{ 186, &AlterMoneyPotion<e_money_type::processing_point> },
{ 187, &AlterMoneyPotion<e_money_type::hunter_point> },
{ 188, &AlterMoneyPotion<e_money_type::gold_point> }
};
for (auto& kv : vecNewFunc)
{
g_TempEffectFunc[kv.first] = kv.second;
}
enable_hook(&ATF::CPotionMgr::ApplyPotion, &CPvpPotion::ApplyPotion);
}
void CPvpPotion::unload()
{
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CPvpPotion::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "addons.pvp_potion";
return name;
}
void CPvpPotion::configure(const rapidjson::Value & nodeConfig)
{
CPvpPotion::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false);
}
int CPvpPotion::ApplyPotion(
ATF::CPotionMgr* pObj,
ATF::CPlayer* pUsePlayer,
ATF::CPlayer* pApplyPlayer,
ATF::_skill_fld* pEffecFld,
ATF::_CheckPotion_fld* pCheckFld,
ATF::_PotionItem_fld* pfB,
bool bCommonPotion,
ATF::Info::CPotionMgrApplyPotion2_ptr next)
{
if (!CPvpPotion::m_bActivated)
return next(pObj, pUsePlayer, pApplyPlayer, pEffecFld, pCheckFld, pfB, bCommonPotion);
if (!pUsePlayer || !pApplyPlayer || !pEffecFld)
return -1;
if (pCheckFld)
{
for (auto& i : pCheckFld->m_CheckEffectCode)
{
if (!ATF::Global::_CheckPotionData(&i, pApplyPlayer))
return 19;
}
}
int nContEffectResult = -1;
int nResult = -1;
if (pEffecFld->m_nContEffectType != -1 && bCommonPotion)
{
int indxDelBuff = 0;
bool bExpiresBuff = false;
for (int k = 0; k < _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData); ++k)
{
int n = pUsePlayer->m_PotionParam.m_ContCommonPotionData[k].GetEffectIndex();
auto pPotionFld = (ATF::_PotionItem_fld*)ATF::Global::g_MainThread
->m_tblItemData[(int)e_code_item_table::tbl_code_potion].GetRecord(n);
auto pCurrFld = (ATF::_skill_fld*)pObj->m_tblPotionEffectData.GetRecord(n);
if (!pCurrFld)
continue;
if (CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType) ||
CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType2) ||
CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType) ||
CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType2))
{
if (pPotionFld)
{
if (pPotionFld->m_nPotionCheck <= pfB->m_nPotionCheck)
{
bExpiresBuff = true;
indxDelBuff = k;
}
}
}
}
if (pApplyPlayer->m_PotionBufUse.IsExtPotionUse())
{
if (!bExpiresBuff)
indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, true, false);
}
else
{
indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, false, false);
}
if (indxDelBuff > _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData))
return 25;
nContEffectResult = pObj->InsertPotionContEffect(
pApplyPlayer,
&pUsePlayer->m_PotionParam.m_ContCommonPotionData[indxDelBuff],
pEffecFld,
pEffecFld->m_nContEffectSec[0]);
}
if (pEffecFld->m_nTempEffectType != -1)
{
if (pEffecFld->m_nTempEffectType >= 150 && pEffecFld->m_nTempEffectType < detail::count_orig_effect_func ||
pEffecFld->m_nTempEffectType >= detail::count_new_effect_func)
{
nResult = -1;
}
else
{
float fValue = 0.0;
if (ATF::Global::_GetTempEffectValue(pEffecFld, pEffecFld->m_nTempEffectType, &fValue))
{
char nRet = -1;
auto fnEffect = CPvpPotion::g_TempEffectFunc[pEffecFld->m_nTempEffectType];
if (fnEffect && fnEffect(pUsePlayer, pApplyPlayer, fValue, &nRet))
nResult = 0;
else
nResult = nRet;
}
else
{
nResult = -1;
}
}
}
int result;
if (nContEffectResult && nResult)
result = nContEffectResult;
else
result = 0;
return result;
}
}
}
<|endoftext|> |
<commit_before>#include <Python.h>
#include "structmember.h"
#include <string>
#include <vector>
#include "cc/analysis/analyzer.h"
#include "cc/base/unicode/unicode.h"
using std::string;
using std::vector;
namespace {
/*-----------------------------------------------------------------------------
* PhraserExt object
*-----------------------------------------------------------------------------*/
typedef struct {
PyObject_HEAD
Analyzer* ANALYZER;
} PhraserExt;
char PHRASER_DOC[] =
"Python extension that detects phrases in text.\n"
"\n"
"phrase config texts -> error str or None.\n"
"\n"
" >>> open('plaudit.txt', 'wb').write('\\n'.join([\n"
" 'plaudit = verb object',\n"
" '----------',\n"
" 'thanks',\n"
" '----------',\n"
" 'obama',\n"
" 'hitler',\n"
" ]))\n"
" >>> phrases_config_ff = ['plaudit.txt']\n"
" >>> phrase_configs = map(lambda f: open(f).read(), phrase_config_ff)\n"
" >>> phraser = PhraserExt(phrase_configs)\n"
" >>> assert phraser\n";
static PyObject *
PhraserExt_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PhraserExt *self;
if ((self = (PhraserExt *)type->tp_alloc(type, 0)) == NULL) {
PyErr_SetString(PyExc_MemoryError, "cannot allocate PhraserExt instance");
return NULL;
}
self->ANALYZER = new Analyzer();
//printf("Created analyzer instance %p\n", (void*)self->ANALYZER);
if (self->ANALYZER == NULL) {
Py_DECREF(self);
PyErr_SetString(PyExc_MemoryError, "cannot allocate analyzer object");
return NULL;
}
return (PyObject *)self;
}
static void
PhraserExt_dealloc(PhraserExt* self)
{
//printf("Removing analyzer instance %p\n", (void*)self->ANALYZER);
delete self->ANALYZER;
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int
PhraserExt_init(PhraserExt *self, PyObject *args, PyObject *kwds)
{
// Get args.
PyObject* list;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) {
return -1;
}
// Extract phrase configs from list.
vector<string> phrase_configs;
Py_ssize_t length = PyList_Size(list);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject* s = PyList_GetItem(list, i);
if (!PyString_Check(s)) {
PyErr_Format(PyExc_ValueError,
"[PhraserExt] List item at index %ld was not a string.", i);
return -1;
}
phrase_configs.emplace_back(PyString_AsString(s));
}
if (!self->ANALYZER) {
PyErr_SetString(PyExc_RuntimeError, "not initialized");
return -1;
}
// Call Init().
string error;
if (!self->ANALYZER->Init(phrase_configs, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return -1;
}
return 0;
}
char ANALYZE_DOC[] =
"Given an input Unicode string and a dict of options, analyze the string "
"and return a result dict\n"
"\n"
"text, options -> phrase detection result dict.\n"
"\n"
"Analyze the text. Any errors are raised as exceptions\n"
"\n"
" >>> text = u'This is a comment.'\n"
" >>> options = {\n"
" 'destutter_max_consecutive': 3,\n"
" 'replace_html_entities': True,\n"
" }\n"
" >>> result = phraserext.analyze(text, options)\n"
" >>> assert isinstance(result, dict)\n";
bool AnalysisOptionsFromDict(
PyObject* obj, AnalysisOptions* options, string* error) {
Py_ssize_t pos = 0;
PyObject* key;
PyObject* value;
while (PyDict_Next(obj, &pos, &key, &value)) {
if (!PyString_Check(key)) {
*error = "[PhraserExt] Analysis options key is not a string.";
return false;
}
const char* key_s = PyString_AsString(key);
if (!strcmp(key_s, "destutter_max_consecutive")) {
if (!PyInt_Check(value)) {
*error = "[PhraserExt] Analysis option "
"'destutter_max_consecutive' is an integer.";
return false;
}
Py_ssize_t size = PyInt_AsSsize_t(value);
options->destutter_max_consecutive = static_cast<size_t>(size);
} else if (!strcmp(key_s, "replace_html_entities")) {
if (!PyBool_Check(value)) {
*error = "[PhraserExt] Analysis option 'replace_html_entities' is "
"a bool.";
return false;
}
options->replace_html_entities = PyObject_IsTrue(value);
} else {
*error = "[PhraserExt] Unknown analysis option.";
return false;
}
}
return true;
}
PyObject* UnicodeFromUstring(const ustring& s) {
#ifdef Py_UNICODE_WIDE
// UCS 4 (eg, Linux).
return PyUnicode_FromUnicode(s.data(), s.size());
#else
// UCS 2 (eg, Mac OS X).
vector<Py_UNICODE> v;
for (auto& c : s) {
v.emplace_back(static_cast<Py_UNICODE>(c));
}
return PyUnicode_FromUnicode(v.data(), v.size());
#endif
}
PyObject* MakeDict(const vector<PyObject*>& keys,
const vector<PyObject*>& values)
{
auto num_keys = keys.size();
auto num_vals = values.size();
auto num_pairs = std::min(num_keys, num_vals);
PyObject* d = PyDict_New();
for (auto i = 0u; i < num_pairs; ++i) {
PyObject* k = keys[i];
PyObject* v = values[i];
if (!k) {
PyErr_Format(PyExc_KeyError, "Missing key at index %u", i);
Py_DECREF(d);
return NULL;
}
else if (!v) {
PyErr_Format(PyExc_ValueError, "Missing value at index %u", i);
Py_DECREF(d);
return NULL;
}
auto code = PyDict_SetItem(d, k, v);
Py_DECREF(k);
Py_DECREF(v);
if (code) {
PyErr_Format(PyExc_RuntimeError, "Could not set item at index %u", i);
Py_DECREF(d);
return NULL;
}
}
return d;
}
// Returned dicts look like
//
// {
// 'original_text': 'Some texxxxxxxt',
// 'clean_text': 'Some texxxt',
// 'tokens': ['some', 'text'],
// 'phrase_results': [...],
// }
//
// where 'phrase_results' is a list like
//
// {
// 'phrase_name': 'threat_statement',
// 'subsequence_names': ['subject', 'aux', 'verb'],
// 'index_lists': [...]
// }
PyObject* DictFromAnalysisResult(const AnalysisResult& result, string* error) {
PyObject* key;
PyObject* value;
vector<PyObject*> keys;
vector<PyObject*> values;
key = PyString_FromString("original_text");
value = UnicodeFromUstring(result.original_text);
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("clean_text");
value = UnicodeFromUstring(result.clean_text);
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("tokens");
value = PyList_New(result.tokens.size());
for (auto i = 0u; i < result.tokens.size(); ++i) {
PyObject* token = PyString_FromString(result.tokens[i].data());
PyList_SET_ITEM(value, i, token);
}
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("phrase_matches");
value = PyList_New(result.phrase_results.size());
for (auto i = 0u; i < result.phrase_results.size(); ++i) {
auto& phrase_result = result.phrase_results[i];
vector<PyObject*> tmp_keys;
vector<PyObject*> tmp_values;
PyObject* tmp_key = PyString_FromString("phrase_name");
PyObject* tmp_value = PyString_FromString(
phrase_result.phrase_name.data());
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
tmp_key = PyString_FromString("subsequence_names");
tmp_value = PyList_New(phrase_result.piece_names.size());
for (auto j = 0u; j < phrase_result.piece_names.size(); ++j) {
PyObject* subsequence_name =
PyString_FromString(phrase_result.piece_names[j].data());
PyList_SET_ITEM(tmp_value, j, subsequence_name);
}
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
tmp_key = PyString_FromString("index_lists");
tmp_value = PyList_New(phrase_result.matches.size());
for (auto j = 0u; j < phrase_result.matches.size(); ++j) {
auto& match = phrase_result.matches[j];
PyObject* index_list = PyList_New(
match.piece_begin_indexes.size() + 1);
for (auto k = 0u; k < match.piece_begin_indexes.size(); ++k) {
PyObject* item = PyInt_FromLong(match.piece_begin_indexes[k]);
PyList_SET_ITEM(index_list, k, item);
}
PyObject* item = PyInt_FromLong(match.end_excl);
PyList_SET_ITEM(index_list, match.piece_begin_indexes.size(), item);
PyList_SET_ITEM(tmp_value, j, index_list);
}
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
PyObject* tmp_d = MakeDict(tmp_keys, tmp_values);
PyList_SET_ITEM(value, i, tmp_d);
}
keys.emplace_back(key);
values.emplace_back(value);
return MakeDict(keys, values);
}
static PyObject*
PhraserExt_analyze(PhraserExt* self, PyObject* args) {
// Get args.
//
PyObject* py_text;
PyObject* options_dict;
if (!PyArg_ParseTuple(args, "UO!", &py_text, &PyDict_Type, &options_dict)) {
// TODO: call PyErr_SetString here as well?
return NULL;
}
// Check if initialized.
if (!self->ANALYZER) {
PyErr_SetString(PyExc_RuntimeError, "PhraserExt has not been initialized");
return NULL;
}
// Get the input text to analyze.
ustring text;
Py_ssize_t size = PyUnicode_GetSize(py_text);
for (Py_ssize_t i = 0; i < size; ++i) {
text.emplace_back(PyUnicode_AsUnicode(py_text)[i]);
}
// Set the analysis options.
AnalysisOptions options;
string error;
if (!AnalysisOptionsFromDict(options_dict, &options, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
// Analyze the text.
AnalysisResult result;
if (!self->ANALYZER->Analyze(text, options, &result, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
// Convert the results to a python dict.
PyObject* result_dict;
if (!(result_dict = DictFromAnalysisResult(result, &error))) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
return result_dict;
}
static PyMethodDef PhraserExt_methods[] = {
{"analyze", (PyCFunction)PhraserExt_analyze, METH_VARARGS, ANALYZE_DOC},
{ NULL, NULL, 0, NULL } /* sentinel */
};
static PyMemberDef PhraserExt_members[] = {
{ NULL, 0, 0, 0, NULL } /* sentinel */
};
static PyTypeObject PhraserExtType = {
PyVarObject_HEAD_INIT(NULL, 0)
"phraserext.PhraserExt", /* tp_name */
sizeof(PhraserExt), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)PhraserExt_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
PHRASER_DOC, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
PhraserExt_methods, /* tp_methods */
PhraserExt_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PhraserExt_init, /* tp_init */
0, /* tp_alloc */
PhraserExt_new, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* tp_version_tag */
};
} // namespace
extern "C" void initphraserext(void);
PyMODINIT_FUNC initphraserext(void) {
PyObject* m;
if (PyType_Ready(&PhraserExtType) < 0)
return;
m = Py_InitModule3("phraserext", PhraserExt_methods,
"Example module that creates an extension type.");
Py_INCREF(&PhraserExtType);
PyModule_AddObject(m, "PhraserExt", (PyObject *)&PhraserExtType);
}
<commit_msg>refactor makedict<commit_after>#include <Python.h>
#include "structmember.h"
#include <string>
#include <vector>
#include "cc/analysis/analyzer.h"
#include "cc/base/unicode/unicode.h"
using std::string;
using std::vector;
namespace {
/*-----------------------------------------------------------------------------
* PhraserExt object
*-----------------------------------------------------------------------------*/
typedef struct {
PyObject_HEAD
Analyzer* ANALYZER;
} PhraserExt;
char PHRASER_DOC[] =
"Python extension that detects phrases in text.\n"
"\n"
"phrase config texts -> error str or None.\n"
"\n"
" >>> open('plaudit.txt', 'wb').write('\\n'.join([\n"
" 'plaudit = verb object',\n"
" '----------',\n"
" 'thanks',\n"
" '----------',\n"
" 'obama',\n"
" 'hitler',\n"
" ]))\n"
" >>> phrases_config_ff = ['plaudit.txt']\n"
" >>> phrase_configs = map(lambda f: open(f).read(), phrase_config_ff)\n"
" >>> phraser = PhraserExt(phrase_configs)\n"
" >>> assert phraser\n";
static PyObject *
PhraserExt_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PhraserExt *self;
if ((self = (PhraserExt *)type->tp_alloc(type, 0)) == NULL) {
PyErr_SetString(PyExc_MemoryError, "cannot allocate PhraserExt instance");
return NULL;
}
self->ANALYZER = new Analyzer();
//printf("Created analyzer instance %p\n", (void*)self->ANALYZER);
if (self->ANALYZER == NULL) {
Py_DECREF(self);
PyErr_SetString(PyExc_MemoryError, "cannot allocate analyzer object");
return NULL;
}
return (PyObject *)self;
}
static void
PhraserExt_dealloc(PhraserExt* self)
{
//printf("Removing analyzer instance %p\n", (void*)self->ANALYZER);
delete self->ANALYZER;
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int
PhraserExt_init(PhraserExt *self, PyObject *args, PyObject *kwds)
{
// Get args.
PyObject* list;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) {
return -1;
}
// Extract phrase configs from list.
vector<string> phrase_configs;
Py_ssize_t length = PyList_Size(list);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject* s = PyList_GetItem(list, i);
if (!PyString_Check(s)) {
PyErr_Format(PyExc_ValueError,
"[PhraserExt] List item at index %ld was not a string.", i);
return -1;
}
phrase_configs.emplace_back(PyString_AsString(s));
}
if (!self->ANALYZER) {
PyErr_SetString(PyExc_RuntimeError, "not initialized");
return -1;
}
// Call Init().
string error;
if (!self->ANALYZER->Init(phrase_configs, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return -1;
}
return 0;
}
char ANALYZE_DOC[] =
"Given an input Unicode string and a dict of options, analyze the string "
"and return a result dict\n"
"\n"
"text, options -> phrase detection result dict.\n"
"\n"
"Analyze the text. Any errors are raised as exceptions\n"
"\n"
" >>> text = u'This is a comment.'\n"
" >>> options = {\n"
" 'destutter_max_consecutive': 3,\n"
" 'replace_html_entities': True,\n"
" }\n"
" >>> result = phraserext.analyze(text, options)\n"
" >>> assert isinstance(result, dict)\n";
bool AnalysisOptionsFromDict(
PyObject* obj, AnalysisOptions* options, string* error) {
Py_ssize_t pos = 0;
PyObject* key;
PyObject* value;
while (PyDict_Next(obj, &pos, &key, &value)) {
if (!PyString_Check(key)) {
*error = "[PhraserExt] Analysis options key is not a string.";
return false;
}
const char* key_s = PyString_AsString(key);
if (!strcmp(key_s, "destutter_max_consecutive")) {
if (!PyInt_Check(value)) {
*error = "[PhraserExt] Analysis option "
"'destutter_max_consecutive' is an integer.";
return false;
}
Py_ssize_t size = PyInt_AsSsize_t(value);
options->destutter_max_consecutive = static_cast<size_t>(size);
} else if (!strcmp(key_s, "replace_html_entities")) {
if (!PyBool_Check(value)) {
*error = "[PhraserExt] Analysis option 'replace_html_entities' is "
"a bool.";
return false;
}
options->replace_html_entities = PyObject_IsTrue(value);
} else {
*error = "[PhraserExt] Unknown analysis option.";
return false;
}
}
return true;
}
PyObject* UnicodeFromUstring(const ustring& s) {
#ifdef Py_UNICODE_WIDE
// UCS 4 (eg, Linux).
return PyUnicode_FromUnicode(s.data(), s.size());
#else
// UCS 2 (eg, Mac OS X).
vector<Py_UNICODE> v;
for (auto& c : s) {
v.emplace_back(static_cast<Py_UNICODE>(c));
}
return PyUnicode_FromUnicode(v.data(), v.size());
#endif
}
PyObject* MakeDict(const vector<PyObject*>& keys,
const vector<PyObject*>& values,
string* error)
{
auto num_keys = keys.size();
auto num_vals = values.size();
auto num_pairs = std::min(num_keys, num_vals);
PyObject* d = PyDict_New();
for (auto i = 0u; i < num_pairs; ++i) {
PyObject* k = keys[i];
PyObject* v = values[i];
if (!k) {
*error = "Missing key";
Py_DECREF(d);
return NULL;
}
else if (!v) {
*error = "Missing value";
Py_DECREF(d);
return NULL;
}
auto code = PyDict_SetItem(d, k, v);
Py_DECREF(k);
Py_DECREF(v);
if (code) {
*error = "Could not set item";
Py_DECREF(d);
return NULL;
}
}
return d;
}
// Returned dicts look like
//
// {
// 'original_text': 'Some texxxxxxxt',
// 'clean_text': 'Some texxxt',
// 'tokens': ['some', 'text'],
// 'phrase_results': [...],
// }
//
// where 'phrase_results' is a list like
//
// {
// 'phrase_name': 'threat_statement',
// 'subsequence_names': ['subject', 'aux', 'verb'],
// 'index_lists': [...]
// }
PyObject* DictFromAnalysisResult(const AnalysisResult& result, string* error) {
PyObject* key;
PyObject* value;
vector<PyObject*> keys;
vector<PyObject*> values;
key = PyString_FromString("original_text");
value = UnicodeFromUstring(result.original_text);
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("clean_text");
value = UnicodeFromUstring(result.clean_text);
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("tokens");
value = PyList_New(result.tokens.size());
for (auto i = 0u; i < result.tokens.size(); ++i) {
PyObject* token = PyString_FromString(result.tokens[i].data());
PyList_SET_ITEM(value, i, token);
}
keys.emplace_back(key);
values.emplace_back(value);
key = PyString_FromString("phrase_matches");
value = PyList_New(result.phrase_results.size());
for (auto i = 0u; i < result.phrase_results.size(); ++i) {
auto& phrase_result = result.phrase_results[i];
vector<PyObject*> tmp_keys;
vector<PyObject*> tmp_values;
PyObject* tmp_key = PyString_FromString("phrase_name");
PyObject* tmp_value = PyString_FromString(
phrase_result.phrase_name.data());
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
tmp_key = PyString_FromString("subsequence_names");
tmp_value = PyList_New(phrase_result.piece_names.size());
for (auto j = 0u; j < phrase_result.piece_names.size(); ++j) {
PyObject* subsequence_name =
PyString_FromString(phrase_result.piece_names[j].data());
PyList_SET_ITEM(tmp_value, j, subsequence_name);
}
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
tmp_key = PyString_FromString("index_lists");
tmp_value = PyList_New(phrase_result.matches.size());
for (auto j = 0u; j < phrase_result.matches.size(); ++j) {
auto& match = phrase_result.matches[j];
PyObject* index_list = PyList_New(
match.piece_begin_indexes.size() + 1);
for (auto k = 0u; k < match.piece_begin_indexes.size(); ++k) {
PyObject* item = PyInt_FromLong(match.piece_begin_indexes[k]);
PyList_SET_ITEM(index_list, k, item);
}
PyObject* item = PyInt_FromLong(match.end_excl);
PyList_SET_ITEM(index_list, match.piece_begin_indexes.size(), item);
PyList_SET_ITEM(tmp_value, j, index_list);
}
tmp_keys.emplace_back(tmp_key);
tmp_values.emplace_back(tmp_value);
PyObject* tmp_d = MakeDict(tmp_keys, tmp_values, error);
if (!tmp_d) { return NULL; }
PyList_SET_ITEM(value, i, tmp_d);
}
keys.emplace_back(key);
values.emplace_back(value);
return MakeDict(keys, values, error);
}
static PyObject*
PhraserExt_analyze(PhraserExt* self, PyObject* args) {
// Get args.
//
PyObject* py_text;
PyObject* options_dict;
if (!PyArg_ParseTuple(args, "UO!", &py_text, &PyDict_Type, &options_dict)) {
// TODO: call PyErr_SetString here as well?
return NULL;
}
// Check if initialized.
if (!self->ANALYZER) {
PyErr_SetString(PyExc_RuntimeError, "PhraserExt has not been initialized");
return NULL;
}
// Get the input text to analyze.
ustring text;
Py_ssize_t size = PyUnicode_GetSize(py_text);
for (Py_ssize_t i = 0; i < size; ++i) {
text.emplace_back(PyUnicode_AsUnicode(py_text)[i]);
}
// Set the analysis options.
AnalysisOptions options;
string error;
if (!AnalysisOptionsFromDict(options_dict, &options, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
// Analyze the text.
AnalysisResult result;
if (!self->ANALYZER->Analyze(text, options, &result, &error)) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
// Convert the results to a python dict.
PyObject* result_dict;
if (!(result_dict = DictFromAnalysisResult(result, &error))) {
PyErr_SetString(PyExc_RuntimeError, error.data());
return NULL;
}
return result_dict;
}
static PyMethodDef PhraserExt_methods[] = {
{"analyze", (PyCFunction)PhraserExt_analyze, METH_VARARGS, ANALYZE_DOC},
{ NULL, NULL, 0, NULL } /* sentinel */
};
static PyMemberDef PhraserExt_members[] = {
{ NULL, 0, 0, 0, NULL } /* sentinel */
};
static PyTypeObject PhraserExtType = {
PyVarObject_HEAD_INIT(NULL, 0)
"phraserext.PhraserExt", /* tp_name */
sizeof(PhraserExt), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)PhraserExt_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
PHRASER_DOC, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
PhraserExt_methods, /* tp_methods */
PhraserExt_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PhraserExt_init, /* tp_init */
0, /* tp_alloc */
PhraserExt_new, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* tp_version_tag */
};
} // namespace
extern "C" void initphraserext(void);
PyMODINIT_FUNC initphraserext(void) {
PyObject* m;
if (PyType_Ready(&PhraserExtType) < 0)
return;
m = Py_InitModule3("phraserext", PhraserExt_methods,
"Example module that creates an extension type.");
Py_INCREF(&PhraserExtType);
PyModule_AddObject(m, "PhraserExt", (PyObject *)&PhraserExtType);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysetcontainer.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:19:52 $
*
* 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 __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_
#include <helper/propertysetcontainer.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#include <vcl/svapp.hxx>
#define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!"
using namespace rtl;
using namespace vos;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
namespace framework
{
PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& )
: ThreadHelpBase( &Application::GetSolarMutex() )
, OWeakObject()
{
}
PropertySetContainer::~PropertySetContainer()
{
}
// XInterface
void SAL_CALL PropertySetContainer::acquire() throw ()
{
OWeakObject::acquire();
}
void SAL_CALL PropertySetContainer::release() throw ()
{
OWeakObject::release();
}
Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType )
throw ( RuntimeException )
{
Any a = ::cppu::queryInterface(
rType ,
SAL_STATIC_CAST( XIndexContainer*, this ),
SAL_STATIC_CAST( XIndexReplace*, this ),
SAL_STATIC_CAST( XIndexAccess*, this ),
SAL_STATIC_CAST( XElementAccess*, this ) );
if( a.hasValue() )
{
return a;
}
return OWeakObject::queryInterface( rType );
}
// XIndexContainer
void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
sal_Int32 nSize = m_aPropertySetVector.size();
if ( nSize >= Index )
{
Reference< XPropertySet > aPropertySetElement;
if ( Element >>= aPropertySetElement )
{
if ( nSize == Index )
m_aPropertySetVector.push_back( aPropertySetElement );
else
{
PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
aIter += Index;
m_aPropertySetVector.insert( aIter, aPropertySetElement );
}
}
else
{
throw IllegalArgumentException(
OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
(OWeakObject *)this, 2 );
}
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index )
throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
aIter += Index;
m_aPropertySetVector.erase( aIter );
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XIndexReplace
void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
Reference< XPropertySet > aPropertySetElement;
if ( Element >>= aPropertySetElement )
{
m_aPropertySetVector[ Index ] = aPropertySetElement;
}
else
{
throw IllegalArgumentException(
OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
(OWeakObject *)this, 2 );
}
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XIndexAccess
sal_Int32 SAL_CALL PropertySetContainer::getCount()
throw ( RuntimeException )
{
ResetableGuard aGuard( m_aLock );
return m_aPropertySetVector.size();
}
Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index )
throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
Any a;
a <<= m_aPropertySetVector[ Index ];
return a;
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XElementAccess
sal_Bool SAL_CALL PropertySetContainer::hasElements()
throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aGuard( m_aLock );
return !( m_aPropertySetVector.empty() );
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.52); FILE MERGED 2006/09/01 17:29:11 kaib 1.3.52.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysetcontainer.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:00:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
#ifndef __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_
#include <helper/propertysetcontainer.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#include <vcl/svapp.hxx>
#define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!"
using namespace rtl;
using namespace vos;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
namespace framework
{
PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& )
: ThreadHelpBase( &Application::GetSolarMutex() )
, OWeakObject()
{
}
PropertySetContainer::~PropertySetContainer()
{
}
// XInterface
void SAL_CALL PropertySetContainer::acquire() throw ()
{
OWeakObject::acquire();
}
void SAL_CALL PropertySetContainer::release() throw ()
{
OWeakObject::release();
}
Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType )
throw ( RuntimeException )
{
Any a = ::cppu::queryInterface(
rType ,
SAL_STATIC_CAST( XIndexContainer*, this ),
SAL_STATIC_CAST( XIndexReplace*, this ),
SAL_STATIC_CAST( XIndexAccess*, this ),
SAL_STATIC_CAST( XElementAccess*, this ) );
if( a.hasValue() )
{
return a;
}
return OWeakObject::queryInterface( rType );
}
// XIndexContainer
void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
sal_Int32 nSize = m_aPropertySetVector.size();
if ( nSize >= Index )
{
Reference< XPropertySet > aPropertySetElement;
if ( Element >>= aPropertySetElement )
{
if ( nSize == Index )
m_aPropertySetVector.push_back( aPropertySetElement );
else
{
PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
aIter += Index;
m_aPropertySetVector.insert( aIter, aPropertySetElement );
}
}
else
{
throw IllegalArgumentException(
OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
(OWeakObject *)this, 2 );
}
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index )
throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
aIter += Index;
m_aPropertySetVector.erase( aIter );
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XIndexReplace
void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
Reference< XPropertySet > aPropertySetElement;
if ( Element >>= aPropertySetElement )
{
m_aPropertySetVector[ Index ] = aPropertySetElement;
}
else
{
throw IllegalArgumentException(
OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
(OWeakObject *)this, 2 );
}
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XIndexAccess
sal_Int32 SAL_CALL PropertySetContainer::getCount()
throw ( RuntimeException )
{
ResetableGuard aGuard( m_aLock );
return m_aPropertySetVector.size();
}
Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index )
throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
ResetableGuard aGuard( m_aLock );
if ( (sal_Int32)m_aPropertySetVector.size() > Index )
{
Any a;
a <<= m_aPropertySetVector[ Index ];
return a;
}
else
throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}
// XElementAccess
sal_Bool SAL_CALL PropertySetContainer::hasElements()
throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aGuard( m_aLock );
return !( m_aPropertySetVector.empty() );
}
}
<|endoftext|> |
<commit_before>// Copyright 2013 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 "ash/touch/touch_hud_projection.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wm/property_util.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/linear_animation.h"
#include "ui/base/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
const int kPointRadius = 20;
const SkColor kProjectionFillColor = SkColorSetRGB(0xF5, 0xF5, 0xDC);
const SkColor kProjectionStrokeColor = SK_ColorGRAY;
const int kProjectionAlpha = 0xB0;
const int kFadeoutDurationInMs = 250;
const int kFadeoutFrameRate = 60;
// TouchPointView draws a single touch point. This object manages its own
// lifetime and deletes itself upon fade-out completion or whenever |Remove()|
// is explicitly called.
class TouchPointView : public views::View,
public ui::AnimationDelegate,
public views::WidgetObserver {
public:
explicit TouchPointView(views::Widget* parent_widget)
: circle_center_(kPointRadius + 1, kPointRadius + 1),
gradient_center_(SkPoint::Make(kPointRadius + 1,
kPointRadius + 1)) {
SetPaintToLayer(true);
SetFillsBoundsOpaquely(false);
SetSize(gfx::Size(2 * kPointRadius + 2, 2 * kPointRadius + 2));
stroke_paint_.setStyle(SkPaint::kStroke_Style);
stroke_paint_.setColor(kProjectionStrokeColor);
gradient_colors_[0] = kProjectionFillColor;
gradient_colors_[1] = kProjectionStrokeColor;
gradient_pos_[0] = SkFloatToScalar(0.9f);
gradient_pos_[1] = SkFloatToScalar(1.0f);
parent_widget->GetContentsView()->AddChildView(this);
parent_widget->AddObserver(this);
}
void UpdateTouch(const ui::TouchEvent& touch) {
if (touch.type() == ui::ET_TOUCH_RELEASED ||
touch.type() == ui::ET_TOUCH_CANCELLED) {
fadeout_.reset(new ui::LinearAnimation(kFadeoutDurationInMs,
kFadeoutFrameRate,
this));
fadeout_->Start();
} else {
SetX(touch.root_location().x() - kPointRadius - 1);
SetY(touch.root_location().y() - kPointRadius - 1);
}
}
void Remove() {
delete this;
}
private:
virtual ~TouchPointView() {
GetWidget()->RemoveObserver(this);
parent()->RemoveChildView(this);
}
// Overridden from views::View.
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
int alpha = kProjectionAlpha;
if (fadeout_)
alpha = static_cast<int>(fadeout_->CurrentValueBetween(alpha, 0));
fill_paint_.setAlpha(alpha);
stroke_paint_.setAlpha(alpha);
SkShader* shader = SkGradientShader::CreateRadial(
gradient_center_,
SkIntToScalar(kPointRadius),
gradient_colors_,
gradient_pos_,
arraysize(gradient_colors_),
SkShader::kMirror_TileMode,
NULL);
fill_paint_.setShader(shader);
shader->unref();
canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
fill_paint_);
canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
stroke_paint_);
}
// Overridden from ui::AnimationDelegate.
virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE {
DCHECK_EQ(fadeout_.get(), animation);
delete this;
}
virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE {
DCHECK_EQ(fadeout_.get(), animation);
SchedulePaint();
}
virtual void AnimationCanceled(const ui::Animation* animation) OVERRIDE {
AnimationEnded(animation);
}
// Overridden from views::WidgetObserver.
virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
fadeout_->Stop();
}
const gfx::Point circle_center_;
const SkPoint gradient_center_;
SkPaint fill_paint_;
SkPaint stroke_paint_;
SkColor gradient_colors_[2];
SkScalar gradient_pos_[2];
scoped_ptr<ui::Animation> fadeout_;
DISALLOW_COPY_AND_ASSIGN(TouchPointView);
};
TouchHudProjection::TouchHudProjection(aura::RootWindow* initial_root)
: TouchObserverHUD(initial_root) {
}
TouchHudProjection::~TouchHudProjection() {
}
void TouchHudProjection::Clear() {
for (std::map<int, TouchPointView*>::iterator iter = points_.begin();
iter != points_.end(); iter++)
iter->second->Remove();
points_.clear();
}
void TouchHudProjection::OnTouchEvent(ui::TouchEvent* event) {
if (event->type() == ui::ET_TOUCH_PRESSED) {
TouchPointView* point = new TouchPointView(widget());
point->UpdateTouch(*event);
std::pair<std::map<int, TouchPointView*>::iterator, bool> result =
points_.insert(std::make_pair(event->touch_id(), point));
// If a |TouchPointView| is already mapped to the touch id, remove it and
// replace it with the new one.
if (!result.second) {
result.first->second->Remove();
result.first->second = point;
}
} else {
std::map<int, TouchPointView*>::iterator iter =
points_.find(event->touch_id());
if (iter != points_.end()) {
iter->second->UpdateTouch(*event);
if (event->type() == ui::ET_TOUCH_RELEASED ||
event->type() == ui::ET_TOUCH_CANCELLED)
points_.erase(iter);
}
}
}
void TouchHudProjection::SetHudForRootWindowController(
RootWindowController* controller) {
controller->set_touch_hud_projection(this);
}
void TouchHudProjection::UnsetHudForRootWindowController(
RootWindowController* controller) {
controller->set_touch_hud_projection(NULL);
}
} // namespace internal
} // namespace ash
<commit_msg>Fix projection touch HUD in RTL<commit_after>// Copyright 2013 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 "ash/touch/touch_hud_projection.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wm/property_util.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/linear_animation.h"
#include "ui/base/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
const int kPointRadius = 20;
const SkColor kProjectionFillColor = SkColorSetRGB(0xF5, 0xF5, 0xDC);
const SkColor kProjectionStrokeColor = SK_ColorGRAY;
const int kProjectionAlpha = 0xB0;
const int kFadeoutDurationInMs = 250;
const int kFadeoutFrameRate = 60;
// TouchPointView draws a single touch point. This object manages its own
// lifetime and deletes itself upon fade-out completion or whenever |Remove()|
// is explicitly called.
class TouchPointView : public views::View,
public ui::AnimationDelegate,
public views::WidgetObserver {
public:
explicit TouchPointView(views::Widget* parent_widget)
: circle_center_(kPointRadius + 1, kPointRadius + 1),
gradient_center_(SkPoint::Make(kPointRadius + 1,
kPointRadius + 1)) {
SetPaintToLayer(true);
SetFillsBoundsOpaquely(false);
SetSize(gfx::Size(2 * kPointRadius + 2, 2 * kPointRadius + 2));
stroke_paint_.setStyle(SkPaint::kStroke_Style);
stroke_paint_.setColor(kProjectionStrokeColor);
gradient_colors_[0] = kProjectionFillColor;
gradient_colors_[1] = kProjectionStrokeColor;
gradient_pos_[0] = SkFloatToScalar(0.9f);
gradient_pos_[1] = SkFloatToScalar(1.0f);
parent_widget->GetContentsView()->AddChildView(this);
parent_widget->AddObserver(this);
}
void UpdateTouch(const ui::TouchEvent& touch) {
if (touch.type() == ui::ET_TOUCH_RELEASED ||
touch.type() == ui::ET_TOUCH_CANCELLED) {
fadeout_.reset(new ui::LinearAnimation(kFadeoutDurationInMs,
kFadeoutFrameRate,
this));
fadeout_->Start();
} else {
SetX(parent()->GetMirroredXInView(touch.root_location().x()) -
kPointRadius - 1);
SetY(touch.root_location().y() - kPointRadius - 1);
}
}
void Remove() {
delete this;
}
private:
virtual ~TouchPointView() {
GetWidget()->RemoveObserver(this);
parent()->RemoveChildView(this);
}
// Overridden from views::View.
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
int alpha = kProjectionAlpha;
if (fadeout_)
alpha = static_cast<int>(fadeout_->CurrentValueBetween(alpha, 0));
fill_paint_.setAlpha(alpha);
stroke_paint_.setAlpha(alpha);
SkShader* shader = SkGradientShader::CreateRadial(
gradient_center_,
SkIntToScalar(kPointRadius),
gradient_colors_,
gradient_pos_,
arraysize(gradient_colors_),
SkShader::kMirror_TileMode,
NULL);
fill_paint_.setShader(shader);
shader->unref();
canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
fill_paint_);
canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
stroke_paint_);
}
// Overridden from ui::AnimationDelegate.
virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE {
DCHECK_EQ(fadeout_.get(), animation);
delete this;
}
virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE {
DCHECK_EQ(fadeout_.get(), animation);
SchedulePaint();
}
virtual void AnimationCanceled(const ui::Animation* animation) OVERRIDE {
AnimationEnded(animation);
}
// Overridden from views::WidgetObserver.
virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
fadeout_->Stop();
}
const gfx::Point circle_center_;
const SkPoint gradient_center_;
SkPaint fill_paint_;
SkPaint stroke_paint_;
SkColor gradient_colors_[2];
SkScalar gradient_pos_[2];
scoped_ptr<ui::Animation> fadeout_;
DISALLOW_COPY_AND_ASSIGN(TouchPointView);
};
TouchHudProjection::TouchHudProjection(aura::RootWindow* initial_root)
: TouchObserverHUD(initial_root) {
}
TouchHudProjection::~TouchHudProjection() {
}
void TouchHudProjection::Clear() {
for (std::map<int, TouchPointView*>::iterator iter = points_.begin();
iter != points_.end(); iter++)
iter->second->Remove();
points_.clear();
}
void TouchHudProjection::OnTouchEvent(ui::TouchEvent* event) {
if (event->type() == ui::ET_TOUCH_PRESSED) {
TouchPointView* point = new TouchPointView(widget());
point->UpdateTouch(*event);
std::pair<std::map<int, TouchPointView*>::iterator, bool> result =
points_.insert(std::make_pair(event->touch_id(), point));
// If a |TouchPointView| is already mapped to the touch id, remove it and
// replace it with the new one.
if (!result.second) {
result.first->second->Remove();
result.first->second = point;
}
} else {
std::map<int, TouchPointView*>::iterator iter =
points_.find(event->touch_id());
if (iter != points_.end()) {
iter->second->UpdateTouch(*event);
if (event->type() == ui::ET_TOUCH_RELEASED ||
event->type() == ui::ET_TOUCH_CANCELLED)
points_.erase(iter);
}
}
}
void TouchHudProjection::SetHudForRootWindowController(
RootWindowController* controller) {
controller->set_touch_hud_projection(this);
}
void TouchHudProjection::UnsetHudForRootWindowController(
RootWindowController* controller) {
controller->set_touch_hud_projection(NULL);
}
} // namespace internal
} // namespace ash
<|endoftext|> |
<commit_before>#ifndef RBX_EXCEPTION_POINT_HPP
#define RBX_EXCEPTION_POINT_HPP
#include <setjmp.h>
#include "windows_compat.h"
namespace rubinius {
class NativeMethodEnvironment;
class ExceptionPoint {
bool jumped_to_;
ExceptionPoint* previous_;
public:
jmp_buf __jump_buffer;
public:
ExceptionPoint(NativeMethodEnvironment* env);
bool jumped_to() {
return jumped_to_;
}
void reset() {
jumped_to_ = false;
}
void return_to(NativeMethodEnvironment* env);
void unwind_to_previous(NativeMethodEnvironment* env) {
previous_->return_to(env);
}
void pop(NativeMethodEnvironment* env);
};
}
#define PLACE_EXCEPTION_POINT(ep) set_jump(ep.__jump_buffer)
#endif
<commit_msg>Store file and line number where exception point is placed<commit_after>#ifndef RBX_EXCEPTION_POINT_HPP
#define RBX_EXCEPTION_POINT_HPP
#include <setjmp.h>
#include "windows_compat.h"
namespace rubinius {
class NativeMethodEnvironment;
class ExceptionPoint {
bool jumped_to_;
ExceptionPoint* previous_;
public:
jmp_buf __jump_buffer;
const char* file;
int line;
public:
ExceptionPoint(NativeMethodEnvironment* env);
bool jumped_to() {
return jumped_to_;
}
void reset() {
jumped_to_ = false;
}
void return_to(NativeMethodEnvironment* env);
void unwind_to_previous(NativeMethodEnvironment* env) {
previous_->return_to(env);
}
void pop(NativeMethodEnvironment* env);
};
}
#define PLACE_EXCEPTION_POINT(ep) ep.file = __FILE__; ep.line = __LINE__; set_jump(ep.__jump_buffer)
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "rglob.h"
using namespace std;
using namespace rglob;
static void validate(string p, string t, bool x = true, bool pp = false);
/*
Both the main and validate functions below illustrate some sample patterns
and targets, as well as providing a useful framework for simple testing.
N.B. - it should be emphasized that "globs" are NOT "regexps", and in
particular, a single character class, no matter how complex, will match AT
MOST a SINGLE [UTF-8] character / "code point" from the target string.
*/
int main(int argc, char* argv[])
{
// validate the simplest patterns...
validate("abc", "abc");
validate("abc", "abC", false);
validate("ab?", "abC");
validate("*bar", "foobar");
validate("*ba?", "foobaR");
// ... now for some character classes
validate("[A-Z][0-9][^0-9]", "B2B");
validate("[A-Z][0-9][^0-9]", "B2Bx", false);
validate("[A-Z][0-9][^0-9]*", "B2Bx-ray");
validate("[A-Z][0-9][^0-9]", "B23", false);
// can you spot why this will throw an exception?
validate("[A-Z][0-9][^0-9*", "B2Bx-ray");
// how about some fun?
validate("a?c*def*[^]ABx-z]*", "abcYdefABBA Van Halen");
validate("a?c*def[^]ABx-z]*", "abcYdefABBA Van Halen", false);
validate("a?c*def[]ABx-z]*", "abcYdefABBA Van Halen");
// the next two validations are really about showing the equivalence between
// two different ways of inserting Unicode chars into strings (hard vs easy)
// (they really ARE the same pattern, see the pretty_print output yourself!)
validate(u8"*[\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F]BAR", u8"fu\u041f \u0444BAR", true, true);
validate(u8"*[А-Я а-я][А-Я а-я][А-Я а-я]BAR", u8"fuП фBAR", true, true);
return 0;
}
/*
validate "wraps" pattern compiling, optional pretty-printing, and matching,
displaying a [generally] single-line/test formatted report, while catching
and reporting any of the exceptions thrown by rglob.
Usage
=====
p pattern to compile and match against
t target text for matching
x expected result of match (true -> MATCH, false -> FAIL!)
pp pretty_print the compiled version of this pattern
N.B. - whether or not the handy "u8" from of string literals is used, both
the pattern and target will be interpreted as containing Unicode in UTF-8!
*/
static void validate(string p, string t, bool x, bool pp)
{
auto mf = [](bool tf) { return tf ? "MATCH" : "FAIL!"; };
glob g;
try {
g.compile(p);
} catch (invalid_argument& e) {
cerr << "*** Compiling " << p << " => std::invalid_argument: " << e.what() << endl;
return; // we're outta here - after a compile fail, "match" is undefined
} catch (length_error& e) {
cerr << "*** Compiling " << p << " => std::length_error: " << e.what() << endl;
return; // we're outta here - after a compile fail, "match" is undefined
}
if (pp)
cout << "Pretty_print of " << p << ':' << endl, g.pretty_print(cout);
try {
const auto r = g.match(t);
cout << "Wanted "
<< mf(x) << ", got "
<< mf(r) << " ("
<< ((r != x) ? "BZZZT!" : "OK") << ") with "
<< t << " -> "
<< p << endl;
} catch (invalid_argument& e) {
cerr << "*** Matching " << t << " => std::invalid_argument: " << e.what() << endl;
}
}
<commit_msg>Natural languages have so many sources of ambiguities...<commit_after>#include <iostream>
#include "rglob.h"
using namespace std;
using namespace rglob;
static void validate(string p, string t, bool x = true, bool pp = false);
/*
Both the main and validate functions below illustrate some sample patterns
and targets, as well as providing a useful framework for simple testing.
N.B. - it should be emphasized that "globs" are NOT "regexps", and in
particular, a single character class, no matter how complex, will match AT
MOST a SINGLE [UTF-8] character / "code point" from the target string - no
number of '+' or '*' chars after the closing ']' will change this, because
well, "glob" patterns really AREN'T regular expressions (like we said).
*/
int main(int argc, char* argv[])
{
// validate the simplest patterns...
validate("abc", "abc");
validate("abc", "abC", false);
validate("ab?", "abC");
validate("*bar", "foobar");
validate("*ba?", "foobaR");
// ... now for some character classes
validate("[A-Z][0-9][^0-9]", "B2B");
validate("[A-Z][0-9][^0-9]", "B2Bx", false);
validate("[A-Z][0-9][^0-9]*", "B2Bx-ray");
validate("[A-Z][0-9][^0-9]", "B23", false);
// can you spot why this will throw an exception?
validate("[A-Z][0-9][^0-9*", "B2Bx-ray");
// how about some fun?
validate("a?c*def*[^]ABx-z]*", "abcYdefABBA Van Halen");
validate("a?c*def[^]ABx-z]*", "abcYdefABBA Van Halen", false);
validate("a?c*def[]ABx-z]*", "abcYdefABBA Van Halen");
// the next two validations are really about showing the equivalence between
// two different ways of inserting Unicode chars into strings (hard vs easy)
// (they really ARE the same pattern, see the pretty_print output yourself!)
validate(u8"*[\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F]BAR", u8"fu\u041f \u0444BAR", true, true);
validate(u8"*[А-Я а-я][А-Я а-я][А-Я а-я]BAR", u8"fuП фBAR", true, true);
return 0;
}
/*
validate "wraps" pattern compiling, optional pretty-printing, and matching,
displaying a [generally] single-line/test formatted report, while catching
and reporting any of the exceptions thrown by rglob.
Usage
=====
p pattern to compile and match against
t target text for matching
x expected result of match (true -> MATCH, false -> FAIL!)
pp pretty_print the compiled version of this pattern
N.B. - whether or not the handy "u8" from of string literals is used, both
the pattern and target will be interpreted as containing Unicode in UTF-8!
*/
static void validate(string p, string t, bool x, bool pp)
{
auto mf = [](bool tf) { return tf ? "MATCH" : "FAIL!"; };
glob g;
try {
g.compile(p);
} catch (invalid_argument& e) {
cerr << "*** Compiling " << p << " => std::invalid_argument: " << e.what() << endl;
return; // we're outta here - after a compile fail, "match" is undefined
} catch (length_error& e) {
cerr << "*** Compiling " << p << " => std::length_error: " << e.what() << endl;
return; // we're outta here - after a compile fail, "match" is undefined
}
if (pp)
cout << "Pretty_print of " << p << ':' << endl, g.pretty_print(cout);
try {
const auto r = g.match(t);
cout << "Wanted "
<< mf(x) << ", got "
<< mf(r) << " ("
<< ((r != x) ? "BZZZT!" : "OK") << ") with "
<< t << " -> "
<< p << endl;
} catch (invalid_argument& e) {
cerr << "*** Matching " << t << " => std::invalid_argument: " << e.what() << endl;
}
}
<|endoftext|> |
<commit_before>#include "vvLoadDataReaction.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqObjectBuilder.h"
#include "pqPipelineRepresentation.h"
#include "pqPipelineSource.h"
#include "pqServer.h"
#include "pqView.h"
#include "vtkDataObject.h"
#include "vtkPVArrayInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMReaderFactory.h"
#include <QFileDialog>
//-----------------------------------------------------------------------------
vvLoadDataReaction::vvLoadDataReaction(QAction* parentAction)
: Superclass(parentAction)
{
QObject::connect(this, SIGNAL(loadedData(pqPipelineSource*)),
this, SLOT(onDataLoaded(pqPipelineSource*)));
}
//-----------------------------------------------------------------------------
vvLoadDataReaction::~vvLoadDataReaction()
{
}
//-----------------------------------------------------------------------------
void vvLoadDataReaction::onDataLoaded(pqPipelineSource* source)
{
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
if (this->PreviousSource)
{
builder->destroy(this->PreviousSource);
}
Q_ASSERT(this->PreviousSource == NULL);
this->PreviousSource = source;
pqActiveObjects::instance().setActiveSource(source);
pqPipelineRepresentation* repr = qobject_cast<pqPipelineRepresentation*>(
builder->createDataRepresentation(
source->getOutputPort(0), pqActiveObjects::instance().activeView()));
if (!repr)
{
qWarning("Failed to create representation");
return;
}
vtkSMPropertyHelper(repr->getProxy(), "Representation").Set("Points");
// color by "intensity" if array is present.
vtkPVDataInformation* info = repr->getInputDataInformation();
vtkPVArrayInformation* arrayInfo =
info->GetPointDataInformation()->GetArrayInformation("intensity");
if (arrayInfo !=NULL)
{
repr->colorByArray("intensity", vtkDataObject::FIELD_ASSOCIATION_POINTS);
}
repr->getProxy()->UpdateVTKObjects();
repr->renderViewEventually();
pqActiveObjects::instance().activeView()->resetDisplay();
}
//-----------------------------------------------------------------------------
pqPipelineSource* vvLoadDataReaction::loadData()
{
pqServer* server = pqActiveObjects::instance().activeServer();
vtkSMReaderFactory* readerFactory =
vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
QString filters = readerFactory->GetSupportedFileTypes(server->session());
if (!filters.isEmpty())
{
filters += ";;";
}
filters += "All files (*)";
QString fileName = QFileDialog::getOpenFileName(
pqCoreUtilities::mainWidget(), tr("Open File"), QString(), filters);
if (!fileName.isEmpty())
{
QStringList files;
files << fileName;
return pqLoadDataReaction::loadData(files);
}
return NULL;
}
<commit_msg>Disable InterpolateScalarsBeforeMapping after loading the point cloud data<commit_after>#include "vvLoadDataReaction.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqObjectBuilder.h"
#include "pqPipelineRepresentation.h"
#include "pqPipelineSource.h"
#include "pqServer.h"
#include "pqView.h"
#include "vtkDataObject.h"
#include "vtkPVArrayInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMReaderFactory.h"
#include <QFileDialog>
//-----------------------------------------------------------------------------
vvLoadDataReaction::vvLoadDataReaction(QAction* parentAction)
: Superclass(parentAction)
{
QObject::connect(this, SIGNAL(loadedData(pqPipelineSource*)),
this, SLOT(onDataLoaded(pqPipelineSource*)));
}
//-----------------------------------------------------------------------------
vvLoadDataReaction::~vvLoadDataReaction()
{
}
//-----------------------------------------------------------------------------
void vvLoadDataReaction::onDataLoaded(pqPipelineSource* source)
{
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
if (this->PreviousSource)
{
builder->destroy(this->PreviousSource);
}
Q_ASSERT(this->PreviousSource == NULL);
this->PreviousSource = source;
pqActiveObjects::instance().setActiveSource(source);
pqPipelineRepresentation* repr = qobject_cast<pqPipelineRepresentation*>(
builder->createDataRepresentation(
source->getOutputPort(0), pqActiveObjects::instance().activeView()));
if (!repr)
{
qWarning("Failed to create representation");
return;
}
vtkSMPropertyHelper(repr->getProxy(), "Representation").Set("Points");
vtkSMPropertyHelper(repr->getProxy(), "InterpolateScalarsBeforeMapping").Set(0);
// color by "intensity" if array is present.
vtkPVDataInformation* info = repr->getInputDataInformation();
vtkPVArrayInformation* arrayInfo =
info->GetPointDataInformation()->GetArrayInformation("intensity");
if (arrayInfo !=NULL)
{
repr->colorByArray("intensity", vtkDataObject::FIELD_ASSOCIATION_POINTS);
}
repr->getProxy()->UpdateVTKObjects();
repr->renderViewEventually();
pqActiveObjects::instance().activeView()->resetDisplay();
}
//-----------------------------------------------------------------------------
pqPipelineSource* vvLoadDataReaction::loadData()
{
pqServer* server = pqActiveObjects::instance().activeServer();
vtkSMReaderFactory* readerFactory =
vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
QString filters = readerFactory->GetSupportedFileTypes(server->session());
if (!filters.isEmpty())
{
filters += ";;";
}
filters += "All files (*)";
QString fileName = QFileDialog::getOpenFileName(
pqCoreUtilities::mainWidget(), tr("Open File"), QString(), filters);
if (!fileName.isEmpty())
{
QStringList files;
files << fileName;
return pqLoadDataReaction::loadData(files);
}
return NULL;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "CPUSPHFluidForceFieldWithOpenCL.h"
void CPUSPHFluidForceFieldWithOpenCL::addForce(unsigned int _gsize, const _device_pointer _cells, const _device_pointer _cellGhost, GPUSPHFluid* params,_device_pointer _f, const _device_pointer _pos4, const _device_pointer _v)
{
float3 *f = new float3[NUM_ELEMENTS];
float4 *pos4 = new float4[NUM_ELEMENTS];
int *cells = new int[32800+8*NUM_ELEMENTS];
int *cellGhost = new int[32768];
float3 *v = new float3[NUM_ELEMENTS];
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,f,_f.m,_f.offset,sizeof(float3)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,pos4,_pos4.m,_pos4.offset,sizeof(float4)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cells,_cells.m,_cells.offset,sizeof(int)*(32800+8*NUM_ELEMENTS));
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cellGhost,_cellGhost.m,_cellGhost.offset,sizeof(int)*32768);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,v,_v.m,_v.offset,sizeof(float3)*NUM_ELEMENTS);
vectorAddForce(_gsize,cells,cellGhost,*params,f,pos4,v);
sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_v.m,_v.offset,v,sizeof(float3)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_f.m,_f.offset,f,sizeof(float3)*NUM_ELEMENTS);
delete(pos4);
delete(cells);
delete(cellGhost);
delete(v);
delete(f);
}
<commit_msg>SofaOpenCL: fixing deletings<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "CPUSPHFluidForceFieldWithOpenCL.h"
void CPUSPHFluidForceFieldWithOpenCL::addForce(unsigned int _gsize, const _device_pointer _cells, const _device_pointer _cellGhost, GPUSPHFluid* params,_device_pointer _f, const _device_pointer _pos4, const _device_pointer _v)
{
float3 *f = new float3[NUM_ELEMENTS];
float4 *pos4 = new float4[NUM_ELEMENTS];
int *cells = new int[32800+8*NUM_ELEMENTS];
int *cellGhost = new int[32768];
float3 *v = new float3[NUM_ELEMENTS];
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,f,_f.m,_f.offset,sizeof(float3)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,pos4,_pos4.m,_pos4.offset,sizeof(float4)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cells,_cells.m,_cells.offset,sizeof(int)*(32800+8*NUM_ELEMENTS));
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cellGhost,_cellGhost.m,_cellGhost.offset,sizeof(int)*32768);
sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,v,_v.m,_v.offset,sizeof(float3)*NUM_ELEMENTS);
vectorAddForce(_gsize,cells,cellGhost,*params,f,pos4,v);
sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_v.m,_v.offset,v,sizeof(float3)*NUM_ELEMENTS);
sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_f.m,_f.offset,f,sizeof(float3)*NUM_ELEMENTS);
delete [] pos4;
delete [] cells;
delete [] cellGhost;
delete [] v;
delete [] f;
}
<|endoftext|> |
<commit_before>/*
* SSLConfig.cpp
*
* Created on: May 1, 2016
* Author: James Hong
*/
#include "tcp/SSLConfig.h"
#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include <iostream>
#include <sstream>
#include "Debug.h"
#include "util/file.h"
bool SSLConfig::initialized = false;
std::mutex SSLConfig::initMutex;
SSLConfig::SSLConfig(bool verifyPeers, bool isServer, std::string cert, std::string key,
std::string caCert) {
initMutex.lock();
if (!initialized) {
SSL_load_error_strings();
SSL_library_init();
initialized = true;
}
initMutex.unlock();
const SSL_METHOD *method;
if (isServer) {
method = TLSv1_2_server_method();
} else {
method = TLSv1_2_client_method();
}
ctx = SSL_CTX_new(method);
SSL_CTX_load_verify_locations(ctx, caCert.c_str(), NULL);
if (verifyPeers) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
[](int preverify_ok, X509_STORE_CTX *ctx) -> int {
char buf[512];
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
if (debug) {
std::stringstream ss;
ss << buf;
pdebug(ss.str());
}
/*
* At this point, err contains the last verification error. We can use
* it for something special
*/
if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT))
{
X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf));
printf("issuer= %s\n", buf);
}
return preverify_ok;
});
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
}
SSL_CTX_set_timeout(ctx, 6);
SSL_CTX_set_verify_depth(ctx, 2);
SSL_CTX_set_cipher_list(ctx, "HIGH");
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
if (!file_exists(cert)) {
throw std::invalid_argument("cert not found: " + cert);
}
if (!file_exists(key)) {
throw std::invalid_argument("key not found: " + key);
}
/* Set the key and cert */
if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) < 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) < 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
SSLConfig::~SSLConfig() {
SSL_CTX_free(ctx);
ERR_free_strings();
EVP_cleanup();
}
SSL_CTX *SSLConfig::getCtx() {
return ctx;
}
<commit_msg>Add comment.<commit_after>/*
* SSLConfig.cpp
*
* Created on: May 1, 2016
* Author: James Hong
*/
#include "tcp/SSLConfig.h"
#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include <iostream>
#include <sstream>
#include "Debug.h"
#include "util/file.h"
bool SSLConfig::initialized = false;
std::mutex SSLConfig::initMutex;
SSLConfig::SSLConfig(bool verifyPeers, bool isServer, std::string cert, std::string key,
std::string caCert) {
initMutex.lock();
if (!initialized) {
SSL_load_error_strings();
SSL_library_init();
initialized = true;
}
initMutex.unlock();
const SSL_METHOD *method;
if (isServer) {
method = TLSv1_2_server_method();
} else {
method = TLSv1_2_client_method();
}
ctx = SSL_CTX_new(method);
SSL_CTX_load_verify_locations(ctx, caCert.c_str(), NULL);
if (verifyPeers) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
[](int preverify_ok, X509_STORE_CTX *ctx) -> int {
char buf[512];
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
/*
* TODO: use fields to identify gateway, controller, applications
*/
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
if (debug) {
std::stringstream ss;
ss << buf;
pdebug(ss.str());
}
/*
* At this point, err contains the last verification error. We can use
* it for something special
*/
if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT))
{
X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf));
printf("issuer= %s\n", buf);
}
return preverify_ok;
});
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
}
SSL_CTX_set_timeout(ctx, 6);
SSL_CTX_set_verify_depth(ctx, 2);
SSL_CTX_set_cipher_list(ctx, "HIGH");
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
if (!file_exists(cert)) {
throw std::invalid_argument("cert not found: " + cert);
}
if (!file_exists(key)) {
throw std::invalid_argument("key not found: " + key);
}
/* Set the key and cert */
if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) < 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) < 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
SSLConfig::~SSLConfig() {
SSL_CTX_free(ctx);
ERR_free_strings();
EVP_cleanup();
}
SSL_CTX *SSLConfig::getCtx() {
return ctx;
}
<|endoftext|> |
<commit_before>
/*
passiveLocationPush
Example app using samsonClient lib
It generates random xml documents simulating information from OSS Passive Location pilot
AUTHOR: Andreu Urruela
*/
#include <stdio.h> // printf
#include <stdlib.h> // exit
#include <string.h> // memcpy
#include <iostream> // std::cout
#include <time.h> // strptime, struct tm
#include "au/time.h" // au::todatString()
#include "au/string.h" // au::str()
#include "au/Cronometer.h" // au::Cronometer
#include "au/CommandLine.h" // au::CommandLine
#include "samson/client/SamsonClient.h" // samson::SamsonClient
bool random_user = false;
size_t last_user = 0;
int main( int argc , const char *argv[] )
{
au::CommandLine cmd;
cmd.set_flag_int( "users" , 100000 );
cmd.parse( argc , argv );
int num_users = cmd.get_flag_int("users");
if( cmd.get_num_arguments() < 2 )
{
fprintf(stderr,"Usage %s rate_in_messages_per_second -users <num_users>\n", argv[0] );
exit(0);
}
size_t rate = atoll( argv[1] );
size_t max_kvs = 0;
if( argc > 2 )
max_kvs = atoll( argv[2] );
// Small mini-buffer to generate
char *line = (char*) malloc( 20000 );
// Control of time and size
au::Cronometer cronometer;
size_t total_size = 0;
size_t num_messages = 0;
size_t theoretical_seconds = 0;
while( true )
{
// Generat 5 seconds data
fprintf(stderr,"Generating %d messages\n", (int)(5 * rate) );
for( int i = 0 ; i < (int)(5 * rate); i++)
{
size_t user_id;
if( random_user )
user_id = rand()%num_users;
else
{
last_user = (last_user+1)%num_users;
user_id = last_user;
}
int cell = 65528;
if( (time(NULL)%200)> 100 )
cell = 65534;
snprintf( line, 20000 , "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:AMRReport xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns0='http://O2.arcanum.vitria.com' xsi:schemaLocation='http://O2.arcanum.vitria.com AMR.xsd'> <SubscriberReport> <User> <IMSI>%lu</IMSI> <PTMSI>FB869371</PTMSI> <CellID>%d</CellID> <Paging> <Location> <LocationArea>12124</LocationArea> <RoutingArea>134</RoutingArea> </Location> </Paging> </SubscriberReport> <Timestamp>2011-07-21T16:07:47</Timestamp></ns0:AMRReport>" , user_id , cell );
total_size += strlen(line);
num_messages++;
// Emit line to the output
std::cout << line << "\n";
}
if( max_kvs > 0 )
if( num_messages > max_kvs )
{
fprintf(stderr,"Finish since a limit of %lu kvs was specified. Generated %lu key-vaue\n", max_kvs ,num_messages);
return 0;
}
// Detect if we need to sleep....
theoretical_seconds += 5;
size_t ellapsed_seconds = cronometer.diffTimeInSeconds();
// Sleep some time to simulate a particular rate
if( ellapsed_seconds < theoretical_seconds )
{
int sleep_seconds = theoretical_seconds - ellapsed_seconds;
std::cerr << "Sleeping " << sleep_seconds << " seconds... num messages " << au::str(num_messages) << " size " << au::str( total_size , "bytes") << " time " << au::time_string(ellapsed_seconds) << " theoretical time " << au::time_string(theoretical_seconds)<<"\n";
sleep( sleep_seconds );
}
}
}
<commit_msg>Update in the passive location generator<commit_after>
/*
passiveLocationPush
Example app using samsonClient lib
It generates random xml documents simulating information from OSS Passive Location pilot
AUTHOR: Andreu Urruela
*/
#include <stdio.h> // printf
#include <stdlib.h> // exit
#include <string.h> // memcpy
#include <iostream> // std::cout
#include <time.h> // strptime, struct tm
#include "au/time.h" // au::todatString()
#include "au/string.h" // au::str()
#include "au/Cronometer.h" // au::Cronometer
#include "au/CommandLine.h" // au::CommandLine
#include "samson/client/SamsonClient.h" // samson::SamsonClient
size_t get_user_id( size_t pos )
{
return 666666666 + pos;
}
int main( int argc , const char *argv[] )
{
au::CommandLine cmd;
cmd.set_flag_uint64( "users" , 100000 );
cmd.set_flag_uint64( "num" , 0 ); // Number of messages
cmd.set_flag_boolean( "random" ); // Generate a message for all users
cmd.parse( argc , argv );
size_t num_users = cmd.get_flag_uint64("users");
size_t num = cmd.get_flag_uint64("num");
bool random_user = cmd.get_flag_bool("random");
srand( time(NULL) );
if( cmd.get_num_arguments() < 2 )
{
fprintf(stderr,"Usage %s rate_in_messages_per_second -users <num_users> -num <max_num_messages> -random \n", argv[0] );
exit(0);
}
size_t rate = atoll( cmd.get_argument(1).c_str() );
fprintf(stderr, "Running generator with rate=%lu num=%lu users=%lu\n" , rate , num , num_users );
// Small mini-buffer to generate
char *line = (char*) malloc( 20000 );
// Control of time and size
au::Cronometer cronometer;
size_t last_user = 0;
size_t total_size = 0;
size_t num_messages = 0;
size_t theoretical_seconds = 0;
while( true )
{
// Generat 5 seconds data
fprintf(stderr,"Generating %d messages ( mesages in 5 seconds at %lu events/s ) \n", (int)(5 * rate) , rate );
for( int i = 0 ; i < (int)(5 * rate); i++)
{
size_t user_id;
if( random_user )
user_id = get_user_id( rand()%num_users );
else
{
last_user = get_user_id( (last_user+1)%num_users );
user_id = last_user;
}
int cell = 65528;
if( (time(NULL)%200)> 100 )
cell = 65534;
snprintf( line, 20000 , "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:AMRReport xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns0='http://O2.arcanum.vitria.com' xsi:schemaLocation='http://O2.arcanum.vitria.com AMR.xsd'> <SubscriberReport> <User> <IMSI>%lu</IMSI> <PTMSI>FB869371</PTMSI> <CellID>%d</CellID> <Paging> <Location> <LocationArea>12124</LocationArea> <RoutingArea>134</RoutingArea> </Location> </Paging> </SubscriberReport> <Timestamp>2011-07-21T16:07:47</Timestamp></ns0:AMRReport>" , user_id , cell );
total_size += strlen(line);
num_messages++;
// Emit line to the output
std::cout << line << "\n";
if( num > 0 )
{
if( num_messages >= num )
{
fprintf(stderr,"Generated %s messages" , au::str( num_messages).c_str() );
exit(0);
}
}
}
// Detect if we need to sleep....
theoretical_seconds += 5;
size_t ellapsed_seconds = cronometer.diffTimeInSeconds();
// Sleep some time to simulate a particular rate
if( ellapsed_seconds < theoretical_seconds )
{
int sleep_seconds = theoretical_seconds - ellapsed_seconds;
std::cerr << "Sleeping " << sleep_seconds << " seconds... We have generate " << au::str(num_messages) << " messages with size " << au::str( total_size , "bytes") << " time " << au::time_string(ellapsed_seconds) << " theoretical time " << au::time_string(theoretical_seconds)<<"\n";
sleep( sleep_seconds );
}
}
}
<|endoftext|> |
<commit_before>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "conv_layer_wrapper.h"
#include <tiramisu/utils.h>
// MKL-DNN default format is NCHW according to
// https://www.tensorflow.org/performance/performance_guide
int main(int, char**)
{
Halide::Buffer<float> input(N+K, N+K, FIn, BATCH_SIZE);
Halide::Buffer<float> filter(K, K, FIn, FOut);
Halide::Buffer<float> bias(FIn);
Halide::Buffer<float> conv(N, N, FOut, BATCH_SIZE);
Halide::Buffer<float> conv_tiramisu_buffer(N, N, FOut, BATCH_SIZE);
Halide::Buffer<int> parameters(5);
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
for (int y = 0; y < N+K; ++y)
for (int x = 0; x < N+K; ++x)
for (int z = 0; z < FIn; ++z)
for (int n = 0; n < BATCH_SIZE; ++n)
input(x, y, z, n) = 1;
for (int z = 0; z < FIn; ++z)
bias(z) = 1;
for (int y = 0; y < K; ++y)
for (int x = 0; x < K; ++x)
for (int z = 0; z < FIn; ++z)
for (int q = 0; q < FOut; ++q)
filter(x, y, z, q) = 1;
std::cout << "\t\tBuffers initialized" << std::endl;
unsigned int count = 0;
// Initialize parameters[]
parameters(0) = N;
parameters(1) = K;
parameters(2) = FIn;
parameters(3) = FOut;
parameters(4) = BATCH_SIZE;
for (int i=0; i<NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
conv_tiramisu(parameters.raw_buffer(), input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv_tiramisu_buffer.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector_2) << "; " << std::endl;
std::cout << "\t\tResult" << ": ";
count = 0;
for (int y = 0; y < N+K; ++y)
for (int x = 0; x < N+K; ++x)
for (int z = 0; z < FIn; ++z)
for (int n = 0; n < BATCH_SIZE; ++n)
if (count < 10)
{
std::cerr << conv_tiramisu_buffer(x, y, z, n) << ", ";
count++;
}
std::cout << std::endl;
return 0;
}
<commit_msg>Update conv_layer_wrapper.cpp<commit_after>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "conv_layer_wrapper.h"
#include <tiramisu/utils.h>
// MKL-DNN default format is NCHW according to
// https://www.tensorflow.org/performance/performance_guide
int main(int, char **)
{
int sizes[26][4];
sizes[0][0] = 32;
sizes[0][1] = 8;
sizes[0][2] = 16;
sizes[0][3] = 16;
sizes[1][0] = 64;
sizes[1][1] = 32;
sizes[1][2] = 16;
sizes[1][3] = 16;
sizes[2][0] = 512;
sizes[2][1] = 100;
sizes[2][2] = 16;
sizes[2][3] = 16;
sizes[3][0] = 224;
sizes[3][1] = 8;
sizes[3][2] = 3;
sizes[3][3] = 64;
sizes[4][0] = 224;
sizes[4][1] = 32;
sizes[4][2] = 3;
sizes[4][3] = 64;
sizes[5][0] = 224;
sizes[5][1] = 100;
sizes[5][2] = 3;
sizes[5][3] = 64;
sizes[6][0] = 56;
sizes[6][1] = 8;
sizes[6][2] = 64;
sizes[6][3] = 64;
sizes[7][0] = 56;
sizes[7][1] = 32;
sizes[7][2] = 64;
sizes[7][3] = 64;
sizes[8][0] = 56;
sizes[8][1] = 100;
sizes[8][2] = 64;
sizes[8][3] = 64;
sizes[9][0] = 56;
sizes[9][1] = 8;
sizes[9][2] = 64;
sizes[9][3] = 128;
sizes[10][0] = 56;
sizes[10][1] = 32;
sizes[10][2] = 64;
sizes[10][3] = 128;
sizes[11][0] = 56;
sizes[11][1] = 100;
sizes[11][2] = 64;
sizes[11][3] = 128;
sizes[12][0] = 28;
sizes[12][1] = 8;
sizes[12][2] = 128;
sizes[12][3] = 128;
sizes[13][0] = 28;
sizes[13][1] = 32;
sizes[13][2] = 128;
sizes[13][3] = 128;
sizes[14][0] = 28;
sizes[14][1] = 100;
sizes[14][2] = 128;
sizes[14][3] = 128;
sizes[15][0] = 28;
sizes[15][1] = 8;
sizes[15][2] = 100;
sizes[15][3] = 256;
sizes[16][0] = 28;
sizes[16][1] = 32;
sizes[16][2] = 100;
sizes[16][3] = 256;
sizes[17][0] = 28;
sizes[17][1] = 100;
sizes[17][2] = 100;
sizes[17][3] = 256;
sizes[18][0] = 14;
sizes[18][1] = 8;
sizes[18][2] = 256;
sizes[18][3] = 256;
sizes[19][0] = 14;
sizes[19][1] = 32;
sizes[19][2] = 256;
sizes[19][3] = 256;
sizes[20][0] = 14;
sizes[20][1] = 100;
sizes[20][2] = 256;
sizes[20][3] = 256;
sizes[21][0] = 14;
sizes[21][1] = 8;
sizes[21][2] = 310;
sizes[21][3] = 512;
sizes[22][0] = 14;
sizes[22][1] = 32;
sizes[22][2] = 310;
sizes[22][3] = 512;
sizes[23][0] = 14;
sizes[23][1] = 100;
sizes[23][2] = 310;
sizes[23][3] = 512;
sizes[24][0] = 7;
sizes[24][1] = 8;
sizes[24][2] = 512;
sizes[24][3] = 512;
sizes[25][0] = 7;
sizes[25][1] = 32;
sizes[25][2] = 512;
sizes[25][3] = 512;
sizes[26][0] = 7;
sizes[26][1] = 100;
sizes[26][2] = 512;
sizes[26][3] = 512;
std::ofstream resultfile;
resultfile.open("tiramisu_result.txt");
for (int j = 0; j < 20; ++j)
{
int N = sizes[j][0];
int BATCH_SIZE = sizes[j][1];
int FIn = sizes[j][2];
int FOut = sizes[j][3];
Halide::Buffer<double> input(N + K, N + K, FIn, BATCH_SIZE);
Halide::Buffer<double> filter(K, K, FIn, FOut);
Halide::Buffer<double> bias(FIn);
Halide::Buffer<double> conv(N, N, FOut, BATCH_SIZE);
Halide::Buffer<double> conv_tiramisu_buffer(N, N, FOut, BATCH_SIZE);
Halide::Buffer<int> parameters(5);
std::vector<std::chrono::duration<double, std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double, std::milli>> duration_vector_2;
for (int y = 0; y < N + K; ++y)
for (int x = 0; x < N + K; ++x)
for (int z = 0; z < FIn; ++z)
for (int n = 0; n < BATCH_SIZE; ++n)
input(x, y, z, n) = 1;
for (int z = 0; z < FIn; ++z)
bias(z) = 1;
for (int y = 0; y < K; ++y)
for (int x = 0; x < K; ++x)
for (int z = 0; z < FIn; ++z)
for (int q = 0; q < FOut; ++q)
filter(x, y, z, q) = 1;
std::cout << "\t\tBuffers initialized" << std::endl;
unsigned int count = 0;
// Initialize parameters[]
parameters(0) = N;
parameters(1) = K;
parameters(2) = FIn;
parameters(3) = FOut;
parameters(4) = BATCH_SIZE;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
conv_tiramisu(parameters.raw_buffer(), input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv_tiramisu_buffer.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tTiramisu conv"
<< ": " << median(duration_vector_2) << "; " << std::endl;
resultfile << median(duration_vector_2) << "\n";
std::cout << "\t\tResult"
<< ": ";
count = 0;
for (int y = 0; y < N + K; ++y)
for (int x = 0; x < N + K; ++x)
for (int z = 0; z < FIn; ++z)
for (int n = 0; n < BATCH_SIZE; ++n)
if (count < 10)
{
std::cerr << conv_tiramisu_buffer(x, y, z, n) << ", ";
count++;
}
std::cout << std::endl;
}
resultfile.close();
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.